Open History to see the last commit
1import { tmpdir } from 'node:os'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import { z } from 'zod'
4import { EventType, toolDefinition } from '@tanstack/ai'
5import { memoryPersistence } from '@tanstack/ai-persistence'
6import {
7 PermissionRules,
8 createHarnessHost,
9 defineHarness,
10 definePlugin,
11} from '@tanstack/ai-harness'
12import { PermissionResources, permissions } from '@tanstack/ai-harness/plugins'
13import { workspaceTools } from '@tanstack/ai-harness/plugins/coding'
14import { codeMode } from '../src/harness'
15import type {
16 AnyTextAdapter,
17 AnyTool,
18 Logger,
19 MetadataStore,
20 StreamChunk,
21 TextOptions,
22 ToolExecutionContext,
23} from '@tanstack/ai'
24import type {
25 HarnessPersistence,
26 HarnessPlugin,
27 HarnessSession,
28} from '@tanstack/ai-harness'
29import type { ExecutionResult, IsolateDriver } from '../src/types'
30
31// Polled checks wait up to 5 s: coverage runs in CI are slow.
32const waitFor = (check: () => void) => vi.waitFor(check, { timeout: 5_000 })
33
34const now = () => Date.now()
35
36/** A model whose turns are scripted. Records the options of every call. */
37function scripted(turns: Array<Array<StreamChunk>>) {
38 const calls: Array<TextOptions> = []
39 const adapter: AnyTextAdapter = {
40 kind: 'text',
41 name: 'mock',
42 model: 'test-model',
43 // Type-only fields have no value, so each cast gives one its type.
44 '~types': {
45 providerOptions: {} as Record<string, unknown>,
46 inputModalities: ['text'] as readonly ['text'],
47 messageMetadataByModality: {
48 text: undefined as unknown,
49 image: undefined as unknown,
50 audio: undefined as unknown,
51 video: undefined as unknown,
52 document: undefined as unknown,
53 },
54 toolCapabilities: [] as ReadonlyArray<string>,
55 toolCallMetadata: undefined as unknown,
56 systemPromptMetadata: undefined as never,
57 },
58 structuredOutput: async () => ({ data: {}, rawText: '{}' }),
59 chatStream: (options) => {
60 calls.push(options)
61 const chunks = turns[calls.length - 1] ?? []
62 return (async function* () {
63 yield* chunks
64 })()
65 },
66 }
67 return { adapter, calls }
68}
69
70/** The tool names of a model call. */
71const toolNames = (call: TextOptions | undefined) =>
72 call?.tools?.map((tool) => tool.name)
73
74/** The system prompts of a model call, as one text. */
75const promptsOf = (call: TextOptions | undefined) =>
76 JSON.stringify(call?.systemPrompts ?? [])
77
78const textTurn = (content: string): Array<StreamChunk> => [
79 { type: EventType.RUN_STARTED, runId: 'r', threadId: 't', timestamp: now() },
80 {
81 type: EventType.TEXT_MESSAGE_START,
82 messageId: 'm',
83 role: 'assistant',
84 timestamp: now(),
85 },
86 {
87 type: EventType.TEXT_MESSAGE_CONTENT,
88 messageId: 'm',
89 delta: content,
90 timestamp: now(),
91 },
92 { type: EventType.TEXT_MESSAGE_END, messageId: 'm', timestamp: now() },
93 {
94 type: EventType.RUN_FINISHED,
95 runId: 'r',
96 threadId: 't',
97 timestamp: now(),
98 metadata: { tanstack: { finishReason: 'stop' } },
99 },
100]
101
102/** A model turn that calls one tool with `args`. */
103const callTurn = (
104 toolName: string,
105 args: unknown,
106 toolCallId = `call-${toolName}`,
107): Array<StreamChunk> => [
108 { type: EventType.RUN_STARTED, runId: 'r', threadId: 't', timestamp: now() },
109 {
110 type: EventType.TOOL_CALL_START,
111 toolCallId,
112 toolCallName: toolName,
113 timestamp: now(),
114 },
115 {
116 type: EventType.TOOL_CALL_ARGS,
117 toolCallId,
118 delta: JSON.stringify(args),
119 timestamp: now(),
120 },
121 { type: EventType.TOOL_CALL_END, toolCallId, timestamp: now() },
122 {
123 type: EventType.RUN_FINISHED,
124 runId: 'r',
125 threadId: 't',
126 timestamp: now(),
127 metadata: { tanstack: { finishReason: 'tool_calls' } },
128 },
129]
130
131/**
132 * A model turn that runs a program. The log keeps the calls of a program
133 * under its tool call id, so each program of a session needs its own id.
134 */
135const codeTurn = (code: string, toolCallId?: string) =>
136 callTurn('execute_typescript', { typescriptCode: code }, toolCallId)
137
138/** Calls a binding of the isolate, as a program calls `external_*`. */
139type CallBinding = (name: string, args: unknown) => Promise<unknown>
140
141/** The program of `fakeDriver` by default: two calls, and both results. */
142async function lookupBoth(call: CallBinding) {
143 return {
144 lookup: await call('external_lookup', { q: 'x' }),
145 notion: await call('external_notion_search', { query: 'y' }),
146 }
147}
148
149/**
150 * A stand-in isolate: it records the bindings and the timeout it got, and
151 * runs `program` for any code. A call that throws fails the program, as in
152 * a real isolate. Real drivers run the code itself.
153 */
154function fakeDriver(
155 program: (call: CallBinding) => Promise<unknown> = lookupBoth,
156) {
157 const seen: Array<Array<string>> = []
158 const timeouts: Array<number | undefined> = []
159 const driver: IsolateDriver = {
160 createContext: async ({ bindings, timeout }) => {
161 seen.push(Object.keys(bindings).sort())
162 timeouts.push(timeout)
163 const call: CallBinding = async (name, args) => {
164 const binding = bindings[name]
165 if (!binding) throw new Error(`No binding ${name}.`)
166 return binding.execute(args)
167 }
168 return {
169 execute: async <T>(): Promise<ExecutionResult<T>> => {
170 try {
171 const value = await program(call)
172 // The caller picks T. This stand-in returns what the program returns.
173 return { success: true, value: value as T, logs: [] }
174 } catch (error) {
175 const message =
176 error instanceof Error ? error.message : String(error)
177 return {
178 success: false,
179 error: { name: 'Error', message },
180 logs: [],
181 }
182 }
183 },
184 dispose: async () => {},
185 }
186 },
187 }
188 return { driver, seen, timeouts }
189}
190
191const lookup = vi.fn(async () => 'fact')
192const notionSearch = vi.fn(async () => ({ results: ['page'] }))
193const tools = {
194 lookup: toolDefinition({
195 name: 'lookup',
196 description: 'Look up a fact',
197 inputSchema: z.object({ q: z.string() }),
198 }).server(lookup),
199 remove: toolDefinition({
200 name: 'remove',
201 description: 'Remove a file',
202 needsApproval: true,
203 inputSchema: z.object({ path: z.string() }),
204 }).server(async () => 'removed'),
205 writeFile: toolDefinition({
206 name: 'write_file',
207 description: 'Write a file',
208 inputSchema: z.object({ path: z.string() }),
209 }).server(async () => 'written'),
210 notionSearch: toolDefinition({
211 name: 'notion_search',
212 description: 'Search Notion',
213 inputSchema: z.object({ query: z.string() }),
214 }).server(notionSearch),
215 askUser: toolDefinition({
216 name: 'ask_user',
217 description: 'Ask the user in the browser',
218 inputSchema: z.object({}),
219 }).client(),
220}
221
222// A tool plugin that marks write_file as an edit, like workspaceTools does.
223const writes = definePlugin({
224 name: 'test/writes',
225 setup: () => ({
226 tools: [tools.writeFile],
227 contribute: [
228 PermissionRules.item({
229 tool: 'write_file',
230 decision: 'ask',
231 kind: 'edit',
232 }),
233 ],
234 }),
235})
236// A connector whose tool appears at run time.
237const notion = definePlugin({
238 name: 'test/notion',
239 setup: () => ({ discoverTools: () => [tools.notionSearch] }),
240})
241
242/** A server tool marked for code mode, like the tools of `mcp({ codeMode })`. */
243function markedTool(name: string, needsApproval = false) {
244 return toolDefinition({
245 name,
246 description: 'A marked tool',
247 inputSchema: z.object({}),
248 needsApproval,
249 metadata: { codeMode: true },
250 }).server(async () => name)
251}
252
253/** The path that a call of a file tool touches. */
254const pathOf = (input: unknown) =>
255 typeof input === 'object' &&
256 input !== null &&
257 'path' in input &&
258 typeof input.path === 'string'
259 ? [input.path]
260 : []
261
262/**
263 * File tools with the permissions of the tools of `workspaceTools()`:
264 * `read_file` is allowed and safe to run again, and `write_file` asks and
265 * is not safe to run again. Both say which path a call touches. Each tool
266 * counts its calls.
267 */
268function fileTools() {
269 const counted = (verb: string) =>
270 vi.fn(
271 async ({ path }: { path: string }, _context?: ToolExecutionContext) =>
272 `${verb} ${path}`,
273 )
274 const read = counted('text of')
275 const write = counted('wrote')
276 const input = z.object({ path: z.string() })
277 const plugin = definePlugin({
278 name: 'test/files',
279 setup: () => ({
280 tools: [
281 toolDefinition({
282 name: 'read_file',
283 description: 'Read a file',
284 inputSchema: input,
285 replay: 'safe',
286 }).server(read),
287 toolDefinition({
288 name: 'write_file',
289 description: 'Write a file',
290 inputSchema: input,
291 }).server(write),
292 ],
293 contribute: [
294 PermissionRules.item({
295 tool: 'read_file',
296 decision: 'allow',
297 kind: 'read',
298 }),
299 PermissionRules.item({
300 tool: 'write_file',
301 decision: 'ask',
302 kind: 'edit',
303 }),
304 PermissionResources.item({
305 read_file: { paths: pathOf },
306 write_file: { paths: pathOf },
307 }),
308 ],
309 }),
310 })
311 return { plugin, read, write }
312}
313
314/** A program that reads `a.txt`, then writes `b.txt`. */
315const readThenWrite = async (call: CallBinding) => ({
316 read: await call('external_read_file', { path: 'a.txt' }),
317 write: await call('external_write_file', { path: 'b.txt' }),
318})
319
320/** A program that writes `b.txt`. */
321const writeOnly = (call: CallBinding) =>
322 call('external_write_file', { path: 'b.txt' })
323
324/** Opens a session of a harness with `tools` and `plugins`, on a new host. */
325async function openSession(options: {
326 adapter: AnyTextAdapter
327 tools?: ReadonlyArray<AnyTool>
328 plugins: ReadonlyArray<HarnessPlugin>
329 persistence?: HarnessPersistence
330 /** The logger of the host. Default: the console. */
331 logger?: Logger
332}) {
333 const host = createHarnessHost({
334 persistence: options.persistence ?? memoryPersistence(),
335 logger: options.logger,
336 })
337 const session = await host.open(
338 defineHarness({
339 name: 'test/code-mode',
340 adapter: options.adapter,
341 tools: options.tools ?? [],
342 plugins: () => options.plugins,
343 }),
344 { threadId: 't' },
345 )
346 return { host, session }
347}
348
349/**
350 * Opens a session with `fileTools()`, `guard`, and code mode with
351 * `include: () => true`. Each program runs `program`.
352 */
353async function openFiles(options: {
354 program: (call: CallBinding) => Promise<unknown>
355 turns: Array<Array<StreamChunk>>
356 /** The permission plugins. Default: `permissions({ default: 'ask' })`. */
357 guard?: ReadonlyArray<HarnessPlugin>
358 persistence?: HarnessPersistence
359}) {
360 const files = fileTools()
361 const { adapter } = scripted(options.turns)
362 const code = codeMode({
363 driver: fakeDriver(options.program).driver,
364 include: () => true,
365 })
366 const guard = options.guard ?? [permissions({ default: 'ask' })]
367 const opened = await openSession({
368 adapter,
369 plugins: [files.plugin, ...guard, code],
370 persistence: options.persistence,
371 })
372 return { ...opened, files }
373}
374
375/**
376 * `store`, with `setIf` writes that wait until `open` resolves.
377 * `permissions()` saves an `always` answer with `setIf`.
378 */
379function heldWrites(store: MetadataStore, open: Promise<void>) {
380 const held: MetadataStore = {
381 get: (namespace, key) => store.get(namespace, key),
382 set: (namespace, key, value) => store.set(namespace, key, value),
383 delete: (namespace, key) => store.delete(namespace, key),
384 getVersioned: async (namespace, key) =>
385 (await store.getVersioned?.(namespace, key)) ?? null,
386 setIf: async (namespace, key, value, revision) => {
387 await open
388 const written = await store.setIf?.(namespace, key, value, revision)
389 return written ?? { ok: false, reason: 'conflict' }
390 },
391 }
392 return held
393}
394
395/** Opens a code mode session, sends one message, and returns the first model call. */
396async function firstCall(options: {
397 tools?: ReadonlyArray<AnyTool>
398 plugins: ReadonlyArray<HarnessPlugin>
399}) {
400 const { adapter, calls } = scripted([textTurn('ok')])
401 const { host, session } = await openSession({ adapter, ...options })
402 await session.send('hi')
403 await host.close()
404 return calls[0]
405}
406
407/** Opens a code mode session and returns the tool names of the first model call. */
408const firstToolNames = async (options: {
409 tools?: ReadonlyArray<AnyTool>
410 plugins: ReadonlyArray<HarnessPlugin>
411}) => toolNames(await firstCall(options))
412
413/** The one open wait of `session`, once it opened. */
414async function openWait(session: HarnessSession) {
415 await waitFor(() => expect(session.snapshot().pendingWaits).toHaveLength(1))
416 const [wait] = session.snapshot().pendingWaits
417 if (!wait) throw new Error('No wait.')
418 return wait
419}
420
421/** The result of the program of `toolCallId`, as the model got it. */
422async function programResult(
423 session: HarnessSession,
424 toolCallId = 'call-execute_typescript',
425) {
426 const message = (await session.transcript()).find(
427 (each) => each.role === 'tool' && each.toolCallId === toolCallId,
428 )
429 const content = message?.content
430 const result: unknown =
431 typeof content === 'string' ? JSON.parse(content) : content
432 return result
433}
434
435/**
436 * Runs `program` on a first host until a call waits for the approval of
437 * the user. Then `beforeStop` runs, and the first host stops, as for a
438 * deploy. A second host opens the session on the same stores, and the turn
439 * goes on there.
440 */
441async function stopAndReopen(options: {
442 files: ReturnType<typeof fileTools>
443 program: (call: CallBinding) => Promise<unknown>
444 beforeStop?: (session: HarnessSession, waitId: string) => Promise<void>
445 /** The permission plugin. Default: `permissions()`. */
446 guard?: HarnessPlugin
447}) {
448 const persistence = memoryPersistence()
449 const plugins = [
450 options.files.plugin,
451 options.guard ?? permissions(),
452 codeMode({
453 driver: fakeDriver(options.program).driver,
454 include: () => true,
455 }),
456 ]
457 const first = await openSession({
458 adapter: scripted([codeTurn('return await read_then_write()')]).adapter,
459 plugins,
460 persistence,
461 })
462 void first.session.send('go', { inputId: 'in-1' }).then(
463 () => {},
464 () => {},
465 )
466 const wait = await openWait(first.session)
467 await options.beforeStop?.(first.session, wait.waitId)
468 await first.host.close({ recoverable: true })
469 const next = await openSession({
470 adapter: scripted([textTurn('done')]).adapter,
471 plugins,
472 persistence,
473 })
474 return { ...next, waitId: wait.waitId }
475}
476
477/**
478 * The first call of `tool` runs until the run stops. Resolves when it
479 * started.
480 */
481function hangFirst(tool: ReturnType<typeof fileTools>['write']) {
482 return new Promise<void>((started) => {
483 tool.mockImplementationOnce(
484 (_args, context) =>
485 new Promise<string>((_resolve, reject) => {
486 started()
487 context?.abortSignal?.addEventListener(
488 'abort',
489 () => reject(new Error('stopped')),
490 { once: true },
491 )
492 }),
493 )
494 })
495}
496
497beforeEach(() => {
498 vi.clearAllMocks()
499})
500
501afterEach(() => {
502 vi.restoreAllMocks()
503})
504
505describe('codeMode', () => {
506 it('moves safe tools, including discovered ones, behind execute_typescript', async () => {
507 const { driver, seen } = fakeDriver()
508 const { adapter, calls } = scripted([
509 codeTurn('return { a: await external_lookup({ q: "x" }) }'),
510 textTurn('done'),
511 ])
512 const { host, session } = await openSession({
513 adapter,
514 tools: [tools.lookup, tools.remove, tools.askUser],
515 plugins: [writes, notion, codeMode({ driver })],
516 })
517 const turn = await session.send('look it up')
518 expect(turn.text).toBe('done')
519
520 expect(toolNames(calls[0])).toEqual([
521 'remove',
522 'ask_user',
523 'write_file',
524 'execute_typescript',
525 ])
526 const prompts = promptsOf(calls[0])
527 expect(prompts).toContain('external_lookup')
528 expect(prompts).toContain('external_notion_search')
529 expect(prompts).not.toContain('external_write_file')
530 // Only safe tools moved, so no call in a program checks the rules.
531 expect(prompts).not.toContain('Permission checks')
532
533 expect(seen[0]).toEqual(['external_lookup', 'external_notion_search'])
534 expect(lookup).toHaveBeenCalledTimes(1)
535 expect(notionSearch).toHaveBeenCalledTimes(1)
536 expect(JSON.stringify(calls[1]?.messages)).toContain('page')
537 await host.close()
538 })
539
540 it('uses include to pick the tools, and leaves the list alone when none match', async () => {
541 const { driver } = fakeDriver()
542 const picked = await firstCall({
543 tools: [tools.lookup, tools.notionSearch],
544 plugins: [
545 codeMode({ driver, include: (tool) => tool.name === 'lookup' }),
546 ],
547 })
548 expect(toolNames(picked)).toEqual(['notion_search', 'execute_typescript'])
549
550 const none = await firstCall({
551 tools: [tools.remove],
552 plugins: [codeMode({ driver })],
553 })
554 expect(toolNames(none)).toEqual(['remove'])
555 expect(promptsOf(none)).not.toContain('execute_typescript')
556 })
557
558 it('with lazy, lists only the tool names and gives signatures on discover_tools', async () => {
559 const { driver } = fakeDriver()
560 const { adapter, calls } = scripted([
561 callTurn('discover_tools', { toolNames: ['external_lookup'] }),
562 textTurn('found it'),
563 ])
564 const { host, session } = await openSession({
565 adapter,
566 tools: [tools.lookup, tools.remove],
567 plugins: [codeMode({ driver, lazy: true })],
568 })
569 expect((await session.send('what can you call?')).text).toBe('found it')
570
571 expect(toolNames(calls[0])).toEqual([
572 'remove',
573 'execute_typescript',
574 'discover_tools',
575 ])
576 // The prompt names the tool, but its input shape comes from discovery.
577 const prompts = promptsOf(calls[0])
578 expect(prompts).toContain('Discoverable APIs')
579 expect(prompts).toContain('external_lookup')
580 expect(prompts).not.toContain('q: string')
581 expect(JSON.stringify(calls[1]?.messages)).toContain('q: string')
582 await host.close()
583 })
584
585 it('gives tools with names that are not identifiers a safe name', async () => {
586 const { driver, seen } = fakeDriver((call) =>
587 call('external_web_search', {}),
588 )
589 const named = (name: string, reply: string) =>
590 toolDefinition({
591 name,
592 description: 'A tool',
593 inputSchema: z.object({}),
594 }).server(async () => reply)
595 const { adapter, calls } = scripted([codeTurn('return 1'), textTurn('ok')])
596 const { host, session } = await openSession({
597 adapter,
598 tools: [
599 named('web-search', 'from web-search'),
600 named('web_search', 'from web_search'),
601 named('2fa', 'code'),
602 ],
603 plugins: [codeMode({ driver })],
604 })
605 await session.send('search')
606 // web_search clashes with web-search after the rename, so it stays direct.
607 expect(toolNames(calls[0])).toEqual(['web_search', 'execute_typescript'])
608 expect(seen[0]).toEqual(['external__2fa', 'external_web_search'])
609 expect(JSON.stringify(calls[1]?.messages)).toContain('from web-search')
610 await host.close()
611 })
612
613 it('moves a tool that a rule asks for when include picks it, keeps a tool that needs approval or that a rule denies, and warns once to the host logger', async () => {
614 const consoleWarn = vi.spyOn(console, 'warn')
615 const warn = vi.fn<Logger['warn']>()
616 const denyDocs = definePlugin({
617 name: 'test/deny-docs',
618 setup: () => ({
619 contribute: [
620 PermissionRules.item({ tool: 'docs_deny', decision: 'deny' }),
621 PermissionRules.item({ tool: 'docs_ask', decision: 'ask' }),
622 ],
623 }),
624 })
625 const { adapter, calls } = scripted([textTurn('one'), textTurn('two')])
626 const { host, session } = await openSession({
627 adapter,
628 tools: [
629 tools.lookup,
630 tools.remove,
631 toolDefinition({
632 name: 'docs_deny',
633 description: 'A tool that a rule denies',
634 inputSchema: z.object({}),
635 }).server(async () => 'denied'),
636 toolDefinition({
637 name: 'docs_ask',
638 description: 'A tool that a rule asks for',
639 inputSchema: z.object({}),
640 }).server(async () => 'asked'),
641 ],
642 plugins: [
643 denyDocs,
644 codeMode({ driver: fakeDriver().driver, include: () => true }),
645 ],
646 logger: { debug: () => {}, info: () => {}, warn, error: () => {} },
647 })
648 await session.send('first')
649 await session.send('second')
650 await host.close()
651
652 for (const call of calls) {
653 expect(toolNames(call)).toEqual([
654 'remove',
655 'docs_deny',
656 'execute_typescript',
657 ])
658 }
659 // Each call of docs_ask in a program gets the decision of a direct call.
660 expect(promptsOf(calls[0])).toContain(
661 'These functions check the permission rules before they run, as a direct tool call does: `external_docs_ask`.',
662 )
663 // One warning for each kept tool, not one for each turn.
664 expect(warn.mock.calls.map(([message]) => message)).toEqual([
665 '[@tanstack/ai-code-mode] include picked the tool "remove", but it needs approval, or the rules deny it. Such a tool stays a normal tool call.',
666 '[@tanstack/ai-code-mode] include picked the tool "docs_deny", but it needs approval, or the rules deny it. Such a tool stays a normal tool call.',
667 ])
668 expect(consoleWarn).not.toHaveBeenCalled()
669 })
670
671 it('moves a marked tool that include does not pick, unless a rule or an approval stops it', async () => {
672 const rules = definePlugin({
673 name: 'test/marked-rules',
674 setup: () => ({
675 contribute: [
676 PermissionRules.item({ tool: 'docs_allowed', decision: 'allow' }),
677 PermissionRules.item({ tool: 'docs_ask', decision: 'ask' }),
678 PermissionRules.item({ tool: 'docs_deny', decision: 'deny' }),
679 ],
680 }),
681 })
682 const names = await firstToolNames({
683 tools: [
684 markedTool('docs_allowed'),
685 markedTool('docs_ask'),
686 markedTool('docs_deny'),
687 markedTool('docs_write', true),
688 ],
689 plugins: [
690 rules,
691 codeMode({ driver: fakeDriver().driver, include: () => false }),
692 ],
693 })
694 expect(names).toEqual([
695 'docs_ask',
696 'docs_deny',
697 'docs_write',
698 'execute_typescript',
699 ])
700 })
701
702 it('keeps a tool that a rule of permissions() asks for as a tool call', async () => {
703 const names = await firstToolNames({
704 tools: [
705 markedTool('docs_search'),
706 markedTool('notes_search'),
707 tools.lookup,
708 ],
709 plugins: [
710 permissions({
711 rules: [
712 { tool: 'docs_*', decision: 'ask' },
713 { tool: 'lookup', decision: 'ask' },
714 ],
715 }),
716 codeMode({ driver: fakeDriver().driver }),
717 ],
718 })
719 // The default pick moves no tool that asks, so both tools stay.
720 expect(names).toEqual(['docs_search', 'lookup', 'execute_typescript'])
721 })
722
723 it.each(['before', 'after'])(
724 'keeps a tool with no rule as a tool call when permissions() asks by default, mounted %s code mode',
725 async (order) => {
726 const guard = permissions({
727 default: 'ask',
728 rules: [{ tool: 'lookup', decision: 'allow' }],
729 })
730 const code = codeMode({ driver: fakeDriver().driver })
731 const names = await firstToolNames({
732 tools: [markedTool('docs_search'), tools.lookup],
733 plugins: order === 'before' ? [guard, code] : [code, guard],
734 })
735 expect(names).toEqual(['docs_search', 'execute_typescript'])
736 },
737 )
738
739 it('keeps a tool that a rule of permissions() asks for, when a later plugin allows it', async () => {
740 const later = definePlugin({
741 name: 'test/later-allow',
742 setup: () => ({
743 contribute: [
744 PermissionRules.item({ tool: 'docs_search', decision: 'allow' }),
745 ],
746 }),
747 })
748 const names = await firstToolNames({
749 tools: [markedTool('docs_search'), tools.lookup],
750 plugins: [
751 permissions({ rules: [{ tool: 'docs_search', decision: 'ask' }] }),
752 later,
753 codeMode({ driver: fakeDriver().driver }),
754 ],
755 })
756 // permissions() checks its own rules last, so the call would ask.
757 expect(names).toEqual(['docs_search', 'execute_typescript'])
758 })
759
760 it('keeps a tool that declares permission resources as a tool call', async () => {
761 const resources = definePlugin({
762 name: 'test/resources',
763 setup: () => ({
764 contribute: [
765 PermissionResources.item({ read_file: { paths: () => ['a.txt'] } }),
766 ],
767 }),
768 })
769 const names = await firstToolNames({
770 tools: [tools.lookup, markedTool('read_file')],
771 plugins: [resources, codeMode({ driver: fakeDriver().driver })],
772 })
773 expect(names).toEqual(['read_file', 'execute_typescript'])
774 })
775
776 it.each(['default', 'plan'])(
777 'runs a program with no question when permissions() asks by default, in %s mode',
778 async (mode) => {
779 const { driver, seen } = fakeDriver()
780 const { adapter } = scripted([codeTurn('return 1'), textTurn('done')])
781 const { host, session } = await openSession({
782 adapter,
783 tools: [tools.lookup],
784 plugins: [
785 permissions({
786 default: 'ask',
787 rules: [
788 { tool: 'lookup', decision: 'allow' },
789 { tool: 'notion_search', decision: 'allow' },
790 ],
791 }),
792 notion,
793 codeMode({ driver }),
794 ],
795 })
796 if (mode === 'plan')
797 await session.runCommand({ name: 'mode', input: 'plan' })
798 expect((await session.send('look it up')).text).toBe('done')
799 // The program ran: a question would wait, and plan mode would deny it.
800 expect(seen).toHaveLength(1)
801 await host.close()
802 },
803 )
804
805 it('asks before a program when a rule of the user asks for execute_typescript', async () => {
806 const { driver, seen } = fakeDriver()
807 const { adapter } = scripted([codeTurn('return 1'), textTurn('done')])
808 const { host, session } = await openSession({
809 adapter,
810 tools: [tools.lookup],
811 plugins: [
812 permissions({
813 rules: [{ tool: 'execute_typescript', decision: 'ask' }],
814 }),
815 notion,
816 codeMode({ driver }),
817 ],
818 })
819 // The approval is a turn wait at the boundary: the turn stops, and a
820 // `resolve` answers it.
821 void session.send('look it up')
822 const wait = await openWait(session)
823 expect(wait.kind).toBe('approval')
824 expect(wait.message).toContain('execute_typescript')
825 const inputId = `answer:${wait.waitId}`
826 await session.resolve({
827 resume: [
828 { interruptId: wait.waitId, status: 'resolved', payload: 'reject' },
829 ],
830 inputId,
831 })
832 await session.settled({ inputId })
833 const messages = await session.transcript()
834 expect(messages.at(-1)).toMatchObject({
835 role: 'assistant',
836 content: 'done',
837 })
838 expect(seen).toEqual([])
839 await host.close()
840 })
841
842 it('drops the prompt of the last turn when the pick fails', async () => {
843 const { driver } = fakeDriver()
844 const { adapter, calls } = scripted([textTurn('one'), textTurn('two')])
845 let isBroken = false
846 const { host, session } = await openSession({
847 adapter,
848 tools: [tools.lookup],
849 plugins: [
850 codeMode({
851 driver,
852 include: () => {
853 if (isBroken) throw new Error('The pick failed.')
854 return true
855 },
856 }),
857 ],
858 })
859 await session.send('first')
860 expect(promptsOf(calls[0])).toContain('external_lookup')
861
862 isBroken = true
863 await session.send('second')
864 // The harness keeps the tool list as it was, without the old prompt.
865 expect(toolNames(calls[1])).toEqual(['lookup'])
866 expect(promptsOf(calls[1])).not.toContain('external_lookup')
867 await host.close()
868 })
869})
870
871describe('codeMode with tools that have permission checks', () => {
872 /** The coding tools of `workspaceTools()` for the model of `scripted`. */
873 const CODING_TOOLS = [
874 'read_file',
875 'write_file',
876 'edit_file',
877 'list_files',
878 'grep',
879 'bash',
880 'webfetch',
881 ]
882
883 it('moves the coding tools that include picks, and the prompt says that a call can throw', async () => {
884 const call = await firstCall({
885 plugins: [
886 workspaceTools({ root: tmpdir() }),
887 permissions(),
888 codeMode({ driver: fakeDriver().driver, include: () => true }),
889 ],
890 })
891 expect(toolNames(call)).toEqual(['execute_typescript'])
892 const prompts = promptsOf(call)
893 for (const name of CODING_TOOLS) {
894 expect(prompts).toContain(`external_${name}`)
895 }
896 expect(prompts).toContain(
897 'When the user refuses the call or a rule denies it, the call throws an error that says why.',
898 )
899 })
900
901 it('keeps the coding tools that edit or run a command as tool calls in plan mode', async () => {
902 vi.spyOn(console, 'warn').mockImplementation(() => {})
903 const { adapter, calls } = scripted([textTurn('ok')])
904 const { host, session } = await openSession({
905 adapter,
906 plugins: [
907 workspaceTools({ root: tmpdir() }),
908 permissions(),
909 codeMode({ driver: fakeDriver().driver, include: () => true }),
910 ],
911 })
912 await session.runCommand({ name: 'mode', input: 'plan' })
913 await session.send('plan it')
914 // Plan mode denies edits, commands, and every call that would ask.
915 expect(toolNames(calls[0])).toEqual([
916 'write_file',
917 'edit_file',
918 'bash',
919 'webfetch',
920 'execute_typescript',
921 ])
922 expect(promptsOf(calls[0])).toContain('external_read_file')
923 expect(promptsOf(calls[0])).not.toContain('external_write_file')
924 await host.close()
925 })
926
927 it('runs a call that the rules allow, with no question', async () => {
928 const { host, session, files } = await openFiles({
929 program: (call) => call('external_read_file', { path: 'a.txt' }),
930 turns: [
931 codeTurn('return await external_read_file({ path: "a.txt" })'),
932 textTurn('done'),
933 ],
934 })
935 expect((await session.send('read it')).text).toBe('done')
936 expect(await programResult(session)).toEqual({
937 success: true,
938 result: 'text of a.txt',
939 logs: [],
940 })
941 expect(files.read).toHaveBeenCalledTimes(1)
942 await host.close()
943 })
944
945 it('runs a call with no question when permissions() is not mounted, as a direct call does', async () => {
946 const { host, session, files } = await openFiles({
947 program: writeOnly,
948 turns: [codeTurn('return await write_it()'), textTurn('done')],
949 guard: [],
950 })
951 expect((await session.send('write it')).text).toBe('done')
952 expect(await programResult(session)).toEqual({
953 success: true,
954 result: 'wrote b.txt',
955 logs: [],
956 })
957 expect(files.write).toHaveBeenCalledTimes(1)
958 await host.close()
959 })
960
961 it('throws in the program when the rules deny a call', async () => {
962 vi.spyOn(console, 'warn').mockImplementation(() => {})
963 const { host, session, files } = await openFiles({
964 program: (call) => call('external_read_file', { path: '.env' }),
965 turns: [
966 codeTurn('return await external_read_file({ path: ".env" })'),
967 textTurn('done'),
968 ],
969 })
970 await session.runCommand({ name: 'mode', input: 'plan' })
971 await session.send('read the env file')
972 // A .env file asks, and plan mode denies each call that would ask, as
973 // for a direct call.
974 expect(await programResult(session)).toMatchObject({
975 success: false,
976 error: { message: 'This tool is not allowed in plan mode.' },
977 })
978 expect(files.read).not.toHaveBeenCalled()
979 await host.close()
980 })
981
982 it('waits for the approval of a call as a question, and runs the call on once', async () => {
983 const { host, session, files } = await openFiles({
984 program: writeOnly,
985 turns: [codeTurn('return await write_it()'), textTurn('done')],
986 })
987 const turn = session.send('write it')
988 const wait = await openWait(session)
989 // `default: 'ask'` asks for no program: only the call inside asks. The
990 // wait is named for the first call and the hash of its arguments.
991 expect(wait).toMatchObject({
992 waitId: expect.stringMatching(
993 /^ask:call-execute_typescript:approve:1:[0-9a-f]+$/,
994 ),
995 kind: 'question',
996 message:
997 'Allow write_file {"path":"b.txt"}? Answer once, always, or reject.',
998 })
999 expect(files.write).not.toHaveBeenCalled()
1000
1001 expect(
1002 await session.answer({ questionId: wait.waitId, value: 'once' }),
1003 ).toMatchObject({ status: 'accepted' })
1004 expect((await turn).text).toBe('done')
1005 expect(await programResult(session)).toEqual({
1006 success: true,
1007 result: 'wrote b.txt',
1008 logs: [],
1009 })
1010 expect(files.write).toHaveBeenCalledTimes(1)
1011 await host.close()
1012 })
1013
1014 it('saves an always answer, so the same call in the next program runs with no question', async () => {
1015 const { host, session, files } = await openFiles({
1016 program: writeOnly,
1017 turns: [
1018 codeTurn('return await write_it()', 'call-1'),
1019 textTurn('one'),
1020 codeTurn('return await write_it()', 'call-2'),
1021 textTurn('two'),
1022 ],
1023 })
1024 const first = session.send('write it')
1025 const wait = await openWait(session)
1026 await session.answer({ questionId: wait.waitId, value: 'always' })
1027 await first
1028
1029 expect((await session.send('write it again')).text).toBe('two')
1030 expect(await programResult(session, 'call-2')).toEqual({
1031 success: true,
1032 result: 'wrote b.txt',
1033 logs: [],
1034 })
1035 expect(files.write).toHaveBeenCalledTimes(2)
1036 await host.close()
1037 })
1038
1039 it('throws the message of a reject in the program, and does not run the call', async () => {
1040 const { host, session, files } = await openFiles({
1041 program: writeOnly,
1042 turns: [codeTurn('return await write_it()'), textTurn('done')],
1043 })
1044 const turn = session.send('write it')
1045 const wait = await openWait(session)
1046 await session.answer({
1047 questionId: wait.waitId,
1048 value: { answer: 'reject', message: 'Write c.txt instead.' },
1049 })
1050 await turn
1051 expect(await programResult(session)).toMatchObject({
1052 success: false,
1053 error: { message: 'Write c.txt instead.' },
1054 })
1055 expect(files.write).not.toHaveBeenCalled()
1056 await host.close()
1057 })
1058
1059 it('does not run a call whose approval comes after the program ended', async () => {
1060 let endProgram = () => {}
1061 const ended = new Promise<void>((resolve) => {
1062 endProgram = resolve
1063 })
1064 const { host, session, files } = await openFiles({
1065 // The call waits for the approval, and the program ends first, as on
1066 // a timeout.
1067 program: async (call) => {
1068 writeOnly(call).catch(() => {})
1069 await ended
1070 throw new Error('Execution timed out')
1071 },
1072 turns: [codeTurn('return await write_it()'), textTurn('done')],
1073 })
1074 const turn = session.send('write it')
1075 const wait = await openWait(session)
1076 endProgram()
1077 await turn
1078
1079 // The end of the program ended the wait, so the answer comes too late.
1080 await waitFor(() => expect(session.snapshot().pendingWaits).toEqual([]))
1081 expect(
1082 await session.answer({ questionId: wait.waitId, value: 'once' }),
1083 ).toMatchObject({ status: 'rejected' })
1084 expect(files.write).not.toHaveBeenCalled()
1085 await host.close()
1086 })
1087
1088 it('does not run a call when the program ends while its approval is applied', async () => {
1089 let openWrites = () => {}
1090 const writesOpen = new Promise<void>((resolve) => {
1091 openWrites = resolve
1092 })
1093 let endProgram = () => {}
1094 const ended = new Promise<void>((resolve) => {
1095 endProgram = resolve
1096 })
1097 let pending: Promise<unknown> | undefined
1098 const { log, metadata } = memoryPersistence().stores
1099 const { host, session, files } = await openFiles({
1100 program: async (call) => {
1101 pending = writeOnly(call)
1102 pending.catch(() => {})
1103 await ended
1104 throw new Error('Execution timed out')
1105 },
1106 turns: [codeTurn('return await write_it()'), textTurn('done')],
1107 // An `always` answer saves a rule. The save waits for `openWrites`.
1108 persistence: {
1109 stores: { log, metadata: heldWrites(metadata, writesOpen) },
1110 },
1111 })
1112 const turn = session.send('write it')
1113 const wait = await openWait(session)
1114 await session.answer({ questionId: wait.waitId, value: 'always' })
1115 // The program ends while the answer is applied.
1116 endProgram()
1117 await turn
1118 openWrites()
1119
1120 await expect(pending).rejects.toThrow(
1121 'The program ended, so this call of write_file did not run.',
1122 )
1123 expect(files.write).not.toHaveBeenCalled()
1124 await host.close()
1125 })
1126
1127 it('keeps the moved tools in the tool list with directCalls keep, until the setting changes', async () => {
1128 const files = fileTools()
1129 const { adapter, calls } = scripted([textTurn('one'), textTurn('two')])
1130 const { host, session } = await openSession({
1131 adapter,
1132 plugins: [
1133 files.plugin,
1134 permissions(),
1135 codeMode({
1136 driver: fakeDriver().driver,
1137 include: () => true,
1138 directCalls: 'keep',
1139 }),
1140 ],
1141 })
1142 await session.send('first')
1143 expect(toolNames(calls[0])).toEqual([
1144 'read_file',
1145 'write_file',
1146 'execute_typescript',
1147 ])
1148 expect(promptsOf(calls[0])).toContain('external_write_file')
1149
1150 expect(
1151 await session.setPluginSetting({ key: 'directCalls', value: 'remove' }),
1152 ).toMatchObject({ status: 'accepted' })
1153 await session.send('second')
1154 expect(toolNames(calls[1])).toEqual(['execute_typescript'])
1155 await host.close()
1156 })
1157
1158 it.each([
1159 {
1160 when: 'a tool with checks moved',
1161 options: { include: () => true },
1162 timeout: 600_000,
1163 },
1164 {
1165 when: 'the user set it',
1166 options: { include: () => true, timeout: 5_000 },
1167 timeout: 5_000,
1168 },
1169 { when: 'only safe tools moved', options: {}, timeout: 30_000 },
1170 ])(
1171 'gives a program the timeout $timeout when $when',
1172 async ({ options, timeout }) => {
1173 const files = fileTools()
1174 const { driver, timeouts } = fakeDriver(async () => 'ran')
1175 const { adapter } = scripted([codeTurn('return "ran"'), textTurn('done')])
1176 const { host, session } = await openSession({
1177 adapter,
1178 tools: [tools.lookup],
1179 plugins: [
1180 files.plugin,
1181 permissions(),
1182 codeMode({ driver, ...options }),
1183 ],
1184 })
1185 await session.send('run it')
1186 expect(timeouts).toEqual([timeout])
1187 await host.close()
1188 },
1189 )
1190
1191 it('runs a program again on the next host after a stop, and a call that ended before does not run again', async () => {
1192 const files = fileTools()
1193 const { host, session, waitId } = await stopAndReopen({
1194 files,
1195 program: readThenWrite,
1196 })
1197 expect(files.read).toHaveBeenCalledTimes(1)
1198
1199 // The program runs again, and waits for the same approval.
1200 const wait = await openWait(session)
1201 expect(wait.waitId).toBe(waitId)
1202 await session.answer({ questionId: wait.waitId, value: 'once' })
1203 expect(await session.settled({ inputId: 'in-1' })).toMatchObject({
1204 outcome: 'completed',
1205 })
1206 expect(await programResult(session)).toEqual({
1207 success: true,
1208 result: { read: 'text of a.txt', write: 'wrote b.txt' },
1209 logs: [],
1210 })
1211 expect(files.read).toHaveBeenCalledTimes(1)
1212 expect(files.write).toHaveBeenCalledTimes(1)
1213 await host.close()
1214 })
1215
1216 it('does not run a call again that a stop cut while it ran', async () => {
1217 const files = fileTools()
1218 const writing = hangFirst(files.write)
1219 const { host, session } = await stopAndReopen({
1220 files,
1221 program: readThenWrite,
1222 beforeStop: async (first, waitId) => {
1223 await first.answer({ questionId: waitId, value: 'once' })
1224 await writing
1225 },
1226 })
1227 expect(await session.settled({ inputId: 'in-1' })).toMatchObject({
1228 outcome: 'completed',
1229 })
1230 expect(await programResult(session)).toMatchObject({
1231 success: false,
1232 error: {
1233 message:
1234 'This call was cut by a stop and does not run again. The tool may or may not have run. Check before you retry.',
1235 },
1236 })
1237 expect(files.write).toHaveBeenCalledTimes(1)
1238 await host.close()
1239 })
1240
1241 it('does not give a call the kept result of another call when the program changed after a stop', async () => {
1242 const files = fileTools()
1243 const writing = hangFirst(files.write)
1244 let runs = 0
1245 const { host, session } = await stopAndReopen({
1246 files,
1247 // The second run of the program reads another file.
1248 program: async (call) => {
1249 runs += 1
1250 const path = runs === 1 ? 'a.txt' : 'z.txt'
1251 return {
1252 read: await call('external_read_file', { path }),
1253 write: await call('external_write_file', { path: 'b.txt' }),
1254 }
1255 },
1256 beforeStop: async (first, waitId) => {
1257 await first.answer({ questionId: waitId, value: 'once' })
1258 await writing
1259 },
1260 })
1261 await session.settled({ inputId: 'in-1' })
1262 expect(await programResult(session)).toMatchObject({
1263 success: false,
1264 error: {
1265 message:
1266 'The program changed after a stop: call 1 of read_file has other arguments now, so it did not run.',
1267 },
1268 })
1269 expect(files.read).toHaveBeenCalledTimes(1)
1270 await host.close()
1271 })
1272
1273 it('asks again when the program changed after a stop, so an answer never approves another call', async () => {
1274 const files = fileTools()
1275 // read_file is safe to run again, so the log keeps no start of it.
1276 const reading = hangFirst(files.read)
1277 let runs = 0
1278 const { host, session, waitId } = await stopAndReopen({
1279 files,
1280 guard: permissions({ rules: [{ tool: 'read_file', decision: 'ask' }] }),
1281 // The second run of the program reads another file.
1282 program: (call) => {
1283 runs += 1
1284 const path = runs === 1 ? 'a.txt' : 'z.txt'
1285 return call('external_read_file', { path })
1286 },
1287 beforeStop: async (first, firstWaitId) => {
1288 await first.answer({ questionId: firstWaitId, value: 'once' })
1289 await reading
1290 },
1291 })
1292 // The answer of the first run was for a.txt. The call of z.txt asks.
1293 const wait = await openWait(session)
1294 expect(wait.waitId).not.toBe(waitId)
1295 expect(wait.message).toBe(
1296 'Allow read_file {"path":"z.txt"}? Answer once, always, or reject.',
1297 )
1298 expect(files.read).toHaveBeenCalledTimes(1)
1299 await host.close()
1300 })
1301})