diff --git a/ui/apps/chat/src/lib/constants/agentic.constants.ts b/ui/apps/chat/src/lib/constants/agentic.constants.ts index 3e2c2dcad5a3..979e78607837 100644 --- a/ui/apps/chat/src/lib/constants/agentic.constants.ts +++ b/ui/apps/chat/src/lib/constants/agentic.constants.ts @@ -75,3 +75,20 @@ export const LEGACY_AGENTIC_REGEX = { REASONING_EXTRACT: /<<>>([\s\S]*?)<<>>/, REASONING_OPEN: /<<>>[\s\S]*$/ } as const; + +/** The tool that loads tools on demand. */ +export const TOOL_SEARCH_NAME = 'tool_search'; +/** A search for tools by exact name: `select:a,b`. */ +export const TOOL_SEARCH_SELECT_PREFIX = 'select:'; +export const TOOL_SEARCH_DEFAULT_LIMIT = 5; + +export const TOOL_LOADING = { + /** Automatic mode loads on demand once definitions pass this share of the context. */ + AUTO_SHARE: 0.1, + /** Rough characters per token, to size tool definitions without a tokenizer. */ + CHARS_PER_TOKEN: 4, + /** Context assumed when the server does not report its size. */ + DEFAULT_CONTEXT_TOKENS: 8192, + /** The share of the context the list of tools to load may take. */ + LIST_SHARE: 0.05 +} as const; diff --git a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts index cf18451e8958..5daadba6e868 100644 --- a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts @@ -85,6 +85,7 @@ export const SETTINGS_KEYS = { TITLE_GENERATION_USE_LLM: 'titleGenerationUseLLM', TOOL_CALL_SHOWN_ARG: 'toolCallShownArg', TOOL_CALL_SHOWN_ARG_OVERRIDES: 'toolCallShownArgOverrides', + TOOL_LOADING: 'toolLoading', TOP_K: 'top_k', TOP_P: 'top_p', TYP_P: 'typ_p', diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts index 4ff10e312182..a799b6ff906c 100644 --- a/ui/apps/chat/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -14,18 +14,26 @@ import Database from '@lucide/svelte/icons/database'; import Eye from '@lucide/svelte/icons/eye'; import FilePen from '@lucide/svelte/icons/file-pen'; import Funnel from '@lucide/svelte/icons/funnel'; +import Layers from '@lucide/svelte/icons/layers'; import ListRestart from '@lucide/svelte/icons/list-restart'; +import ListTree from '@lucide/svelte/icons/list-tree'; import Mic from '@lucide/svelte/icons/mic'; import Monitor from '@lucide/svelte/icons/monitor'; import Moon from '@lucide/svelte/icons/moon'; import PencilRuler from '@lucide/svelte/icons/pencil-ruler'; import Puzzle from '@lucide/svelte/icons/puzzle'; +import Search from '@lucide/svelte/icons/search'; import ShieldQuestion from '@lucide/svelte/icons/shield-question-mark'; import SlidersVertical from '@lucide/svelte/icons/sliders-vertical'; import Sun from '@lucide/svelte/icons/sun'; import TextCursorInput from '@lucide/svelte/icons/text-cursor-input'; import Zap from '@lucide/svelte/icons/zap'; -import { PermissionMode, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts'; +import { + PermissionMode, + SyncableParameterType, + ToolLoadingMode, + VoiceInputMode +} from '#lib/enums/index.ts'; import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; import { ColorMode } from '#lib/enums/ui.enums.ts'; import type { @@ -559,6 +567,18 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ ], type: SettingsFieldType.SELECT }, + { + defaultValue: ToolLoadingMode.AUTO, + help: 'How MCP and custom tools reach the model. On demand sends a short list of them and a search tool; the model loads the ones it needs, and they stay loaded for the conversation. Automatic does that once the tools would take more than a tenth of the context. Built-in and llama-server tools are always sent in full.', + key: SETTINGS_KEYS.TOOL_LOADING, + label: 'Tool loading', + options: [ + { icon: ListTree, label: 'Automatic', value: ToolLoadingMode.AUTO }, + { icon: Search, label: 'On demand', value: ToolLoadingMode.ON_DEMAND }, + { icon: Layers, label: 'All up front', value: ToolLoadingMode.UP_FRONT } + ], + type: SettingsFieldType.SELECT + }, { defaultValue: DEFAULT_MCP_CONFIG.requestTimeoutSeconds, extension: 'mcp', diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 4a54bbc90420..25324e8c14b5 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -120,6 +120,7 @@ export { SearchChatsOrder, ServerToolType, ToolSource, + ToolLoadingMode, ToolPermissionDecision, ToolResponseField } from './tools.enums'; diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts index 99bbe29f165a..3ed16b1be229 100644 --- a/ui/apps/chat/src/lib/enums/tools.enums.ts +++ b/ui/apps/chat/src/lib/enums/tools.enums.ts @@ -25,6 +25,16 @@ export enum ToolPermissionDecision { SESSION = 'session' } +/** How tool definitions reach the model. */ +export enum ToolLoadingMode { + /** On demand once the definitions take a large share of the context. */ + AUTO = 'auto', + /** MCP and custom tools as a list to load from, always. */ + ON_DEMAND = 'on_demand', + /** Every enabled tool in every request. */ + UP_FRONT = 'up_front' +} + export enum ToolResponseField { ERROR = 'error', PLAIN_TEXT = 'plain_text_response' diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts index 573239edb92f..cab30ddf7296 100644 --- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts @@ -26,7 +26,9 @@ import { DEFAULT_AGENTIC_CONFIG, NEWLINE, SETTINGS_KEYS, - TOOL_DENIED_RESULT + TOOL_DENIED_RESULT, + TOOL_LOADING, + TOOL_SEARCH_NAME } from '#lib/constants/index.ts'; import { AUDIO_MIME_TO_EXTENSION, @@ -41,6 +43,7 @@ import { BuiltInTool, PermissionEffect, PermissionMode, + ToolLoadingMode, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts'; @@ -99,6 +102,7 @@ import { isAbortError, throwIfAborted } from '#lib/utils/index.ts'; +import { createToolCatalog, definitionsSize, type ToolCatalog } from '#lib/utils/tool-catalog.ts'; import { SvelteMap } from 'svelte/reactivity'; function createDefaultSession(): AgenticSession { @@ -171,6 +175,8 @@ function withTotalTime(timings: T, sta class AgenticStore { // permission, continue and steering gates the loop waits on between turns private gates = new AgenticGates(); + /** Tools loaded on demand per conversation: they stay loaded, so the tool list only grows */ + private loadedTools = new Map>(); private sessions = new SvelteMap(); get isAnyRunning(): boolean { @@ -442,6 +448,10 @@ class AgenticStore { signal?: AbortSignal ): Promise { const toolName = toolCall.function.name; + + // loading a tool is not using it: the loaded tool asks when it is called + if (toolName === TOOL_SEARCH_NAME) return { type: 'allow' }; + const toolKey = toolsStore.getPermissionKey(toolName) ?? toolName; const isServerTool = toolsStore.getToolSource(toolName) === ToolSource.SERVER; const args = this.parseToolArguments(toolCall.function.arguments); @@ -679,22 +689,36 @@ class AgenticStore { execute: (toolCall, context) => this.executeTool({ callbacks, context, conversationId, effectiveModel, toolCall }) })); + const catalog = this.toolCatalog(conversationId, harnessTools, effectiveModel); // result messages of streaming tools, created while the tool runs, by tool call id const streamedResults = new SvelteMap(); - const events = harness.run(toAgenticMessages(messages) as Message[], harnessTools, signal, { - authorize: (toolCall, runSignal) => this.authorizeTool(conversationId, toolCall, runSignal), - interrupted: () => this.gates.hasPendingSteeringMessage(conversationId), - maxTurns: agenticConfig.maxTurns, - onTurnLimit: async () => { - // Turn limit reached - ask user whether to continue - const shouldContinue = await this.gates.requestContinue(conversationId, signal); - - // Yield to allow Svelte to flush the UI update - await new Promise((r) => setTimeout(r, 0)); - - return shouldContinue; + const events = harness.run( + toAgenticMessages(messages) as Message[], + catalog ? catalog.initialTools() : harnessTools, + signal, + { + authorize: (toolCall, runSignal) => this.authorizeTool(conversationId, toolCall, runSignal), + interrupted: () => this.gates.hasPendingSteeringMessage(conversationId), + maxTurns: agenticConfig.maxTurns, + onTurnLimit: async () => { + // Turn limit reached - ask user whether to continue + const shouldContinue = await this.gates.requestContinue(conversationId, signal); + + // Yield to allow Svelte to flush the UI update + await new Promise((r) => setTimeout(r, 0)); + + return shouldContinue; + }, + prepareTurn: catalog + ? async ({ tools: sent }) => { + const loaded = catalog.takeNewlyLoaded(); + + return loaded.length > 0 ? { tools: [...sent, ...loaded] } : undefined; + } + : undefined, + resolveTool: catalog ? (name) => catalog.resolve(name) : undefined } - }); + ); let totalToolCallCount = 0; let lastStreamingToolCallName = ''; @@ -1046,6 +1070,52 @@ class AgenticStore { * makes a provider start over; a caller without a policy falls back to * the global defaults. */ + /** + * The catalog that loads MCP and custom tools on demand, or nothing when + * every tool goes up front: by the setting, or in automatic mode while + * the definitions take a small share of the context. + */ + private toolCatalog(conversationId: string, tools: Tool[], model: string): ToolCatalog | null { + const mode = toolLoadingMode(settingsStore.config[SETTINGS_KEYS.TOOL_LOADING]); + + if (mode === ToolLoadingMode.UP_FRONT) return null; + + const isDeferred = (tool: Tool) => { + const source = toolsStore.getToolSource(tool.definition.function.name); + + return source === ToolSource.MCP || source === ToolSource.CUSTOM; + }; + const deferred = tools.filter(isDeferred); + + if (deferred.length === 0) return null; + + const contextTokens = + modelsStore.props.getModelContextSize(model) ?? TOOL_LOADING.DEFAULT_CONTEXT_TOKENS; + const definitionTokens = definitionsSize(tools) / TOOL_LOADING.CHARS_PER_TOKEN; + + if ( + mode === ToolLoadingMode.AUTO && + definitionTokens < contextTokens * TOOL_LOADING.AUTO_SHARE + ) { + return null; + } + + let loaded = this.loadedTools.get(conversationId); + + if (!loaded) { + loaded = new Set(); + this.loadedTools.set(conversationId, loaded); + } + + return createToolCatalog({ + core: tools.filter((tool) => !isDeferred(tool)), + deferred, + groupOf: (tool) => toolsStore.getToolServerLabel(tool.definition.function.name) || 'Other', + listBudgetChars: contextTokens * TOOL_LOADING.LIST_SHARE * TOOL_LOADING.CHARS_PER_TOKEN, + loaded + }); + } + private async toolsFor(toolPolicy?: AgenticToolPolicy): Promise { if ( !toolsStore.hasServerTools && @@ -1090,3 +1160,9 @@ function permissionMode(value: unknown): PermissionMode { ? (value as PermissionMode) : PermissionMode.ASK; } + +function toolLoadingMode(value: unknown): ToolLoadingMode { + return Object.values(ToolLoadingMode).includes(value as ToolLoadingMode) + ? (value as ToolLoadingMode) + : ToolLoadingMode.AUTO; +} diff --git a/ui/apps/chat/src/lib/utils/tool-catalog.ts b/ui/apps/chat/src/lib/utils/tool-catalog.ts new file mode 100644 index 000000000000..034c2339f839 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/tool-catalog.ts @@ -0,0 +1,232 @@ +/** + * Tools on demand: the core tools go to the model in full, the others as a + * short list in the description of one search tool. A search, or a call to + * a listed tool, loads the tool, and it stays loaded for the conversation so + * the tool list only grows and the server can keep reusing its prompt cache. + */ + +import type { Tool, ToolDefinition } from '@ggml-org/llama-harness'; +import { + TOOL_SEARCH_DEFAULT_LIMIT, + TOOL_SEARCH_NAME, + TOOL_SEARCH_SELECT_PREFIX +} from '#lib/constants/index.ts'; + +export interface ToolCatalog { + /** The tools for the first request: the core ones, the loaded ones, and the search tool when any is left. */ + initialTools(): Tool[]; + /** A listed tool by name, loaded on the way. */ + resolve(name: string): Tool | undefined; + /** Tools loaded since the last call, to append to the next request. */ + takeNewlyLoaded(): Tool[]; +} + +interface CatalogOptions { + core: Tool[]; + deferred: Tool[]; + /** Names loaded earlier in the conversation, kept in place. Loading adds to it. */ + loaded: Set; + /** The most characters the list of deferred tools may take in the search tool's description. */ + listBudgetChars: number; + /** The group a deferred tool belongs to, for the short list when the full one is too long. */ + groupOf?: (tool: Tool) => string; +} + +export function createToolCatalog(options: CatalogOptions): ToolCatalog { + const { core, deferred, groupOf, listBudgetChars, loaded } = options; + const byName = new Map(deferred.map((tool) => [toolName(tool), tool])); + const pending: Tool[] = []; + const load = (tool: Tool) => { + const name = toolName(tool); + + if (loaded.has(name)) return; + + loaded.add(name); + pending.push(tool); + }; + const searchTool: Tool = { + definition: searchDefinition( + deferred.filter((tool) => !loaded.has(toolName(tool))), + listBudgetChars, + groupOf + ), + execute: async (call) => { + const query = parseQuery(call.function.arguments); + const found = searchTools(deferred, query.text, query.limit); + + for (const tool of found) load(tool); + + if (found.length === 0) { + return { content: `No tool matches "${query.text}". Try other words, or select:.` }; + } + + return { + content: + `Loaded ${found.length} tool${found.length === 1 ? '' : 's'}; call ${found.length === 1 ? 'it' : 'them'} like any other tool:\n\n` + + JSON.stringify( + found.map((tool) => tool.definition.function), + null, + 2 + ) + }; + } + }; + + return { + initialTools() { + const kept = deferred.filter((tool) => loaded.has(toolName(tool))); + const hasMore = deferred.some((tool) => !loaded.has(toolName(tool))); + + return [...core, ...kept, ...(hasMore ? [searchTool] : [])]; + }, + resolve(name) { + const tool = byName.get(name); + + if (tool) load(tool); + + return tool; + }, + takeNewlyLoaded() { + return pending.splice(0, pending.length); + } + }; +} + +/** + * Deferred tools that match a query: `select:a,b` by exact name, anything + * else by words found in the name (worth most), the description and the + * parameter names. + */ +export function searchTools( + tools: Tool[], + query: string, + limit = TOOL_SEARCH_DEFAULT_LIMIT +): Tool[] { + const trimmed = query.trim(); + + if (trimmed.startsWith(TOOL_SEARCH_SELECT_PREFIX)) { + const names = trimmed + .slice(TOOL_SEARCH_SELECT_PREFIX.length) + .split(',') + .map((name) => name.trim()) + .filter(Boolean); + + return names + .map((name) => tools.find((tool) => toolName(tool) === name)) + .filter((tool): tool is Tool => !!tool); + } + + const words = trimmed + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter((word) => word.length > 1); + + if (words.length === 0) return []; + + return tools + .map((tool) => ({ score: score(tool.definition, words), tool })) + .filter((entry) => entry.score > 0) + .sort((a, b) => b.score - a.score) + .slice(0, limit) + .map((entry) => entry.tool); +} + +/** About how many characters the definitions of these tools take in a request. */ +export function definitionsSize(tools: Tool[]): number { + return tools.reduce((sum, tool) => sum + JSON.stringify(tool.definition).length, 0); +} + +function score(definition: ToolDefinition, words: string[]): number { + const name = definition.function.name.toLowerCase(); + const description = (definition.function.description ?? '').toLowerCase(); + const params = Object.keys( + (definition.function.parameters?.properties as Record | undefined) ?? {} + ) + .join(' ') + .toLowerCase(); + + return words.reduce( + (sum, word) => + sum + + (name.includes(word) ? 3 : 0) + + (description.includes(word) ? 1 : 0) + + (params.includes(word) ? 1 : 0), + 0 + ); +} + +function searchDefinition( + listed: Tool[], + budget: number, + groupOf?: (tool: Tool) => string +): ToolDefinition { + const lines = listed.map((tool) => `- ${toolName(tool)}: ${firstSentence(tool)}`); + + let list = lines.join('\n'); + + // too long for the budget: one line per group instead + if (list.length > budget && groupOf) { + const groups = new Map(); + + for (const tool of listed) { + const group = groupOf(tool); + + groups.set(group, [...(groups.get(group) ?? []), toolName(tool)]); + } + + list = [...groups] + .map( + ([group, names]) => + `- ${group}: ${names.length} tools, e.g. ${names.slice(0, 3).join(', ')}` + ) + .join('\n'); + } + + return { + function: { + description: + 'Load more tools before calling them. More tools are available than are listed in this request:\n' + + `${list}\n\n` + + `Search with words (e.g. "create issue"), or load by name with "${TOOL_SEARCH_SELECT_PREFIX}name1,name2". ` + + 'The tools found are loaded and can be called right after.', + name: TOOL_SEARCH_NAME, + parameters: { + properties: { + limit: { description: 'How many tools to load at most.', type: 'integer' }, + query: { + description: `Words to search for, or "${TOOL_SEARCH_SELECT_PREFIX}" and tool names.`, + type: 'string' + } + }, + required: ['query'], + type: 'object' + } + }, + type: 'function' + }; +} + +function parseQuery(args: string): { limit?: number; text: string } { + try { + const parsed = JSON.parse(args || '{}') as { limit?: unknown; query?: unknown }; + + return { + limit: typeof parsed.limit === 'number' && parsed.limit > 0 ? parsed.limit : undefined, + text: typeof parsed.query === 'string' ? parsed.query : '' + }; + } catch { + return { text: '' }; + } +} + +function firstSentence(tool: Tool): string { + const description = (tool.definition.function.description ?? '').replace(/\s+/g, ' ').trim(); + const end = description.search(/[.!?](\s|$)/); + const sentence = end >= 0 ? description.slice(0, end + 1) : description; + + return sentence.length > 120 ? `${sentence.slice(0, 117)}...` : sentence || '(no description)'; +} + +function toolName(tool: Tool): string { + return tool.definition.function.name; +} diff --git a/ui/apps/chat/tests/unit/agentic-flow.test.ts b/ui/apps/chat/tests/unit/agentic-flow.test.ts index e989c12d4b2d..c01110322e1c 100644 --- a/ui/apps/chat/tests/unit/agentic-flow.test.ts +++ b/ui/apps/chat/tests/unit/agentic-flow.test.ts @@ -7,10 +7,12 @@ vi.mock('#lib/services/database.service.ts', () => ({ DatabaseService: {} })); +import { SETTINGS_KEYS, TOOL_SEARCH_NAME } from '#lib/constants/index.ts'; import { BuiltInTool, MessageRole, PermissionEffect, + ToolLoadingMode, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts'; @@ -21,6 +23,7 @@ import { ToolsService } from '#lib/services/tools.service.ts'; import { agenticStore } from '#lib/stores/agentic/index.svelte.ts'; import { modelsStore } from '#lib/stores/models/index.svelte.ts'; import { permissionsStore } from '#lib/stores/permissions.svelte.ts'; +import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import { toolsStore } from '#lib/stores/tools.svelte.ts'; import type { AgenticFlowCallbacks } from '#lib/types/agentic.js'; import type { ApiChatMessageData } from '#lib/types/api.js'; @@ -275,6 +278,43 @@ describe('agentic flow', () => { }); }); + it('loads a listed MCP tool on demand when the model calls it, and sends it from then on', async () => { + const config = settingsStore.config; + + settingsStore.config = { ...config, [SETTINGS_KEYS.TOOL_LOADING]: ToolLoadingMode.ON_DEMAND }; + mockTools(ToolSource.MCP, 'create_issue', 'list_issues'); + await activateExtension({ + activate: (ctx) => + ctx.contribute( + 'tools', + makeProvider({ execute: async () => ({ content: 'issue #7', isError: false }) }) + ) + }); + + const sent: string[][] = []; + + vi.spyOn(ChatService, 'sendMessage').mockImplementation(async (_messages, options) => { + sent.push( + (options?.tools ?? []).map((tool: { function: { name: string } }) => tool.function.name) + ); + + if (sent.length === 1) options?.onToolCallChunk?.(toolCalls('create_issue')); + else options?.onChunk?.('done'); + }); + + try { + const { callbacks, named } = recorder(); + + await runFlow(callbacks); + + // the tool list only grows: the loaded tool is appended after the search tool + expect(sent).toEqual([[TOOL_SEARCH_NAME], [TOOL_SEARCH_NAME, 'create_issue']]); + expect(named('createToolResultMessage')[0][2]).toBe('issue #7'); + } finally { + settingsStore.config = config; + } + }); + it('reports a failing tool to the model and goes on', async () => { mockTools(ToolSource.SERVER, 'read_file'); vi.spyOn(ToolsService, 'executeTool').mockRejectedValue(new Error('no such file')); diff --git a/ui/apps/chat/tests/unit/tool-catalog.test.ts b/ui/apps/chat/tests/unit/tool-catalog.test.ts new file mode 100644 index 000000000000..1d3435f3d90a --- /dev/null +++ b/ui/apps/chat/tests/unit/tool-catalog.test.ts @@ -0,0 +1,165 @@ +import type { Tool, ToolCall } from '@ggml-org/llama-harness'; +import { TOOL_SEARCH_NAME } from '#lib/constants/index.ts'; +import { createToolCatalog, definitionsSize, searchTools } from '#lib/utils/tool-catalog.ts'; +import { describe, expect, it } from 'vitest'; + +function tool(name: string, description = '', params: string[] = []): Tool { + return { + definition: { + function: { + description, + name, + parameters: { + properties: Object.fromEntries(params.map((p) => [p, { type: 'string' }])), + type: 'object' + } + }, + type: 'function' + }, + execute: async () => ({ content: `${name} ran` }) + }; +} + +const CORE = [tool('read_file', 'Read a file.')]; +const DEFERRED = [ + tool('create_issue', 'Create a GitHub issue. Needs a repository.', ['title', 'body']), + tool('list_issues', 'List the issues of a repository.', ['state']), + tool('send_message', 'Send a Slack message to a channel.', ['channel', 'text']) +]; + +function call(args: object): ToolCall { + return { + function: { arguments: JSON.stringify(args), name: TOOL_SEARCH_NAME }, + id: 'c1', + type: 'function' + }; +} + +function names(tools: Tool[]): string[] { + return tools.map((t) => t.definition.function.name); +} + +function search(catalog: ReturnType) { + const searchTool = catalog + .initialTools() + .find((t) => t.definition.function.name === TOOL_SEARCH_NAME)!; + + return (args: object) => searchTool.execute(call(args), { update: () => {} }); +} + +describe('searchTools', () => { + it('ranks by words in the name first, then the description and parameters', () => { + expect(names(searchTools(DEFERRED, 'issue'))).toEqual(['create_issue', 'list_issues']); + expect(names(searchTools(DEFERRED, 'slack channel'))).toEqual(['send_message']); + expect(searchTools(DEFERRED, 'weather')).toEqual([]); + }); + + it('loads by exact name with select:', () => { + expect(names(searchTools(DEFERRED, 'select:send_message, list_issues, nope'))).toEqual([ + 'send_message', + 'list_issues' + ]); + }); +}); + +describe('createToolCatalog', () => { + it('sends the core tools and a search tool that lists the others', () => { + const catalog = createToolCatalog({ + core: CORE, + deferred: DEFERRED, + listBudgetChars: 10_000, + loaded: new Set() + }); + const tools = catalog.initialTools(); + const description = tools[1].definition.function.description!; + + expect(names(tools)).toEqual(['read_file', TOOL_SEARCH_NAME]); + expect(description).toContain('- create_issue: Create a GitHub issue.'); + expect(description).not.toContain('Needs a repository'); + }); + + it('lists one line per group when the full list is over budget', () => { + const catalog = createToolCatalog({ + core: CORE, + deferred: DEFERRED, + groupOf: (t) => (t.definition.function.name.includes('issue') ? 'GitHub' : 'Slack'), + listBudgetChars: 20, + loaded: new Set() + }); + const description = catalog.initialTools()[1].definition.function.description!; + + expect(description).toContain('- GitHub: 2 tools, e.g. create_issue, list_issues'); + expect(description).toContain('- Slack: 1 tools, e.g. send_message'); + }); + + it('loads what a search finds, once, and hands it over for the next request', async () => { + const loaded = new Set(); + const catalog = createToolCatalog({ + core: CORE, + deferred: DEFERRED, + listBudgetChars: 10_000, + loaded + }); + const result = await search(catalog)({ limit: 1, query: 'issue' }); + + expect(result.content).toContain('"name": "create_issue"'); + expect(names(catalog.takeNewlyLoaded())).toEqual(['create_issue']); + expect(catalog.takeNewlyLoaded()).toEqual([]); + + await search(catalog)({ query: 'select:create_issue' }); + + expect(catalog.takeNewlyLoaded()).toEqual([]); + expect([...loaded]).toEqual(['create_issue']); + }); + + it('loads a listed tool the model calls without searching', () => { + const catalog = createToolCatalog({ + core: CORE, + deferred: DEFERRED, + listBudgetChars: 10_000, + loaded: new Set() + }); + + expect(catalog.resolve('send_message')?.definition.function.name).toBe('send_message'); + expect(catalog.resolve('nope')).toBeUndefined(); + expect(names(catalog.takeNewlyLoaded())).toEqual(['send_message']); + }); + + it('keeps tools loaded earlier in the conversation, and drops the search tool once all are loaded', () => { + const some = createToolCatalog({ + core: CORE, + deferred: DEFERRED, + listBudgetChars: 10_000, + loaded: new Set(['list_issues']) + }); + + expect(names(some.initialTools())).toEqual(['read_file', 'list_issues', TOOL_SEARCH_NAME]); + expect(some.initialTools()[2].definition.function.description).not.toContain('list_issues'); + + const all = createToolCatalog({ + core: CORE, + deferred: DEFERRED, + listBudgetChars: 10_000, + loaded: new Set(names(DEFERRED)) + }); + + expect(names(all.initialTools())).toEqual(['read_file', ...names(DEFERRED)]); + }); + + it('says so when nothing matches', async () => { + const catalog = createToolCatalog({ + core: CORE, + deferred: DEFERRED, + listBudgetChars: 10_000, + loaded: new Set() + }); + + expect((await search(catalog)({ query: 'weather' })).content).toContain('No tool matches'); + }); +}); + +describe('definitionsSize', () => { + it('measures the definitions as sent', () => { + expect(definitionsSize(CORE)).toBe(JSON.stringify(CORE[0].definition).length); + }); +}); diff --git a/ui/lib/harness/README.md b/ui/lib/harness/README.md index 516b47b283d4..16d5191ff2b0 100644 --- a/ui/lib/harness/README.md +++ b/ui/lib/harness/README.md @@ -40,7 +40,7 @@ interface Harness { - **Events:** `turn_start`, `request`, `text`, `reasoning`, `tool_call_delta`, `timings`, `model`, `completion_id`, `message` (a turn's assistant message), `tool_call`, `tool_update` (a streaming tool's output so far), `tool_result`, `turn_end`, and last `done` or `error`. `run` never throws. - **The loop waits for you.** It does not go on until you ask for the next event, so you can store each message before the next step runs. - **It keeps nothing.** No conversation state, no storage: the app owns the history and passes it in. -- **Hooks:** `options.authorize` decides whether each tool call runs, e.g. by asking the user; a denial reaches the model as the call's error result. `options.prepareTurn` runs before each request and may replace the tools (e.g. to add tools loaded on demand) or the history (e.g. a compacted one). The `request` event shows what each turn sends. +- **Hooks:** `options.authorize` decides whether each tool call runs, e.g. by asking the user; a denial reaches the model as the call's error result. `options.prepareTurn` runs before each request and may replace the tools (e.g. to add tools loaded on demand) or the history (e.g. a compacted one). `options.resolveTool` finds a tool the model called that is not in the list, e.g. one it knows of but has not loaded. The `request` event shows what each turn sends. - **Stopping:** `signal` stops at once. `options.interrupted` ends the run at the next safe point, e.g. when the user sent a new message. `options.maxTurns` with `options.onTurnLimit` asks before it goes past a turn limit. An app can put another loop behind the same `Harness` interface. What sits above the loop is the same for every loop: the tools and the hooks, such as a permission prompt behind `authorize`. diff --git a/ui/lib/harness/src/harness.ts b/ui/lib/harness/src/harness.ts index 3e0ff4e8df1f..3e369115d62b 100644 --- a/ui/lib/harness/src/harness.ts +++ b/ui/lib/harness/src/harness.ts @@ -67,7 +67,14 @@ async function* run( signal?: AbortSignal, options: RunOptions = {}, ): AsyncGenerator { - const { authorize, interrupted = () => false, maxTurns = Infinity, onTurnLimit, prepareTurn } = options; + const { + authorize, + interrupted = () => false, + maxTurns = Infinity, + onTurnLimit, + prepareTurn, + resolveTool, + } = options; let history = [...messages]; let currentTools = tools; let definitions = currentTools.map((tool) => tool.definition); @@ -298,7 +305,7 @@ async function* run( yield { toolCall, type: "tool_call" }; - const tool = toolsByName.get(toolCall.function.name); + const tool = toolsByName.get(toolCall.function.name) ?? resolveTool?.(toolCall.function.name); let authorization: Authorization = { type: "allow" }; diff --git a/ui/lib/harness/src/types.ts b/ui/lib/harness/src/types.ts index f4abd8858c5a..e1a59e3fc855 100644 --- a/ui/lib/harness/src/types.ts +++ b/ui/lib/harness/src/types.ts @@ -207,6 +207,12 @@ export interface RunOptions { * rest of the run. Keep the tool list append-only within a conversation, so the server can reuse its prompt cache. */ prepareTurn?: (turn: TurnState) => Promise; + /** + * Find a tool the model called that is not in the tool list, e.g. one it knows of but has not loaded yet. Return it + * to run the call, through `authorize`, as if it were listed; return nothing for an `Unknown tool` error. It is not + * added to the list: `prepareTurn` does that if the app wants it in the next requests. + */ + resolveTool?: (name: string) => Tool | undefined; } export type Authorization = { type: "allow" } | { type: "deny"; reason: string }; diff --git a/ui/lib/harness/tests/harness.test.ts b/ui/lib/harness/tests/harness.test.ts index 8410b85da640..7e398919ebee 100644 --- a/ui/lib/harness/tests/harness.test.ts +++ b/ui/lib/harness/tests/harness.test.ts @@ -456,4 +456,24 @@ describe("createHarness", () => { expect(requests).toHaveLength(0); expect(types(events)).toEqual(["turn_start", "error"]); }); + + it("runs a call to a tool that resolveTool finds, without listing it", async () => { + const { client, requests } = scriptedClient([[callEvent("hidden")], []]); + const asked: string[] = []; + const events = await collect(client, [tool("search")], { + authorize: async (call) => (asked.push(call.function.name), { type: "allow" }), + resolveTool: (name) => (name === "hidden" ? tool("hidden") : undefined), + }); + + expect(results(events)[0]).toMatchObject({ result: { content: "hidden ran" } }); + expect(asked).toEqual(["hidden"]); + expect(requests[1].tools?.map((t) => t.function.name)).toEqual(["search"]); + }); + + it("still reports an unknown tool when resolveTool finds nothing", async () => { + const { client } = scriptedClient([[callEvent("ghost")], []]); + const events = await collect(client, [], { resolveTool: () => undefined }); + + expect(results(events)[0]).toMatchObject({ result: { content: "Error: Unknown tool: ghost" } }); + }); });