cli.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. /**
  2. * Command parser and one-turn driver for `dsh-cli-demo`. The executable wrapper
  3. * owns process signals; this module owns output, durability, and cleanup.
  4. * @module @deepseek-ai/dsh-cli-demo/cli
  5. */
  6. import { parseArgs } from 'node:util'
  7. import type { Context } from 'cordis'
  8. import type { Agent } from '@deepseek-ai/dsh-agent'
  9. import type { TokenUsage } from '@deepseek-ai/dsh-llm'
  10. import type { SessionEvent, TurnEndReason } from '@deepseek-ai/dsh-session'
  11. import { boot, loadEnv, resolveConfigPath } from '@deepseek-ai/dsh-app-boot'
  12. const CLI_NAME = 'dsh-cli-demo'
  13. const DEFAULT_CONFIG_PATH = './cordis.yml'
  14. const OUTPUT_FORMATS = ['text', 'json', 'stream-json'] as const
  15. const USAGE = `Usage: ${CLI_NAME} [--config path] [--output-format text|json|stream-json] <task>\n`
  16. /** Supported CLI output encodings. */
  17. export type OutputFormat = typeof OUTPUT_FORMATS[number]
  18. /** Parsed command: help exits before boot; run carries one validated task. */
  19. export type CliCommand =
  20. | { readonly kind: 'help' }
  21. | {
  22. readonly kind: 'run'
  23. readonly configPath: string
  24. readonly outputFormat: OutputFormat
  25. readonly task: string
  26. }
  27. /** DSH-native final record emitted by JSON modes. */
  28. export interface CliResult {
  29. readonly type: 'result'
  30. readonly success: boolean
  31. readonly sessionId: string
  32. readonly turn: number
  33. readonly result: string
  34. readonly reason: TurnEndReason
  35. readonly usage?: TokenUsage
  36. }
  37. /** Options for one turn against the configured top-level agent. */
  38. export interface OneShotOptions {
  39. /** Exactly one nonblank user task. */
  40. readonly task: string
  41. /** Optional signal that cancels the selected agent. */
  42. readonly signal?: AbortSignal
  43. /** Synchronous task-turn observer; a throw cancels the agent and fails the run after flush. */
  44. readonly onEvent?: (sessionId: string, event: SessionEvent) => void
  45. }
  46. /** Injectable process boundaries used by {@link executeCli}. */
  47. export interface CliRuntime {
  48. /** Process cwd for config resolution and `.env` loading. */
  49. readonly cwd?: string
  50. /** Cancellation signal, normally aborted by SIGINT or SIGTERM. */
  51. readonly signal?: AbortSignal
  52. /** Loader boot boundary. */
  53. readonly boot?: (name: string, absoluteConfigPath: string) => Promise<Context>
  54. /** Optional `.env` loader boundary. */
  55. readonly loadEnv?: (name: string, dir: string, warn: (line: string) => void) => void
  56. /** Stdout sink; throws are treated as output failures. */
  57. readonly writeStdout?: (chunk: string) => unknown
  58. /** Stderr diagnostic sink. */
  59. readonly writeStderr?: (chunk: string) => unknown
  60. /** Context disposal boundary. */
  61. readonly dispose?: (ctx: Context) => Promise<void>
  62. }
  63. interface ParsedArguments {
  64. readonly values: {
  65. readonly config?: string
  66. readonly 'output-format'?: string
  67. readonly help?: boolean
  68. }
  69. readonly positionals: string[]
  70. }
  71. class CliArgumentError extends Error {
  72. constructor(message: string) {
  73. super(message)
  74. this.name = 'CliArgumentError'
  75. }
  76. }
  77. class CliInterruptedError extends Error {
  78. constructor(reason: string) {
  79. super(reason)
  80. this.name = 'CliInterruptedError'
  81. }
  82. }
  83. /** Render an arbitrary value without trusting its type traps or string coercion. */
  84. function renderUnknown(value: unknown): string {
  85. try {
  86. return String(value)
  87. } catch {
  88. return '[unrenderable thrown value]'
  89. }
  90. }
  91. /** Normalize an arbitrary thrown value without letting inspection escape containment. */
  92. function toError(error: unknown): Error {
  93. try {
  94. if (error instanceof Error) return error
  95. } catch {
  96. // A hostile proxy may throw during instanceof; use the total renderer below.
  97. }
  98. return new Error(renderUnknown(error))
  99. }
  100. function interruptionReason(signal: AbortSignal): string {
  101. return signal.reason === undefined ? 'interrupted' : renderUnknown(signal.reason)
  102. }
  103. /**
  104. * Parse the bin arguments and enforce the one-positional-task contract.
  105. * @param args - arguments after the executable name.
  106. * @returns a help or run command.
  107. * @throws {@link CliArgumentError} for unknown flags, invalid formats, or task cardinality.
  108. */
  109. export function parseCliArgs(args: readonly string[]): CliCommand {
  110. let parsed: ParsedArguments
  111. try {
  112. parsed = parseArgs({
  113. args: [...args],
  114. options: {
  115. config: { type: 'string' },
  116. 'output-format': { type: 'string' },
  117. help: { type: 'boolean' },
  118. },
  119. allowPositionals: true,
  120. strict: true,
  121. })
  122. } catch (error: unknown) {
  123. throw new CliArgumentError(toError(error).message)
  124. }
  125. if (parsed.values.help === true) return { kind: 'help' }
  126. if (parsed.positionals.length !== 1) {
  127. throw new CliArgumentError(`expected exactly one positional task, received ${parsed.positionals.length}`)
  128. }
  129. // Cardinality was checked above, so index zero exists.
  130. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  131. const task = parsed.positionals[0]!
  132. if (task.trim().length === 0) throw new CliArgumentError('task must not be blank')
  133. const requestedFormat = parsed.values['output-format'] ?? 'text'
  134. if (!OUTPUT_FORMATS.some(format => format === requestedFormat)) {
  135. throw new CliArgumentError(`unsupported output format ${JSON.stringify(requestedFormat)}`)
  136. }
  137. return {
  138. kind: 'run',
  139. configPath: parsed.values.config ?? DEFAULT_CONFIG_PATH,
  140. outputFormat: requestedFormat as OutputFormat,
  141. task,
  142. }
  143. }
  144. function addUsage(total: TokenUsage | undefined, step: TokenUsage): TokenUsage {
  145. const next: TokenUsage = {
  146. inputTokens: (total?.inputTokens ?? 0) + step.inputTokens,
  147. outputTokens: (total?.outputTokens ?? 0) + step.outputTokens,
  148. }
  149. for (const key of ['cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens'] as const) {
  150. if (total?.[key] !== undefined || step[key] !== undefined) next[key] = (total?.[key] ?? 0) + (step[key] ?? 0)
  151. }
  152. return next
  153. }
  154. function assistantText(event: Extract<SessionEvent, { type: 'assistant/message' }>): string | undefined {
  155. const blocks = event.data.content.filter(block => block.type === 'text')
  156. return blocks.length === 0 ? undefined : blocks.map(block => block.text).join('')
  157. }
  158. /** Wait for startup quiescence while making pre-run cancellation terminal. */
  159. async function waitForStartupIdle(agent: Agent, signal?: AbortSignal): Promise<void> {
  160. if (signal === undefined) {
  161. await agent.whenIdle()
  162. return
  163. }
  164. if (signal.aborted) {
  165. agent.cancel({ kind: 'user' })
  166. throw new CliInterruptedError(interruptionReason(signal))
  167. }
  168. await new Promise<void>((resolve, reject) => {
  169. const onAbort = (): void => {
  170. agent.cancel({ kind: 'user' })
  171. reject(new CliInterruptedError(interruptionReason(signal)))
  172. }
  173. signal.addEventListener('abort', onAbort, { once: true })
  174. void agent.whenIdle().then(resolve, reject).finally(() => {
  175. signal.removeEventListener('abort', onAbort)
  176. })
  177. })
  178. }
  179. /**
  180. * Run one message-triggered turn on the configured top-level agent, aggregate its
  181. * final text and model usage, wait for idle plus an explicit persistence flush,
  182. * and return its durable ending. Only the selected agent's task turn reaches
  183. * `onEvent`; startup injections and unrelated sessions are ignored. The context
  184. * must contain exactly one top-level agent. Signal abort cancels that agent; an
  185. * abort before the correlated task turn rejects. An observer throw cancels the
  186. * turn and is rethrown after the agent reaches idle and the session flushes.
  187. * @param ctx - settled Loader root containing one agent plus `ctx.sessions`.
  188. * @param options - task, optional cancellation, and optional stream observer.
  189. * @returns the DSH-native result envelope after durable quiescence.
  190. */
  191. export async function runOneShot(ctx: Context, options: OneShotOptions): Promise<CliResult> {
  192. const agents = ctx.get('agents')?.roots() ?? []
  193. const [agent] = agents
  194. if (agent === undefined || agents.length !== 1) {
  195. throw new Error(`config must create exactly one top-level agent, found ${agents.length}`)
  196. }
  197. await waitForStartupIdle(agent, options.signal)
  198. let targetTurn: number | undefined
  199. let reason: TurnEndReason | undefined
  200. let result = ''
  201. const usageByStep = new Map<number, TokenUsage>()
  202. let outputError: Error | undefined
  203. let resolveTurn!: () => void
  204. let rejectTurn!: (error: Error) => void
  205. let settled = false
  206. const turnEnded = new Promise<void>((resolve, reject) => {
  207. resolveTurn = resolve
  208. rejectTurn = reject
  209. })
  210. const settleResolved = (): void => {
  211. settled = true
  212. resolveTurn()
  213. }
  214. const settleRejected = (error: Error): void => {
  215. settled = true
  216. rejectTurn(error)
  217. }
  218. const observe = (sessionId: string, event: SessionEvent): void => {
  219. if (outputError !== undefined || options.onEvent === undefined) return
  220. try {
  221. options.onEvent(sessionId, event)
  222. } catch (error: unknown) {
  223. outputError = toError(error)
  224. agent.cancel({ kind: 'user' })
  225. }
  226. }
  227. const disposeListener = ctx.on('session/event', (session, event) => {
  228. if (session !== agent.session || settled) return
  229. if (targetTurn === undefined) {
  230. if (event.type !== 'turn/start' || event.data.trigger.kind !== 'message') return
  231. targetTurn = event.data.turn
  232. }
  233. observe(session.id, event)
  234. if (event.type === 'assistant/chunk'
  235. && event.data.turn === targetTurn
  236. && event.data.chunk.type === 'usage') {
  237. usageByStep.set(event.data.step, event.data.chunk.usage)
  238. }
  239. if (event.type === 'assistant/message' && event.data.turn === targetTurn) {
  240. result = assistantText(event) ?? result
  241. if (event.data.usage !== undefined) usageByStep.set(event.data.step, event.data.usage)
  242. }
  243. if (event.type === 'turn/end' && event.data.turn === targetTurn) {
  244. reason = event.data.reason
  245. settleResolved()
  246. }
  247. })
  248. const signal = options.signal
  249. let onAbort: (() => void) | undefined
  250. if (signal !== undefined) {
  251. onAbort = (): void => {
  252. agent.cancel({ kind: 'user' })
  253. if (targetTurn === undefined) settleRejected(new CliInterruptedError(interruptionReason(signal)))
  254. }
  255. signal.addEventListener('abort', onAbort, { once: true })
  256. /* v8 ignore next -- closes the race between startup-idle completion and listener registration */
  257. if (signal.aborted) onAbort()
  258. }
  259. try {
  260. /* v8 ignore next -- skips send only when cancellation wins the listener-registration race above */
  261. if (!settled) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition
  262. agent.send([{ type: 'text', text: options.task }])
  263. }
  264. await turnEnded
  265. } finally {
  266. if (onAbort !== undefined) signal?.removeEventListener('abort', onAbort)
  267. disposeListener()
  268. await agent.whenIdle()
  269. }
  270. /* v8 ignore next 3 -- turnEnded resolves only from the matching branch that assigns both values */
  271. if (targetTurn === undefined || reason === undefined) {
  272. throw new Error('task ended without a correlated turn/end event')
  273. }
  274. await ctx.sessions.flush(agent.session)
  275. if (outputError !== undefined) throw outputError
  276. const usage = [...usageByStep.values()].reduce<TokenUsage | undefined>(addUsage, undefined)
  277. return {
  278. type: 'result',
  279. success: reason.kind === 'completed',
  280. sessionId: agent.session.id,
  281. turn: targetTurn,
  282. result,
  283. reason,
  284. ...usage === undefined ? {} : { usage },
  285. }
  286. }
  287. function renderResult(outputFormat: OutputFormat, result: CliResult): string {
  288. return outputFormat === 'text' ? `${result.result}\n` : `${JSON.stringify(result)}\n`
  289. }
  290. /**
  291. * Race Loader boot with cancellation without abandoning a context that becomes
  292. * available after the caller has been released. Waiting for that late context
  293. * would recreate the signal hang, so its disposal and diagnostics run detached.
  294. */
  295. async function bootInterruptibly(
  296. start: () => Promise<Context>,
  297. signal: AbortSignal | undefined,
  298. disposeLateContext: (ctx: Context) => Promise<void>,
  299. reportLateDisposalFailure: (error: unknown) => void,
  300. ): Promise<Context> {
  301. if (signal === undefined) return await start()
  302. if (signal.aborted) throw new CliInterruptedError(interruptionReason(signal))
  303. let onAbort!: () => void
  304. const interruptedBoot = new Promise<never>((_resolve, reject) => {
  305. onAbort = (): void => {
  306. reject(new CliInterruptedError(interruptionReason(signal)))
  307. }
  308. signal.addEventListener('abort', onAbort, { once: true })
  309. /* v8 ignore next -- closes registration against a non-standard synchronously mutating signal */
  310. if (signal.aborted) onAbort()
  311. })
  312. const booting = Promise.resolve().then(start)
  313. try {
  314. return await Promise.race([booting, interruptedBoot])
  315. } catch (error: unknown) {
  316. // The awaited race permits the signal to change after the preflight check.
  317. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  318. if (signal.aborted) {
  319. void booting.then(
  320. async (lateContext) => {
  321. try {
  322. await disposeLateContext(lateContext)
  323. } catch (error: unknown) {
  324. reportLateDisposalFailure(error)
  325. }
  326. },
  327. () => {},
  328. )
  329. }
  330. throw error
  331. } finally {
  332. signal.removeEventListener('abort', onAbort)
  333. }
  334. }
  335. /**
  336. * Render a non-completed turn reason for stderr.
  337. * @param reason - durable turn ending to describe.
  338. * @returns a concise diagnostic fragment.
  339. */
  340. export function formatTurnFailure(reason: TurnEndReason): string {
  341. switch (reason.kind) {
  342. case 'completed': return 'completed'
  343. case 'aborted': return 'was aborted'
  344. case 'error': return `failed at step ${reason.step}: ${'failure' in reason ? reason.failure.message : reason.message}`
  345. case 'disposed': return 'was disposed'
  346. case 'max-tokens': return 'reached the model output-token limit'
  347. case 'rejected': return `was rejected: ${reason.reason}`
  348. case 'interrupted': return 'was interrupted during persistence recovery'
  349. default: return `ended with ${JSON.stringify(reason)}`
  350. }
  351. }
  352. /**
  353. * Execute one CLI invocation. Argument and boot failures never write stdout;
  354. * context disposal is awaited before return, and its failure does not replace
  355. * an earlier diagnostic.
  356. * @param args - arguments after the executable name.
  357. * @param runtime - optional injected process boundaries for tests and embedding.
  358. * @returns the ordinary process exit code; the thin bin overrides it for Unix signals.
  359. */
  360. export async function executeCli(args: readonly string[], runtime: CliRuntime = {}): Promise<number> {
  361. /* v8 ignore next -- default process sinks are exercised by the built-bin smoke */
  362. const writeStdout = runtime.writeStdout ?? (chunk => process.stdout.write(chunk))
  363. /* v8 ignore next -- default process sinks are exercised by the built-bin smoke */
  364. const writeStderr = runtime.writeStderr ?? (chunk => process.stderr.write(chunk))
  365. let command: CliCommand
  366. try {
  367. command = parseCliArgs(args)
  368. } catch (error: unknown) {
  369. writeStderr(`${CLI_NAME}: ${toError(error).message}\n${USAGE}`)
  370. return 1
  371. }
  372. if (command.kind === 'help') {
  373. writeStdout(USAGE)
  374. return 0
  375. }
  376. /* v8 ignore next -- default process cwd is exercised by the built-bin smoke */
  377. const cwd = runtime.cwd ?? process.cwd()
  378. /* v8 ignore next -- default env/boot boundaries are exercised by the Loader and built-bin smokes */
  379. const loadEnvironment = runtime.loadEnv ?? loadEnv
  380. /* v8 ignore next -- default env/boot boundaries are exercised by the Loader and built-bin smokes */
  381. const bootContext = runtime.boot ?? boot
  382. /* v8 ignore next -- default disposal is exercised by the built-bin smoke */
  383. const disposeContext = runtime.dispose ?? (target => target.fiber.dispose())
  384. let ctx: Context | undefined
  385. let exitCode = 1
  386. let diagnostic: string | undefined
  387. try {
  388. loadEnvironment(CLI_NAME, cwd, line => writeStderr(line))
  389. ctx = await bootInterruptibly(
  390. () => bootContext(CLI_NAME, resolveConfigPath(command.configPath, undefined, cwd)),
  391. runtime.signal,
  392. disposeContext,
  393. error => writeStderr(`${CLI_NAME}: dispose after interrupted boot failed: ${toError(error).message}\n`),
  394. )
  395. const result = await runOneShot(ctx, {
  396. task: command.task,
  397. ...runtime.signal === undefined ? {} : { signal: runtime.signal },
  398. ...command.outputFormat === 'stream-json'
  399. ? { onEvent: (sessionId: string, event: SessionEvent) => {
  400. writeStdout(`${JSON.stringify({ type: 'session_event', sessionId, event })}\n`)
  401. } }
  402. : {},
  403. })
  404. writeStdout(renderResult(command.outputFormat, result))
  405. exitCode = result.success ? 0 : 1
  406. if (!result.success) diagnostic = `${CLI_NAME}: turn ${result.turn} ${formatTurnFailure(result.reason)}\n`
  407. } catch (error: unknown) {
  408. diagnostic = `${CLI_NAME}: ${toError(error).message}\n`
  409. } finally {
  410. if (ctx !== undefined) {
  411. try {
  412. await disposeContext(ctx)
  413. } catch (error: unknown) {
  414. diagnostic = `${diagnostic ?? ''}${CLI_NAME}: dispose failed: ${toError(error).message}\n`
  415. exitCode = 1
  416. }
  417. }
  418. }
  419. if (diagnostic !== undefined) writeStderr(diagnostic)
  420. return exitCode
  421. }