tools.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { afterEach, describe, expect, it } from 'vitest'
  5. import { Context } from '@deepseek-ai/cordis'
  6. import { FsVersion } from '@deepseek-ai/dsh-fs'
  7. import { ToolCallId } from '@deepseek-ai/dsh-llm'
  8. import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session'
  9. import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
  10. import type { Agent } from '@deepseek-ai/dsh-agent'
  11. import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
  12. import * as FsPolicy from '@deepseek-ai/dsh-fs-observation-policy'
  13. import SandboxedFileSystem from '@deepseek-ai/dsh-fs-sandbox'
  14. import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy'
  15. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  16. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  17. import ToolRuntime from '@deepseek-ai/dsh-tools'
  18. import * as ToolStrReplaceEditor from '@deepseek-ai/dsh-tool-str-replace-editor'
  19. const contexts: Context[] = []
  20. const roots: string[] = []
  21. let callNumber = 0
  22. afterEach(async () => {
  23. for (const ctx of contexts.splice(0)) await ctx.fiber.dispose()
  24. for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
  25. })
  26. function agent(ctx: Context, cwd: string): Agent {
  27. const id = SessionId(`str-replace-editor-owner-${callNumber}`)
  28. const scope = ctx.plugin(() => {})
  29. const session = Session.create(id, [], {
  30. version: SESSION_FORMAT_VERSION, id, createdAt: 0, cwd, isSeeded: false,
  31. })
  32. const value: Agent = {
  33. id,
  34. options: {},
  35. session,
  36. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  37. status: 'idle',
  38. ctx: scope.ctx,
  39. send: () => {},
  40. followup: () => {},
  41. steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
  42. inject: () => {},
  43. cancel() {},
  44. runMaintenance: task => task(new AbortController().signal),
  45. whenIdle: () => Promise.resolve(),
  46. }
  47. ctx.agents.register(value)
  48. return value
  49. }
  50. function text(result: { content: { type: string; text?: string }[] }): string {
  51. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  52. }
  53. function call(ctx: Context, owner: Agent | undefined, args: unknown) {
  54. return ctx.tools.execute({
  55. signal: new AbortController().signal,
  56. callId: ToolCallId(`str-replace-editor-${++callNumber}`),
  57. name: 'str_replace_editor',
  58. arguments: args,
  59. ...owner === undefined ? {} : { agent: owner },
  60. })
  61. }
  62. async function setup(
  63. config: ToolStrReplaceEditor.Config = {},
  64. options: { fsPolicy?: boolean; sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access' } = {},
  65. ) {
  66. const root = await mkdtemp(join(tmpdir(), 'dsh-tool-str-replace-editor-'))
  67. roots.push(root)
  68. const ctx = new Context()
  69. contexts.push(ctx)
  70. await ctx.plugin(SystemPrompt)
  71. await ctx.plugin(ToolRuntime)
  72. await ctx.plugin(AgentRegistry)
  73. if (options.sandboxMode === undefined) {
  74. await ctx.plugin(LocalFileSystem, { cwd: root })
  75. } else {
  76. // SandboxPolicy declares the registry as a required injection; mount it
  77. // before the policy activates.
  78. await ctx.plugin(SessionProjectionRegistry)
  79. await ctx.plugin(SandboxPolicy, { mode: options.sandboxMode, workspaceRoot: root })
  80. await ctx.plugin(SandboxedFileSystem, { cwd: root })
  81. }
  82. if (options.fsPolicy === true) await ctx.plugin(FsPolicy)
  83. const fiber = await ctx.plugin(ToolStrReplaceEditor, config)
  84. return { ctx, root, fiber, owner: agent(ctx, root) }
  85. }
  86. describe('tool-str-replace-editor', () => {
  87. it('registers the standalone schema and configurable description', async () => {
  88. const { ctx, fiber } = await setup({ description: 'custom editor description' })
  89. const schema = ctx.tools.schemas()[0]
  90. expect(ctx.tools.schemas().map(item => item.name)).toEqual(['str_replace_editor'])
  91. expect(schema?.description).toBe('custom editor description')
  92. const properties = (schema?.parameters as {
  93. properties: Record<string, {
  94. type?: string
  95. items?: { type?: string }
  96. oneOf?: { type?: string; items?: { type?: string } }[]
  97. }>
  98. }).properties
  99. expect(properties).not.toHaveProperty('replace_all')
  100. expect(properties.file_text?.oneOf?.map(option => option.type)).toEqual(['string', 'null'])
  101. expect(properties.insert_line?.oneOf?.map(option => option.type)).toEqual(['integer', 'null'])
  102. expect(properties.new_str?.oneOf?.map(option => option.type)).toEqual(['string', 'null'])
  103. expect(properties.old_str?.oneOf?.map(option => option.type)).toEqual(['string', 'null'])
  104. expect(properties.view_range?.oneOf?.map(option => option.type)).toEqual(['array', 'null'])
  105. expect(properties.view_range?.oneOf?.[0]?.items?.type).toBe('integer')
  106. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  107. command: 'view',
  108. path: '/workspace/a.txt',
  109. file_text: null,
  110. insert_line: null,
  111. new_str: null,
  112. old_str: null,
  113. view_range: null,
  114. })).toMatchObject({
  115. card: 'generic',
  116. kind: 'read',
  117. locations: [{ path: '/workspace/a.txt' }],
  118. })
  119. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  120. command: 'create',
  121. path: '/workspace/a.txt',
  122. file_text: 'hello',
  123. insert_line: null,
  124. new_str: null,
  125. old_str: null,
  126. view_range: null,
  127. })).toMatchObject({
  128. card: 'diff',
  129. diffs: [{ path: '/workspace/a.txt', oldText: null, newText: 'hello' }],
  130. })
  131. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  132. command: 'str_replace',
  133. path: '/workspace/a.txt',
  134. old_str: 'old',
  135. new_str: 'new',
  136. file_text: null,
  137. insert_line: null,
  138. view_range: null,
  139. })).toMatchObject({
  140. card: 'diff',
  141. diffs: [{ path: '/workspace/a.txt', oldText: 'old', newText: 'new' }],
  142. })
  143. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  144. command: 'insert',
  145. path: '/workspace/a.txt',
  146. insert_line: null,
  147. new_str: 'x',
  148. })).toMatchObject({
  149. card: 'generic',
  150. kind: 'edit',
  151. locations: [{ path: '/workspace/a.txt' }],
  152. })
  153. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  154. command: 'insert',
  155. path: '/workspace/a.txt',
  156. insert_line: 0,
  157. new_str: 'x',
  158. file_text: null,
  159. old_str: null,
  160. view_range: null,
  161. })).toMatchObject({
  162. card: 'generic',
  163. kind: 'edit',
  164. locations: [{ path: '/workspace/a.txt', line: 1 }],
  165. })
  166. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  167. command: 'create',
  168. path: '/workspace/empty.txt',
  169. })).toMatchObject({
  170. diffs: [{ path: '/workspace/empty.txt', oldText: null, newText: '' }],
  171. })
  172. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  173. command: 'str_replace',
  174. path: '/workspace/a.txt',
  175. })).toMatchObject({
  176. diffs: [{ path: '/workspace/a.txt', oldText: null, newText: '' }],
  177. })
  178. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  179. command: 'insert',
  180. path: '/workspace/a.txt',
  181. })).toMatchObject({
  182. locations: [{ path: '/workspace/a.txt' }],
  183. })
  184. await fiber.dispose()
  185. expect(ctx.tools.schemas()).toEqual([])
  186. expect(ctx.tools.get('str_replace_editor')).toBeUndefined()
  187. })
  188. it('creates, views, replaces, and inserts with the canonical model-facing output', async () => {
  189. const { ctx, root, owner } = await setup()
  190. const sample = join(root, 'sample.txt')
  191. expect(text(await call(ctx, owner, {
  192. command: 'create',
  193. path: sample,
  194. file_text: 'one\ntwo\nthree\n',
  195. insert_line: null,
  196. new_str: null,
  197. old_str: null,
  198. view_range: null,
  199. }))).toBe(`New file created successfully at: ${sample}`)
  200. expect(text(await call(ctx, owner, {
  201. command: 'view',
  202. path: sample,
  203. file_text: null,
  204. insert_line: null,
  205. new_str: null,
  206. old_str: null,
  207. view_range: null,
  208. }))).toContain(' 2 two')
  209. expect(text(await call(ctx, owner, {
  210. command: 'view',
  211. path: sample,
  212. view_range: [2, -1],
  213. }))).toBe([
  214. `Here's the content of ${sample} with line numbers (which has a total of 4 lines) with view_range=[2, -1]:`,
  215. ' 2 two',
  216. ' 3 three',
  217. ' 4 ',
  218. '',
  219. ].join('\n'))
  220. expect(text(await call(ctx, owner, {
  221. command: 'str_replace',
  222. path: sample,
  223. old_str: 'two',
  224. new_str: 'TWO',
  225. file_text: null,
  226. insert_line: null,
  227. view_range: null,
  228. }))).toBe(`The file ${sample} has been edited successfully.`)
  229. expect(text(await call(ctx, owner, {
  230. command: 'str_replace',
  231. path: sample,
  232. old_str: 'TWO',
  233. }))).toBe(`The file ${sample} has been edited successfully.`)
  234. expect(text(await call(ctx, owner, {
  235. command: 'insert',
  236. path: sample,
  237. insert_line: 1,
  238. new_str: 'between',
  239. file_text: null,
  240. old_str: null,
  241. view_range: null,
  242. }))).toBe(`The file ${sample} has been edited successfully.`)
  243. expect(await readFile(sample, 'utf8')).toBe('one\nbetween\n\nthree\n')
  244. })
  245. it('a failed view records absence so create can recover after external deletion', async () => {
  246. const { ctx, root, owner } = await setup({}, { fsPolicy: true })
  247. const sample = join(root, 'deleted.txt')
  248. await writeFile(sample, 'original')
  249. expect((await call(ctx, owner, { command: 'view', path: sample })).isError).toBe(false)
  250. await rm(sample)
  251. const missing = await call(ctx, owner, { command: 'view', path: sample })
  252. expect(missing.isError).toBe(true)
  253. expect(missing.error).toMatchObject({ info: { code: 'FS_NOT_FOUND' } })
  254. const edit = await call(ctx, owner, {
  255. command: 'str_replace',
  256. path: sample,
  257. old_str: 'original',
  258. new_str: 'edited',
  259. })
  260. expect(edit.isError).toBe(true)
  261. expect(edit.error).toMatchObject({ info: { code: 'FS_NOT_FOUND' } })
  262. const created = await call(ctx, owner, {
  263. command: 'create',
  264. path: sample,
  265. file_text: 'fresh',
  266. })
  267. expect(created.isError).toBe(false)
  268. expect(await readFile(sample, 'utf8')).toBe('fresh')
  269. })
  270. it('writes replacement text literally', async () => {
  271. const { ctx, root, owner } = await setup()
  272. const sample = join(root, 'literal.txt')
  273. const replacement = "$&|$`|$'|$$"
  274. await writeFile(sample, 'before OLD after')
  275. expect((await call(ctx, owner, {
  276. command: 'str_replace',
  277. path: sample,
  278. old_str: 'OLD',
  279. new_str: replacement,
  280. })).isError).toBe(false)
  281. expect(await readFile(sample, 'utf8')).toBe(`before ${replacement} after`)
  282. })
  283. it('lists visible entries to depth two and clips at the configured view limit', async () => {
  284. const { ctx, root, owner } = await setup({ maxOutputChars: 10_000 })
  285. await mkdir(join(root, 'dir', 'nested', 'third'), { recursive: true })
  286. await mkdir(join(root, 'dir', 'node_modules', 'pkg'), { recursive: true })
  287. await mkdir(join(root, 'dir', 'node_modules_old'), { recursive: true })
  288. await mkdir(join(root, 'dir', '__pycache__'), { recursive: true })
  289. await mkdir(join(root, 'dir', '__pycache__backup'), { recursive: true })
  290. await writeFile(join(root, 'dir', 'visible.txt'), 'ok')
  291. await writeFile(join(root, 'dir', '.hidden'), 'hidden')
  292. await writeFile(join(root, 'dir', 'nested', 'child.txt'), 'child')
  293. await writeFile(join(root, 'dir', 'nested', 'third', 'too-deep.txt'), 'deep')
  294. await writeFile(join(root, 'dir', 'node_modules', 'pkg', 'index.js'), 'hidden dependency')
  295. await writeFile(join(root, 'dir', 'node_modules_old', 'kept.js'), 'visible source')
  296. await writeFile(join(root, 'dir', '__pycache__', 'module.pyc'), 'cache')
  297. await writeFile(join(root, 'dir', '__pycache__backup', 'kept.py'), 'visible source')
  298. const listDir = ctx.fs.listDir.bind(ctx.fs)
  299. const otherTarget = await ctx.fs.resolve(join(root, 'dir', 'other'))
  300. ctx.fs.listDir = async (target, signal) => {
  301. const entries = await listDir(target, signal)
  302. return target.displayPath === join(root, 'dir')
  303. ? [
  304. { name: 'same-target', type: 'other', target: otherTarget },
  305. { name: 'other', type: 'other', target: otherTarget },
  306. ...entries.toReversed(),
  307. ]
  308. : entries
  309. }
  310. const listing = text(await call(ctx, owner, { command: 'view', path: join(root, 'dir') }))
  311. expect(listing).not.toContain('.hidden')
  312. expect(listing).not.toContain('too-deep.txt')
  313. expect(listing).not.toContain('index.js')
  314. expect(listing).not.toContain('module.pyc')
  315. // The listing carries absolute display paths; the POSIX-style substrings
  316. // only match on Linux, so assert with platform separators.
  317. expect(listing).toContain(join('node_modules_old', 'kept.js'))
  318. expect(listing).toContain(join('__pycache__backup', 'kept.py'))
  319. const clipped = await setup({ maxOutputChars: 10 })
  320. await writeFile(join(clipped.root, 'large.txt'), 'x'.repeat(100))
  321. expect(text(await call(clipped.ctx, clipped.owner, {
  322. command: 'view',
  323. path: join(clipped.root, 'large.txt'),
  324. })))
  325. .toContain('<response clipped>')
  326. })
  327. it('matches canonical empty-line, range, and end-insert behavior', async () => {
  328. const { ctx, root, owner } = await setup()
  329. const empty = join(root, 'empty.txt')
  330. const newline = join(root, 'newline.txt')
  331. const plain = join(root, 'plain.txt')
  332. await writeFile(empty, '')
  333. await writeFile(newline, '\n')
  334. await writeFile(plain, 'one\ntwo')
  335. expect(text(await call(ctx, owner, { command: 'view', path: empty })))
  336. .toContain('(which has a total of 1 lines):\n 1 \n')
  337. expect(text(await call(ctx, owner, { command: 'view', path: newline })))
  338. .toContain('(which has a total of 2 lines):\n 1 \n 2 \n')
  339. expect(text(await call(ctx, owner, {
  340. command: 'view',
  341. path: plain,
  342. view_range: [1, 2],
  343. }))).toContain(' 2 two')
  344. expect(text(await call(ctx, undefined, {
  345. command: 'view',
  346. path: plain,
  347. }))).toContain(' 1 one')
  348. expect((await call(ctx, undefined, {
  349. command: 'create',
  350. path: join(root, 'ownerless.txt'),
  351. file_text: 'ownerless',
  352. })).isError).toBe(false)
  353. await call(ctx, owner, {
  354. command: 'insert',
  355. path: plain,
  356. insert_line: 2,
  357. new_str: 'three',
  358. })
  359. expect(await readFile(plain, 'utf8')).toBe('one\ntwo\nthree')
  360. await writeFile(newline, 'one\n')
  361. await call(ctx, owner, {
  362. command: 'insert',
  363. path: newline,
  364. insert_line: 2,
  365. new_str: 'three',
  366. })
  367. expect(await readFile(newline, 'utf8')).toBe('one\n\nthree')
  368. })
  369. it('uses old_str-only replacement failures and rejects relative paths', async () => {
  370. const { ctx, root, owner } = await setup()
  371. const ambiguous = join(root, 'ambiguous.txt')
  372. await writeFile(ambiguous, 'same\nother\nsame')
  373. const missing = await call(ctx, owner, {
  374. command: 'str_replace',
  375. path: ambiguous,
  376. old_str: 'absent',
  377. new_str: 'x',
  378. })
  379. expect(missing.isError).toBe(true)
  380. expect(text(missing)).toContain(`old_str \`absent\` did not appear verbatim in ${ambiguous}`)
  381. expect(text(missing)).not.toContain('old_string')
  382. const repeated = await call(ctx, owner, {
  383. command: 'str_replace',
  384. path: ambiguous,
  385. old_str: 'same',
  386. new_str: 'x',
  387. })
  388. expect(repeated.isError).toBe(true)
  389. expect(text(repeated)).toContain('Multiple occurrences of old_str `same` in lines [1, 3]')
  390. expect(text(repeated)).not.toContain('replace_all')
  391. await writeFile(ambiguous, 'alpha\nbeta\nmiddle\nalpha\nbeta')
  392. const repeatedMultiline = await call(ctx, owner, {
  393. command: 'str_replace',
  394. path: ambiguous,
  395. old_str: 'alpha\nbeta',
  396. new_str: 'x',
  397. })
  398. expect(text(repeatedMultiline))
  399. .toContain('Multiple occurrences of old_str `alpha\nbeta` in lines [1, 4]')
  400. const mixedEol = join(root, 'mixed-eol.txt')
  401. await writeFile(mixedEol, 'alpha\r\nbeta\nmiddle\nalpha\nbeta')
  402. expect((await call(ctx, owner, {
  403. command: 'str_replace',
  404. path: mixedEol,
  405. old_str: 'alpha\r\nbeta',
  406. new_str: 'replaced',
  407. })).isError).toBe(false)
  408. expect(await readFile(mixedEol, 'utf8')).toBe('replaced\nmiddle\nalpha\nbeta')
  409. const relative = await call(ctx, owner, { command: 'view', path: 'ambiguous.txt' })
  410. expect(relative.isError).toBe(true)
  411. expect(text(relative)).toContain('is not an absolute path')
  412. expect(await readFile(ambiguous, 'utf8')).toBe('alpha\nbeta\nmiddle\nalpha\nbeta')
  413. })
  414. it('reports invalid commands or arguments without mutating files', async () => {
  415. const { ctx, root, owner } = await setup()
  416. const ambiguous = join(root, 'ambiguous.txt')
  417. const empty = join(root, 'empty.txt')
  418. const trailingNewline = join(root, 'trailing-newline.txt')
  419. const threeLines = join(root, 'three-lines.txt')
  420. const directory = join(root, 'directory')
  421. await writeFile(ambiguous, 'same same')
  422. await writeFile(empty, '')
  423. await writeFile(trailingNewline, 'one\n')
  424. await writeFile(threeLines, 'one\ntwo\nthree')
  425. await mkdir(directory)
  426. const cases = [
  427. { command: null, path: ambiguous },
  428. { command: 'view', path: null },
  429. { command: 'view', path: '' },
  430. { command: 'view', path: join(root, 'missing.txt') },
  431. { command: 'view', path: ambiguous, view_range: [1] },
  432. { command: 'view', path: ambiguous, view_range: [0, 1] },
  433. { command: 'view', path: ambiguous, view_range: [1.5, 2] },
  434. { command: 'view', path: threeLines, view_range: [1, 99] },
  435. { command: 'view', path: threeLines, view_range: [2, 1] },
  436. { command: 'view', path: directory, view_range: [1, 1] },
  437. { command: 'create', path: join(root, 'new.txt') },
  438. { command: 'create', path: join(root, 'new.txt'), file_text: null },
  439. { command: 'create', path: ambiguous, file_text: 'overwrite' },
  440. { command: 'str_replace', path: ambiguous, new_str: 'x' },
  441. { command: 'str_replace', path: ambiguous, old_str: null, new_str: 'x' },
  442. { command: 'str_replace', path: ambiguous, old_str: 'same same', new_str: null },
  443. { command: 'str_replace', path: ambiguous, old_str: '', new_str: 'x' },
  444. { command: 'insert', path: ambiguous, new_str: 'x' },
  445. { command: 'insert', path: ambiguous, insert_line: null, new_str: 'x' },
  446. { command: 'insert', path: ambiguous, insert_line: 0, new_str: null },
  447. { command: 'insert', path: ambiguous, insert_line: -1, new_str: 'x' },
  448. { command: 'insert', path: ambiguous, insert_line: 1.5, new_str: 'x' },
  449. { command: 'insert', path: ambiguous, insert_line: 99, new_str: 'x' },
  450. { command: 'insert', path: empty, insert_line: 2, new_str: 'x' },
  451. { command: 'insert', path: directory, insert_line: 0, new_str: 'x' },
  452. ]
  453. for (const args of cases) {
  454. expect((await call(ctx, owner, args)).isError).toBe(true)
  455. }
  456. expect(await readFile(ambiguous, 'utf8')).toBe('same same')
  457. ctx.fs.stat = async () => ({ version: FsVersion('special'), type: 'other' })
  458. const special = await call(ctx, owner, { command: 'view', path: join(root, 'special') })
  459. expect(special.isError).toBe(true)
  460. expect(special.error).toMatchObject({ info: { code: 'FS_NOT_REGULAR_FILE' } })
  461. expect((await call(ctx, owner, {
  462. command: 'str_replace',
  463. path: join(root, 'special'),
  464. old_str: 'x',
  465. new_str: 'y',
  466. })).error).toMatchObject({ info: { code: 'FS_NOT_REGULAR_FILE' } })
  467. expect((await call(ctx, owner, {
  468. command: 'insert',
  469. path: join(root, 'special'),
  470. insert_line: 0,
  471. new_str: 'x',
  472. })).error).toMatchObject({ info: { code: 'FS_NOT_REGULAR_FILE' } })
  473. })
  474. it('delegates read-before-edit decisions to fs-observation-policy', async () => {
  475. const { ctx, root, owner } = await setup({}, { fsPolicy: true })
  476. const existing = join(root, 'existing.txt')
  477. const created = join(root, 'created.txt')
  478. await writeFile(existing, 'before')
  479. const blindEdit = await call(ctx, owner, {
  480. command: 'str_replace',
  481. path: existing,
  482. old_str: 'before',
  483. new_str: 'after',
  484. })
  485. expect(blindEdit.error).toMatchObject({ info: { code: 'FS_NOT_OBSERVED' } })
  486. expect(await readFile(existing, 'utf8')).toBe('before')
  487. await call(ctx, owner, { command: 'view', path: existing })
  488. expect((await call(ctx, owner, {
  489. command: 'str_replace',
  490. path: existing,
  491. old_str: 'before',
  492. new_str: 'after',
  493. })).isError).toBe(false)
  494. expect(await readFile(existing, 'utf8')).toBe('after')
  495. expect((await call(ctx, owner, {
  496. command: 'insert',
  497. path: existing,
  498. insert_line: 1,
  499. new_str: 'tail',
  500. })).isError).toBe(false)
  501. expect(await readFile(existing, 'utf8')).toBe('after\ntail')
  502. expect((await call(ctx, owner, {
  503. command: 'create',
  504. path: created,
  505. file_text: 'new',
  506. })).isError).toBe(false)
  507. expect(await readFile(created, 'utf8')).toBe('new')
  508. })
  509. it('passes the session sandbox policy to every mutation', async () => {
  510. const { ctx, root, owner } = await setup({}, { sandboxMode: 'read-only' })
  511. const path = join(root, 'blocked.txt')
  512. const result = await call(ctx, owner, {
  513. command: 'create',
  514. path,
  515. file_text: 'blocked',
  516. })
  517. expect(result.error).toMatchObject({ info: { code: 'FS_SANDBOX_DENIED' } })
  518. expect(text(result)).toContain('[sandbox: file access denied under read-only mode]')
  519. const ownerless = await call(ctx, undefined, {
  520. command: 'create',
  521. path: join(root, 'ownerless-blocked.txt'),
  522. file_text: 'blocked',
  523. })
  524. expect(ownerless.error).toMatchObject({ info: { code: 'FS_SANDBOX_DENIED' } })
  525. })
  526. it('preserves tabs outside the edited region', async () => {
  527. const { ctx, root, owner } = await setup()
  528. const path = join(root, 'Makefile')
  529. await writeFile(path, 'target:\n\told\nremove\n')
  530. expect(text(await call(ctx, owner, { command: 'view', path })))
  531. .toContain(' 2 \told')
  532. await call(ctx, owner, {
  533. command: 'str_replace',
  534. path,
  535. old_str: '\told',
  536. new_str: '\tnew',
  537. })
  538. await call(ctx, owner, {
  539. command: 'str_replace',
  540. path,
  541. old_str: 'remove\n',
  542. })
  543. await call(ctx, owner, {
  544. command: 'insert',
  545. path,
  546. insert_line: 1,
  547. new_str: '\tkept',
  548. })
  549. expect(await readFile(path, 'utf8')).toBe('target:\n\tkept\n\tnew\n')
  550. })
  551. it('reports missing sandbox-policy composition during plugin startup', async () => {
  552. const root = await mkdtemp(join(tmpdir(), 'dsh-tool-str-replace-editor-missing-policy-'))
  553. roots.push(root)
  554. const ctx = new Context()
  555. contexts.push(ctx)
  556. await ctx.plugin(SystemPrompt)
  557. await ctx.plugin(ToolRuntime)
  558. await ctx.plugin(AgentRegistry)
  559. await ctx.plugin(LocalFileSystem, { cwd: root })
  560. Object.defineProperty(ctx.fs, 'sandboxMode', { value: 'read-only' })
  561. await expect(ctx.plugin(ToolStrReplaceEditor))
  562. .rejects.toThrow('the mounted filesystem confines but ctx.sandboxPolicy is missing')
  563. })
  564. it('maps unexpected backend write failures for replace and insert', async () => {
  565. const { ctx, root, owner } = await setup()
  566. const path = join(root, 'backend-error.txt')
  567. await writeFile(path, 'old\n')
  568. const failWrite = async (): Promise<never> => {
  569. throw new Error('backend write failed')
  570. }
  571. ctx.fs.writeText = failWrite
  572. const replace = await call(ctx, owner, {
  573. command: 'str_replace',
  574. path,
  575. old_str: 'old',
  576. new_str: 'new',
  577. })
  578. expect(replace.isError).toBe(true)
  579. expect(text(replace)).toContain('backend write failed')
  580. const insert = await call(ctx, owner, {
  581. command: 'insert',
  582. path,
  583. insert_line: 1,
  584. new_str: 'new',
  585. })
  586. expect(insert.isError).toBe(true)
  587. expect(text(insert)).toContain('backend write failed')
  588. })
  589. it('rejects invalid plugin config', () => {
  590. expect(() => {
  591. ToolStrReplaceEditor.apply(new Context(), { maxOutputChars: 0 })
  592. }).toThrow('maxOutputChars must be a positive safe integer')
  593. expect(() => {
  594. ToolStrReplaceEditor.apply(new Context(), { description: ' ' })
  595. }).toThrow('description must be non-empty')
  596. })
  597. })