tools.spec.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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 = 'stub> '
  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, stdin_read 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'))).toContain('increment')
  333. session.mode = 'prompt-only'
  334. const promptFallback = text(await call(ctx, owner, 'bad {'))
  335. expect(promptFallback).toContain('bash: synt')
  336. session.mode = 'prompt-crlf'
  337. session.scrollback = ''
  338. const crlfPromptFallback = text(await call(ctx, owner, 'bad {'))
  339. expect(crlfPromptFallback).toContain('bash: synt')
  340. session.mode = 'end-only'
  341. session.scrollback = ''
  342. const missingStart = text(await call(ctx, owner, 'recover marker'))
  343. expect(missingStart).toContain('recovered')
  344. expect(missingStart).toContain('beginning of this command output was dropped')
  345. expect(missingStart).toContain('<response clipped>')
  346. session.mode = 'large'
  347. expect(text(await call(ctx, owner, 'large'))).toContain('<response clipped>')
  348. session.mode = 'nonzero'
  349. expect(text(await call(ctx, owner, 'false'))).toBe('[exit code: 7]')
  350. session.mode = 'exit'
  351. const exited = text(await call(ctx, owner, 'exit'))
  352. expect(exited).toContain('hello from')
  353. expect(exited).toContain('[shell exited: code 9]')
  354. expect(exited).not.toContain('[exit code: 9]')
  355. expect(exited).toContain('next bash call starts from the workspace')
  356. expect(session.closed).toContain('persistent bash shell exited')
  357. await call(ctx, owner, 'new shell')
  358. expect(stub.sessions).toHaveLength(2)
  359. const replacement = stub.sessions[1]!
  360. replacement.mode = 'signal-exit'
  361. expect(text(await call(ctx, owner, 'kill shell')))
  362. .toContain('[shell killed by signal: SIGTERM]')
  363. await call(ctx, owner, 'another shell')
  364. expect(stub.sessions).toHaveLength(3)
  365. const externallyClosed = ctx.terminals.list(owner)[0]?.sessionId
  366. expect(externallyClosed).toBeDefined()
  367. await ctx.terminals.kill(owner, externallyClosed!, 'external cleanup')
  368. await fiber.dispose()
  369. expect(stub.sessions[2]?.closed).toEqual(['external cleanup'])
  370. })
  371. it('waits for status digits after a torn completion marker', async () => {
  372. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  373. await call(ctx, owner, 'warm up')
  374. stub.sessions[0]!.mode = 'torn-status'
  375. stub.sessions[0]!.scrollback = ''
  376. expect(text(await call(ctx, owner, 'torn status'))).toBe('hello from stub\n[exit code: 7]')
  377. })
  378. it('reports the exit path when the shell exits between send settlement and the next poll', async () => {
  379. const { ctx, owner, stub } = await setup({ backendType: 'stub' })
  380. await call(ctx, owner, 'warm up')
  381. const session = stub.sessions[0]!
  382. session.mode = 'exit-after-send'
  383. const result = text(await call(ctx, owner, 'exit'))
  384. expect(result).toContain('[shell exited: code 9]')
  385. expect(result).toContain('next bash call starts from the workspace')
  386. expect(session.closed).toContain('persistent bash shell exited')
  387. expect(text(await call(ctx, owner, 'echo "$PWD"'))).toBe('hello from stub')
  388. expect(stub.sessions).toHaveLength(2)
  389. })
  390. it('reports a shell exit when the backend has no code or signal', async () => {
  391. const { ctx, owner, stub } = await setup({ backendType: 'stub' })
  392. await call(ctx, owner, 'warm up')
  393. stub.sessions[0]!.mode = 'unknown-exit'
  394. expect(text(await call(ctx, owner, 'exit without status'))).toContain('[shell exited]')
  395. })
  396. it('marks a short missing-prefix result and tolerates exhausted scrollback pages', async () => {
  397. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  398. await call(ctx, owner, 'warm up')
  399. const session = stub.sessions[0]!
  400. session.mode = 'end-only'
  401. session.scrollback = ''
  402. expect(text(await call(ctx, owner, 'missing start')))
  403. .toContain('beginning of this command output was dropped')
  404. session.mode = 'empty-read'
  405. expect(text(await call(ctx, owner, 'empty page'))).toContain('hello from stub')
  406. session.mode = 'stalled-read'
  407. expect(text(await call(ctx, owner, 'stalled page'))).toContain('hello from stub')
  408. session.mode = 'empty-page-after-latest'
  409. expect(text(await call(ctx, owner, 'empty continuation page'))).toContain('hello from stub')
  410. })
  411. it('assembles retained output across backward scrollback pages', async () => {
  412. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  413. await call(ctx, owner, 'warm up')
  414. const session = stub.sessions[0]!
  415. session.mode = 'paged-scrollback'
  416. session.scrollback = 'older one\nolder two\nolder three\nolder four\n'
  417. expect(text(await call(ctx, owner, 'paged output'))).toBe('hello from stub')
  418. })
  419. it('returns a stdin_read fallback reached after multiple polling rounds', async () => {
  420. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  421. await call(ctx, owner, 'warm up')
  422. const session = stub.sessions[0]!
  423. session.mode = 'prompt-after-idle'
  424. session.scrollback = ''
  425. const result = text(await call(ctx, owner, 'bad {'))
  426. expect(result).toContain('partial syntax output')
  427. expect(result).toContain('bash: syntax error')
  428. // The backend owns the prompt text, so the fallback retains it verbatim.
  429. expect(result.endsWith('stub> ')).toBe(true)
  430. expect(result).not.toContain('DSH_PERSISTENT_BASH_START')
  431. })
  432. it('does not attribute old scrollback truncation to a complete current command', async () => {
  433. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  434. await call(ctx, owner, 'warm up')
  435. stub.sessions[0]!.historyTruncated = true
  436. const result = text(await call(ctx, owner, 'short command'))
  437. expect(result).toBe('hello from stub')
  438. expect(result).not.toContain('<response clipped>')
  439. expect(result).not.toContain('beginning of this command output was dropped')
  440. })
  441. it('closes a timed-out shell and reports bounded partial output', async () => {
  442. const { ctx, owner, stub } = await setup({ backendType: 'stub', timeoutMs: 10 })
  443. await call(ctx, owner, 'warm up')
  444. stub.sessions[0]!.mode = 'wait-for-abort'
  445. const result = await call(ctx, owner, 'hang')
  446. expect(text(result)).toContain('timed out after 0 seconds or experienced an OOM error')
  447. expect(text(result)).toContain('partial output')
  448. expect(text(result)).toContain('next bash call starts from the workspace')
  449. expect(stub.sessions[0]?.closed).toContain('persistent bash command timed out')
  450. })
  451. it.each(['wait-for-abort', 'end-on-abort'] as const)(
  452. 'cancels %s work, resets the shell, and releases a queued call',
  453. async (mode) => {
  454. const { ctx, owner, stub } = await setup({ backendType: 'stub', timeoutMs: 5_000 })
  455. await call(ctx, owner, 'warm up')
  456. stub.sessions[0]!.mode = mode
  457. const controller = new AbortController()
  458. const cancelled = call(ctx, owner, 'hang', controller.signal)
  459. const queued = call(ctx, owner, 'after cancellation')
  460. setTimeout(() => {
  461. controller.abort(new Error('caller stopped'))
  462. }, 5)
  463. expect((await cancelled).isError).toBe(true)
  464. expect(text(await queued)).toBe('hello from stub')
  465. expect(stub.sessions[0]?.closed).toContain('persistent bash command aborted')
  466. expect(stub.sessions).toHaveLength(2)
  467. },
  468. )
  469. it.each(['init-exit', 'init-timeout'] as const)(
  470. 'fails initialization and closes the unusable shell for %s',
  471. async (mode) => {
  472. const { ctx, owner, stub } = await setup({ backendType: 'stub' }, mode)
  473. expect((await call(ctx, owner, 'pwd')).isError).toBe(true)
  474. expect(stub.sessions[0]?.closed).toContain('persistent bash initialization failed')
  475. },
  476. )
  477. it('clears a failed spawn without trying to close an unpublished shell', async () => {
  478. const { ctx, owner, stub } = await setup({ backendType: 'stub' }, 'spawn-error')
  479. expect((await call(ctx, owner, 'pwd')).isError).toBe(true)
  480. expect(stub.sessions).toHaveLength(0)
  481. })
  482. it('resets a cached shell after startSend fails', async () => {
  483. const { ctx, owner, stub } = await setup()
  484. await call(ctx, owner, 'warm up')
  485. stub.sessions[0]!.mode = 'send-error'
  486. expect((await call(ctx, owner, 'fails')).isError).toBe(true)
  487. expect(stub.sessions[0]?.closed).toContain('persistent bash send failed')
  488. expect(text(await call(ctx, owner, 'recovers'))).toBe('hello from stub')
  489. expect(stub.sessions).toHaveLength(2)
  490. })
  491. it('cancels and awaits a pending shell spawn when the plugin is disposed', async () => {
  492. const ctx = new Context()
  493. contexts.push(ctx)
  494. await ctx.plugin(SystemPrompt)
  495. await ctx.plugin(ToolRuntime)
  496. await ctx.plugin(AgentRegistry)
  497. await ctx.plugin(TerminalSessionService)
  498. const spawnStarted = Promise.withResolvers<undefined>()
  499. const spawnAborted = Promise.withResolvers<undefined>()
  500. ctx.terminals.registerBackend({
  501. type: 'slow',
  502. spawn: spec => new Promise((_resolve, reject) => {
  503. spawnStarted.resolve(undefined)
  504. spec.signal?.addEventListener('abort', () => {
  505. spawnAborted.resolve(undefined)
  506. const reason: unknown = spec.signal?.reason
  507. reject(reason instanceof Error
  508. ? reason
  509. : new Error('slow PTY spawn aborted', { cause: reason }))
  510. }, { once: true })
  511. }),
  512. })
  513. const fiber = await ctx.plugin(ToolBashPersistent, { backendType: 'slow' })
  514. const owner = agent(ctx, '/workspace')
  515. const running = call(ctx, owner, 'pwd')
  516. await spawnStarted.promise
  517. await fiber.dispose()
  518. await spawnAborted.promise
  519. expect((await running).isError).toBe(true)
  520. expect(ctx.terminals.list(owner)).toEqual([])
  521. })
  522. it('rejects invalid config and invalid calls', async () => {
  523. const { ctx, owner, stub } = await setup()
  524. expect((await call(ctx, undefined, 'pwd')).isError).toBe(true)
  525. expect(text(await call(ctx, owner, ' '))).toContain('command must be a non-empty string')
  526. const controller = new AbortController()
  527. controller.abort(new Error('caller stopped'))
  528. expect((await call(ctx, owner, 'pwd', controller.signal)).isError).toBe(true)
  529. expect(stub.sessions).toHaveLength(0)
  530. expect(() => {
  531. ToolBashPersistent.apply(new Context(), { backendType: '' })
  532. }).toThrow('backendType must be non-empty')
  533. expect(() => {
  534. ToolBashPersistent.apply(new Context(), { timeoutMs: 0 })
  535. }).toThrow('timeoutMs must be a positive safe integer')
  536. expect(() => {
  537. ToolBashPersistent.apply(new Context(), { maxOutputChars: 0 })
  538. }).toThrow('maxOutputChars must be a positive safe integer')
  539. expect(() => {
  540. ToolBashPersistent.apply(new Context(), { description: ' ' })
  541. }).toThrow('description must be non-empty')
  542. })
  543. })