tools.spec.ts 25 KB

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