tools.spec.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. /**
  2. * Consumer-surface tests over a fake provider and the real policy collaborator: schemas,
  3. * validation, formatting, typed errors, intent dispatch, and observation-driven authorization.
  4. */
  5. import { describe, expect, it, vi } from 'vitest'
  6. import { Context } from 'cordis'
  7. import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'
  8. import { tmpdir } from 'node:os'
  9. import { join, resolve, sep } from 'node:path'
  10. import { CallId } from '@deepseek-ai/dsh-llm'
  11. import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt'
  12. import ToolRegistry, { type ToolResult } from '@deepseek-ai/dsh-tools'
  13. import { FileSystem, FsError, FsTargetKey, FsVersion } from '@deepseek-ai/dsh-fs'
  14. import type {
  15. FsDirEntry,
  16. FsEditOutcome,
  17. FsEditRequest,
  18. FsInfo,
  19. FsPathInfo,
  20. FsTarget,
  21. FsWriteIntent,
  22. FsWriteOutcome,
  23. } from '@deepseek-ai/dsh-fs'
  24. import * as FsPolicy from '@deepseek-ai/dsh-fs-policy'
  25. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  26. import { STREAM_MIN_SIZE } from '../src/read.ts'
  27. import { formatReadOutput } from '../src/read-render.ts'
  28. import type { FileReadOutcome } from '../src/read-render.ts'
  29. import { sessionCwd } from '../src/session-cwd.ts'
  30. import ApprovalService from '@deepseek-ai/dsh-user-approval'
  31. import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox'
  32. import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy'
  33. const testToolSignal = new AbortController().signal
  34. /** An in-memory fake provider; a test can arm a rejection on any primitive. */
  35. class FakeFs extends FileSystem {
  36. files = new Map<string, string>()
  37. rejectWith?: FsError
  38. writeIntents: (FsWriteIntent | undefined)[] = []
  39. editIntents: ({ version: FsVersion } | undefined)[] = []
  40. private throwIfArmed(): void {
  41. if (this.rejectWith) throw this.rejectWith
  42. }
  43. override async resolve(path: string): Promise<FsTarget> {
  44. return { targetKey: FsTargetKey(`key:${path}`), displayPath: `/abs/${path}` }
  45. }
  46. override async stat(target: FsTarget): Promise<FsInfo | undefined> {
  47. this.throwIfArmed()
  48. const content = this.files.get(target.targetKey)
  49. if (content === undefined) return undefined
  50. return { version: FsVersion('v1'), type: 'file', size: content.length }
  51. }
  52. override async lstat(path: string): Promise<FsPathInfo | undefined> {
  53. const content = this.files.get(`key:${path}`)
  54. if (content === undefined) return undefined
  55. return { version: FsVersion('v1'), type: 'file', size: content.length }
  56. }
  57. override async readText(target: FsTarget): Promise<string> {
  58. return this.files.get(target.targetKey) ?? ''
  59. }
  60. override async streamText(target: FsTarget): Promise<AsyncIterable<string>> {
  61. const content = this.files.get(target.targetKey) ?? ''
  62. return (async function* () { yield content })()
  63. }
  64. override async listDir(_target: FsTarget): Promise<FsDirEntry[]> {
  65. return []
  66. }
  67. override async writeText(target: FsTarget, content: string, expected?: FsWriteIntent): Promise<FsWriteOutcome> {
  68. this.throwIfArmed()
  69. this.writeIntents.push(expected)
  70. const before = this.files.get(target.targetKey) ?? null
  71. this.files.set(target.targetKey, content)
  72. return { operation: before !== null ? 'update' : 'create', version: FsVersion('v2'), before, after: content }
  73. }
  74. override async editText(target: FsTarget, edit: FsEditRequest, expected?: { version: FsVersion }): Promise<FsEditOutcome> {
  75. this.throwIfArmed()
  76. this.editIntents.push(expected)
  77. const content = this.files.get(target.targetKey) ?? ''
  78. const after = content.split(edit.oldString).join(edit.newString)
  79. this.files.set(target.targetKey, after)
  80. return { version: FsVersion('v3'), before: content, after }
  81. }
  82. }
  83. async function setup() {
  84. const ctx = new Context()
  85. await ctx.plugin(SystemPrompt)
  86. await ctx.plugin(ToolRegistry)
  87. await ctx.plugin(FakeFs)
  88. await ctx.plugin(FsPolicy)
  89. await ctx.plugin(ToolFs)
  90. const fs = ctx.fs as FakeFs
  91. return { ctx, fs }
  92. }
  93. let callCounter = 0
  94. function call(ctx: Context, name: string, args: unknown, agent?: object) {
  95. return ctx.tools.execute({
  96. signal: testToolSignal,
  97. callId: CallId(`call-${++callCounter}`),
  98. name,
  99. arguments: args,
  100. ...agent ? { agent: agent as never } : {},
  101. })
  102. }
  103. function text(result: { content: { type: string; text?: string }[] }): string {
  104. return result.content.filter(b => b.type === 'text').map(b => b.text).join('')
  105. }
  106. describe('session cwd resolution', () => {
  107. const execution = (cwd?: string) => cwd === undefined
  108. ? {}
  109. : { agent: { session: { header: { cwd } } } }
  110. it('retains ordinary spelling but resolves the cwd before parent traversal', () => {
  111. const cwd = process.cwd()
  112. const throughParent = `${cwd}${sep}..`
  113. expect(sessionCwd(execution() as never, 'file.txt')).toBeUndefined()
  114. expect(sessionCwd(execution(cwd) as never, 'file.txt')).toBe(cwd)
  115. expect(sessionCwd(execution(throughParent) as never, 'file.txt')).toBe(realpathSync.native(throughParent))
  116. const root = mkdtempSync(join(tmpdir(), 'dsh-tool-fs-session-cwd-'))
  117. const physical = join(root, 'physical')
  118. const link = join(root, 'link')
  119. try {
  120. mkdirSync(physical)
  121. symlinkSync(physical, link, process.platform === 'win32' ? 'junction' : 'dir')
  122. expect(sessionCwd(execution(link) as never, 'child.txt')).toBe(link)
  123. expect(sessionCwd(execution(link) as never, `..${sep}parent.txt`)).toBe(realpathSync.native(link))
  124. } finally {
  125. rmSync(root, { recursive: true, force: true })
  126. }
  127. })
  128. })
  129. describe('registration', () => {
  130. it('registers read, write, and edit', async () => {
  131. const { ctx } = await setup()
  132. expect(ctx.tools.schemas().map(s => s.name).sort()).toEqual(['edit', 'read', 'write'])
  133. })
  134. it('declares read parallel-safe while write/edit remain exclusive', async () => {
  135. const { ctx } = await setup()
  136. expect(ctx.tools.executionMode({ signal: testToolSignal, callId: CallId('read-safe'), name: 'read', arguments: { file_path: 'a.txt' } }))
  137. .toEqual({ kind: 'parallel' })
  138. expect(ctx.tools.executionMode({ signal: testToolSignal, callId: CallId('write-exclusive'), name: 'write', arguments: { file_path: 'a.txt', content: 'x' } }))
  139. .toEqual({ kind: 'exclusive' })
  140. expect(ctx.tools.executionMode({ signal: testToolSignal, callId: CallId('edit-exclusive'), name: 'edit', arguments: { file_path: 'a.txt', old_string: 'x', new_string: 'y' } }))
  141. .toEqual({ kind: 'exclusive' })
  142. })
  143. it('registers prompt sections for each tool', async () => {
  144. const { ctx } = await setup()
  145. const prompt = renderPrompt(await ctx.systemPrompt.assemble())
  146. expect(prompt).toContain('Use the read tool')
  147. expect(prompt).toContain('Use the write tool')
  148. expect(prompt).toContain('Use the edit tool')
  149. })
  150. it('stays pending until ctx.fs exists (inject)', async () => {
  151. const ctx = new Context()
  152. await ctx.plugin(SystemPrompt)
  153. await ctx.plugin(ToolRegistry)
  154. await ctx.plugin(ToolFs) // no fs provider
  155. expect(ctx.tools.schemas()).toHaveLength(0)
  156. })
  157. it('unregisters everything on fiber disposal (HMR safety)', async () => {
  158. const ctx = new Context()
  159. await ctx.plugin(SystemPrompt)
  160. await ctx.plugin(ToolRegistry)
  161. await ctx.plugin(FakeFs)
  162. await ctx.plugin(FsPolicy)
  163. const fiber = await ctx.plugin(ToolFs)
  164. // Each tool contributes BOTH a schema and a prompt section; disposal must
  165. // withdraw both, not just the schemas.
  166. expect(ctx.tools.schemas()).toHaveLength(3)
  167. const sectionNames = (a: { sections: { name: string }[] }) => a.sections.map(s => s.name).sort()
  168. expect(sectionNames(await ctx.systemPrompt.assemble())).toEqual(['deployment:persona', 'harness:identity', 'tool:edit', 'tool:read', 'tool:write'])
  169. await fiber.dispose()
  170. expect(ctx.tools.schemas()).toHaveLength(0)
  171. // Only the system-prompt plugin's own built-in sections remain.
  172. expect(sectionNames(await ctx.systemPrompt.assemble())).toEqual(['deployment:persona', 'harness:identity'])
  173. })
  174. })
  175. describe('read tool', () => {
  176. it('formats line-numbered content with a footer', async () => {
  177. const { ctx, fs } = await setup()
  178. fs.files.set('key:a.txt', 'hello\nworld')
  179. const result = await call(ctx, 'read', { file_path: 'a.txt' })
  180. expect(result.isError).toBe(false)
  181. if (result.isError) throw new Error('expected read success')
  182. expect(result.value).toEqual({
  183. path: '/abs/a.txt',
  184. offset: 1,
  185. lines: [{ number: 1, text: 'hello' }, { number: 2, text: 'world' }],
  186. totalLines: 2,
  187. })
  188. expect(text(result)).toBe(`<path>/abs/a.txt</path>
  189. <type>file</type>
  190. <content>
  191. 1: hello
  192. 2: world
  193. (End of file - total 2 lines)
  194. </content>`)
  195. })
  196. it('returns an explicit empty canonical line window for an empty file', async () => {
  197. const { ctx, fs } = await setup()
  198. fs.files.set('key:empty.txt', '')
  199. const result = await call(ctx, 'read', { file_path: 'empty.txt' })
  200. if (result.isError) throw new Error('expected empty read success')
  201. expect(result.value).toEqual({ path: '/abs/empty.txt', offset: 1, lines: [], totalLines: 0 })
  202. expect(text(result)).toContain('(End of file - total 0 lines)')
  203. })
  204. it('rejects a non-positive offset via arg validation', async () => {
  205. const { ctx } = await setup()
  206. const result = await call(ctx, 'read', { file_path: 'a.txt', offset: 0 })
  207. expect(result.isError).toBe(true)
  208. expect(text(result)).toContain('offset must be a positive integer')
  209. })
  210. it('rejects a fractional offset and a zero/negative limit', async () => {
  211. const { ctx } = await setup()
  212. for (const args of [
  213. { file_path: 'a.txt', offset: 1.5 },
  214. { file_path: 'a.txt', limit: 0 },
  215. { file_path: 'a.txt', limit: -3 },
  216. ]) {
  217. const result = await call(ctx, 'read', args)
  218. expect(result.isError, JSON.stringify(args)).toBe(true)
  219. expect(text(result)).toMatch(/must be a positive integer/)
  220. }
  221. })
  222. it('rejects a non-JSON numeric offset before tool-specific validation', async () => {
  223. const { ctx } = await setup()
  224. const result = await call(ctx, 'read', { file_path: 'a.txt', offset: Number.NaN })
  225. expect(result.isError).toBe(true)
  226. expect(text(result)).toContain('tool execution arguments must be losslessly JSON-serializable')
  227. })
  228. it('rejects a limit above the cap', async () => {
  229. const { ctx } = await setup()
  230. const result = await call(ctx, 'read', { file_path: 'a.txt', limit: 99999 })
  231. expect(result.isError).toBe(true)
  232. expect(text(result)).toContain('less than or equal to 2000')
  233. })
  234. it('rejects a blank file_path', async () => {
  235. const { ctx } = await setup()
  236. const result = await call(ctx, 'read', { file_path: ' ' })
  237. expect(result.isError).toBe(true)
  238. expect(text(result)).toContain('file_path must be a non-empty string')
  239. })
  240. it('records observed state so a follow-up edit by the same session is authorized', async () => {
  241. const { ctx, fs } = await setup()
  242. const session = { header: {} }
  243. fs.files.set('key:a.txt', 'hello')
  244. expect((await call(ctx, 'read', { file_path: 'a.txt' }, { session })).isError).toBe(false)
  245. const edited = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'hello', new_string: 'bye' }, { session })
  246. expect(edited.isError).toBe(false)
  247. expect(fs.editIntents).toEqual([{ version: 'v1' }])
  248. })
  249. it('propagates FS_NOT_FOUND for an absent file', async () => {
  250. const { ctx } = await setup()
  251. const result = await call(ctx, 'read', { file_path: 'missing.txt' })
  252. expect(result.isError).toBe(true)
  253. expect(result.error).toMatchObject({ info: { code: 'FS_NOT_FOUND' } })
  254. })
  255. it('rejects a non-regular target', async () => {
  256. const { ctx, fs } = await setup()
  257. fs.files.set('key:d', '')
  258. fs.stat = async () => ({ version: FsVersion('v1'), type: 'directory' })
  259. const result = await call(ctx, 'read', { file_path: 'd' })
  260. expect(result.isError).toBe(true)
  261. expect(result.error).toMatchObject({ info: { code: 'FS_NOT_REGULAR_FILE' } })
  262. })
  263. it('streams a large file (size at/above the cap) instead of reading whole', async () => {
  264. const { ctx, fs } = await setup()
  265. fs.files.set('key:big.txt', 'alpha\nbeta')
  266. const readSpy = vi.spyOn(fs, 'readText')
  267. const streamSpy = vi.spyOn(fs, 'streamText')
  268. fs.stat = async () => ({ version: FsVersion('v1'), type: 'file', size: STREAM_MIN_SIZE })
  269. const result = await call(ctx, 'read', { file_path: 'big.txt' })
  270. expect(result.isError).toBe(false)
  271. expect(text(result)).toContain('1: alpha')
  272. expect(streamSpy).toHaveBeenCalled()
  273. expect(readSpy).not.toHaveBeenCalled()
  274. })
  275. it('streams when the backend reports no size (never buffers a size-less file)', async () => {
  276. const { ctx, fs } = await setup()
  277. fs.files.set('key:a.txt', 'alpha')
  278. const streamSpy = vi.spyOn(fs, 'streamText')
  279. fs.stat = async () => ({ version: FsVersion('v1'), type: 'file' }) // no size
  280. const result = await call(ctx, 'read', { file_path: 'a.txt' })
  281. expect(result.isError).toBe(false)
  282. expect(streamSpy).toHaveBeenCalled()
  283. })
  284. it('surfaces a byte-capped read as a truncated footer', async () => {
  285. const { ctx, fs } = await setup()
  286. // Many long lines so the window hits the byte cap before EOF.
  287. fs.files.set('key:big.txt', Array.from({ length: 2000 }, () => 'y'.repeat(100)).join('\n'))
  288. const result = await call(ctx, 'read', { file_path: 'big.txt' })
  289. expect(result.isError).toBe(false)
  290. expect(text(result)).toContain('Output capped.')
  291. })
  292. it('attaches the structured window as presentation meta, and presentResult narrows it into a read card', async () => {
  293. const { ctx, fs } = await setup()
  294. fs.files.set('key:a.ts', 'const x = 1\nconst y = 2')
  295. const result = await call(ctx, 'read', { file_path: 'a.ts' })
  296. expect(result.isError).toBe(false)
  297. if (result.isError) throw new Error('expected read success')
  298. // The extension drives the lang hint; the window rides on persisted meta.
  299. expect(result.meta).toEqual({
  300. path: '/abs/a.ts',
  301. offset: 1,
  302. lines: [{ number: 1, text: 'const x = 1' }, { number: 2, text: 'const y = 2' }],
  303. totalLines: 2,
  304. lang: 'ts',
  305. })
  306. const view = ctx.tools.get('read')?.presentResult?.({ file_path: 'a.ts' }, result)
  307. expect(view).toEqual({
  308. card: 'read',
  309. path: '/abs/a.ts',
  310. offset: 1,
  311. lines: [{ number: 1, text: 'const x = 1' }, { number: 2, text: 'const y = 2' }],
  312. totalLines: 2,
  313. lang: 'ts',
  314. content: [{ type: 'text', text: '1: const x = 1\n2: const y = 2\n\n(End of file - total 2 lines)' }],
  315. })
  316. })
  317. it('omits the lang hint in meta for an extension that maps to no language', async () => {
  318. const { ctx, fs } = await setup()
  319. fs.files.set('key:notes', 'plain')
  320. const result = await call(ctx, 'read', { file_path: 'notes' })
  321. if (result.isError) throw new Error('expected read success')
  322. expect(result.meta).toEqual({ path: '/abs/notes', offset: 1, lines: [{ number: 1, text: 'plain' }], totalLines: 1 })
  323. })
  324. })
  325. describe('formatReadOutput footer variants', () => {
  326. const base: FileReadOutcome = { offset: 1, lines: [{ number: 1, text: 'x' }], totalLines: 1 }
  327. it('reports a byte-capped read', () => {
  328. const out = formatReadOutput('/f', { ...base, totalLines: 99, truncatedByBytes: true })
  329. expect(out).toContain('(Output capped. Showing lines 1-1. Use offset=2 to continue.)')
  330. })
  331. it('reports a more-remaining page', () => {
  332. const out = formatReadOutput('/f', { ...base, totalLines: 99 })
  333. expect(out).toContain('(Showing lines 1-1 of 99. Use offset=2 to continue.)')
  334. })
  335. it('reports end-of-file', () => {
  336. expect(formatReadOutput('/f', base)).toContain('(End of file - total 1 lines)')
  337. })
  338. it('renders an empty file as just the footer', () => {
  339. const out = formatReadOutput('/f', { ...base, lines: [], totalLines: 0 })
  340. expect(out).toContain('(End of file - total 0 lines)')
  341. expect(out).not.toContain(': ')
  342. })
  343. })
  344. describe('write tool', () => {
  345. it('formats a create result and uses createIfAbsent (unobserved, with the gate)', async () => {
  346. const { ctx, fs } = await setup()
  347. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'hi' }, { session: { header: {} } })
  348. expect(result.isError).toBe(false)
  349. if (result.isError) throw new Error('expected write success')
  350. expect(result.value).toEqual({ path: '/abs/a.txt', operation: 'create', before: null, after: 'hi' })
  351. expect(text(result)).toContain('Created file')
  352. expect(fs.writeIntents).toEqual([{ kind: 'createIfAbsent' }])
  353. })
  354. it('rejects a blank file_path', async () => {
  355. const { ctx } = await setup()
  356. const result = await call(ctx, 'write', { file_path: ' ', content: 'hi' })
  357. expect(result.isError).toBe(true)
  358. expect(text(result)).toContain('file_path must be a non-empty string')
  359. })
  360. it('propagates a backend FsError as an isError result carrying its code', async () => {
  361. const { ctx, fs } = await setup()
  362. fs.rejectWith = new FsError('blocked', 'FS_STALE_VERSION')
  363. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'hi' })
  364. expect(result.isError).toBe(true)
  365. expect(result.error).toMatchObject({ info: { name: 'FsError', code: 'FS_STALE_VERSION' } })
  366. })
  367. })
  368. describe('edit tool', () => {
  369. it('formats a single-replacement success after a read', async () => {
  370. const { ctx, fs } = await setup()
  371. const session = { header: {} }
  372. fs.files.set('key:a.txt', 'a')
  373. await call(ctx, 'read', { file_path: 'a.txt' }, { session })
  374. const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'a', new_string: 'b' }, { session })
  375. if (result.isError) throw new Error('expected edit success')
  376. expect(result.value).toEqual({ path: '/abs/a.txt', before: 'a', after: 'b' })
  377. expect(text(result)).toBe('The file /abs/a.txt has been updated successfully.')
  378. })
  379. it('formats the replace_all success message distinctly', async () => {
  380. const { ctx, fs } = await setup()
  381. const session = { header: {} }
  382. fs.files.set('key:a.txt', 'a a a')
  383. await call(ctx, 'read', { file_path: 'a.txt' }, { session })
  384. const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'a', new_string: 'b', replace_all: true }, { session })
  385. expect(text(result)).toBe('The file /abs/a.txt has been updated. All occurrences were successfully replaced.')
  386. })
  387. it('rejects identical old/new strings', async () => {
  388. const { ctx } = await setup()
  389. const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'x', new_string: 'x' })
  390. expect(result.isError).toBe(true)
  391. expect(text(result)).toContain('must differ')
  392. })
  393. it('rejects an empty old_string', async () => {
  394. const { ctx } = await setup()
  395. const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: '', new_string: 'x' })
  396. expect(result.isError).toBe(true)
  397. expect(text(result)).toContain('old_string must be a non-empty string')
  398. })
  399. it('rejects a blank file_path', async () => {
  400. const { ctx } = await setup()
  401. const result = await call(ctx, 'edit', { file_path: ' ', old_string: 'a', new_string: 'b' })
  402. expect(result.isError).toBe(true)
  403. expect(text(result)).toContain('file_path must be a non-empty string')
  404. })
  405. it('propagates FS_NOT_OBSERVED when the file was never read (the gate decides)', async () => {
  406. const { ctx, fs } = await setup()
  407. fs.files.set('key:a.txt', 'hello')
  408. const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'a', new_string: 'b' }, { session: { header: {} } })
  409. expect(result.isError).toBe(true)
  410. expect(result.error).toMatchObject({ info: { code: 'FS_NOT_OBSERVED' } })
  411. })
  412. })
  413. describe('tool-owned presentation (pure presentCall)', () => {
  414. // presentCall is a pure display function of args (no I/O); it drives the
  415. // card's title/kind and the `locations` a UI follows along to.
  416. const presentCall = async (name: string, args: unknown) => {
  417. const { ctx } = await setup()
  418. return ctx.tools.get(name)?.presentCall?.(args)
  419. }
  420. const presentResult = async (name: string, args: unknown, result: ToolResult) => {
  421. const { ctx } = await setup()
  422. return ctx.tools.get(name)?.presentResult?.(args, result)
  423. }
  424. it('read: generic card titled by file with the read window, read kind, location with the offset line', async () => {
  425. expect(await presentCall('read', { file_path: 'src/a.ts', offset: 12, limit: 40 })).toEqual({
  426. card: 'generic', title: 'Read src/a.ts (12 - 51)', kind: 'read',
  427. locations: [{ path: 'src/a.ts', line: 12 }],
  428. })
  429. })
  430. it('read: bare title and line-1 location when offset/limit are unset', async () => {
  431. expect(await presentCall('read', { file_path: 'a.txt' })).toEqual({
  432. card: 'generic', title: 'Read a.txt', kind: 'read', locations: [{ path: 'a.txt', line: 1 }],
  433. })
  434. })
  435. it('read: completed presentation is a read card carrying the structured window with the envelope stripped', async () => {
  436. // The structured line data rides on persisted meta (the raw output object is
  437. // not on the wire); presentResult narrows it and appends the stripped text as
  438. // the no-capability `content` fallback.
  439. const meta = { path: '/tmp/a.ts', offset: 1, lines: [{ number: 1, text: 'hello' }], totalLines: 1, lang: 'ts' }
  440. expect(await presentResult('read', { file_path: 'a.ts' }, {
  441. content: [{ type: 'text', text: '<path>/tmp/a.ts</path>\n<type>file</type>\n<content>\n1: hello\n\n(End of file - total 1 lines)\n</content>' }],
  442. isError: false,
  443. meta,
  444. })).toEqual({
  445. card: 'read',
  446. path: '/tmp/a.ts',
  447. offset: 1,
  448. lines: [{ number: 1, text: 'hello' }],
  449. totalLines: 1,
  450. lang: 'ts',
  451. content: [{ type: 'text', text: '1: hello\n\n(End of file - total 1 lines)' }],
  452. })
  453. // A window whose extension maps to no language omits `lang` from the card.
  454. expect(await presentResult('read', { file_path: 'notes' }, {
  455. content: [{ type: 'text', text: '<path>/tmp/notes</path>\n<type>file</type>\n<content>\nbody\n</content>' }],
  456. isError: false,
  457. meta: { path: '/tmp/notes', offset: 1, lines: [{ number: 1, text: 'body' }], totalLines: 1 },
  458. })).toEqual({
  459. card: 'read',
  460. path: '/tmp/notes',
  461. offset: 1,
  462. lines: [{ number: 1, text: 'body' }],
  463. totalLines: 1,
  464. content: [{ type: 'text', text: 'body' }],
  465. })
  466. // Malformed envelope text with valid meta still declines (the fallback text is unavailable).
  467. expect(await presentResult('read', { file_path: 'a.ts' }, {
  468. content: [{ type: 'text', text: 'malformed replay' }],
  469. isError: false,
  470. meta,
  471. })).toBeUndefined()
  472. // Valid envelope but absent/malformed meta declines to the generic fallback.
  473. expect(await presentResult('read', { file_path: 'a.ts' }, {
  474. content: [{ type: 'text', text: '<path>/tmp/a.ts</path>\n<type>file</type>\n<content>\n1: hello\n</content>' }],
  475. isError: false,
  476. })).toBeUndefined()
  477. expect(await presentResult('read', { file_path: 'a.ts' }, {
  478. content: [{ type: 'text', text: '<path>/tmp/a.ts</path>\n<type>file</type>\n<content>\n1: hello\n</content>' }],
  479. isError: false,
  480. meta: { path: '/tmp/a.ts', lines: 'nope', totalLines: 1 },
  481. })).toBeUndefined()
  482. })
  483. it('read: completed presentation declines errors and non-single-text content', async () => {
  484. const envelope = '<path>/tmp/a.txt</path>\n<type>file</type>\n<content>\nbody\n</content>'
  485. const meta = { path: '/tmp/a.txt', offset: 1, lines: [{ number: 1, text: 'body' }], totalLines: 1 }
  486. expect(await presentResult('read', { file_path: 'a.txt' }, {
  487. content: [{ type: 'text', text: envelope }],
  488. isError: true,
  489. meta,
  490. })).toBeUndefined()
  491. expect(await presentResult('read', { file_path: 'a.txt' }, {
  492. content: [{ type: 'text', text: envelope }, { type: 'text', text: 'second' }],
  493. isError: false,
  494. meta,
  495. })).toBeUndefined()
  496. expect(await presentResult('read', { file_path: 'a.txt' }, {
  497. content: [{ type: 'reasoning', text: envelope }],
  498. isError: false,
  499. meta,
  500. })).toBeUndefined()
  501. })
  502. it('read: "from line N" window when only offset is set', async () => {
  503. expect(await presentCall('read', { file_path: 'a.txt', offset: 5 })).toEqual({
  504. card: 'generic', title: 'Read a.txt (from line 5)', kind: 'read', locations: [{ path: 'a.txt', line: 5 }],
  505. })
  506. })
  507. it('write: diff card (new-file style, oldText null), location', async () => {
  508. expect(await presentCall('write', { file_path: 'out.txt', content: 'hello' })).toEqual({
  509. card: 'diff', title: 'Write out.txt',
  510. diffs: [{ path: 'out.txt', oldText: null, newText: 'hello' }],
  511. locations: [{ path: 'out.txt' }],
  512. })
  513. })
  514. it('read: a limit with no offset windows from line 1', async () => {
  515. expect(await presentCall('read', { file_path: 'a.txt', limit: 10 })).toEqual({
  516. card: 'generic', title: 'Read a.txt (1 - 10)', kind: 'read', locations: [{ path: 'a.txt', line: 1 }],
  517. })
  518. })
  519. it('edit: an empty old_string maps to oldText null (a whole-file replace diff)', async () => {
  520. // presentCall runs on replay of raw logged args, which parseEditArgs does not
  521. // gate — an empty old_string must still produce a valid diff (oldText null).
  522. expect(await presentCall('edit', { file_path: 'a.txt', old_string: '', new_string: 'seed' })).toEqual({
  523. card: 'diff', title: 'Edit a.txt',
  524. diffs: [{ path: 'a.txt', oldText: null, newText: 'seed' }],
  525. locations: [{ path: 'a.txt' }],
  526. })
  527. })
  528. })
  529. describe('result-time contextual diff (meta + presentResult)', () => {
  530. // An edit records the applied contextual hunk on `tool/result` meta, and the tool's
  531. // presentResult narrows it back into a replayable `diff` result card.
  532. const withContext = 'a\nb\nc\nOLD\nd\ne\nf\n'
  533. it('edit: execute attaches the applied hunk as meta { diffs }', async () => {
  534. const { ctx, fs } = await setup()
  535. const session = { header: {} }
  536. fs.files.set('key:a.txt', withContext)
  537. await call(ctx, 'read', { file_path: 'a.txt' }, { session })
  538. const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'OLD', new_string: 'NEW' }, { session })
  539. expect(result.isError).toBe(false)
  540. expect(result.meta).toEqual({
  541. diffs: [{ path: 'a.txt', oldText: 'a\nb\nc\nOLD\nd\ne\nf', newText: 'a\nb\nc\nNEW\nd\ne\nf' }],
  542. })
  543. })
  544. it('edit: presentResult turns the meta into a diff result card', async () => {
  545. const { ctx, fs } = await setup()
  546. const session = { header: {} }
  547. fs.files.set('key:a.txt', withContext)
  548. await call(ctx, 'read', { file_path: 'a.txt' }, { session })
  549. const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'OLD', new_string: 'NEW' }, { session })
  550. const view = ctx.tools.get('edit')?.presentResult?.({ file_path: 'a.txt', old_string: 'OLD', new_string: 'NEW' }, result)
  551. expect(view).toEqual({
  552. card: 'diff', title: 'Edit a.txt',
  553. diffs: [{ path: 'a.txt', oldText: 'a\nb\nc\nOLD\nd\ne\nf', newText: 'a\nb\nc\nNEW\nd\ne\nf' }],
  554. })
  555. })
  556. it('write OVERWRITE: execute attaches a contextual hunk; presentResult renders a diff card', async () => {
  557. const { ctx, fs } = await setup()
  558. const session = { header: {} }
  559. fs.files.set('key:a.txt', withContext)
  560. await call(ctx, 'read', { file_path: 'a.txt' }, { session })
  561. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'a\nb\nc\nNEW\nd\ne\nf\n' }, { session })
  562. expect(result.isError).toBe(false)
  563. expect(result.meta).toEqual({ diffs: [{ path: 'a.txt', oldText: 'a\nb\nc\nOLD\nd\ne\nf', newText: 'a\nb\nc\nNEW\nd\ne\nf' }] })
  564. const view = ctx.tools.get('write')?.presentResult?.({ file_path: 'a.txt', content: 'x' }, result)
  565. expect(view).toEqual({ card: 'diff', title: 'Write a.txt', diffs: [{ path: 'a.txt', oldText: 'a\nb\nc\nOLD\nd\ne\nf', newText: 'a\nb\nc\nNEW\nd\ne\nf' }] })
  566. })
  567. it('write CREATE: an empty applied-diff projection still falls back to the whole-file diff card', async () => {
  568. // A create has no prior content, yet the completed replacement view must
  569. // remain a diff instead of clobbering the pending new-file diff with text.
  570. const { ctx } = await setup()
  571. const session = { header: {} }
  572. const result = await call(ctx, 'write', { file_path: 'new.txt', content: 'fresh\n' }, { session })
  573. expect(result.isError).toBe(false)
  574. expect(result.meta).toEqual({ diffs: [] })
  575. const view = ctx.tools.get('write')?.presentResult?.({ file_path: 'new.txt', content: 'fresh\n' }, result)
  576. expect(view).toEqual({ card: 'diff', title: 'Write new.txt', diffs: [{ path: 'new.txt', oldText: null, newText: 'fresh\n' }] })
  577. })
  578. it('write OVERWRITE with identical content: an empty applied-diff projection falls back to a whole-file diff', async () => {
  579. const { ctx, fs } = await setup()
  580. const session = { header: {} }
  581. fs.files.set('key:a.txt', 'same\n')
  582. await call(ctx, 'read', { file_path: 'a.txt' }, { session })
  583. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'same\n' }, { session })
  584. expect(result.isError).toBe(false)
  585. expect(result.meta).toEqual({ diffs: [] })
  586. const view = ctx.tools.get('write')?.presentResult?.({ file_path: 'a.txt', content: 'same\n' }, result)
  587. expect(view).toEqual({ card: 'diff', title: 'Write a.txt', diffs: [{ path: 'a.txt', oldText: null, newText: 'same\n' }] })
  588. })
  589. it('presentResult returns undefined on an error result (nothing applied)', async () => {
  590. const { ctx } = await setup()
  591. const errorResult = { content: [{ type: 'text' as const, text: 'Error: boom' }], isError: true }
  592. expect(ctx.tools.get('edit')?.presentResult?.({ file_path: 'a.txt', old_string: 'x', new_string: 'y' }, errorResult)).toBeUndefined()
  593. expect(ctx.tools.get('write')?.presentResult?.({ file_path: 'a.txt', content: 'y' }, errorResult)).toBeUndefined()
  594. })
  595. it('edit presentResult returns undefined on malformed meta (defensive narrowing)', async () => {
  596. // edit has no whole-file fallback (only a literal replacement), so a malformed
  597. // meta yields the generic "updated successfully" rendering.
  598. const { ctx } = await setup()
  599. const badMeta = { content: [{ type: 'text' as const, text: 'ok' }], isError: false, meta: { diffs: 'nope' } }
  600. expect(ctx.tools.get('edit')?.presentResult?.({ file_path: 'a.txt', old_string: 'x', new_string: 'y' }, badMeta)).toBeUndefined()
  601. })
  602. it('write presentResult falls back to a whole-file diff on malformed meta (never leaks the result text)', async () => {
  603. // write always renders a diff card so the completed update can't clobber the
  604. // pending diff with the model-facing text; a malformed meta falls back to the
  605. // args-derived whole-file diff, same as a create.
  606. const { ctx } = await setup()
  607. const badMeta = { content: [{ type: 'text' as const, text: 'ok' }], isError: false, meta: { diffs: 'nope' } }
  608. const view = ctx.tools.get('write')?.presentResult?.({ file_path: 'a.txt', content: 'y' }, badMeta)
  609. expect(view).toEqual({ card: 'diff', title: 'Write a.txt', diffs: [{ path: 'a.txt', oldText: null, newText: 'y' }] })
  610. })
  611. })
  612. describe('read caps are plugin config', () => {
  613. async function setupWith(config: ToolFs.Config) {
  614. const ctx = new Context()
  615. await ctx.plugin(SystemPrompt)
  616. await ctx.plugin(ToolRegistry)
  617. await ctx.plugin(FakeFs)
  618. await ctx.plugin(FsPolicy)
  619. await ctx.plugin(ToolFs, config)
  620. return { ctx, fs: ctx.fs as FakeFs }
  621. }
  622. it('a configured readLimit is both the default and the cap, and the schema names it', async () => {
  623. const { ctx, fs } = await setupWith({ readLimit: 2 })
  624. fs.files.set('key:a.txt', 'one\ntwo\nthree\nfour')
  625. const result = await call(ctx, 'read', { file_path: 'a.txt' })
  626. expect(text(result)).toContain('(Showing lines 1-2 of 4. Use offset=3 to continue.)')
  627. const overCap = await call(ctx, 'read', { file_path: 'a.txt', limit: 3 })
  628. expect(overCap.isError).toBe(true)
  629. expect(text(overCap)).toContain('less than or equal to 2')
  630. const readSchema = ctx.tools.schemas().find(s => s.name === 'read')
  631. expect(JSON.stringify(readSchema)).toContain('Defaults to 2.')
  632. })
  633. it('a configured readMaxLineLength truncates lines at the configured length', async () => {
  634. const { ctx, fs } = await setupWith({ readMaxLineLength: 4 })
  635. fs.files.set('key:a.txt', 'abcdefgh')
  636. const result = await call(ctx, 'read', { file_path: 'a.txt' })
  637. expect(text(result)).toContain('1: abcd... (line truncated to 4 chars)')
  638. })
  639. it('a configured readMaxBytes caps the window at the configured bytes', async () => {
  640. const { ctx, fs } = await setupWith({ readMaxBytes: 9 })
  641. fs.files.set('key:a.txt', 'aaaa\nbbbb\ncccc')
  642. const result = await call(ctx, 'read', { file_path: 'a.txt' })
  643. expect(result.isError).toBe(false)
  644. if (result.isError) throw new Error('expected read success')
  645. expect(result.value).toMatchObject({ totalLines: 3 })
  646. expect(text(result)).toContain('Output capped.')
  647. expect(text(result)).not.toContain('cccc')
  648. })
  649. it('a configured readStreamMinSize routes smaller files to the streaming path', async () => {
  650. const { ctx, fs } = await setupWith({ readStreamMinSize: 5 })
  651. fs.files.set('key:a.txt', 'alpha\nbeta')
  652. const readSpy = vi.spyOn(fs, 'readText')
  653. const streamSpy = vi.spyOn(fs, 'streamText')
  654. const result = await call(ctx, 'read', { file_path: 'a.txt' })
  655. expect(result.isError).toBe(false)
  656. expect(streamSpy).toHaveBeenCalled()
  657. expect(readSpy).not.toHaveBeenCalled()
  658. })
  659. it.each([
  660. ['readLimit', { readLimit: 0 }],
  661. ['readLimit', { readLimit: 2.5 }],
  662. ['readMaxLineLength', { readMaxLineLength: -1 }],
  663. ['readMaxBytes', { readMaxBytes: Number.NaN }],
  664. ['readStreamMinSize', { readStreamMinSize: 0 }],
  665. ] as const)('rejects a non-positive or fractional %s at load', async (name, config) => {
  666. const ctx = new Context()
  667. await ctx.plugin(SystemPrompt)
  668. await ctx.plugin(ToolRegistry)
  669. await ctx.plugin(FakeFs)
  670. await expect(ctx.plugin(ToolFs, config)).rejects.toThrow(new RegExp(`tool-fs: ${name} must be a positive integer`))
  671. })
  672. it('has no default export (namespace plugin export shape)', () => {
  673. expect('default' in ToolFs).toBe(false)
  674. })
  675. })
  676. describe('sandbox escalation surface (write/edit)', () => {
  677. /** A confining fake `ctx.fs`: reports a default mode, records each per-call policy, and can arm a sandbox denial. */
  678. class SandboxingFakeFs extends FakeFs {
  679. stamped: (SandboxExecutionPolicy | undefined)[] = []
  680. override get sandboxMode(): SandboxMode {
  681. return 'workspace-write'
  682. }
  683. override async writeText(
  684. target: FsTarget,
  685. content: string,
  686. expected?: FsWriteIntent,
  687. _signal?: AbortSignal,
  688. sandboxPolicy?: SandboxExecutionPolicy,
  689. ): Promise<FsWriteOutcome> {
  690. this.stamped.push(sandboxPolicy)
  691. return super.writeText(target, content, expected)
  692. }
  693. override async editText(
  694. target: FsTarget,
  695. edit: FsEditRequest,
  696. expected?: { version: FsVersion },
  697. _signal?: AbortSignal,
  698. sandboxPolicy?: SandboxExecutionPolicy,
  699. ): Promise<FsEditOutcome> {
  700. this.stamped.push(sandboxPolicy)
  701. return super.editText(target, edit, expected)
  702. }
  703. }
  704. async function setupConfining(opts: { approval?: boolean } = {}) {
  705. const ctx = new Context()
  706. await ctx.plugin(SystemPrompt)
  707. await ctx.plugin(ToolRegistry)
  708. await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write' })
  709. await ctx.plugin(SandboxingFakeFs)
  710. await ctx.plugin(FsPolicy)
  711. if (opts.approval === true) await ctx.plugin(ApprovalService)
  712. await ctx.plugin(ToolFs)
  713. return { ctx, fs: ctx.fs as SandboxingFakeFs }
  714. }
  715. /** A fake agent whose session records appends (the approval audit surface), mid-turn, carrying the given events for the fold. */
  716. function escalationAgent(events: Array<{ type: string; data?: Record<string, unknown> }> = []): object {
  717. return {
  718. id: 'agent-fs-esc',
  719. session: {
  720. header: { version: 0, id: 'sess-fs-esc', createdAt: 0, cwd: '/session-project' },
  721. events: [{ type: 'turn/start' }, ...events],
  722. append: (type: string, data: Record<string, unknown>) => { events.push({ type, data }) },
  723. },
  724. }
  725. }
  726. function fsSchema(ctx: Context, name: 'write' | 'edit') {
  727. const schema = ctx.tools.schemas().find(s => s.name === name)
  728. if (!schema) throw new Error(`${name} tool not registered`)
  729. return schema as unknown as { parameters: { properties: Record<string, { enum?: string[] }> } }
  730. }
  731. it('fails load when a confining filesystem has no shared sandbox-policy resolver', async () => {
  732. const ctx = new Context()
  733. await ctx.plugin(SystemPrompt)
  734. await ctx.plugin(ToolRegistry)
  735. await ctx.plugin(SandboxingFakeFs)
  736. await expect(ctx.plugin(ToolFs)).rejects.toThrow('tool-fs: the mounted filesystem confines but ctx.sandboxPolicy is missing')
  737. })
  738. it('advertises no escalation fields under a non-confining backend', async () => {
  739. const { ctx } = await setup()
  740. expect(ctx.fs.sandboxMode).toBeUndefined()
  741. for (const name of ['write', 'edit'] as const) {
  742. const props = fsSchema(ctx, name).parameters.properties
  743. expect(props['sandbox_permissions']).toBeUndefined()
  744. expect(props['justification']).toBeUndefined()
  745. }
  746. })
  747. it('advertises the closed target vocabulary on write and edit under a confining backend', async () => {
  748. const { ctx } = await setupConfining()
  749. for (const name of ['write', 'edit'] as const) {
  750. const props = fsSchema(ctx, name).parameters.properties
  751. expect(props['sandbox_permissions']?.enum).toEqual(['workspace-write', 'danger-full-access'])
  752. expect(props['justification']).toBeDefined()
  753. }
  754. })
  755. it('a plain write stamps the default mode with the calling session root', async () => {
  756. const { ctx, fs } = await setupConfining()
  757. await call(ctx, 'write', { file_path: 'a.txt', content: 'x' }, escalationAgent())
  758. expect(fs.stamped).toEqual([{ mode: 'workspace-write', workspaceRoot: resolve('/session-project') }])
  759. })
  760. it('a standing session override folds onto the stamp', async () => {
  761. const { ctx, fs } = await setupConfining()
  762. await call(ctx, 'write', { file_path: 'a.txt', content: 'x' }, escalationAgent([{ type: 'sandbox/mode', data: { mode: 'read-only' } }]))
  763. expect(fs.stamped).toEqual([{ mode: 'read-only', workspaceRoot: resolve('/session-project') }])
  764. })
  765. it('a denied write maps to the shared marker plus the escalation hint (isError)', async () => {
  766. const { ctx, fs } = await setupConfining()
  767. fs.rejectWith = new FsError('denied', 'FS_SANDBOX_DENIED')
  768. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'x' }, escalationAgent())
  769. expect(result.isError).toBe(true)
  770. expect(text(result)).toContain('[sandbox: file access denied under workspace-write mode]')
  771. expect(text(result)).toContain('retry this exact operation once with sandbox_permissions')
  772. })
  773. it('a non-FS_SANDBOX_DENIED provider error passes through unchanged', async () => {
  774. const { ctx, fs } = await setupConfining()
  775. fs.rejectWith = new FsError('boom', 'FS_IO_ERROR')
  776. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'x' }, escalationAgent())
  777. expect(result.isError).toBe(true)
  778. expect(text(result)).toContain('boom')
  779. expect(text(result)).not.toContain('[sandbox:')
  780. })
  781. it('an approved escalation stamps the granted mode onto that write', async () => {
  782. const { ctx, fs } = await setupConfining({ approval: true })
  783. ctx.on('approval/request', () => Promise.resolve('allowed-once' as const))
  784. // Pass a signal so the escalation ask forwards it to the approval request
  785. // (the request rides the tool-execution abort signal).
  786. await ctx.tools.execute({
  787. callId: CallId('call-fs-esc-grant'),
  788. name: 'write',
  789. arguments: { file_path: 'a.txt', content: 'x', sandbox_permissions: 'danger-full-access', justification: 'the test needs it' },
  790. agent: escalationAgent() as never,
  791. signal: new AbortController().signal,
  792. })
  793. expect(fs.stamped).toEqual([{ mode: 'danger-full-access', workspaceRoot: resolve('/session-project') }])
  794. })
  795. it('a rejected escalation fails closed with its own text and never mutates', async () => {
  796. const { ctx, fs } = await setupConfining({ approval: true })
  797. ctx.on('approval/request', () => Promise.resolve('rejected' as const))
  798. const result = await call(ctx, 'edit', { file_path: 'a.txt', old_string: 'x', new_string: 'y', sandbox_permissions: 'danger-full-access', justification: 'the test needs it' }, escalationAgent())
  799. expect(result.isError).toBe(true)
  800. expect(text(result)).toContain('the user rejected escalating this operation to "danger-full-access"')
  801. expect(fs.stamped).toEqual([])
  802. })
  803. it('escalation without an approval service fails closed', async () => {
  804. const { ctx } = await setupConfining()
  805. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'x', sandbox_permissions: 'danger-full-access', justification: 'why' }, escalationAgent())
  806. expect(result.isError).toBe(true)
  807. expect(text(result)).toContain('no approval service is composed')
  808. })
  809. it('escalation with an approval service but no agent fails closed', async () => {
  810. const { ctx } = await setupConfining({ approval: true })
  811. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'x', sandbox_permissions: 'danger-full-access', justification: 'why' })
  812. expect(result.isError).toBe(true)
  813. expect(text(result)).toContain('no agent to route it through')
  814. })
  815. it('rejects the escalation argument pairing (one field without the other)', async () => {
  816. const { ctx } = await setupConfining()
  817. const missing = await call(ctx, 'write', { file_path: 'a.txt', content: 'x', sandbox_permissions: 'workspace-write' }, escalationAgent())
  818. expect(missing.isError).toBe(true)
  819. expect(text(missing)).toContain('sandbox_permissions requires a justification')
  820. })
  821. it('sandbox_permissions under a non-confining backend fails closed (unadvertised field still reaches execute)', async () => {
  822. const { ctx } = await setup()
  823. const result = await call(ctx, 'write', { file_path: 'a.txt', content: 'x', sandbox_permissions: 'workspace-write', justification: 'why' }, escalationAgent())
  824. expect(result.isError).toBe(true)
  825. expect(text(result)).toContain('not available in this composition')
  826. })
  827. })