tools.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import { afterEach, describe, expect, it } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { CallId } from '@deepseek-ai/dsh-llm'
  4. import { Session, SessionId } from '@deepseek-ai/dsh-session'
  5. import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
  6. import type { Agent } from '@deepseek-ai/dsh-agent'
  7. import TerminalSessionService from '@deepseek-ai/dsh-terminal'
  8. import type {
  9. TerminalBackend,
  10. TerminalBackendSession,
  11. TerminalReadRequest,
  12. TerminalSendOperation,
  13. TerminalSendRequest,
  14. TerminalSessionStatus,
  15. TerminalSignal,
  16. TerminalWaitReason,
  17. } from '@deepseek-ai/dsh-terminal'
  18. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  19. import ToolRuntime from '@deepseek-ai/dsh-tools'
  20. import * as ToolBashPersistent from '@deepseek-ai/dsh-tool-bash-persistent'
  21. const contexts: Context[] = []
  22. let callNumber = 0
  23. afterEach(async () => {
  24. for (const ctx of contexts.splice(0)) await ctx.fiber.dispose()
  25. })
  26. function agent(ctx: Context, cwd: string | undefined): Agent {
  27. const id = SessionId(`persistent-bash-owner-${callNumber}`)
  28. const scope = ctx.plugin(() => {})
  29. const session = Session.create(id, [], {
  30. version: 0,
  31. id,
  32. createdAt: 0,
  33. ...cwd === undefined ? {} : { cwd },
  34. })
  35. const value: Agent = {
  36. id,
  37. options: {},
  38. session,
  39. inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }),
  40. status: 'idle',
  41. ctx: scope.ctx,
  42. send: () => {},
  43. followup: () => {},
  44. steer: () => ({ outcome: Promise.resolve({ status: 'rejected' as const }) }),
  45. inject: () => {},
  46. cancel() {},
  47. runMaintenance: task => task(new AbortController().signal),
  48. whenIdle: () => Promise.resolve(),
  49. }
  50. ctx.agents.register(value)
  51. return value
  52. }
  53. function text(result: { content: { type: string; text?: string }[] }): string {
  54. return result.content.filter(block => block.type === 'text').map(block => block.text).join('')
  55. }
  56. function call(
  57. ctx: Context,
  58. owner: Agent | undefined,
  59. command: string,
  60. signal = new AbortController().signal,
  61. ) {
  62. return ctx.tools.execute({
  63. signal,
  64. callId: CallId(`persistent-bash-${++callNumber}`),
  65. name: 'bash',
  66. arguments: { command },
  67. ...owner === undefined ? {} : { agent: owner },
  68. })
  69. }
  70. type StubMode =
  71. | 'normal'
  72. | 'prompt-only'
  73. | 'prompt-crlf'
  74. | 'empty-read'
  75. | 'stalled-read'
  76. | 'exit'
  77. | 'signal-exit'
  78. | 'unknown-exit'
  79. | 'wait-for-abort'
  80. | 'end-on-abort'
  81. | 'idle-then-normal'
  82. | 'large'
  83. | 'nonzero'
  84. | 'torn-status'
  85. | 'finish-torn-status'
  86. | 'end-only'
  87. | 'init-exit'
  88. | 'init-timeout'
  89. | 'spawn-error'
  90. | 'send-error'
  91. | 'prompt-after-idle'
  92. | 'incremental-fallback'
  93. | 'empty-page-after-latest'
  94. | 'paged-scrollback'
  95. | 'exit-after-send'
  96. class StubPtySession implements TerminalBackendSession {
  97. readonly motd = '__DSH_PERSISTENT_BASH_PROMPT__ '
  98. readonly pid = 123
  99. statusValue: TerminalSessionStatus = { kind: 'running' }
  100. scrollback = this.motd
  101. closed: string[] = []
  102. mode: StubMode
  103. sends = 0
  104. pendingText = ''
  105. historyTruncated = false
  106. throwOnSend = false
  107. constructor(mode: StubMode) {
  108. this.mode = mode
  109. }
  110. startSend(request: TerminalSendRequest): TerminalSendOperation {
  111. this.sends += 1
  112. if (request.text.startsWith('stty -echo')) {
  113. if (this.mode === 'init-exit') {
  114. this.statusValue = { kind: 'exited', exitCode: 1, signal: null }
  115. return this.operation(Promise.resolve(this.result('', 'session_exit')))
  116. }
  117. if (this.mode === 'init-timeout') {
  118. return this.operation(Promise.resolve(this.result('', 'timeout')))
  119. }
  120. return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read')))
  121. }
  122. if (this.mode === 'send-error') throw new Error('stub send failed')
  123. if (this.throwOnSend) throw new Error('PTY session has exited')
  124. if (this.mode === 'wait-for-abort' || this.mode === 'end-on-abort') {
  125. const done = new Promise<ReturnType<StubPtySession['result']>>((resolve) => {
  126. request.signal?.addEventListener('abort', () => {
  127. const start = /__DSH_PERSISTENT_BASH_START_[^_]+(?:-[^_]+)*__/.exec(request.text)?.[0]
  128. const end = /__DSH_PERSISTENT_BASH_END_[^:]+:/.exec(request.text)?.[0]
  129. const output = this.mode === 'end-on-abort'
  130. ? `${start ?? ''}\ninterrupted\n${end ?? ''}130\n${this.motd}`
  131. : 'partial output'
  132. this.scrollback += output
  133. resolve(this.result(output, 'stdin_read'))
  134. }, { once: true })
  135. })
  136. return this.operation(done)
  137. }
  138. if (this.mode === 'idle-then-normal') {
  139. this.mode = 'normal'
  140. this.pendingText = request.text
  141. return this.operation(Promise.resolve(this.result('', 'inferred_idle')))
  142. }
  143. if (this.mode === 'prompt-after-idle') {
  144. if (request.text.length > 0) {
  145. const start = /__DSH_PERSISTENT_BASH_START_[^_]+(?:-[^_]+)*__/.exec(request.text)?.[0]
  146. const output = `${start ?? ''}\npartial syntax output\n`
  147. this.scrollback += output
  148. return this.operation(Promise.resolve(this.result(output, 'inferred_idle')))
  149. }
  150. const output = `bash: syntax error\n${this.motd}`
  151. this.scrollback += output
  152. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  153. }
  154. if (this.mode === 'prompt-only' || this.mode === 'prompt-crlf') {
  155. const newline = this.mode === 'prompt-crlf' ? '\r\n' : '\n'
  156. const output = `bash: syntax error${newline}${this.motd}${newline}`
  157. this.scrollback += output
  158. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  159. }
  160. const sent = request.text.length > 0 ? request.text : this.pendingText
  161. this.pendingText = ''
  162. const start = /__DSH_PERSISTENT_BASH_START_[^_]+(?:-[^_]+)*__/.exec(sent)?.[0]
  163. const end = /__DSH_PERSISTENT_BASH_END_[^:]+:/.exec(sent)?.[0]
  164. if (this.mode === 'incremental-fallback') {
  165. const incremental = `${start ?? ''}\nincrement\n${this.motd}`
  166. return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read')), incremental)
  167. }
  168. if (this.mode === 'exit-after-send') {
  169. // A fast `exit` settles the send while the exit event is still in
  170. // flight; the shell flips to exited before the tool's next poll,
  171. // exactly like the real backend. The tool must re-observe status
  172. // instead of sending.
  173. const output = `${start ?? ''}\n`
  174. this.scrollback += output
  175. const settled = this.result(output, 'inferred_idle')
  176. this.statusValue = { kind: 'exited', exitCode: 9, signal: null }
  177. this.throwOnSend = true
  178. return this.operation(Promise.resolve(settled))
  179. }
  180. if (this.mode === 'torn-status') {
  181. const output = `${start ?? ''}\nhello from stub\n${end ?? ''}`
  182. this.scrollback += output
  183. this.mode = 'finish-torn-status'
  184. return this.operation(Promise.resolve(this.result(output, 'inferred_idle')))
  185. }
  186. if (this.mode === 'finish-torn-status') {
  187. const output = `7\n${this.motd}`
  188. this.scrollback += output
  189. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  190. }
  191. if (this.mode === 'end-only') {
  192. const output = `recovered output\n${end ?? ''}0\n${this.motd}`
  193. this.scrollback += output
  194. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  195. }
  196. const commandOutput = this.mode === 'large'
  197. ? 'x'.repeat(100)
  198. : this.mode === 'nonzero' ? '' : 'hello from stub'
  199. const exitCode = this.mode === 'nonzero' ? 7 : 0
  200. const output = `${start ?? ''}\n${commandOutput}\n${end ?? ''}${exitCode}\n${this.motd}`
  201. this.scrollback += output
  202. if (this.mode === 'exit' || this.mode === 'signal-exit' || this.mode === 'unknown-exit') {
  203. const exitedOutput = `${start ?? ''}\nhello from stub\n`
  204. this.scrollback = this.scrollback.slice(0, -output.length) + exitedOutput
  205. this.statusValue = this.mode === 'signal-exit'
  206. ? { kind: 'exited', exitCode: null, signal: 'SIGTERM' }
  207. : this.mode === 'exit'
  208. ? { kind: 'exited', exitCode: 9, signal: null }
  209. : { kind: 'exited', exitCode: null, signal: null }
  210. return this.operation(Promise.resolve(this.result(exitedOutput, 'session_exit')))
  211. }
  212. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  213. }
  214. read(request: TerminalReadRequest) {
  215. if (this.mode === 'empty-read') {
  216. return { text: '', totalLines: 0, lineBegin: 0, lineEnd: 0, truncated: false }
  217. }
  218. if (this.mode === 'stalled-read') {
  219. return { text: 'stalled', totalLines: 1, lineBegin: 0, lineEnd: 0, truncated: false }
  220. }
  221. if (this.mode === 'empty-page-after-latest' && (request.offset ?? 0) > 0) {
  222. return { text: '', totalLines: 2, lineBegin: 1, lineEnd: 1, truncated: false }
  223. }
  224. const lines = this.scrollback.split('\n')
  225. if (this.mode === 'paged-scrollback') {
  226. const offset = request.offset ?? 0
  227. const end = lines.length - offset
  228. const start = Math.max(0, end - 3)
  229. const returnedLines = end - start
  230. return {
  231. text: lines.slice(start, end).join('\n'),
  232. totalLines: lines.length,
  233. lineBegin: offset,
  234. lineEnd: offset + returnedLines,
  235. truncated: this.historyTruncated,
  236. }
  237. }
  238. return {
  239. text: this.scrollback,
  240. totalLines: this.mode === 'empty-page-after-latest' ? lines.length + 1 : lines.length,
  241. lineBegin: 0,
  242. lineEnd: this.mode === 'empty-page-after-latest' ? 1 : lines.length,
  243. truncated: this.historyTruncated,
  244. }
  245. }
  246. signal(_signal: TerminalSignal) {
  247. return Promise.resolve({ delivered: true as const, targetPgid: 123 })
  248. }
  249. status() {
  250. return this.statusValue
  251. }
  252. async close(reason: string) {
  253. this.closed.push(reason)
  254. this.statusValue = { kind: 'exited', exitCode: 0, signal: null }
  255. }
  256. private result(viewport: string, waitReason: TerminalWaitReason) {
  257. return { viewport, waitReason, sessionStatus: this.statusValue, truncated: false }
  258. }
  259. private operation(done: Promise<ReturnType<StubPtySession['result']>>, delta = ''): TerminalSendOperation {
  260. return {
  261. done,
  262. readOutput: () => ({ delta, truncated: false }),
  263. cancel: () => false,
  264. }
  265. }
  266. }
  267. function stubBackend(initialMode: StubMode = 'normal') {
  268. const sessions: StubPtySession[] = []
  269. const backend: TerminalBackend = {
  270. type: 'stub',
  271. async spawn() {
  272. if (initialMode === 'spawn-error') throw new Error('stub spawn failed')
  273. const session = new StubPtySession(initialMode)
  274. sessions.push(session)
  275. return session
  276. },
  277. }
  278. return { backend, sessions }
  279. }
  280. async function setup(
  281. config: ToolBashPersistent.Config = { backendType: 'stub' },
  282. initialMode: StubMode = 'normal',
  283. ) {
  284. const ctx = new Context()
  285. contexts.push(ctx)
  286. await ctx.plugin(SystemPrompt)
  287. await ctx.plugin(ToolRuntime)
  288. await ctx.plugin(AgentRegistry)
  289. await ctx.plugin(TerminalSessionService)
  290. const stub = stubBackend(initialMode)
  291. ctx.terminals.registerBackend(stub.backend)
  292. const fiber = await ctx.plugin(ToolBashPersistent, config)
  293. return { ctx, stub, fiber, owner: agent(ctx, '/workspace') }
  294. }
  295. describe('tool-bash-persistent', () => {
  296. it('registers a configurable schema and reuses one owner shell', async () => {
  297. const { ctx, owner, stub, fiber } = await setup({
  298. backendType: 'stub',
  299. description: 'deployment-specific persistent shell',
  300. })
  301. const schema = ctx.tools.schemas()[0]
  302. expect(ctx.tools.schemas().map(item => item.name)).toEqual(['bash'])
  303. expect(schema?.description).toBe('deployment-specific persistent shell')
  304. expect(schema?.parameters).toMatchObject({
  305. required: ['command'],
  306. properties: { command: { type: 'string' } },
  307. })
  308. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd' }))
  309. .toEqual({ card: 'terminal', title: 'pwd' })
  310. expect(text(await call(ctx, owner, 'echo one'))).toBe('hello from stub')
  311. expect(text(await call(ctx, owner, 'echo two'))).toBe('hello from stub')
  312. expect(stub.sessions).toHaveLength(1)
  313. expect(stub.sessions[0]?.sends).toBe(3)
  314. const ownerWithoutCwd = agent(ctx, undefined)
  315. expect(text(await call(ctx, ownerWithoutCwd, 'pwd'))).toBe('hello from stub')
  316. expect(stub.sessions).toHaveLength(2)
  317. await fiber.dispose()
  318. expect(ctx.tools.schemas()).toEqual([])
  319. expect(ctx.tools.get('bash')).toBeUndefined()
  320. })
  321. it('handles inferred idle, prompt fallback, shell exit, clipping, and cleanup', async () => {
  322. const { ctx, owner, stub, fiber } = await setup({
  323. backendType: 'stub',
  324. maxOutputChars: 10,
  325. })
  326. await call(ctx, owner, 'warm up')
  327. const session = stub.sessions[0]!
  328. session.mode = 'idle-then-normal'
  329. expect(text(await call(ctx, owner, 'silent then complete'))).toContain('hello from')
  330. session.mode = 'incremental-fallback'
  331. session.scrollback = ''
  332. expect(text(await call(ctx, owner, 'incremental fallback'))).toBe('increment')
  333. session.mode = 'prompt-only'
  334. const promptFallback = text(await call(ctx, owner, 'bad {'))
  335. expect(promptFallback).toContain('bash: synt')
  336. expect(promptFallback).not.toContain('DSH_PERSISTENT_BASH_PROMPT')
  337. session.mode = 'prompt-crlf'
  338. session.scrollback = ''
  339. const crlfPromptFallback = text(await call(ctx, owner, 'bad {'))
  340. expect(crlfPromptFallback).toContain('bash: synt')
  341. expect(crlfPromptFallback).not.toContain('DSH_PERSISTENT_BASH_PROMPT')
  342. session.mode = 'end-only'
  343. session.scrollback = ''
  344. const missingStart = text(await call(ctx, owner, 'recover marker'))
  345. expect(missingStart).toContain('recovered')
  346. expect(missingStart).toContain('beginning of this command output was dropped')
  347. expect(missingStart).toContain('<response clipped>')
  348. session.mode = 'large'
  349. expect(text(await call(ctx, owner, 'large'))).toContain('<response clipped>')
  350. session.mode = 'nonzero'
  351. expect(text(await call(ctx, owner, 'false'))).toBe('[exit code: 7]')
  352. session.mode = 'exit'
  353. const exited = text(await call(ctx, owner, 'exit'))
  354. expect(exited).toContain('hello from')
  355. expect(exited).toContain('[shell exited: code 9]')
  356. expect(exited).not.toContain('[exit code: 9]')
  357. expect(exited).toContain('next bash call starts from the workspace')
  358. expect(session.closed).toContain('persistent bash shell exited')
  359. await call(ctx, owner, 'new shell')
  360. expect(stub.sessions).toHaveLength(2)
  361. const replacement = stub.sessions[1]!
  362. replacement.mode = 'signal-exit'
  363. expect(text(await call(ctx, owner, 'kill shell')))
  364. .toContain('[shell killed by signal: SIGTERM]')
  365. await call(ctx, owner, 'another shell')
  366. expect(stub.sessions).toHaveLength(3)
  367. const externallyClosed = ctx.terminals.list(owner)[0]?.sessionId
  368. expect(externallyClosed).toBeDefined()
  369. await ctx.terminals.kill(owner, externallyClosed!, 'external cleanup')
  370. await fiber.dispose()
  371. expect(stub.sessions[2]?.closed).toEqual(['external cleanup'])
  372. })
  373. it('waits for status digits after a torn completion marker', async () => {
  374. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  375. await call(ctx, owner, 'warm up')
  376. stub.sessions[0]!.mode = 'torn-status'
  377. stub.sessions[0]!.scrollback = ''
  378. expect(text(await call(ctx, owner, 'torn status'))).toBe('hello from stub\n[exit code: 7]')
  379. })
  380. it('reports the exit path when the shell exits between send settlement and the next poll', async () => {
  381. const { ctx, owner, stub } = await setup({ backendType: 'stub' })
  382. await call(ctx, owner, 'warm up')
  383. const session = stub.sessions[0]!
  384. session.mode = 'exit-after-send'
  385. const result = text(await call(ctx, owner, 'exit'))
  386. expect(result).toContain('[shell exited: code 9]')
  387. expect(result).toContain('next bash call starts from the workspace')
  388. expect(session.closed).toContain('persistent bash shell exited')
  389. expect(text(await call(ctx, owner, 'echo "$PWD"'))).toBe('hello from stub')
  390. expect(stub.sessions).toHaveLength(2)
  391. })
  392. it('reports a shell exit when the backend has no code or signal', async () => {
  393. const { ctx, owner, stub } = await setup({ backendType: 'stub' })
  394. await call(ctx, owner, 'warm up')
  395. stub.sessions[0]!.mode = 'unknown-exit'
  396. expect(text(await call(ctx, owner, 'exit without status'))).toContain('[shell exited]')
  397. })
  398. it('marks a short missing-prefix result and tolerates exhausted scrollback pages', async () => {
  399. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  400. await call(ctx, owner, 'warm up')
  401. const session = stub.sessions[0]!
  402. session.mode = 'end-only'
  403. session.scrollback = ''
  404. expect(text(await call(ctx, owner, 'missing start')))
  405. .toContain('beginning of this command output was dropped')
  406. session.mode = 'empty-read'
  407. expect(text(await call(ctx, owner, 'empty page'))).toContain('hello from stub')
  408. session.mode = 'stalled-read'
  409. expect(text(await call(ctx, owner, 'stalled page'))).toContain('hello from stub')
  410. session.mode = 'empty-page-after-latest'
  411. expect(text(await call(ctx, owner, 'empty continuation page'))).toContain('hello from stub')
  412. })
  413. it('assembles retained output across backward scrollback pages', async () => {
  414. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  415. await call(ctx, owner, 'warm up')
  416. const session = stub.sessions[0]!
  417. session.mode = 'paged-scrollback'
  418. session.scrollback = 'older one\nolder two\nolder three\nolder four\n'
  419. expect(text(await call(ctx, owner, 'paged output'))).toBe('hello from stub')
  420. })
  421. it('sanitizes a prompt fallback reached after multiple polling rounds', async () => {
  422. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  423. await call(ctx, owner, 'warm up')
  424. const session = stub.sessions[0]!
  425. session.mode = 'prompt-after-idle'
  426. session.scrollback = ''
  427. const result = text(await call(ctx, owner, 'bad {'))
  428. expect(result).toContain('partial syntax output')
  429. expect(result).toContain('bash: syntax error')
  430. expect(result).not.toContain('DSH_PERSISTENT_BASH_PROMPT')
  431. expect(result).not.toContain('DSH_PERSISTENT_BASH_START')
  432. })
  433. it('does not attribute old scrollback truncation to a complete current command', async () => {
  434. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  435. await call(ctx, owner, 'warm up')
  436. stub.sessions[0]!.historyTruncated = true
  437. const result = text(await call(ctx, owner, 'short command'))
  438. expect(result).toBe('hello from stub')
  439. expect(result).not.toContain('<response clipped>')
  440. expect(result).not.toContain('beginning of this command output was dropped')
  441. })
  442. it('closes a timed-out shell and reports bounded partial output', async () => {
  443. const { ctx, owner, stub } = await setup({ backendType: 'stub', timeoutMs: 10 })
  444. await call(ctx, owner, 'warm up')
  445. stub.sessions[0]!.mode = 'wait-for-abort'
  446. const result = await call(ctx, owner, 'hang')
  447. expect(text(result)).toContain('timed out after 0 seconds or experienced an OOM error')
  448. expect(text(result)).toContain('partial output')
  449. expect(text(result)).toContain('next bash call starts from the workspace')
  450. expect(stub.sessions[0]?.closed).toContain('persistent bash command timed out')
  451. })
  452. it.each(['wait-for-abort', 'end-on-abort'] as const)(
  453. 'cancels %s work, resets the shell, and releases a queued call',
  454. async (mode) => {
  455. const { ctx, owner, stub } = await setup({ backendType: 'stub', timeoutMs: 5_000 })
  456. await call(ctx, owner, 'warm up')
  457. stub.sessions[0]!.mode = mode
  458. const controller = new AbortController()
  459. const cancelled = call(ctx, owner, 'hang', controller.signal)
  460. const queued = call(ctx, owner, 'after cancellation')
  461. setTimeout(() => {
  462. controller.abort(new Error('caller stopped'))
  463. }, 5)
  464. expect((await cancelled).isError).toBe(true)
  465. expect(text(await queued)).toBe('hello from stub')
  466. expect(stub.sessions[0]?.closed).toContain('persistent bash command aborted')
  467. expect(stub.sessions).toHaveLength(2)
  468. },
  469. )
  470. it.each(['init-exit', 'init-timeout'] as const)(
  471. 'fails initialization and closes the unusable shell for %s',
  472. async (mode) => {
  473. const { ctx, owner, stub } = await setup({ backendType: 'stub' }, mode)
  474. expect((await call(ctx, owner, 'pwd')).isError).toBe(true)
  475. expect(stub.sessions[0]?.closed).toContain('persistent bash initialization failed')
  476. },
  477. )
  478. it('clears a failed spawn without trying to close an unpublished shell', async () => {
  479. const { ctx, owner, stub } = await setup({ backendType: 'stub' }, 'spawn-error')
  480. expect((await call(ctx, owner, 'pwd')).isError).toBe(true)
  481. expect(stub.sessions).toHaveLength(0)
  482. })
  483. it('resets a cached shell after startSend fails', async () => {
  484. const { ctx, owner, stub } = await setup()
  485. await call(ctx, owner, 'warm up')
  486. stub.sessions[0]!.mode = 'send-error'
  487. expect((await call(ctx, owner, 'fails')).isError).toBe(true)
  488. expect(stub.sessions[0]?.closed).toContain('persistent bash send failed')
  489. expect(text(await call(ctx, owner, 'recovers'))).toBe('hello from stub')
  490. expect(stub.sessions).toHaveLength(2)
  491. })
  492. it('cancels and awaits a pending shell spawn when the plugin is disposed', async () => {
  493. const ctx = new Context()
  494. contexts.push(ctx)
  495. await ctx.plugin(SystemPrompt)
  496. await ctx.plugin(ToolRuntime)
  497. await ctx.plugin(AgentRegistry)
  498. await ctx.plugin(TerminalSessionService)
  499. const spawnStarted = Promise.withResolvers<undefined>()
  500. const spawnAborted = Promise.withResolvers<undefined>()
  501. ctx.terminals.registerBackend({
  502. type: 'slow',
  503. spawn: spec => new Promise((_resolve, reject) => {
  504. spawnStarted.resolve(undefined)
  505. spec.signal?.addEventListener('abort', () => {
  506. spawnAborted.resolve(undefined)
  507. const reason: unknown = spec.signal?.reason
  508. reject(reason instanceof Error
  509. ? reason
  510. : new Error('slow PTY spawn aborted', { cause: reason }))
  511. }, { once: true })
  512. }),
  513. })
  514. const fiber = await ctx.plugin(ToolBashPersistent, { backendType: 'slow' })
  515. const owner = agent(ctx, '/workspace')
  516. const running = call(ctx, owner, 'pwd')
  517. await spawnStarted.promise
  518. await fiber.dispose()
  519. await spawnAborted.promise
  520. expect((await running).isError).toBe(true)
  521. expect(ctx.terminals.list(owner)).toEqual([])
  522. })
  523. it('rejects invalid config and invalid calls', async () => {
  524. const { ctx, owner, stub } = await setup()
  525. expect((await call(ctx, undefined, 'pwd')).isError).toBe(true)
  526. expect(text(await call(ctx, owner, ' '))).toContain('command must be a non-empty string')
  527. const controller = new AbortController()
  528. controller.abort(new Error('caller stopped'))
  529. expect((await call(ctx, owner, 'pwd', controller.signal)).isError).toBe(true)
  530. expect(stub.sessions).toHaveLength(0)
  531. expect(() => {
  532. ToolBashPersistent.apply(new Context(), { backendType: '' })
  533. }).toThrow('backendType must be non-empty')
  534. expect(() => {
  535. ToolBashPersistent.apply(new Context(), { timeoutMs: 0 })
  536. }).toThrow('timeoutMs must be a positive safe integer')
  537. expect(() => {
  538. ToolBashPersistent.apply(new Context(), { maxOutputChars: 0 })
  539. }).toThrow('maxOutputChars must be a positive safe integer')
  540. expect(() => {
  541. ToolBashPersistent.apply(new Context(), { description: ' ' })
  542. }).toThrow('description must be non-empty')
  543. })
  544. })