Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 | 265x 13x 13x 9x 6x 4x 13x 265x 265x 265x 265x 265x 265x 187x 265x 2x 2x 2x 2x 21x 17x 17x 17x 4x 33x 33x 13x 13x 13x 13x 13x 13x 13x 2x 2x 9x 5x 5x 16x 16x 16x 16x 16x 16x 16x 16x 13x 16x 15x 3x 3x 1x 16x 89x 11x 50x 28x 2x 26x 26x 4x 3x 3x 3x 6x 3x 23x 23x 23x 23x 23x 1x 1x 1x 3x 2x 1x 37x 23x 23x 138x 138x 138x 437x 138x 138x 23x 23x 23x 23x 138x 138x 138x 437x 138x 23x 23x 23x 23x 23x 23x 23x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 44x 44x 13x 28x 13x 13x 44x 44x 44x 44x 48x 13x 44x 53x 19x 19x 19x 19x 13x 23x 72x 23x 23x 23x 23x 23x 23x 6x 6x 6x 6x 6x 6x 1x 5x 1x 1x 23x | import * as orama from '@orama/orama';
import type { ChatCompletionFunctionTool } from 'openai/resources/chat/completions';
import type { FunctionTool as OpenAIResponsesFunctionTool } from 'openai/resources/responses/responses';
import { DEFAULT_HYBRID_ALPHA } from './consts';
import { RequestBuilder } from './requestBuilder';
import type {
AISDKToolDefinition,
AISDKToolResult,
ExecuteConfig,
ExecuteOptions,
Experimental_PreExecuteFunction,
Experimental_ToolCreationOptions,
HttpExecuteConfig,
JsonDict,
LocalExecuteConfig,
RpcExecuteConfig,
ToolExecution,
ToolParameters,
} from './types';
import { StackOneError } from './utils/errors';
import { TfidfIndex } from './utils/tfidf-index';
/**
* Base class for all tools. Provides common functionality for executing API calls
* and converting to various formats (OpenAI, AI SDK)
*/
export class BaseTool {
name: string;
description: string;
parameters: ToolParameters;
executeConfig: ExecuteConfig;
protected requestBuilder?: RequestBuilder;
protected experimental_preExecute?: Experimental_PreExecuteFunction;
#exposeExecutionMetadata = true;
#headers: Record<string, string>;
private createExecutionMetadata(): ToolExecution {
const config = (() => {
switch (this.executeConfig.kind) {
case 'http':
return {
kind: 'http',
method: this.executeConfig.method,
url: this.executeConfig.url,
bodyType: this.executeConfig.bodyType,
params: this.executeConfig.params.map((param) => ({ ...param })),
} satisfies HttpExecuteConfig;
case 'rpc':
return {
kind: 'rpc',
method: this.executeConfig.method,
url: this.executeConfig.url,
payloadKeys: { ...this.executeConfig.payloadKeys },
} satisfies RpcExecuteConfig;
case 'local':
return {
kind: 'local',
identifier: this.executeConfig.identifier,
description: this.executeConfig.description,
} satisfies LocalExecuteConfig;
default:
this.executeConfig satisfies never;
throw new StackOneError('Unsupported executeConfig kind');
}
})();
return {
config,
headers: this.getHeaders(),
};
}
constructor(
name: string,
description: string,
parameters: ToolParameters,
executeConfig: ExecuteConfig,
headers?: Record<string, string>,
experimental_preExecute?: Experimental_PreExecuteFunction,
) {
this.name = name;
this.description = description;
this.parameters = parameters;
this.executeConfig = executeConfig;
this.#headers = { ...headers };
if (executeConfig.kind === 'http') {
this.requestBuilder = new RequestBuilder(executeConfig, this.#headers);
}
this.experimental_preExecute = experimental_preExecute;
}
/**
* Set headers for this tool
*/
setHeaders(headers: Record<string, string>): BaseTool {
this.#headers = { ...this.#headers, ...headers };
Eif (this.requestBuilder) {
this.requestBuilder.setHeaders(headers);
}
return this;
}
/**
* Get the current headers
*/
getHeaders(): Record<string, string> {
if (this.requestBuilder) {
const currentHeaders = this.requestBuilder.getHeaders();
this.#headers = { ...currentHeaders };
return currentHeaders;
}
return { ...this.#headers };
}
/**
* Control whether execution metadata should be exposed in AI SDK conversions.
*/
setExposeExecutionMetadata(expose: boolean): this {
this.#exposeExecutionMetadata = expose;
return this;
}
/**
* Execute the tool with the provided parameters
*/
async execute(inputParams?: JsonDict | string, options?: ExecuteOptions): Promise<JsonDict> {
try {
Iif (!this.requestBuilder || this.executeConfig.kind !== 'http') {
// Non-HTTP tools provide their own execute override (e.g. RPC, local meta tools).
throw new StackOneError(
'BaseTool.execute is only available for HTTP-backed tools. Provide a custom execute implementation for non-HTTP tools.',
);
}
// Validate params is either undefined, string, or object
Iif (
inputParams !== undefined &&
typeof inputParams !== 'string' &&
typeof inputParams !== 'object'
) {
throw new StackOneError(
`Invalid parameters type. Expected object or string, got ${typeof inputParams}. Parameters: ${JSON.stringify(inputParams)}`,
);
}
// Convert string params to object
const params = typeof inputParams === 'string' ? JSON.parse(inputParams) : inputParams || {};
// Apply experimental preExecute function (either from tool creation or execution options)
let processedParams = params;
Iif (this.experimental_preExecute) {
processedParams = await this.experimental_preExecute(params);
}
// Execute the request directly with processed parameters
return await this.requestBuilder.execute(processedParams, options);
} catch (error) {
Eif (error instanceof StackOneError) {
throw error;
}
throw new StackOneError(
`Error executing tool: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
/**
* Convert the tool to OpenAI Chat Completions API format
*/
toOpenAI(): ChatCompletionFunctionTool {
return {
type: 'function',
function: {
name: this.name,
description: this.description,
parameters: {
type: 'object',
properties: this.parameters.properties,
required: this.parameters.required,
},
},
};
}
/**
* Convert the tool to OpenAI Responses API format
* @see https://platform.openai.com/docs/api-reference/responses
*/
toOpenAIResponses(options: { strict?: boolean } = {}): OpenAIResponsesFunctionTool {
const { strict = true } = options;
return {
type: 'function',
name: this.name,
description: this.description,
strict,
parameters: {
type: 'object',
properties: this.parameters.properties,
required: this.parameters.required,
...(strict ? { additionalProperties: false } : {}),
},
};
}
/**
* Convert the tool to AI SDK format
*/
async toAISDK(
options: { executable?: boolean; execution?: ToolExecution | false } = {
executable: true,
},
): Promise<AISDKToolResult> {
const schema = {
type: 'object' as const,
properties: this.parameters.properties || {},
required: this.parameters.required || [],
additionalProperties: false,
};
/** AI SDK is optional dependency, import only when needed */
let jsonSchema: typeof import('ai').jsonSchema;
try {
const ai = await import('ai');
jsonSchema = ai.jsonSchema;
} catch {
throw new StackOneError(
'AI SDK is not installed. Please install it with: npm install ai@4.x|5.x or pnpm add ai@4.x|5.x',
);
}
const schemaObject = jsonSchema(schema);
// TODO: Remove ts-ignore once AISDKToolDefinition properly types the inputSchema and parameters
// We avoid defining our own types as much as possible, so we use the AI SDK Tool type
// but need to suppress errors for backward compatibility properties
const toolDefinition = {
inputSchema: schemaObject,
parameters: schemaObject, // v4 (backward compatibility)
description: this.description,
} as AISDKToolDefinition;
const executionOption =
options.execution !== undefined
? options.execution
: this.#exposeExecutionMetadata
? this.createExecutionMetadata()
: false;
if (executionOption !== false) {
toolDefinition.execution = executionOption;
}
if (options.executable ?? true) {
toolDefinition.execute = async (args: Record<string, unknown>) => {
try {
return await this.execute(args as JsonDict);
} catch (error) {
return `Error executing tool: ${error instanceof Error ? error.message : String(error)}`;
}
};
}
return {
[this.name]: toolDefinition,
} as AISDKToolResult;
}
}
/**
* StackOne-specific tool class with additional functionality
*/
export class StackOneTool extends BaseTool {
/**
* Get the current account ID
*/
getAccountId(): string | undefined {
return this.getHeaders()['x-account-id'];
}
/**
* Set the account ID for this tool
*/
setAccountId(accountId: string): StackOneTool {
this.setHeaders({ 'x-account-id': accountId });
return this;
}
}
/**
* Collection of tools with utility methods
*/
export class Tools implements Iterable<BaseTool> {
private tools: BaseTool[];
constructor(tools: BaseTool[]) {
this.tools = tools;
}
/**
* Get the number of tools in the collection
*/
get length(): number {
return this.tools.length;
}
/**
* Get a tool by name
*/
getTool(name: string, options?: Experimental_ToolCreationOptions): BaseTool | undefined {
const originalTool = this.tools.find((tool) => tool.name === name);
if (!originalTool) {
return undefined;
}
// If no experimental options provided, return original tool
Eif (!options?.experimental_schemaOverride && !options?.experimental_preExecute) {
return originalTool;
}
// Create a new tool with experimental schema override and preExecute
let parameters = originalTool.parameters;
// Apply schema override if provided
if (options.experimental_schemaOverride) {
parameters = options.experimental_schemaOverride(originalTool.parameters);
}
// Create new tool instance with modified schema and preExecute function
if (originalTool instanceof StackOneTool) {
const newTool = new StackOneTool(
originalTool.name,
originalTool.description,
parameters,
originalTool.executeConfig,
originalTool.getHeaders(),
options.experimental_preExecute,
);
return newTool;
}
const newTool = new BaseTool(
originalTool.name,
originalTool.description,
parameters,
originalTool.executeConfig,
originalTool.getHeaders(),
options.experimental_preExecute,
);
return newTool;
}
/**
* Get a StackOne tool by name
*/
getStackOneTool(name: string): StackOneTool {
const tool = this.getTool(name);
if (tool instanceof StackOneTool) {
return tool;
}
throw new StackOneError(`Tool ${name} is not a StackOne tool`);
}
/**
* Check if a tool is a StackOne tool
*/
isStackOneTool(tool: BaseTool): tool is StackOneTool {
return tool instanceof StackOneTool;
}
/**
* Get all StackOne tools in the collection
*/
getStackOneTools(): StackOneTool[] {
return this.tools.filter((tool): tool is StackOneTool => tool instanceof StackOneTool);
}
/**
* Convert all tools to OpenAI Chat Completions API format
*/
toOpenAI(): ChatCompletionFunctionTool[] {
return this.tools.map((tool) => tool.toOpenAI());
}
/**
* Convert all tools to OpenAI Responses API format
* @see https://platform.openai.com/docs/api-reference/responses
*/
toOpenAIResponses(options: { strict?: boolean } = {}): OpenAIResponsesFunctionTool[] {
return this.tools.map((tool) => tool.toOpenAIResponses(options));
}
/**
* Convert all tools to AI SDK format
*/
async toAISDK(
options: { executable?: boolean; execution?: ToolExecution | false } = {
executable: true,
},
): Promise<AISDKToolResult> {
const result: AISDKToolResult = {};
for (const tool of this.tools) {
Object.assign(result, await tool.toAISDK(options));
}
return result;
}
/**
* Filter tools by a predicate function
*/
filter(predicate: (tool: BaseTool) => boolean): Tools {
return new Tools(this.tools.filter(predicate));
}
/**
* Return meta tools for tool discovery and execution
* @beta This feature is in beta and may change in future versions
* @param hybridAlpha - Weight for BM25 in hybrid search (0-1). If not provided, uses DEFAULT_HYBRID_ALPHA (0.2).
*/
async metaTools(hybridAlpha = DEFAULT_HYBRID_ALPHA): Promise<Tools> {
const oramaDb = await initializeOramaDb(this.tools);
const tfidfIndex = initializeTfidfIndex(this.tools);
const baseTools = [
metaSearchTools(oramaDb, tfidfIndex, this.tools, hybridAlpha),
metaExecuteTool(this),
];
const tools = new Tools(baseTools);
return tools;
}
/**
* Iterator implementation
*/
[Symbol.iterator](): Iterator<BaseTool> {
let index = 0;
const tools = this.tools;
return {
next(): IteratorResult<BaseTool> {
if (index < tools.length) {
return { value: tools[index++], done: false };
}
return { value: undefined as unknown as BaseTool, done: true };
},
};
}
/**
* Convert to array
*/
toArray(): BaseTool[] {
return [...this.tools];
}
/**
* Map tools to a new array
*/
map<T>(mapper: (tool: BaseTool) => T): T[] {
return this.tools.map(mapper);
}
/**
* Execute a function for each tool
*/
forEach(callback: (tool: BaseTool) => void): void {
this.tools.forEach(callback);
}
}
/**
* Result from meta_search_tools
*/
export interface MetaToolSearchResult {
name: string;
description: string;
parameters: ToolParameters;
score: number;
}
type OramaDb = ReturnType<typeof orama.create>;
/**
* Initialize TF-IDF index for tool search
*/
function initializeTfidfIndex(tools: BaseTool[]): TfidfIndex {
const index = new TfidfIndex();
const corpus = tools.map((tool) => {
// Extract category from tool name (e.g., 'hris_create_employee' -> 'hris')
const parts = tool.name.split('_');
const category = parts[0];
// Extract action type
const actionTypes = ['create', 'update', 'delete', 'get', 'list', 'search'];
const actions = parts.filter((p) => actionTypes.includes(p));
// Build text corpus for TF-IDF (similar weighting strategy as in tool-calling-evals)
const text = [
`${tool.name} ${tool.name} ${tool.name}`, // boost name
`${category} ${actions.join(' ')}`,
tool.description,
parts.join(' '),
].join(' ');
return { id: tool.name, text };
});
index.build(corpus);
return index;
}
/**
* Initialize Orama database with BM25 algorithm for tool search
* Using Orama's BM25 scoring algorithm for relevance ranking
* @see https://docs.orama.com/open-source/usage/create
* @see https://docs.orama.com/open-source/usage/search/bm25-algorithm/
*/
async function initializeOramaDb(tools: BaseTool[]): Promise<OramaDb> {
// Create Orama database schema with BM25 scoring algorithm
// BM25 provides better relevance ranking for natural language queries
const oramaDb = orama.create({
schema: {
name: 'string' as const,
description: 'string' as const,
category: 'string' as const,
tags: 'string[]' as const,
},
components: {
tokenizer: {
stemming: true,
},
},
});
// Index all tools
for (const tool of tools) {
// Extract category from tool name (e.g., 'hris_create_employee' -> 'hris')
const parts = tool.name.split('_');
const category = parts[0];
// Extract action type
const actionTypes = ['create', 'update', 'delete', 'get', 'list', 'search'];
const actions = parts.filter((p) => actionTypes.includes(p));
await orama.insert(oramaDb, {
name: tool.name,
description: tool.description,
category: category,
tags: [...parts, ...actions],
});
}
return oramaDb;
}
function metaSearchTools(
oramaDb: OramaDb,
tfidfIndex: TfidfIndex,
allTools: BaseTool[],
hybridAlpha = DEFAULT_HYBRID_ALPHA,
): BaseTool {
const name = 'meta_search_tools' as const;
const description =
`Searches for relevant tools based on a natural language query using hybrid BM25 + TF-IDF search (alpha=${hybridAlpha}). This tool should be called first to discover available tools before executing them.` as const;
const parameters = {
type: 'object',
properties: {
query: {
type: 'string',
description:
'Natural language query describing what tools you need (e.g., "tools for managing employees", "create time off request")',
},
limit: {
type: 'number',
description: 'Maximum number of tools to return (default: 5)',
default: 5,
},
minScore: {
type: 'number',
description: 'Minimum relevance score (0-1) for results (default: 0.3)',
default: 0.3,
},
},
required: ['query'],
} as const satisfies ToolParameters;
const executeConfig = {
kind: 'local',
identifier: name,
description: 'local://get-relevant-tools',
} as const satisfies LocalExecuteConfig;
const tool = new BaseTool(name, description, parameters, executeConfig);
tool.execute = async (inputParams?: JsonDict | string): Promise<JsonDict> => {
try {
// Validate params is either undefined, string, or object
Iif (
inputParams !== undefined &&
typeof inputParams !== 'string' &&
typeof inputParams !== 'object'
) {
throw new StackOneError(
`Invalid parameters type. Expected object or string, got ${typeof inputParams}. Parameters: ${JSON.stringify(inputParams)}`,
);
}
// Convert string params to object
const params = typeof inputParams === 'string' ? JSON.parse(inputParams) : inputParams || {};
const limit = params.limit || 5;
const minScore = params.minScore ?? 0.3;
const query = params.query || '';
// Hybrid: BM25 + TF-IDF fusion
const alpha = Math.max(0, Math.min(1, hybridAlpha));
// Get results from both algorithms
const [bm25Results, tfidfResults] = await Promise.all([
orama.search(oramaDb, {
term: query,
limit: Math.max(50, limit),
} as Parameters<typeof orama.search>[1]),
Promise.resolve(tfidfIndex.search(query, Math.max(50, limit))),
]);
// Build score map
const scoreMap = new Map<string, { bm25?: number; tfidf?: number }>();
for (const hit of bm25Results.hits) {
const doc = hit.document as { name: string };
scoreMap.set(doc.name, {
...scoreMap.get(doc.name),
bm25: clamp01(hit.score),
});
}
for (const r of tfidfResults) {
scoreMap.set(r.id, {
...scoreMap.get(r.id),
tfidf: clamp01(r.score),
});
}
// Fuse scores
const fused: Array<{ name: string; score: number }> = [];
for (const [name, scores] of scoreMap) {
const bm25 = scores.bm25 ?? 0;
const tfidf = scores.tfidf ?? 0;
const score = alpha * bm25 + (1 - alpha) * tfidf;
fused.push({ name, score });
}
fused.sort((a, b) => b.score - a.score);
const toolConfigs = fused
.filter((r) => r.score >= minScore)
.map((r) => {
const tool = allTools.find((t) => t.name === r.name);
Iif (!tool) return null;
const result: MetaToolSearchResult = {
name: tool.name,
description: tool.description,
parameters: tool.parameters,
score: r.score,
};
return result;
})
.filter((t): t is MetaToolSearchResult => t !== null)
.slice(0, limit);
return { tools: toolConfigs } satisfies JsonDict;
} catch (error) {
if (error instanceof StackOneError) {
throw error;
}
throw new StackOneError(
`Error executing tool: ${error instanceof Error ? error.message : String(error)}`,
);
}
};
return tool;
}
/**
* Clamp value to [0, 1]
*/
function clamp01(x: number): number {
return x < 0 ? 0 : x > 1 ? 1 : x;
}
function metaExecuteTool(tools: Tools): BaseTool {
const name = 'meta_execute_tool' as const;
const description =
'Executes a specific tool by name with the provided parameters. Use this after discovering tools with meta_search_tools.' as const;
const parameters = {
type: 'object',
properties: {
toolName: {
type: 'string',
description: 'Name of the tool to execute',
},
params: {
type: 'object',
description: 'Parameters to pass to the tool',
},
},
required: ['toolName', 'params'],
} as const satisfies ToolParameters;
const executeConfig = {
kind: 'local',
identifier: name,
description: 'local://execute-tool',
} as const satisfies LocalExecuteConfig;
// Create the tool instance
const tool = new BaseTool(name, description, parameters, executeConfig);
// Override the execute method to handle tool execution
// receives tool name and parameters and executes the tool
tool.execute = async (
inputParams?: JsonDict | string,
options?: ExecuteOptions,
): Promise<JsonDict> => {
try {
// Validate params is either undefined, string, or object
Iif (
inputParams !== undefined &&
typeof inputParams !== 'string' &&
typeof inputParams !== 'object'
) {
throw new StackOneError(
`Invalid parameters type. Expected object or string, got ${typeof inputParams}. Parameters: ${JSON.stringify(inputParams)}`,
);
}
// Convert string params to object
const params = typeof inputParams === 'string' ? JSON.parse(inputParams) : inputParams || {};
// Extract tool name and parameters
const { toolName, params: toolParams } = params;
// Find the tool by name
const toolToExecute = tools.getTool(toolName);
if (!toolToExecute) {
throw new StackOneError(`Tool ${toolName} not found`);
}
// Execute the tool with the provided parameters
return await toolToExecute.execute(toolParams, options);
} catch (error) {
Eif (error instanceof StackOneError) {
throw error;
}
throw new StackOneError(
`Error executing tool: ${error instanceof Error ? error.message : String(error)}`,
);
}
};
return tool;
}
|