tools.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. class StubPtySession implements TerminalBackendSession {
  96. readonly motd = 'stub> '
  97. readonly pid = 123
  98. statusValue: TerminalSessionStatus = { kind: 'running' }
  99. scrollback = this.motd
  100. closed: string[] = []
  101. mode: StubMode
  102. sends = 0
  103. pendingText = ''
  104. historyTruncated = false
  105. constructor(mode: StubMode) {
  106. this.mode = mode
  107. }
  108. startSend(request: TerminalSendRequest): TerminalSendOperation {
  109. this.sends += 1
  110. if (request.text.startsWith('stty -echo')) {
  111. if (this.mode === 'init-exit') {
  112. this.statusValue = { kind: 'exited', exitCode: 1, signal: null }
  113. return this.operation(Promise.resolve(this.result('', 'session_exit')))
  114. }
  115. if (this.mode === 'init-timeout') {
  116. return this.operation(Promise.resolve(this.result('', 'timeout')))
  117. }
  118. return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read')))
  119. }
  120. if (this.mode === 'send-error') throw new Error('stub send failed')
  121. if (this.mode === 'wait-for-abort' || this.mode === 'end-on-abort') {
  122. const done = new Promise<ReturnType<StubPtySession['result']>>((resolve) => {
  123. request.signal?.addEventListener('abort', () => {
  124. const start = /__DSH_PERSISTENT_BASH_START_[^_]+(?:-[^_]+)*__/.exec(request.text)?.[0]
  125. const end = /__DSH_PERSISTENT_BASH_END_[^:]+:/.exec(request.text)?.[0]
  126. const output = this.mode === 'end-on-abort'
  127. ? `${start ?? ''}\ninterrupted\n${end ?? ''}130\n${this.motd}`
  128. : 'partial output'
  129. this.scrollback += output
  130. resolve(this.result(output, 'stdin_read'))
  131. }, { once: true })
  132. })
  133. return this.operation(done)
  134. }
  135. if (this.mode === 'idle-then-normal') {
  136. this.mode = 'normal'
  137. this.pendingText = request.text
  138. return this.operation(Promise.resolve(this.result('', 'inferred_idle')))
  139. }
  140. if (this.mode === 'prompt-after-idle') {
  141. if (request.text.length > 0) {
  142. const start = /__DSH_PERSISTENT_BASH_START_[^_]+(?:-[^_]+)*__/.exec(request.text)?.[0]
  143. const output = `${start ?? ''}\npartial syntax output\n`
  144. this.scrollback += output
  145. return this.operation(Promise.resolve(this.result(output, 'inferred_idle')))
  146. }
  147. const output = `bash: syntax error\n${this.motd}`
  148. this.scrollback += output
  149. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  150. }
  151. if (this.mode === 'prompt-only' || this.mode === 'prompt-crlf') {
  152. const newline = this.mode === 'prompt-crlf' ? '\r\n' : '\n'
  153. const output = `bash: syntax error${newline}${this.motd}${newline}`
  154. this.scrollback += output
  155. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  156. }
  157. const sent = request.text.length > 0 ? request.text : this.pendingText
  158. this.pendingText = ''
  159. const start = /__DSH_PERSISTENT_BASH_START_[^_]+(?:-[^_]+)*__/.exec(sent)?.[0]
  160. const end = /__DSH_PERSISTENT_BASH_END_[^:]+:/.exec(sent)?.[0]
  161. if (this.mode === 'incremental-fallback') {
  162. const incremental = `${start ?? ''}\nincrement\n${this.motd}`
  163. return this.operation(Promise.resolve(this.result(this.motd, 'stdin_read')), incremental)
  164. }
  165. if (this.mode === 'torn-status') {
  166. const output = `${start ?? ''}\nhello from stub\n${end ?? ''}`
  167. this.scrollback += output
  168. this.mode = 'finish-torn-status'
  169. return this.operation(Promise.resolve(this.result(output, 'inferred_idle')))
  170. }
  171. if (this.mode === 'finish-torn-status') {
  172. const output = `7\n${this.motd}`
  173. this.scrollback += output
  174. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  175. }
  176. if (this.mode === 'end-only') {
  177. const output = `recovered output\n${end ?? ''}0\n${this.motd}`
  178. this.scrollback += output
  179. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  180. }
  181. const commandOutput = this.mode === 'large'
  182. ? 'x'.repeat(100)
  183. : this.mode === 'nonzero' ? '' : 'hello from stub'
  184. const exitCode = this.mode === 'nonzero' ? 7 : 0
  185. const output = `${start ?? ''}\n${commandOutput}\n${end ?? ''}${exitCode}\n${this.motd}`
  186. this.scrollback += output
  187. if (this.mode === 'exit' || this.mode === 'signal-exit' || this.mode === 'unknown-exit') {
  188. const exitedOutput = `${start ?? ''}\nhello from stub\n`
  189. this.scrollback = this.scrollback.slice(0, -output.length) + exitedOutput
  190. this.statusValue = this.mode === 'signal-exit'
  191. ? { kind: 'exited', exitCode: null, signal: 'SIGTERM' }
  192. : this.mode === 'exit'
  193. ? { kind: 'exited', exitCode: 9, signal: null }
  194. : { kind: 'exited', exitCode: null, signal: null }
  195. return this.operation(Promise.resolve(this.result(exitedOutput, 'session_exit')))
  196. }
  197. return this.operation(Promise.resolve(this.result(output, 'stdin_read')))
  198. }
  199. read(request: TerminalReadRequest) {
  200. if (this.mode === 'empty-read') {
  201. return { text: '', totalLines: 0, lineBegin: 0, lineEnd: 0, truncated: false }
  202. }
  203. if (this.mode === 'stalled-read') {
  204. return { text: 'stalled', totalLines: 1, lineBegin: 0, lineEnd: 0, truncated: false }
  205. }
  206. if (this.mode === 'empty-page-after-latest' && (request.offset ?? 0) > 0) {
  207. return { text: '', totalLines: 2, lineBegin: 1, lineEnd: 1, truncated: false }
  208. }
  209. const lines = this.scrollback.split('\n')
  210. if (this.mode === 'paged-scrollback') {
  211. const offset = request.offset ?? 0
  212. const end = lines.length - offset
  213. const start = Math.max(0, end - 3)
  214. const returnedLines = end - start
  215. return {
  216. text: lines.slice(start, end).join('\n'),
  217. totalLines: lines.length,
  218. lineBegin: offset,
  219. lineEnd: offset + returnedLines,
  220. truncated: this.historyTruncated,
  221. }
  222. }
  223. return {
  224. text: this.scrollback,
  225. totalLines: this.mode === 'empty-page-after-latest' ? lines.length + 1 : lines.length,
  226. lineBegin: 0,
  227. lineEnd: this.mode === 'empty-page-after-latest' ? 1 : lines.length,
  228. truncated: this.historyTruncated,
  229. }
  230. }
  231. signal(_signal: TerminalSignal) {
  232. return Promise.resolve({ delivered: true as const, targetPgid: 123 })
  233. }
  234. status() {
  235. return this.statusValue
  236. }
  237. async close(reason: string) {
  238. this.closed.push(reason)
  239. this.statusValue = { kind: 'exited', exitCode: 0, signal: null }
  240. }
  241. private result(viewport: string, waitReason: TerminalWaitReason) {
  242. return { viewport, waitReason, sessionStatus: this.statusValue, truncated: false }
  243. }
  244. private operation(done: Promise<ReturnType<StubPtySession['result']>>, delta = ''): TerminalSendOperation {
  245. return {
  246. done,
  247. readOutput: () => ({ delta, truncated: false }),
  248. cancel: () => false,
  249. }
  250. }
  251. }
  252. function stubBackend(initialMode: StubMode = 'normal') {
  253. const sessions: StubPtySession[] = []
  254. const backend: TerminalBackend = {
  255. type: 'stub',
  256. async spawn() {
  257. if (initialMode === 'spawn-error') throw new Error('stub spawn failed')
  258. const session = new StubPtySession(initialMode)
  259. sessions.push(session)
  260. return session
  261. },
  262. }
  263. return { backend, sessions }
  264. }
  265. async function setup(
  266. config: ToolBashPersistent.Config = { backendType: 'stub' },
  267. initialMode: StubMode = 'normal',
  268. ) {
  269. const ctx = new Context()
  270. contexts.push(ctx)
  271. await ctx.plugin(SystemPrompt)
  272. await ctx.plugin(ToolRuntime)
  273. await ctx.plugin(AgentRegistry)
  274. await ctx.plugin(TerminalSessionService)
  275. const stub = stubBackend(initialMode)
  276. ctx.terminals.registerBackend(stub.backend)
  277. const fiber = await ctx.plugin(ToolBashPersistent, config)
  278. return { ctx, stub, fiber, owner: agent(ctx, '/workspace') }
  279. }
  280. describe('tool-bash-persistent', () => {
  281. it('registers a configurable schema and reuses one owner shell', async () => {
  282. const { ctx, owner, stub, fiber } = await setup({
  283. backendType: 'stub',
  284. description: 'deployment-specific persistent shell',
  285. })
  286. const schema = ctx.tools.schemas()[0]
  287. expect(ctx.tools.schemas().map(item => item.name)).toEqual(['bash'])
  288. expect(schema?.description).toBe('deployment-specific persistent shell')
  289. expect(schema?.parameters).toMatchObject({
  290. required: ['command'],
  291. properties: { command: { type: 'string' } },
  292. })
  293. expect(ctx.tools.get('bash')?.presentCall?.({ command: 'pwd' }))
  294. .toEqual({ card: 'terminal', title: 'pwd' })
  295. expect(text(await call(ctx, owner, 'echo one'))).toBe('hello from stub')
  296. expect(text(await call(ctx, owner, 'echo two'))).toBe('hello from stub')
  297. expect(stub.sessions).toHaveLength(1)
  298. expect(stub.sessions[0]?.sends).toBe(3)
  299. const ownerWithoutCwd = agent(ctx, undefined)
  300. expect(text(await call(ctx, ownerWithoutCwd, 'pwd'))).toBe('hello from stub')
  301. expect(stub.sessions).toHaveLength(2)
  302. await fiber.dispose()
  303. expect(ctx.tools.schemas()).toEqual([])
  304. expect(ctx.tools.get('bash')).toBeUndefined()
  305. })
  306. it('handles inferred idle, stdin_read fallback, shell exit, clipping, and cleanup', async () => {
  307. const { ctx, owner, stub, fiber } = await setup({
  308. backendType: 'stub',
  309. maxOutputChars: 10,
  310. })
  311. await call(ctx, owner, 'warm up')
  312. const session = stub.sessions[0]!
  313. session.mode = 'idle-then-normal'
  314. expect(text(await call(ctx, owner, 'silent then complete'))).toContain('hello from')
  315. session.mode = 'incremental-fallback'
  316. session.scrollback = ''
  317. expect(text(await call(ctx, owner, 'incremental fallback'))).toContain('increment')
  318. session.mode = 'prompt-only'
  319. const promptFallback = text(await call(ctx, owner, 'bad {'))
  320. expect(promptFallback).toContain('bash: synt')
  321. session.mode = 'prompt-crlf'
  322. session.scrollback = ''
  323. const crlfPromptFallback = text(await call(ctx, owner, 'bad {'))
  324. expect(crlfPromptFallback).toContain('bash: synt')
  325. session.mode = 'end-only'
  326. session.scrollback = ''
  327. const missingStart = text(await call(ctx, owner, 'recover marker'))
  328. expect(missingStart).toContain('recovered')
  329. expect(missingStart).toContain('beginning of this command output was dropped')
  330. expect(missingStart).toContain('<response clipped>')
  331. session.mode = 'large'
  332. expect(text(await call(ctx, owner, 'large'))).toContain('<response clipped>')
  333. session.mode = 'nonzero'
  334. expect(text(await call(ctx, owner, 'false'))).toBe('[exit code: 7]')
  335. session.mode = 'exit'
  336. const exited = text(await call(ctx, owner, 'exit'))
  337. expect(exited).toContain('hello from')
  338. expect(exited).toContain('[shell exited: code 9]')
  339. expect(exited).not.toContain('[exit code: 9]')
  340. expect(exited).toContain('next bash call starts from the workspace')
  341. expect(session.closed).toContain('persistent bash shell exited')
  342. await call(ctx, owner, 'new shell')
  343. expect(stub.sessions).toHaveLength(2)
  344. const replacement = stub.sessions[1]!
  345. replacement.mode = 'signal-exit'
  346. expect(text(await call(ctx, owner, 'kill shell')))
  347. .toContain('[shell killed by signal: SIGTERM]')
  348. await call(ctx, owner, 'another shell')
  349. expect(stub.sessions).toHaveLength(3)
  350. const externallyClosed = ctx.terminals.list(owner)[0]?.sessionId
  351. expect(externallyClosed).toBeDefined()
  352. await ctx.terminals.kill(owner, externallyClosed!, 'external cleanup')
  353. await fiber.dispose()
  354. expect(stub.sessions[2]?.closed).toEqual(['external cleanup'])
  355. })
  356. it('waits for status digits after a torn completion marker', async () => {
  357. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  358. await call(ctx, owner, 'warm up')
  359. stub.sessions[0]!.mode = 'torn-status'
  360. stub.sessions[0]!.scrollback = ''
  361. expect(text(await call(ctx, owner, 'torn status'))).toBe('hello from stub\n[exit code: 7]')
  362. })
  363. it('reports a shell exit when the backend has no code or signal', async () => {
  364. const { ctx, owner, stub } = await setup({ backendType: 'stub' })
  365. await call(ctx, owner, 'warm up')
  366. stub.sessions[0]!.mode = 'unknown-exit'
  367. expect(text(await call(ctx, owner, 'exit without status'))).toContain('[shell exited]')
  368. })
  369. it('marks a short missing-prefix result and tolerates exhausted scrollback pages', async () => {
  370. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  371. await call(ctx, owner, 'warm up')
  372. const session = stub.sessions[0]!
  373. session.mode = 'end-only'
  374. session.scrollback = ''
  375. expect(text(await call(ctx, owner, 'missing start')))
  376. .toContain('beginning of this command output was dropped')
  377. session.mode = 'empty-read'
  378. expect(text(await call(ctx, owner, 'empty page'))).toContain('hello from stub')
  379. session.mode = 'stalled-read'
  380. expect(text(await call(ctx, owner, 'stalled page'))).toContain('hello from stub')
  381. session.mode = 'empty-page-after-latest'
  382. expect(text(await call(ctx, owner, 'empty continuation page'))).toContain('hello from stub')
  383. })
  384. it('assembles retained output across backward scrollback pages', async () => {
  385. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  386. await call(ctx, owner, 'warm up')
  387. const session = stub.sessions[0]!
  388. session.mode = 'paged-scrollback'
  389. session.scrollback = 'older one\nolder two\nolder three\nolder four\n'
  390. expect(text(await call(ctx, owner, 'paged output'))).toBe('hello from stub')
  391. })
  392. it('returns a stdin_read fallback reached after multiple polling rounds', async () => {
  393. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  394. await call(ctx, owner, 'warm up')
  395. const session = stub.sessions[0]!
  396. session.mode = 'prompt-after-idle'
  397. session.scrollback = ''
  398. const result = text(await call(ctx, owner, 'bad {'))
  399. expect(result).toContain('partial syntax output')
  400. expect(result).toContain('bash: syntax error')
  401. // The backend owns the prompt text, so the fallback retains it verbatim.
  402. expect(result.endsWith('stub> ')).toBe(true)
  403. expect(result).not.toContain('DSH_PERSISTENT_BASH_START')
  404. })
  405. it('does not attribute old scrollback truncation to a complete current command', async () => {
  406. const { ctx, owner, stub } = await setup({ backendType: 'stub', maxOutputChars: 1_000 })
  407. await call(ctx, owner, 'warm up')
  408. stub.sessions[0]!.historyTruncated = true
  409. const result = text(await call(ctx, owner, 'short command'))
  410. expect(result).toBe('hello from stub')
  411. expect(result).not.toContain('<response clipped>')
  412. expect(result).not.toContain('beginning of this command output was dropped')
  413. })
  414. it('closes a timed-out shell and reports bounded partial output', async () => {
  415. const { ctx, owner, stub } = await setup({ backendType: 'stub', timeoutMs: 10 })
  416. await call(ctx, owner, 'warm up')
  417. stub.sessions[0]!.mode = 'wait-for-abort'
  418. const result = await call(ctx, owner, 'hang')
  419. expect(text(result)).toContain('timed out after 0 seconds or experienced an OOM error')
  420. expect(text(result)).toContain('partial output')
  421. expect(text(result)).toContain('next bash call starts from the workspace')
  422. expect(stub.sessions[0]?.closed).toContain('persistent bash command timed out')
  423. })
  424. it.each(['wait-for-abort', 'end-on-abort'] as const)(
  425. 'cancels %s work, resets the shell, and releases a queued call',
  426. async (mode) => {
  427. const { ctx, owner, stub } = await setup({ backendType: 'stub', timeoutMs: 5_000 })
  428. await call(ctx, owner, 'warm up')
  429. stub.sessions[0]!.mode = mode
  430. const controller = new AbortController()
  431. const cancelled = call(ctx, owner, 'hang', controller.signal)
  432. const queued = call(ctx, owner, 'after cancellation')
  433. setTimeout(() => {
  434. controller.abort(new Error('caller stopped'))
  435. }, 5)
  436. expect((await cancelled).isError).toBe(true)
  437. expect(text(await queued)).toBe('hello from stub')
  438. expect(stub.sessions[0]?.closed).toContain('persistent bash command aborted')
  439. expect(stub.sessions).toHaveLength(2)
  440. },
  441. )
  442. it.each(['init-exit', 'init-timeout'] as const)(
  443. 'fails initialization and closes the unusable shell for %s',
  444. async (mode) => {
  445. const { ctx, owner, stub } = await setup({ backendType: 'stub' }, mode)
  446. expect((await call(ctx, owner, 'pwd')).isError).toBe(true)
  447. expect(stub.sessions[0]?.closed).toContain('persistent bash initialization failed')
  448. },
  449. )
  450. it('clears a failed spawn without trying to close an unpublished shell', async () => {
  451. const { ctx, owner, stub } = await setup({ backendType: 'stub' }, 'spawn-error')
  452. expect((await call(ctx, owner, 'pwd')).isError).toBe(true)
  453. expect(stub.sessions).toHaveLength(0)
  454. })
  455. it('resets a cached shell after startSend fails', async () => {
  456. const { ctx, owner, stub } = await setup()
  457. await call(ctx, owner, 'warm up')
  458. stub.sessions[0]!.mode = 'send-error'
  459. expect((await call(ctx, owner, 'fails')).isError).toBe(true)
  460. expect(stub.sessions[0]?.closed).toContain('persistent bash send failed')
  461. expect(text(await call(ctx, owner, 'recovers'))).toBe('hello from stub')
  462. expect(stub.sessions).toHaveLength(2)
  463. })
  464. it('cancels and awaits a pending shell spawn when the plugin is disposed', async () => {
  465. const ctx = new Context()
  466. contexts.push(ctx)
  467. await ctx.plugin(SystemPrompt)
  468. await ctx.plugin(ToolRuntime)
  469. await ctx.plugin(AgentRegistry)
  470. await ctx.plugin(TerminalSessionService)
  471. const spawnStarted = Promise.withResolvers<undefined>()
  472. const spawnAborted = Promise.withResolvers<undefined>()
  473. ctx.terminals.registerBackend({
  474. type: 'slow',
  475. spawn: spec => new Promise((_resolve, reject) => {
  476. spawnStarted.resolve(undefined)
  477. spec.signal?.addEventListener('abort', () => {
  478. spawnAborted.resolve(undefined)
  479. const reason: unknown = spec.signal?.reason
  480. reject(reason instanceof Error
  481. ? reason
  482. : new Error('slow PTY spawn aborted', { cause: reason }))
  483. }, { once: true })
  484. }),
  485. })
  486. const fiber = await ctx.plugin(ToolBashPersistent, { backendType: 'slow' })
  487. const owner = agent(ctx, '/workspace')
  488. const running = call(ctx, owner, 'pwd')
  489. await spawnStarted.promise
  490. await fiber.dispose()
  491. await spawnAborted.promise
  492. expect((await running).isError).toBe(true)
  493. expect(ctx.terminals.list(owner)).toEqual([])
  494. })
  495. it('rejects invalid config and invalid calls', async () => {
  496. const { ctx, owner, stub } = await setup()
  497. expect((await call(ctx, undefined, 'pwd')).isError).toBe(true)
  498. expect(text(await call(ctx, owner, ' '))).toContain('command must be a non-empty string')
  499. const controller = new AbortController()
  500. controller.abort(new Error('caller stopped'))
  501. expect((await call(ctx, owner, 'pwd', controller.signal)).isError).toBe(true)
  502. expect(stub.sessions).toHaveLength(0)
  503. expect(() => {
  504. ToolBashPersistent.apply(new Context(), { backendType: '' })
  505. }).toThrow('backendType must be non-empty')
  506. expect(() => {
  507. ToolBashPersistent.apply(new Context(), { timeoutMs: 0 })
  508. }).toThrow('timeoutMs must be a positive safe integer')
  509. expect(() => {
  510. ToolBashPersistent.apply(new Context(), { maxOutputChars: 0 })
  511. }).toThrow('maxOutputChars must be a positive safe integer')
  512. expect(() => {
  513. ToolBashPersistent.apply(new Context(), { description: ' ' })
  514. }).toThrow('description must be non-empty')
  515. })
  516. })