tools.spec.ts 24 KB

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