tools.spec.ts 24 KB

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