index.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. function persistentShells(ctx: Context, config: ResolvedConfig): PersistentShells {
  168. const pending = new WeakMap<Agent, Promise<TerminalSessionId>>()
  169. const live = new Map<Agent, TerminalSessionId>()
  170. const creating = new Set<Promise<TerminalSessionId>>()
  171. const ownerCleanupInstalled = new WeakSet<Agent>()
  172. const lifecycle = new AbortController()
  173. const close = async (owner: Agent, id: TerminalSessionId, reason: string): Promise<void> => {
  174. if (!ctx.terminals.list(owner).some(snapshot => snapshot.sessionId === id)) return
  175. await ctx.terminals.kill(owner, id, reason)
  176. }
  177. ctx.effect(() => async () => {
  178. lifecycle.abort(new Error('tool-bash-persistent disposed during shell creation'))
  179. await Promise.allSettled([...creating])
  180. const closing = [...live].map(async ([owner, id]) => { await close(owner, id, 'tool-bash-persistent disposed') })
  181. await Promise.all(closing)
  182. live.clear()
  183. }, 'tool-bash-persistent shell cleanup')
  184. const reset = async (owner: Agent, reason: string): Promise<void> => {
  185. pending.delete(owner)
  186. const id = live.get(owner)
  187. live.delete(owner)
  188. if (id !== undefined) await close(owner, id, reason)
  189. }
  190. const get = (owner: Agent, signal: AbortSignal): Promise<TerminalSessionId> => {
  191. const existing = pending.get(owner)
  192. if (existing !== undefined) return existing
  193. const combinedSignal = AbortSignal.any([signal, lifecycle.signal])
  194. const creation = (async () => {
  195. try {
  196. const cwd = owner.session.header.cwd
  197. const spawned = await ctx.terminals.spawn(owner, {
  198. type: config.backendType,
  199. ...cwd === undefined ? {} : { cwd },
  200. }, combinedSignal)
  201. live.set(owner, spawned.sessionId)
  202. if (!ownerCleanupInstalled.has(owner)) {
  203. ownerCleanupInstalled.add(owner)
  204. owner.ctx.effect(() => () => {
  205. pending.delete(owner)
  206. live.delete(owner)
  207. }, 'tool-bash-persistent owner cache cleanup')
  208. }
  209. // Echo suppression only: the prompt stays the backend's own, so the
  210. // backend's prompt-based readiness detection keeps working.
  211. const setup = ctx.terminals.startSend(owner, spawned.sessionId, {
  212. text: 'stty -echo',
  213. submit: true,
  214. signal: combinedSignal,
  215. })
  216. const result = await setup.done
  217. if (result.sessionStatus.kind === 'exited' || result.waitReason === 'timeout') {
  218. throw new Error('persistent bash shell did not accept initialization')
  219. }
  220. return spawned.sessionId
  221. } catch (error: unknown) {
  222. await reset(owner, 'persistent bash initialization failed')
  223. throw error
  224. }
  225. })()
  226. const tracked = creation.finally(() => {
  227. creating.delete(tracked)
  228. })
  229. creating.add(tracked)
  230. pending.set(owner, tracked)
  231. return tracked
  232. }
  233. return { get, reset }
  234. }
  235. async function executeCommand(
  236. ctx: Context,
  237. shells: PersistentShells,
  238. owner: Agent,
  239. command: string,
  240. config: ResolvedConfig,
  241. upstream: AbortSignal,
  242. ): Promise<string> {
  243. using commandDeadline = deadline(upstream, config.timeoutMs, TIMEOUT_CODE)
  244. const id = await shells.get(owner, commandDeadline.signal)
  245. const marker = markers()
  246. const wrapped = wrapCommand(command, marker)
  247. let first = true
  248. let fallback = ''
  249. let fallbackTruncated = false
  250. while (true) {
  251. let operation
  252. let result
  253. try {
  254. operation = ctx.terminals.startSend(owner, id, {
  255. text: first ? wrapped : '',
  256. submit: first,
  257. signal: commandDeadline.signal,
  258. })
  259. first = false
  260. result = await operation.done
  261. } catch (error: unknown) {
  262. await shells.reset(owner, 'persistent bash send failed')
  263. throw error
  264. }
  265. const incremental = operation.readOutput()
  266. fallback = incremental.delta.length > 0 ? fallback + incremental.delta : result.viewport
  267. fallbackTruncated ||= incremental.truncated || result.truncated
  268. const latest = ctx.terminals.read(owner, id, { offset: 0, count: SCROLLBACK_PAGE_LINES })
  269. const timedOut = timeoutOf(commandDeadline.signal, TIMEOUT_CODE)
  270. if (timedOut !== undefined) {
  271. const snapshot = retainedScrollback(ctx, owner, id, latest)
  272. const partial = renderCaptured(
  273. partialOutput(snapshot, marker, fallback, fallbackTruncated),
  274. config.maxOutputChars,
  275. )
  276. await shells.reset(owner, 'persistent bash command timed out')
  277. return [
  278. // TODO: Report a timeout only; this signal does not establish an OOM.
  279. `Your command timed out after ${Math.round(timedOut.timeoutMs / 1000)} seconds or experienced an OOM error. Below is partial output:`,
  280. partial,
  281. SHELL_RESET_MESSAGE,
  282. ].join('\n')
  283. }
  284. if (commandDeadline.signal.aborted) {
  285. await shells.reset(owner, 'persistent bash command aborted')
  286. commandDeadline.signal.throwIfAborted()
  287. }
  288. if (latest.text.includes(marker.end)) {
  289. const complete = commandOutput(retainedScrollback(ctx, owner, id, latest), marker)
  290. if (complete !== undefined) return renderCaptured(complete, config.maxOutputChars)
  291. }
  292. if (result.sessionStatus.kind === 'exited') {
  293. const snapshot = retainedScrollback(ctx, owner, id, latest)
  294. await shells.reset(owner, 'persistent bash shell exited')
  295. return [
  296. renderShellExitStatus(
  297. renderCaptured(partialOutput(snapshot, marker, fallback, fallbackTruncated), config.maxOutputChars),
  298. result.sessionStatus.exitCode,
  299. result.sessionStatus.signal,
  300. ),
  301. SHELL_RESET_MESSAGE,
  302. ].filter(part => part.length > 0).join('\n')
  303. }
  304. // The shell reads stdin again (its prompt, or a foreground child's own
  305. // read) without having printed the end marker — e.g. `exec`, an interrupt,
  306. // or an interactive child. Return what was captured instead of spinning
  307. // until the command deadline.
  308. if (result.waitReason === 'stdin_read') {
  309. const snapshot = retainedScrollback(ctx, owner, id, latest)
  310. return renderCaptured(
  311. partialOutput(snapshot, marker, fallback, fallbackTruncated),
  312. config.maxOutputChars,
  313. )
  314. }
  315. await pause()
  316. }
  317. }
  318. /**
  319. * Register the model-facing persistent `bash` tool.
  320. * @param ctx - plugin context carrying tools and the owner-scoped PTY service.
  321. * @param config - selected PTY backend and command deadline.
  322. */
  323. function registerPersistentBash(ctx: Context, config: ResolvedConfig): void {
  324. const shells = persistentShells(ctx, config)
  325. const queues = new WeakMap<Agent, Promise<void>>()
  326. const serialized = async <T>(owner: Agent, operation: () => Promise<T>): Promise<T> => {
  327. const prior = queues.get(owner) ?? Promise.resolve()
  328. const run = prior.then(operation, operation)
  329. const tail = run.then(() => undefined, () => undefined)
  330. queues.set(owner, tail)
  331. try {
  332. return await run
  333. } finally {
  334. if (queues.get(owner) === tail) queues.delete(owner)
  335. }
  336. }
  337. ctx.tools.register(defineTool({
  338. name: 'bash',
  339. description: config.description,
  340. parameters: {
  341. command: {
  342. type: 'string',
  343. required: true,
  344. description: 'The bash command to run. Relative path is preferred in the command.',
  345. },
  346. },
  347. output: {
  348. schema: { type: 'string' },
  349. render: (_args, value) => [{ type: 'text', text: value }],
  350. },
  351. async execute(args, exec) {
  352. if (args.command.trim().length === 0) throw new Error('command must be a non-empty string')
  353. const owner = exec.agent
  354. if (owner === undefined) throw new Error('bash requires an owning agent session')
  355. return serialized(owner, async () => {
  356. exec.signal.throwIfAborted()
  357. return executeCommand(ctx, shells, owner, args.command, config, exec.signal)
  358. })
  359. },
  360. presentCall: args => ({ card: 'terminal', title: args.command }),
  361. }))
  362. }
  363. export const name = 'tool-bash-persistent'
  364. export const inject = ['tools', 'terminals']
  365. /** Configuration for the persistent Bash tool. */
  366. export interface Config {
  367. /** PTY backend used for each owner-isolated persistent shell (default `shell`). */
  368. backendType?: string
  369. /** Wall-clock limit for one command (default 300000). */
  370. timeoutMs?: number
  371. /** Maximum returned command-output characters before clipping (default 16000). */
  372. maxOutputChars?: number
  373. /** Model-facing tool description; deployments may describe their environment. */
  374. description?: string
  375. }
  376. /** Runtime configuration schema for the persistent Bash tool. */
  377. export const Config: z<Config> = z.object({
  378. backendType: z.string().default('shell'),
  379. timeoutMs: z.number().default(300_000),
  380. maxOutputChars: z.number().default(16_000),
  381. description: z.string().default(DEFAULT_DESCRIPTION),
  382. })
  383. /** Register one owner-scoped persistent `bash` tool. */
  384. export function apply(ctx: Context, config: Config): void {
  385. const resolved: ResolvedConfig = {
  386. backendType: config.backendType ?? 'shell',
  387. timeoutMs: config.timeoutMs ?? 300_000,
  388. maxOutputChars: config.maxOutputChars ?? 16_000,
  389. description: config.description ?? DEFAULT_DESCRIPTION,
  390. }
  391. if (resolved.backendType.trim().length === 0) {
  392. throw new Error('tool-bash-persistent: backendType must be non-empty')
  393. }
  394. if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0) {
  395. throw new Error('tool-bash-persistent: timeoutMs must be a positive safe integer')
  396. }
  397. if (!Number.isSafeInteger(resolved.maxOutputChars) || resolved.maxOutputChars <= 0) {
  398. throw new Error('tool-bash-persistent: maxOutputChars must be a positive safe integer')
  399. }
  400. if (resolved.description.trim().length === 0) {
  401. throw new Error('tool-bash-persistent: description must be non-empty')
  402. }
  403. registerPersistentBash(ctx, resolved)
  404. }