index.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /**
  2. * Model-facing persistent `bash` tool over the owner-scoped PTY seam.
  3. * @module @deepseek-ai/dsh-tool-bash-persistent
  4. */
  5. import { randomUUID } from 'node:crypto'
  6. import type { Context } from '@deepseek-ai/cordis'
  7. import z from '@deepseek-ai/schemastery'
  8. import type { Agent } from '@deepseek-ai/dsh-agent'
  9. import type { TerminalReadResult, TerminalSessionId } from '@deepseek-ai/dsh-terminal'
  10. import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout'
  11. import { defineTool } from '@deepseek-ai/dsh-tools'
  12. // TODO: Replace the file-search advice; arbitrary command output need not come from a searchable file.
  13. const TRUNCATED_MESSAGE = '<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>'
  14. const LOST_PREFIX_MESSAGE = '<response clipped><NOTE>The beginning of this command output was dropped by the terminal scrollback limit. The following text is the earliest retained output.</NOTE>\n'
  15. const SHELL_RESET_MESSAGE = 'The persistent bash shell was reset; the next bash call starts from the workspace with a fresh current directory and environment.'
  16. const TIMEOUT_CODE = 'PERSISTENT_BASH_TIMEOUT'
  17. // One page is enough to find a just-emitted completion marker; the full
  18. // scrollback is assembled only when a command settles or needs partial output.
  19. const SCROLLBACK_PAGE_LINES = 1_000
  20. const POLL_INTERVAL_MS = 25
  21. const DEFAULT_DESCRIPTION = 'Run commands in a persistent bash shell. State, including the current directory and exported environment variables, persists across calls for this agent.'
  22. interface ResolvedConfig {
  23. backendType: string
  24. timeoutMs: number
  25. maxOutputChars: number
  26. description: string
  27. }
  28. interface CommandMarkers {
  29. start: string
  30. end: string
  31. }
  32. interface RetainedOutput {
  33. text: string
  34. truncated: boolean
  35. }
  36. interface CapturedOutput {
  37. text: string
  38. incomplete: boolean
  39. exitCode?: number
  40. }
  41. interface PersistentShells {
  42. get(owner: Agent, signal: AbortSignal): Promise<TerminalSessionId>
  43. reset(owner: Agent, reason: string): Promise<void>
  44. }
  45. function maybeTruncate(content: string, maxOutputChars: number, incomplete = false): string {
  46. if (content.length <= maxOutputChars && !incomplete) return content
  47. return content.length <= maxOutputChars
  48. ? content + TRUNCATED_MESSAGE
  49. : content.slice(0, maxOutputChars) + TRUNCATED_MESSAGE
  50. }
  51. function markers(): CommandMarkers {
  52. const nonce = randomUUID()
  53. return {
  54. start: `__DSH_PERSISTENT_BASH_START_${nonce}__`,
  55. end: `__DSH_PERSISTENT_BASH_END_${nonce}:`,
  56. }
  57. }
  58. function quoteForBash(value: string): string {
  59. return `$'${value
  60. .replaceAll('\\', '\\\\')
  61. .replaceAll("'", "\\'")
  62. .replaceAll('\r', '\\r')
  63. .replaceAll('\n', '\\n')}'`
  64. }
  65. function wrapCommand(command: string, marker: CommandMarkers): string {
  66. // Keep the wrapper on one physical line. An interactive bash prints PS2 for
  67. // embedded newlines before executing the buffer, which would leak terminal
  68. // prompts and marker source text into the model-facing result.
  69. return `printf '%s\\n' ${quoteForBash(marker.start)}; eval -- ${quoteForBash(command)}; __dsh_persistent_bash_status=$?; printf '%s%s\\n' ${quoteForBash(marker.end)} "$__dsh_persistent_bash_status"`
  70. }
  71. function trimTrailingNewline(text: string): string {
  72. return text.replace(/\r?\n$/, '')
  73. }
  74. function commandOutput(
  75. snapshot: RetainedOutput,
  76. marker: CommandMarkers,
  77. ): CapturedOutput | undefined {
  78. const text = snapshot.text
  79. const end = text.lastIndexOf(marker.end)
  80. const status = /^(\d+)\r?\n/.exec(text.slice(end + marker.end.length))?.[1]
  81. if (status === undefined) return undefined
  82. const startMarker = text.lastIndexOf(marker.start, end)
  83. const start = startMarker < 0 ? 0 : startMarker + marker.start.length
  84. return {
  85. text: trimTrailingNewline(text.slice(start, end).replace(/^\r?\n/, '')),
  86. incomplete: startMarker < 0,
  87. exitCode: Number(status),
  88. }
  89. }
  90. function partialOutput(
  91. snapshot: RetainedOutput,
  92. marker: CommandMarkers,
  93. fallback: string,
  94. fallbackTruncated = false,
  95. ): CapturedOutput {
  96. const startMarker = snapshot.text.lastIndexOf(marker.start)
  97. if (startMarker >= 0) {
  98. return {
  99. text: trimTrailingNewline(snapshot.text.slice(startMarker + marker.start.length).replace(/^\r?\n/, '')),
  100. incomplete: false,
  101. }
  102. }
  103. const fallbackStart = fallback.lastIndexOf(marker.start)
  104. const afterStart = fallbackStart < 0
  105. ? fallback
  106. : fallback.slice(fallbackStart + marker.start.length).replace(/^\r?\n/, '')
  107. const fallbackEnd = afterStart.lastIndexOf(marker.end)
  108. const beforeEnd = fallbackEnd < 0 ? afterStart : afterStart.slice(0, fallbackEnd)
  109. return {
  110. text: trimTrailingNewline(beforeEnd),
  111. incomplete: fallbackTruncated || fallbackStart < 0,
  112. }
  113. }
  114. async function pause(): Promise<void> {
  115. await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS))
  116. }
  117. function nextScrollbackOffset(page: TerminalReadResult, offset: number): number | undefined {
  118. if (page.text.length === 0 || page.lineEnd <= offset) return undefined
  119. return page.lineEnd
  120. }
  121. function retainedScrollback(
  122. ctx: Context,
  123. owner: Agent,
  124. id: TerminalSessionId,
  125. latest = ctx.terminals.read(owner, id, { offset: 0, count: SCROLLBACK_PAGE_LINES }),
  126. ): RetainedOutput {
  127. const pages: string[] = latest.text.length === 0 ? [] : [latest.text]
  128. let offset = latest.lineEnd
  129. let truncated = latest.truncated
  130. while (true) {
  131. if (offset >= latest.totalLines) break
  132. const page = ctx.terminals.read(owner, id, { offset, count: SCROLLBACK_PAGE_LINES })
  133. truncated ||= page.truncated
  134. if (page.text.length > 0) pages.unshift(page.text)
  135. const next = nextScrollbackOffset(page, offset)
  136. if (next === undefined || next >= page.totalLines) break
  137. offset = next
  138. }
  139. return { text: pages.join('\n'), truncated }
  140. }
  141. function renderCaptured(output: CapturedOutput, maxOutputChars: number): string {
  142. const rendered = maybeTruncate(output.text, maxOutputChars, output.incomplete)
  143. const withPrefix = output.incomplete && output.text.length > 0
  144. ? LOST_PREFIX_MESSAGE + rendered
  145. : rendered
  146. const marker = output.exitCode !== undefined && output.exitCode !== 0
  147. ? `[exit code: ${output.exitCode}]`
  148. : undefined
  149. return appendStatusMarker(withPrefix, marker)
  150. }
  151. function appendStatusMarker(content: string, marker: string | undefined): string {
  152. if (marker === undefined) return content
  153. return content.length === 0 ? marker : `${content}\n${marker}`
  154. }
  155. function renderShellExitStatus(
  156. content: string,
  157. exitCode: number | null,
  158. signal: NodeJS.Signals | null,
  159. ): string {
  160. const marker = signal !== null
  161. ? `[shell killed by signal: ${signal}]`
  162. : exitCode !== null
  163. ? `[shell exited: code ${exitCode}]`
  164. : '[shell exited]'
  165. return appendStatusMarker(content, marker)
  166. }
  167. /**
  168. * Render the exited-session result, reset the owner's shell, and reset the
  169. * message that tells the model the next call starts fresh.
  170. * @param shells - the owner-scoped registry to reset.
  171. * @param status - the exited session status (exit code and signal).
  172. * @returns the complete model-facing result.
  173. */
  174. async function respondToSessionExit(
  175. ctx: Context,
  176. shells: PersistentShells,
  177. owner: Agent,
  178. id: TerminalSessionId,
  179. status: { exitCode: number | null; signal: NodeJS.Signals | null },
  180. marker: CommandMarkers,
  181. fallback: string,
  182. fallbackTruncated: boolean,
  183. config: ResolvedConfig,
  184. ): Promise<string> {
  185. const snapshot = retainedScrollback(ctx, owner, id)
  186. await shells.reset(owner, 'persistent bash shell exited')
  187. return [
  188. renderShellExitStatus(
  189. renderCaptured(partialOutput(snapshot, marker, fallback, fallbackTruncated), config.maxOutputChars),
  190. status.exitCode,
  191. status.signal,
  192. ),
  193. SHELL_RESET_MESSAGE,
  194. ].filter(part => part.length > 0).join('\n')
  195. }
  196. function persistentShells(ctx: Context, config: ResolvedConfig): PersistentShells {
  197. const pending = new WeakMap<Agent, Promise<TerminalSessionId>>()
  198. const live = new Map<Agent, TerminalSessionId>()
  199. const creating = new Set<Promise<TerminalSessionId>>()
  200. const ownerCleanupInstalled = new WeakSet<Agent>()
  201. const lifecycle = new AbortController()
  202. const close = async (owner: Agent, id: TerminalSessionId, reason: string): Promise<void> => {
  203. if (!ctx.terminals.list(owner).some(snapshot => snapshot.sessionId === id)) return
  204. await ctx.terminals.kill(owner, id, reason)
  205. }
  206. ctx.effect(() => async () => {
  207. lifecycle.abort(new Error('tool-bash-persistent disposed during shell creation'))
  208. await Promise.allSettled([...creating])
  209. const closing = [...live].map(async ([owner, id]) => { await close(owner, id, 'tool-bash-persistent disposed') })
  210. await Promise.all(closing)
  211. live.clear()
  212. }, 'tool-bash-persistent shell cleanup')
  213. const reset = async (owner: Agent, reason: string): Promise<void> => {
  214. pending.delete(owner)
  215. const id = live.get(owner)
  216. live.delete(owner)
  217. if (id !== undefined) await close(owner, id, reason)
  218. }
  219. const get = (owner: Agent, signal: AbortSignal): Promise<TerminalSessionId> => {
  220. const existing = pending.get(owner)
  221. if (existing !== undefined) return existing
  222. const combinedSignal = AbortSignal.any([signal, lifecycle.signal])
  223. const creation = (async () => {
  224. try {
  225. const cwd = owner.session.header.cwd
  226. const spawned = await ctx.terminals.spawn(owner, {
  227. type: config.backendType,
  228. ...cwd === undefined ? {} : { cwd },
  229. }, combinedSignal)
  230. live.set(owner, spawned.sessionId)
  231. if (!ownerCleanupInstalled.has(owner)) {
  232. ownerCleanupInstalled.add(owner)
  233. owner.ctx.effect(() => () => {
  234. pending.delete(owner)
  235. live.delete(owner)
  236. }, 'tool-bash-persistent owner cache cleanup')
  237. }
  238. // Echo suppression only: the prompt stays the backend's own, so the
  239. // backend's prompt-based readiness detection keeps working.
  240. const setup = ctx.terminals.startSend(owner, spawned.sessionId, {
  241. text: 'stty -echo',
  242. submit: true,
  243. signal: combinedSignal,
  244. })
  245. const result = await setup.done
  246. if (result.sessionStatus.kind === 'exited' || result.waitReason === 'timeout') {
  247. throw new Error('persistent bash shell did not accept initialization')
  248. }
  249. return spawned.sessionId
  250. } catch (error: unknown) {
  251. await reset(owner, 'persistent bash initialization failed')
  252. throw error
  253. }
  254. })()
  255. const tracked = creation.finally(() => {
  256. creating.delete(tracked)
  257. })
  258. creating.add(tracked)
  259. pending.set(owner, tracked)
  260. return tracked
  261. }
  262. return { get, reset }
  263. }
  264. async function executeCommand(
  265. ctx: Context,
  266. shells: PersistentShells,
  267. owner: Agent,
  268. command: string,
  269. config: ResolvedConfig,
  270. upstream: AbortSignal,
  271. ): Promise<string> {
  272. using commandDeadline = deadline(upstream, config.timeoutMs, TIMEOUT_CODE)
  273. const id = await shells.get(owner, commandDeadline.signal)
  274. const marker = markers()
  275. const wrapped = wrapCommand(command, marker)
  276. let first = true
  277. let fallback = ''
  278. let fallbackTruncated = false
  279. while (true) {
  280. // The shell may flip to exited between iterations (a fast `exit` can
  281. // settle the previous send while its exit event is still in flight);
  282. // re-observing status before the next send closes that gap.
  283. const status = ctx.terminals.list(owner).find(session => session.sessionId === id)?.status
  284. if (status?.kind === 'exited') {
  285. return await respondToSessionExit(
  286. ctx, shells, owner, id, status, marker, fallback, fallbackTruncated, config,
  287. )
  288. }
  289. let operation
  290. let result
  291. try {
  292. operation = ctx.terminals.startSend(owner, id, {
  293. text: first ? wrapped : '',
  294. submit: first,
  295. signal: commandDeadline.signal,
  296. })
  297. first = false
  298. result = await operation.done
  299. } catch (error: unknown) {
  300. await shells.reset(owner, 'persistent bash send failed')
  301. throw error
  302. }
  303. const incremental = operation.readOutput()
  304. fallback = incremental.delta.length > 0 ? fallback + incremental.delta : result.viewport
  305. fallbackTruncated ||= incremental.truncated || result.truncated
  306. const latest = ctx.terminals.read(owner, id, { offset: 0, count: SCROLLBACK_PAGE_LINES })
  307. const timedOut = timeoutOf(commandDeadline.signal, TIMEOUT_CODE)
  308. if (timedOut !== undefined) {
  309. const snapshot = retainedScrollback(ctx, owner, id, latest)
  310. const partial = renderCaptured(
  311. partialOutput(snapshot, marker, fallback, fallbackTruncated),
  312. config.maxOutputChars,
  313. )
  314. await shells.reset(owner, 'persistent bash command timed out')
  315. return [
  316. // TODO: Report a timeout only; this signal does not establish an OOM.
  317. `Your command timed out after ${Math.round(timedOut.timeoutMs / 1000)} seconds or experienced an OOM error. Below is partial output:`,
  318. partial,
  319. SHELL_RESET_MESSAGE,
  320. ].join('\n')
  321. }
  322. if (commandDeadline.signal.aborted) {
  323. await shells.reset(owner, 'persistent bash command aborted')
  324. commandDeadline.signal.throwIfAborted()
  325. }
  326. if (latest.text.includes(marker.end)) {
  327. const complete = commandOutput(retainedScrollback(ctx, owner, id, latest), marker)
  328. if (complete !== undefined) return renderCaptured(complete, config.maxOutputChars)
  329. }
  330. if (result.sessionStatus.kind === 'exited') {
  331. return await respondToSessionExit(
  332. ctx, shells, owner, id, result.sessionStatus, marker, fallback, fallbackTruncated, config,
  333. )
  334. }
  335. // The shell reads stdin again (its prompt, or a foreground child's own
  336. // read) without having printed the end marker — e.g. `exec`, an interrupt,
  337. // or an interactive child. Return what was captured instead of spinning
  338. // until the command deadline.
  339. if (result.waitReason === 'stdin_read') {
  340. const snapshot = retainedScrollback(ctx, owner, id, latest)
  341. return renderCaptured(
  342. partialOutput(snapshot, marker, fallback, fallbackTruncated),
  343. config.maxOutputChars,
  344. )
  345. }
  346. await pause()
  347. }
  348. }
  349. /**
  350. * Register the model-facing persistent `bash` tool.
  351. * @param ctx - plugin context carrying tools and the owner-scoped PTY service.
  352. * @param config - selected PTY backend and command deadline.
  353. */
  354. function registerPersistentBash(ctx: Context, config: ResolvedConfig): void {
  355. const shells = persistentShells(ctx, config)
  356. const queues = new WeakMap<Agent, Promise<void>>()
  357. const serialized = async <T>(owner: Agent, operation: () => Promise<T>): Promise<T> => {
  358. const prior = queues.get(owner) ?? Promise.resolve()
  359. const run = prior.then(operation, operation)
  360. const tail = run.then(() => undefined, () => undefined)
  361. queues.set(owner, tail)
  362. try {
  363. return await run
  364. } finally {
  365. if (queues.get(owner) === tail) queues.delete(owner)
  366. }
  367. }
  368. ctx.tools.register(defineTool({
  369. name: 'bash',
  370. description: config.description,
  371. parameters: {
  372. command: {
  373. type: 'string',
  374. required: true,
  375. description: 'The bash command to run. Relative path is preferred in the command.',
  376. },
  377. },
  378. output: {
  379. schema: { type: 'string' },
  380. render: (_args, value) => [{ type: 'text', text: value }],
  381. },
  382. async execute(args, exec) {
  383. if (args.command.trim().length === 0) throw new Error('command must be a non-empty string')
  384. const owner = exec.agent
  385. if (owner === undefined) throw new Error('bash requires an owning agent session')
  386. return serialized(owner, async () => {
  387. exec.signal.throwIfAborted()
  388. return executeCommand(ctx, shells, owner, args.command, config, exec.signal)
  389. })
  390. },
  391. presentCall: args => ({ card: 'terminal', title: args.command }),
  392. }))
  393. }
  394. export const name = 'tool-bash-persistent'
  395. export const inject = ['tools', 'terminals']
  396. /** Configuration for the persistent Bash tool. */
  397. export interface Config {
  398. /** PTY backend used for each owner-isolated persistent shell (default `shell`). */
  399. backendType?: string
  400. /** Wall-clock limit for one command (default 300000). */
  401. timeoutMs?: number
  402. /** Maximum returned command-output characters before clipping (default 16000). */
  403. maxOutputChars?: number
  404. /** Model-facing tool description; deployments may describe their environment. */
  405. description?: string
  406. }
  407. /** Runtime configuration schema for the persistent Bash tool. */
  408. export const Config: z<Config> = z.object({
  409. backendType: z.string().default('shell'),
  410. timeoutMs: z.number().default(300_000),
  411. maxOutputChars: z.number().default(16_000),
  412. description: z.string().default(DEFAULT_DESCRIPTION),
  413. })
  414. /** Register one owner-scoped persistent `bash` tool. */
  415. export function apply(ctx: Context, config: Config): void {
  416. const resolved: ResolvedConfig = {
  417. backendType: config.backendType ?? 'shell',
  418. timeoutMs: config.timeoutMs ?? 300_000,
  419. maxOutputChars: config.maxOutputChars ?? 16_000,
  420. description: config.description ?? DEFAULT_DESCRIPTION,
  421. }
  422. if (resolved.backendType.trim().length === 0) {
  423. throw new Error('tool-bash-persistent: backendType must be non-empty')
  424. }
  425. if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0) {
  426. throw new Error('tool-bash-persistent: timeoutMs must be a positive safe integer')
  427. }
  428. if (!Number.isSafeInteger(resolved.maxOutputChars) || resolved.maxOutputChars <= 0) {
  429. throw new Error('tool-bash-persistent: maxOutputChars must be a positive safe integer')
  430. }
  431. if (resolved.description.trim().length === 0) {
  432. throw new Error('tool-bash-persistent: description must be non-empty')
  433. }
  434. registerPersistentBash(ctx, resolved)
  435. }