Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

harness.ts

494 lines18.8 KB

1import { toolDefinition } from '@tanstack/ai'
2import {
3 PermissionCallCapability,
4 PermissionDecisionCapability,
5 PermissionResources,
6 PermissionRules,
7 configOption,
8 decidePermission,
9 definePlugin,
10 durableTool,
11} from '@tanstack/ai-harness'
12import { createCodeMode } from './create-code-mode'
13import type { AnyTool, Logger, ToolExecutionContext } from '@tanstack/ai'
14import type {
15 PermissionCallDecision,
16 PermissionMode,
17 ToolStep,
18} from '@tanstack/ai-harness'
19import type {
20 CodeModeCallHook,
21 CodeModeTool,
22 CodeModeToolConfig,
23 CreateCodeModeResult,
24} from './types'
25​
26/** The permission modes of `permissions()`, for the `mode` setting. */
27const MODES: ReadonlyArray<PermissionMode> = [
28 'default',
29 'plan',
30 'acceptEdits',
31 'bypass',
33​
34/**
35 * The default timeout of a program that can wait for the user to approve a
36 * call: 10 minutes.
37 */
38const APPROVAL_TIMEOUT_MS = 600_000
39​
40/** The error of a call that a stop cut while it ran. */
41const CUT_BY_STOP =
42 'This call was cut by a stop and does not run again. The tool may or may not have run. Check before you retry.'
43​
44export interface CodeModePluginOptions extends Omit<
45 CodeModeToolConfig,
46 'tools' | 'aroundCalls'
47> {
48 /**
49 * Which tools move into code mode. Default: every server tool that does
50 * not need approval, that has no permission checks (`PermissionResources`),
51 * and that `permissions()` allows in plan mode (so no edits, no commands,
52 * nothing that asks first). Without `permissions()`, the rules of tool
53 * plugins decide. A safe tool with `metadata.codeMode: true`, for example
54 * a tool of an `mcp()` server with `codeMode: true`, moves even when
55 * `include` does not pick it.
56 *
57 * `include` can also pick a tool with permission checks or an `ask` rule,
58 * for example the coding tools of `workspaceTools()`. Each call of such a
59 * tool in a program gets the same decision as a direct tool call: it
60 * runs, it throws, or the program waits for the user to approve it.
61 * `include` cannot move a tool with `needsApproval`, or a tool that the
62 * rules deny: such a tool stays a normal tool call, and code mode warns
63 * once to the host logger for each one that `include` picks. The rules
64 * decide in the permission mode of the session at each turn, so in plan
65 * mode a tool that edits stays a normal tool call.
66 */
67 include?: (tool: CodeModeTool) => boolean
68 /**
69 * Make each tool that moves into code mode lazy. The prompt then lists only
70 * the tool names, and `lazyToolsConfig.includeDescription` adds part of
71 * each description. The model calls `discover_tools` for the signatures of
72 * the tools it needs, then calls them in `execute_typescript`. This saves
73 * tokens on each turn when there are many tools. Default `false`.
74 */
75 lazy?: boolean
76 /**
77 * What happens to the tools that move into code mode. `'remove'`
78 * (default): they leave the model's tool list, and the model calls them
79 * only in programs. `'keep'`: the model can also call them directly. The
80 * session setting `directCalls` changes it while the session runs, for
81 * example `session.setPluginSetting({ key: 'directCalls', value: 'keep' })`.
82 * A change applies at the next turn.
83 */
84 directCalls?: 'remove' | 'keep'
85 /**
86 * The timeout of a program in milliseconds. Default: 30000, or 600000
87 * (10 minutes) when a tool with permission checks moved, so that a
88 * program can wait for the user to approve a call.
89 */
90 timeout?: number
92​
93/**
94 * A name that works as a JavaScript identifier. Code mode turns each tool
95 * into an `external_<name>` function, and MCP tool names often have `-`.
96 */
97function identifierOf(name: string) {
98 const safe = name.replace(/[^A-Za-z0-9_$]/g, '_')
99 return /^[0-9]/.test(safe) ? `_${safe}` : safe
101​
102/** A tool that runs on the server: not a client tool, and it has `execute`. */
103function isServerTool(tool: AnyTool): tool is CodeModeTool {
104 const side = '__toolSide' in tool ? tool.__toolSide : 'server'
105 return side === 'server' && typeof tool.execute === 'function'
107​
108/**
109 * A short hash of the arguments of a call. A replay compares it, so a
110 * program that changed after a stop does not get the result of another
111 * call.
112 */
113// ponytail: FNV-1a on the JSON text. It only has to see a change, not
114// resist an attack.
115function hashOf(args: unknown) {
116 const json: string | undefined = JSON.stringify(args)
117 let hash = 0x811c9dc5
118 for (const char of json ?? '') {
119 hash = Math.imul(hash ^ (char.codePointAt(0) ?? 0), 0x01000193)
120 }
121 return (hash >>> 0).toString(16)
123​
124/**
125 * A result that the log can keep as a step value. JSON drops a function or
126 * a symbol, as the isolate does, and a `bigint` is not JSON.
127 */
128function isKeepable(
129 value: unknown,
130): value is object | string | number | boolean | null | undefined {
131 const type = typeof value
132 return type !== 'function' && type !== 'symbol' && type !== 'bigint'
134​
135/** A `step` of a durable tool call. */
136function isToolStep(value: unknown): value is ToolStep {
137 return (
138 typeof value === 'object' &&
139 value !== null &&
140 'do' in value &&
141 typeof value.do === 'function' &&
142 'ask' in value &&
143 typeof value.ask === 'function'
144 )
146​
147/**
148 * The `step` of the call that runs the program. The harness gives it to
149 * the durable `execute_typescript`.
150 */
151function stepOf(context: ToolExecutionContext | undefined) {
152 const step: unknown = context && 'step' in context ? context.step : undefined
153 return isToolStep(step) ? step : undefined
155​
156/**
157 * A tool-mode agent asks the user by stopping its turn. A call inside the
158 * isolate cannot stop that turn, so it does not run.
159 */
160const failClosedInAgent = (error: unknown) => {
161 const isTurnAsk =
162 error instanceof Error && error.name === 'MCPInputRequiredError'
163 if (isTurnAsk) {
164 throw new Error(
165 'This call needs the approval of the user, and this agent cannot ask for it, so the call did not run.',
166 )
167 }
168 throw error
170​
171/**
172 * The hook of one program. Each call of a `guarded` tool gets the decision
173 * of a direct tool call: it runs, it throws, or it waits for the user. The
174 * log keeps its result in a step of the `execute_typescript` call, so a
175 * replay of the program after a stop does not run a finished call again.
176 */
177function guardCalls({
178 guarded,
179 decide,
180 context,
181 signal,
182}: {
183 /** The moved tools that a direct call checks, by identifier. */
184 guarded: ReadonlyMap<string, CodeModeTool>
185 /** The decision of `permissions()`. Without it, a call runs, as a direct call does. */
186 decide:
187 | ((call: {
188 tool: string
189 args: unknown
190 }) => Promise<PermissionCallDecision>)
191 | undefined
192 /** The context of the `execute_typescript` call. */
193 context: ToolExecutionContext | undefined
194 /** Aborts when the program ends. */
195 signal: AbortSignal
196}) {
197 const step = stepOf(context)
198 // The number of each guarded call: the same on a replay of the program.
199 let count = 0
200 const hook: CodeModeCallHook = async (call, run) => {
201 const tool = guarded.get(call.name)
202 if (!tool) return run()
203 // The durable `execute_typescript` always gets a step. Fail closed
204 // without one.
205 if (!step) {
206 throw new Error(
207 `Code mode cannot check this call of ${tool.name}, so it did not run.`,
208 )
209 }
210 count += 1
211 const n = count
212 const { name } = tool
213 const hash = hashOf(call.args)
214 const ran = (value: unknown) => ({
215 ok: true as const,
216 value: isKeepable(value) ? value : undefined,
217 hash,
218 })
219 const failed = (error: string) => ({ ok: false as const, error, hash })
220 const attempt = async () => {
221 const checked = (await decide?.({ tool: name, args: call.args })) ?? {
222 decision: 'allow' as const,
223 }
224 switch (checked.decision) {
225 case 'deny':
226 return failed(checked.error)
227 case 'ask': {
228 // A question wait: a UI answers it with `session.answer`. The name
229 // has the hash of the arguments, so after a stop a program that
230 // changed asks again, and no answer approves another call.
231 const reply = await step
232 .ask({
233 name: `approve:${n}:${hash}`,
234 message: checked.message,
235 schema: checked.schema,
236 signal,
237 })
238 .catch(failClosedInAgent)
239 const refusal = await checked.settle(reply)
240 if (refusal !== undefined) return failed(refusal)
241 break
242 }
243 case 'allow':
244 break
245 }
246 // A late answer never runs a call after the program ended.
247 if (signal.aborted) {
248 throw new Error(
249 `The program ended, so this call of ${name} did not run.`,
250 )
251 }
252 if (tool.replay !== 'safe') {
253 // A start with no result in the log: a stop cut the call while it ran.
254 let isFirstStart = false
255 await step.do(`start:${n}:${name}`, () => {
256 isFirstStart = true
257 return true
258 })
259 if (!isFirstStart) throw new Error(CUT_BY_STOP)
260 }
261 // A tool error is a result too: a replay throws it again and does not
262 // run the tool twice. A stop closes the log first, so a call that it
263 // cut keeps no result.
264 try {
265 return ran(await run())
266 } catch (error) {
267 return failed(error instanceof Error ? error.message : String(error))
268 }
269 }
270 const kept = await step.do(`call:${n}:${name}`, attempt)
271 if (kept.hash !== hash) {
272 throw new Error(
273 `The program changed after a stop: call ${n} of ${name} has other arguments now, so it did not run.`,
274 )
275 }
276 if (!kept.ok) throw new Error(kept.error)
277 return kept.value
278 }
279 return hook
281​
282/**
283 * `tool` (`execute_typescript`) as a durable tool. Its execute gets `step`,
284 * so the log keeps the checked calls of each program. After a stop, the
285 * next host runs the program again, and a finished call returns its kept
286 * result.
287 */
288function durable(tool: CreateCodeModeResult['tool']) {
289 const { execute } = tool
290 if (!execute) throw new Error('execute_typescript has no execute function.')
291 return durableTool(
292 toolDefinition({
293 name: tool.name,
294 description: tool.description,
295 inputSchema: tool.inputSchema,
296 outputSchema: tool.outputSchema,
297 }),
298 (args, context) => execute(args, context),
299 )
301​
302/** The prompt part for the functions that check the permission rules. */
303function checksPrompt(identifiers: Iterable<string>) {
304 const names = [...identifiers]
305 .map((identifier) => `\`external_${identifier}\``)
306 .join(', ')
307 return `
308### Permission checks
309​
310These functions check the permission rules before they run, as a direct tool call does: ${names}. A call can wait for the user to approve it. When the user refuses the call or a rule denies it, the call throws an error that says why.
313​
314/**
315 * A harness plugin that gives the model an `execute_typescript` tool. The
316 * model writes one TypeScript program that calls several tools, and the
317 * program runs in the isolate of `driver` (any `@tanstack/ai-isolate-*`
318 * driver). The tools it calls leave the model's tool list, including tools
319 * that plugins find at run time, such as MCP tools after `/connect`.
320 *
321 * By default, only tools that are safe to run without a question move into
322 * code mode. The other tools stay normal tool calls. A tool with
323 * `metadata.codeMode: true` moves even when `include` does not pick it, but
324 * only when it is safe in the same way.
325 *
326 * `include` can pick more tools, also tools with permission checks, such as
327 * the coding tools of `workspaceTools()`. Each call of such a tool in a
328 * program gets the same decision as a direct tool call from `permissions()`:
329 * it runs, it throws an error with the reason, or the program waits for the
330 * user to approve it (a question that `session.answer` answers). The log
331 * keeps the result of each such call, so after a stop the next host runs
332 * the program again without running a finished call twice. `include` never
333 * moves a tool with `needsApproval`, or a tool that the rules deny.
334 *
335 * With `lazy: true`, the model gets only the names of the moved tools and
336 * asks `discover_tools` for the signatures. With `directCalls: 'keep'`, the
337 * model can still call the moved tools directly.
338 *
339 * @example
340 * ```ts
341 * import { codeMode } from '@tanstack/ai-code-mode/harness'
342 * import { createQuickJSIsolateDriver } from '@tanstack/ai-isolate-quickjs'
343 *
344 * defineHarness({
345 * name: 'acme/agent',
346 * adapter,
347 * plugins: () => [codeMode({ driver: createQuickJSIsolateDriver() })],
348 * })
349 * ```
350 */
351export function codeMode(options: CodeModePluginOptions) {
352 const { include, lazy = false, directCalls = 'remove', ...config } = options
353 /** The tools that `include` picked but cannot move, warned once each. */
354 const warned = new Set<string>()
355 const warnKept = (logger: Logger, name: string) => {
356 if (warned.has(name)) return
357 warned.add(name)
358 logger.warn(
359 `[@tanstack/ai-code-mode] include picked the tool ${JSON.stringify(name)}, but it needs approval, or the rules deny it. Such a tool stays a normal tool call.`,
360 )
361 }
362 return definePlugin({
363 name: 'tanstack/code-mode',
364 optionalRequires: [PermissionDecisionCapability, PermissionCallCapability],
365 setup: (ctx) => {
366 const rules = ctx.collect(PermissionRules)
367 const resources = ctx.collect(PermissionResources)
368 // The system prompt for the tools of the current turn.
369 let prompt = ''
370 // Each moved tool is safe, or each of its calls gets the decision of
371 // a direct call, so a program is as safe as its tools. Allow the code
372 // mode tools, so `default: 'ask'` does not ask for (or plan mode deny)
373 // every program. A snippet runs code of its own, so with snippets
374 // they get no rule. The user's rules come later and still win.
375 const allowCodeMode = config.getSnippetBindings
376 ? []
377 : ['execute_typescript', 'discover_tools'].map((tool) =>
378 PermissionRules.item({ tool, decision: 'allow', kind: 'read' }),
379 )
380 return {
381 config: {
382 directCalls: configOption.select({
383 options: ['remove', 'keep'],
384 default: directCalls,
385 description:
386 'remove: the tools of code mode leave the tool list. keep: the model can also call them directly.',
387 }),
388 },
389 prompts: [{ id: 'tanstack/code-mode', text: () => prompt }],
390 contribute: allowCodeMode,
391 prepareTools: ({ tools }) => {
392 // A failed run below must not leave the prompt of a past turn.
393 prompt = ''
394 // Ask permissions() when it is mounted: it knows all rules in its
395 // order and its default. Read here, so it can come after code mode.
396 const decide = ctx.getOptional(PermissionDecisionCapability)
397 const decisionOf = (tool: CodeModeTool, mode: PermissionMode) =>
398 decide?.(tool.name, mode) ??
399 decidePermission(rules, tool.name, mode)
400 // A direct call of such a tool checks the paths or the commands
401 // that it touches.
402 const hasChecks = (tool: CodeModeTool) =>
403 resources.some((map) => Object.hasOwn(map, tool.name))
404 // The default pick: a call needs no approval and no check, also
405 // in plan mode.
406 const safe = (tool: CodeModeTool) =>
407 !tool.needsApproval &&
408 !hasChecks(tool) &&
409 decisionOf(tool, 'plan') === 'allow'
410 // The permission mode of the session now, read at each turn. In
411 // plan mode, a tool that edits must stay a tool call, where the
412 // rules deny it.
413 const value = ctx.config.get('mode')
414 const mode = MODES.find((each) => each === value) ?? 'default'
415 // `include` widens the pick past plan mode: each call of a tool
416 // with checks gets the decision of a direct call. A call inside the
417 // isolate cannot wait for `needsApproval`, and a tool that the
418 // rules deny stays a tool call.
419 const canInclude = (tool: CodeModeTool) =>
420 !tool.needsApproval && decisionOf(tool, mode) !== 'deny'
421 const moves = (tool: CodeModeTool) => {
422 // A marked tool still needs the checks of the default pick.
423 const isMarked = tool.metadata?.codeMode === true
424 if (isMarked && safe(tool)) return true
425 if (!include) return safe(tool)
426 if (!include(tool)) return false
427 if (canInclude(tool)) return true
428 warnKept(ctx.logger, tool.name)
429 return false
430 }
431 // Two tools that map to the same identifier: the first one moves.
432 const byIdentifier = new Map<string, CodeModeTool>()
433 for (const tool of tools.filter(isServerTool)) {
434 if (!moves(tool)) continue
435 const identifier = identifierOf(tool.name)
436 if (!byIdentifier.has(identifier))
437 byIdentifier.set(identifier, tool)
438 }
439 if (byIdentifier.size === 0) return tools
440 // The moved tools that a direct call checks. Each of their calls in
441 // a program gets the same decision.
442 const guarded = new Map(
443 [...byIdentifier].filter(
444 ([, tool]) =>
445 hasChecks(tool) || decisionOf(tool, mode) !== 'allow',
446 ),
447 )
448 const isGuarded = guarded.size > 0
449 // A program with checked calls can wait for the user.
450 const timeout =
451 config.timeout ?? (isGuarded ? APPROVAL_TIMEOUT_MS : undefined)
452 const created = createCodeMode({
453 ...config,
454 timeout,
455 tools: [...byIdentifier].map(([identifier, tool]) =>
456 identifier === tool.name && !lazy
457 ? tool
458 : { ...tool, name: identifier, ...(lazy ? { lazy } : {}) },
459 ),
460 aroundCalls: isGuarded
461 ? (context, signal) =>
462 guardCalls({
463 guarded,
464 decide: ctx.getOptional(PermissionCallCapability),
465 context,
466 signal,
467 })
468 : undefined,
469 })
470 prompt = isGuarded
471 ? `${created.systemPrompt}${checksPrompt(guarded.keys())}`
472 : created.systemPrompt
473 // The log keeps the checked calls of a program, so it is durable.
474 const program = isGuarded ? durable(created.tool) : created.tool
475 const moved = new Set(
476 [...byIdentifier.values()].map((tool) => tool.name),
477 )
478 // With `directCalls: 'keep'`, the model can still call a moved
479 // tool directly.
480 const keepsDirect = ctx.config.get('directCalls') === 'keep'
481 const direct = keepsDirect
482 ? tools
483 : tools.filter((tool) => !moved.has(tool.name))
484 return [
485 ...direct,
486 ...created.tools.map((tool) =>
487 tool === created.tool ? program : tool,
488 ),
489 ]
490 },
491 }
492 },
493 })