tools.spec.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 '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-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 ToolRegistry 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(ToolRegistry)
  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, { type?: string; items?: { type?: string } }>
  88. }).properties
  89. expect(properties).not.toHaveProperty('replace_all')
  90. expect(properties.insert_line?.type).toBe('integer')
  91. expect(properties.view_range?.items?.type).toBe('integer')
  92. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  93. command: 'view',
  94. path: '/workspace/a.txt',
  95. })).toMatchObject({
  96. card: 'generic',
  97. kind: 'read',
  98. locations: [{ path: '/workspace/a.txt' }],
  99. })
  100. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  101. command: 'create',
  102. path: '/workspace/a.txt',
  103. file_text: 'hello',
  104. })).toMatchObject({
  105. card: 'diff',
  106. diffs: [{ path: '/workspace/a.txt', oldText: null, newText: 'hello' }],
  107. })
  108. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  109. command: 'str_replace',
  110. path: '/workspace/a.txt',
  111. old_str: 'old',
  112. new_str: 'new',
  113. })).toMatchObject({
  114. card: 'diff',
  115. diffs: [{ path: '/workspace/a.txt', oldText: 'old', newText: 'new' }],
  116. })
  117. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  118. command: 'insert',
  119. path: '/workspace/a.txt',
  120. insert_line: 0,
  121. new_str: 'x',
  122. })).toMatchObject({
  123. card: 'generic',
  124. kind: 'edit',
  125. locations: [{ path: '/workspace/a.txt', line: 1 }],
  126. })
  127. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  128. command: 'create',
  129. path: '/workspace/empty.txt',
  130. })).toMatchObject({
  131. diffs: [{ path: '/workspace/empty.txt', oldText: null, newText: '' }],
  132. })
  133. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  134. command: 'str_replace',
  135. path: '/workspace/a.txt',
  136. })).toMatchObject({
  137. diffs: [{ path: '/workspace/a.txt', oldText: null, newText: '' }],
  138. })
  139. expect(ctx.tools.get('str_replace_editor')?.presentCall?.({
  140. command: 'insert',
  141. path: '/workspace/a.txt',
  142. })).toMatchObject({
  143. locations: [{ path: '/workspace/a.txt' }],
  144. })
  145. await fiber.dispose()
  146. expect(ctx.tools.schemas()).toEqual([])
  147. expect(ctx.tools.get('str_replace_editor')).toBeUndefined()
  148. })
  149. it('creates, views, replaces, and inserts with the canonical model-facing output', async () => {
  150. const { ctx, root, owner } = await setup()
  151. const sample = join(root, 'sample.txt')
  152. expect(text(await call(ctx, owner, {
  153. command: 'create',
  154. path: sample,
  155. file_text: 'one\ntwo\nthree\n',
  156. }))).toBe(`New file created successfully at: ${sample}`)
  157. expect(text(await call(ctx, owner, {
  158. command: 'view',
  159. path: sample,
  160. view_range: [2, -1],
  161. }))).toBe([
  162. `Here's the content of ${sample} with line numbers (which has a total of 4 lines) with view_range=[2, -1]:`,
  163. ' 2 two',
  164. ' 3 three',
  165. ' 4 ',
  166. '',
  167. ].join('\n'))
  168. expect(text(await call(ctx, owner, {
  169. command: 'str_replace',
  170. path: sample,
  171. old_str: 'two',
  172. new_str: 'TWO',
  173. }))).toBe(`The file ${sample} has been edited successfully.`)
  174. expect(text(await call(ctx, owner, {
  175. command: 'str_replace',
  176. path: sample,
  177. old_str: 'TWO',
  178. }))).toBe(`The file ${sample} has been edited successfully.`)
  179. expect(text(await call(ctx, owner, {
  180. command: 'insert',
  181. path: sample,
  182. insert_line: 1,
  183. new_str: 'between',
  184. }))).toBe(`The file ${sample} has been edited successfully.`)
  185. expect(await readFile(sample, 'utf8')).toBe('one\nbetween\n\nthree\n')
  186. })
  187. it('writes replacement text literally', async () => {
  188. const { ctx, root, owner } = await setup()
  189. const sample = join(root, 'literal.txt')
  190. const replacement = "$&|$`|$'|$$"
  191. await writeFile(sample, 'before OLD after')
  192. expect((await call(ctx, owner, {
  193. command: 'str_replace',
  194. path: sample,
  195. old_str: 'OLD',
  196. new_str: replacement,
  197. })).isError).toBe(false)
  198. expect(await readFile(sample, 'utf8')).toBe(`before ${replacement} after`)
  199. })
  200. it('lists visible entries to depth two and clips at the configured view limit', async () => {
  201. const { ctx, root, owner } = await setup({ maxOutputChars: 10_000 })
  202. await mkdir(join(root, 'dir', 'nested', 'third'), { recursive: true })
  203. await mkdir(join(root, 'dir', 'node_modules', 'pkg'), { recursive: true })
  204. await mkdir(join(root, 'dir', 'node_modules_old'), { recursive: true })
  205. await mkdir(join(root, 'dir', '__pycache__'), { recursive: true })
  206. await mkdir(join(root, 'dir', '__pycache__backup'), { recursive: true })
  207. await writeFile(join(root, 'dir', 'visible.txt'), 'ok')
  208. await writeFile(join(root, 'dir', '.hidden'), 'hidden')
  209. await writeFile(join(root, 'dir', 'nested', 'child.txt'), 'child')
  210. await writeFile(join(root, 'dir', 'nested', 'third', 'too-deep.txt'), 'deep')
  211. await writeFile(join(root, 'dir', 'node_modules', 'pkg', 'index.js'), 'hidden dependency')
  212. await writeFile(join(root, 'dir', 'node_modules_old', 'kept.js'), 'visible source')
  213. await writeFile(join(root, 'dir', '__pycache__', 'module.pyc'), 'cache')
  214. await writeFile(join(root, 'dir', '__pycache__backup', 'kept.py'), 'visible source')
  215. const listDir = ctx.fs.listDir.bind(ctx.fs)
  216. const otherTarget = await ctx.fs.resolve(join(root, 'dir', 'other'))
  217. ctx.fs.listDir = async (target, signal) => {
  218. const entries = await listDir(target, signal)
  219. return target.displayPath === join(root, 'dir')
  220. ? [
  221. { name: 'same-target', type: 'other', target: otherTarget },
  222. { name: 'other', type: 'other', target: otherTarget },
  223. ...entries.toReversed(),
  224. ]
  225. : entries
  226. }
  227. const listing = text(await call(ctx, owner, { command: 'view', path: join(root, 'dir') }))
  228. expect(listing).not.toContain('.hidden')
  229. expect(listing).not.toContain('too-deep.txt')
  230. expect(listing).not.toContain('index.js')
  231. expect(listing).not.toContain('module.pyc')
  232. // The listing carries absolute display paths; the POSIX-style substrings
  233. // only match on Linux, so assert with platform separators.
  234. expect(listing).toContain(join('node_modules_old', 'kept.js'))
  235. expect(listing).toContain(join('__pycache__backup', 'kept.py'))
  236. const clipped = await setup({ maxOutputChars: 10 })
  237. await writeFile(join(clipped.root, 'large.txt'), 'x'.repeat(100))
  238. expect(text(await call(clipped.ctx, clipped.owner, {
  239. command: 'view',
  240. path: join(clipped.root, 'large.txt'),
  241. })))
  242. .toContain('<response clipped>')
  243. })
  244. it('matches canonical empty-line, range, and end-insert behavior', async () => {
  245. const { ctx, root, owner } = await setup()
  246. const empty = join(root, 'empty.txt')
  247. const newline = join(root, 'newline.txt')
  248. const plain = join(root, 'plain.txt')
  249. await writeFile(empty, '')
  250. await writeFile(newline, '\n')
  251. await writeFile(plain, 'one\ntwo')
  252. expect(text(await call(ctx, owner, { command: 'view', path: empty })))
  253. .toContain('(which has a total of 1 lines):\n 1 \n')
  254. expect(text(await call(ctx, owner, { command: 'view', path: newline })))
  255. .toContain('(which has a total of 2 lines):\n 1 \n 2 \n')
  256. expect(text(await call(ctx, owner, {
  257. command: 'view',
  258. path: plain,
  259. view_range: [1, 2],
  260. }))).toContain(' 2 two')
  261. expect(text(await call(ctx, undefined, {
  262. command: 'view',
  263. path: plain,
  264. }))).toContain(' 1 one')
  265. expect((await call(ctx, undefined, {
  266. command: 'create',
  267. path: join(root, 'ownerless.txt'),
  268. file_text: 'ownerless',
  269. })).isError).toBe(false)
  270. await call(ctx, owner, {
  271. command: 'insert',
  272. path: plain,
  273. insert_line: 2,
  274. new_str: 'three',
  275. })
  276. expect(await readFile(plain, 'utf8')).toBe('one\ntwo\nthree')
  277. await writeFile(newline, 'one\n')
  278. await call(ctx, owner, {
  279. command: 'insert',
  280. path: newline,
  281. insert_line: 2,
  282. new_str: 'three',
  283. })
  284. expect(await readFile(newline, 'utf8')).toBe('one\n\nthree')
  285. })
  286. it('uses old_str-only replacement failures and rejects relative paths', async () => {
  287. const { ctx, root, owner } = await setup()
  288. const ambiguous = join(root, 'ambiguous.txt')
  289. await writeFile(ambiguous, 'same\nother\nsame')
  290. const missing = await call(ctx, owner, {
  291. command: 'str_replace',
  292. path: ambiguous,
  293. old_str: 'absent',
  294. new_str: 'x',
  295. })
  296. expect(missing.isError).toBe(true)
  297. expect(text(missing)).toContain(`old_str \`absent\` did not appear verbatim in ${ambiguous}`)
  298. expect(text(missing)).not.toContain('old_string')
  299. const repeated = await call(ctx, owner, {
  300. command: 'str_replace',
  301. path: ambiguous,
  302. old_str: 'same',
  303. new_str: 'x',
  304. })
  305. expect(repeated.isError).toBe(true)
  306. expect(text(repeated)).toContain('Multiple occurrences of old_str `same` in lines [1, 3]')
  307. expect(text(repeated)).not.toContain('replace_all')
  308. await writeFile(ambiguous, 'alpha\nbeta\nmiddle\nalpha\nbeta')
  309. const repeatedMultiline = await call(ctx, owner, {
  310. command: 'str_replace',
  311. path: ambiguous,
  312. old_str: 'alpha\nbeta',
  313. new_str: 'x',
  314. })
  315. expect(text(repeatedMultiline))
  316. .toContain('Multiple occurrences of old_str `alpha\nbeta` in lines [1, 4]')
  317. const mixedEol = join(root, 'mixed-eol.txt')
  318. await writeFile(mixedEol, 'alpha\r\nbeta\nmiddle\nalpha\nbeta')
  319. expect((await call(ctx, owner, {
  320. command: 'str_replace',
  321. path: mixedEol,
  322. old_str: 'alpha\r\nbeta',
  323. new_str: 'replaced',
  324. })).isError).toBe(false)
  325. expect(await readFile(mixedEol, 'utf8')).toBe('replaced\nmiddle\nalpha\nbeta')
  326. const relative = await call(ctx, owner, { command: 'view', path: 'ambiguous.txt' })
  327. expect(relative.isError).toBe(true)
  328. expect(text(relative)).toContain('is not an absolute path')
  329. expect(await readFile(ambiguous, 'utf8')).toBe('alpha\nbeta\nmiddle\nalpha\nbeta')
  330. })
  331. it('reports invalid commands or arguments without mutating files', async () => {
  332. const { ctx, root, owner } = await setup()
  333. const ambiguous = join(root, 'ambiguous.txt')
  334. const empty = join(root, 'empty.txt')
  335. const trailingNewline = join(root, 'trailing-newline.txt')
  336. const threeLines = join(root, 'three-lines.txt')
  337. const directory = join(root, 'directory')
  338. await writeFile(ambiguous, 'same same')
  339. await writeFile(empty, '')
  340. await writeFile(trailingNewline, 'one\n')
  341. await writeFile(threeLines, 'one\ntwo\nthree')
  342. await mkdir(directory)
  343. const cases = [
  344. { command: 'view', path: '' },
  345. { command: 'view', path: join(root, 'missing.txt') },
  346. { command: 'view', path: ambiguous, view_range: [1] },
  347. { command: 'view', path: ambiguous, view_range: [0, 1] },
  348. { command: 'view', path: ambiguous, view_range: [1.5, 2] },
  349. { command: 'view', path: threeLines, view_range: [1, 99] },
  350. { command: 'view', path: threeLines, view_range: [2, 1] },
  351. { command: 'view', path: directory, view_range: [1, 1] },
  352. { command: 'create', path: join(root, 'new.txt') },
  353. { command: 'create', path: ambiguous, file_text: 'overwrite' },
  354. { command: 'str_replace', path: ambiguous, new_str: 'x' },
  355. { command: 'str_replace', path: ambiguous, old_str: '', new_str: 'x' },
  356. { command: 'insert', path: ambiguous, new_str: 'x' },
  357. { command: 'insert', path: ambiguous, insert_line: -1, new_str: 'x' },
  358. { command: 'insert', path: ambiguous, insert_line: 1.5, new_str: 'x' },
  359. { command: 'insert', path: ambiguous, insert_line: 99, new_str: 'x' },
  360. { command: 'insert', path: empty, insert_line: 2, new_str: 'x' },
  361. { command: 'insert', path: directory, insert_line: 0, new_str: 'x' },
  362. ]
  363. for (const args of cases) {
  364. expect((await call(ctx, owner, args)).isError).toBe(true)
  365. }
  366. expect(await readFile(ambiguous, 'utf8')).toBe('same same')
  367. ctx.fs.stat = async () => ({ version: FsVersion('special'), type: 'other' })
  368. const special = await call(ctx, owner, { command: 'view', path: join(root, 'special') })
  369. expect(special.isError).toBe(true)
  370. expect(special.error).toMatchObject({ info: { code: 'FS_NOT_REGULAR_FILE' } })
  371. expect((await call(ctx, owner, {
  372. command: 'str_replace',
  373. path: join(root, 'special'),
  374. old_str: 'x',
  375. new_str: 'y',
  376. })).error).toMatchObject({ info: { code: 'FS_NOT_REGULAR_FILE' } })
  377. expect((await call(ctx, owner, {
  378. command: 'insert',
  379. path: join(root, 'special'),
  380. insert_line: 0,
  381. new_str: 'x',
  382. })).error).toMatchObject({ info: { code: 'FS_NOT_REGULAR_FILE' } })
  383. })
  384. it('delegates read-before-edit decisions to fs-policy', async () => {
  385. const { ctx, root, owner } = await setup({}, { fsPolicy: true })
  386. const existing = join(root, 'existing.txt')
  387. const created = join(root, 'created.txt')
  388. await writeFile(existing, 'before')
  389. const blindEdit = await call(ctx, owner, {
  390. command: 'str_replace',
  391. path: existing,
  392. old_str: 'before',
  393. new_str: 'after',
  394. })
  395. expect(blindEdit.error).toMatchObject({ info: { code: 'FS_NOT_OBSERVED' } })
  396. expect(await readFile(existing, 'utf8')).toBe('before')
  397. await call(ctx, owner, { command: 'view', path: existing })
  398. expect((await call(ctx, owner, {
  399. command: 'str_replace',
  400. path: existing,
  401. old_str: 'before',
  402. new_str: 'after',
  403. })).isError).toBe(false)
  404. expect(await readFile(existing, 'utf8')).toBe('after')
  405. expect((await call(ctx, owner, {
  406. command: 'insert',
  407. path: existing,
  408. insert_line: 1,
  409. new_str: 'tail',
  410. })).isError).toBe(false)
  411. expect(await readFile(existing, 'utf8')).toBe('after\ntail')
  412. expect((await call(ctx, owner, {
  413. command: 'create',
  414. path: created,
  415. file_text: 'new',
  416. })).isError).toBe(false)
  417. expect(await readFile(created, 'utf8')).toBe('new')
  418. })
  419. it('passes the session sandbox policy to every mutation', async () => {
  420. const { ctx, root, owner } = await setup({}, { sandboxMode: 'read-only' })
  421. const path = join(root, 'blocked.txt')
  422. const result = await call(ctx, owner, {
  423. command: 'create',
  424. path,
  425. file_text: 'blocked',
  426. })
  427. expect(result.error).toMatchObject({ info: { code: 'FS_SANDBOX_DENIED' } })
  428. expect(text(result)).toContain('[sandbox: file access denied under read-only mode]')
  429. const ownerless = await call(ctx, undefined, {
  430. command: 'create',
  431. path: join(root, 'ownerless-blocked.txt'),
  432. file_text: 'blocked',
  433. })
  434. expect(ownerless.error).toMatchObject({ info: { code: 'FS_SANDBOX_DENIED' } })
  435. })
  436. it('preserves tabs outside the edited region', async () => {
  437. const { ctx, root, owner } = await setup()
  438. const path = join(root, 'Makefile')
  439. await writeFile(path, 'target:\n\told\nremove\n')
  440. expect(text(await call(ctx, owner, { command: 'view', path })))
  441. .toContain(' 2 \told')
  442. await call(ctx, owner, {
  443. command: 'str_replace',
  444. path,
  445. old_str: '\told',
  446. new_str: '\tnew',
  447. })
  448. await call(ctx, owner, {
  449. command: 'str_replace',
  450. path,
  451. old_str: 'remove\n',
  452. })
  453. await call(ctx, owner, {
  454. command: 'insert',
  455. path,
  456. insert_line: 1,
  457. new_str: '\tkept',
  458. })
  459. expect(await readFile(path, 'utf8')).toBe('target:\n\tkept\n\tnew\n')
  460. })
  461. it('reports missing sandbox-policy composition during plugin startup', async () => {
  462. const root = await mkdtemp(join(tmpdir(), 'dsh-tool-str-replace-editor-missing-policy-'))
  463. roots.push(root)
  464. const ctx = new Context()
  465. contexts.push(ctx)
  466. await ctx.plugin(SystemPrompt)
  467. await ctx.plugin(ToolRegistry)
  468. await ctx.plugin(AgentRegistry)
  469. await ctx.plugin(LocalFileSystem, { cwd: root })
  470. Object.defineProperty(ctx.fs, 'sandboxMode', { value: 'read-only' })
  471. await expect(ctx.plugin(ToolStrReplaceEditor))
  472. .rejects.toThrow('the mounted filesystem confines but ctx.sandboxPolicy is missing')
  473. })
  474. it('maps unexpected backend write failures for replace and insert', async () => {
  475. const { ctx, root, owner } = await setup()
  476. const path = join(root, 'backend-error.txt')
  477. await writeFile(path, 'old\n')
  478. const failWrite = async (): Promise<never> => {
  479. throw new Error('backend write failed')
  480. }
  481. ctx.fs.writeText = failWrite
  482. const replace = await call(ctx, owner, {
  483. command: 'str_replace',
  484. path,
  485. old_str: 'old',
  486. new_str: 'new',
  487. })
  488. expect(replace.isError).toBe(true)
  489. expect(text(replace)).toContain('backend write failed')
  490. const insert = await call(ctx, owner, {
  491. command: 'insert',
  492. path,
  493. insert_line: 1,
  494. new_str: 'new',
  495. })
  496. expect(insert.isError).toBe(true)
  497. expect(text(insert)).toContain('backend write failed')
  498. })
  499. it('rejects invalid plugin config', () => {
  500. expect(() => {
  501. ToolStrReplaceEditor.apply(new Context(), { maxOutputChars: 0 })
  502. }).toThrow('maxOutputChars must be a positive safe integer')
  503. expect(() => {
  504. ToolStrReplaceEditor.apply(new Context(), { description: ' ' })
  505. }).toThrow('description must be non-empty')
  506. })
  507. })