index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /**
  2. * The stdio app's readline UI: reads lines from stdin into `agent.send()` or
  3. * `steer()`, renders the durable event stream to stdout, and exits piped input
  4. * only after submitted work reaches idle.
  5. *
  6. * This package is the independently composable stdio front door. It establishes
  7. * the terminal channel and drives an agent created or resumed by app or
  8. * developer code.
  9. * @module @deepseek-ai/dsh-stdio
  10. */
  11. import { createInterface } from 'node:readline'
  12. import type { Readable, Writable } from 'node:stream'
  13. import type { Context } from 'cordis'
  14. import z from 'schemastery'
  15. import { AgentId } from '@deepseek-ai/dsh-agent'
  16. import {
  17. UserInteractionError,
  18. type AskUserQuestionAnswer,
  19. type AskUserQuestionAnswerItem,
  20. type AskUserQuestionItem,
  21. type AskUserQuestionOption,
  22. type AskUserQuestionRequest,
  23. } from '@deepseek-ai/dsh-user-interaction'
  24. export const name = 'ui-stdio'
  25. export const inject = ['agents', 'userInteraction']
  26. /** Serializable plugin configuration (cordis-native, schemastery). */
  27. export interface Config {
  28. /** Banner printed once on start, before the first `> ` prompt. */
  29. welcome?: string
  30. /** Id of the agent stdin drives (`send`/`steer`) and whose status gates the EOF exit; rendering is global. Defaults to `'main'`. */
  31. agent?: string
  32. }
  33. export const Config: z<Config> = z.object({
  34. welcome: z.string().default('ready.'),
  35. agent: z.string().default('main'),
  36. })
  37. /**
  38. * Process-I/O seam — the side-effecting handles the plugin would otherwise
  39. * reach for as globals. Defaulted to the real `process` streams in
  40. * {@link apply}; injected by tests so the EOF, render, and disposal branches
  41. * are exercised without hijacking globals. Deliberately NOT part of the
  42. * serializable {@link Config} (streams/functions don't belong in YAML config).
  43. */
  44. export interface StdioRuntime {
  45. /** Line source (default `process.stdin`). */
  46. input: Readable
  47. /** Render sink (default `process.stdout`). */
  48. output: Writable
  49. /** Process-exit hook (default `process.exit`); called once on stdin EOF. */
  50. exit: (code: number) => void
  51. }
  52. function isTTYPair(input: Readable, output: Writable): boolean {
  53. return Boolean((input as { isTTY?: boolean }).isTTY && (output as { isTTY?: boolean }).isTTY)
  54. }
  55. interface PendingQuestion {
  56. request: AskUserQuestionRequest
  57. questionIndex: number
  58. answers: AskUserQuestionAnswerItem[]
  59. resolve(answer: AskUserQuestionAnswer): void
  60. reject(error: unknown): void
  61. onAbort: () => void
  62. }
  63. type OptionSelection =
  64. | { kind: 'selected'; options: AskUserQuestionOption[] }
  65. | { kind: 'custom' }
  66. | { kind: 'invalid' }
  67. /**
  68. * Register stdio chat against an injectable I/O runtime.
  69. * @param ctx - agent and event context.
  70. * @param config - plugin config, defaulted for direct callers.
  71. * @param runtime - line source, render sink, and exit hook.
  72. */
  73. export function createStdioChat(ctx: Context, config: Config, runtime: StdioRuntime): void {
  74. // Default here too (not just via schemastery's `.default()`): this helper is
  75. // exported and called directly by tests / programmatic consumers that bypass
  76. // Loader validation, so it must be self-contained rather than trusting the
  77. // cast — `config.welcome as string` would otherwise be `undefined` on `{}`.
  78. const welcome = config.welcome ?? 'ready.'
  79. const agentId = AgentId(config.agent ?? 'main')
  80. const { input, output, exit } = runtime
  81. // Session ids need not equal agent ids. Seed existing agents before listening
  82. // so a pre-created or HMR-surviving agent still gets its short render label.
  83. const labelBySession = new Map<string, string>()
  84. for (const agent of ctx.agents.list()) labelBySession.set(agent.session.header.id, agent.id)
  85. ctx.on('agent/created', (agent) => { labelBySession.set(agent.session.header.id, agent.id) })
  86. ctx.on('agent/disposed', (agent) => { labelBySession.delete(agent.session.header.id) })
  87. // Render the canonical append order from session/event so reasoning state is
  88. // deterministic across chunks and boundaries; there are no agent/* mirrors.
  89. let inReasoning = false
  90. ctx.on('session/event', (session, event) => {
  91. if (event.type === 'assistant/chunk') {
  92. const { chunk } = event.data
  93. if (chunk.type === 'reasoning-delta') {
  94. // Dim the chain-of-thought so the final answer stands out.
  95. if (!inReasoning) output.write('\x1B[2m')
  96. inReasoning = true
  97. output.write(chunk.text)
  98. } else if (chunk.type === 'text-delta') {
  99. if (inReasoning) output.write('\x1B[0m\n')
  100. inReasoning = false
  101. output.write(chunk.text)
  102. }
  103. } else if (event.type === 'turn/start') {
  104. const label = labelBySession.get(session.header.id) ?? session.header.id
  105. output.write(`\n[${label} turn ${event.data.turn}] `)
  106. } else if (event.type === 'turn/end') {
  107. if (inReasoning) output.write('\x1B[0m')
  108. inReasoning = false
  109. output.write('\n> ')
  110. } else if (event.type === 'tool/call') {
  111. const { name: toolName, arguments: args } = event.data
  112. if (inReasoning) output.write('\x1B[0m')
  113. inReasoning = false
  114. output.write(`\n [tool call] ${toolName}(${args})`)
  115. } else if (event.type === 'tool/result') {
  116. const { content } = event.data
  117. const text = content.filter(block => block.type === 'text').map(block => block.text).join('')
  118. output.write(`\n [tool result] ${text}\n `)
  119. } else if (event.type === 'todo/write') {
  120. if (inReasoning) output.write('\x1B[0m')
  121. inReasoning = false
  122. const glyph = (status: string): string =>
  123. status === 'completed' ? '[x]' : status === 'in_progress' ? '[~]' : '[ ]'
  124. const lines = event.data.todos.map(todo => ` ${glyph(todo.status)} ${todo.content}`).join('\n')
  125. output.write(`\n [todos]\n${lines}\n `)
  126. }
  127. })
  128. ctx.effect(() => {
  129. const reader = createInterface({ input, output, terminal: isTTYPair(input, output) })
  130. // On piped EOF, exit immediately if no work was submitted. Otherwise wait
  131. // for a real running state followed by idle: sends do not synchronously mark
  132. // running, and several queued lines may share one turn.
  133. let stdinClosed = false
  134. let disposed = false
  135. let submittedWork = false
  136. let sawRunning = false
  137. let exitTimer: ReturnType<typeof setTimeout> | undefined
  138. let activeQuestion: PendingQuestion | undefined
  139. const questionQueue: PendingQuestion[] = []
  140. const maybeExit = (): void => {
  141. if (disposed || !stdinClosed) return
  142. // No work submitted: nothing will ever run, exit straight away.
  143. // Work submitted: wait until a turn has run and the agent is idle.
  144. if (submittedWork) {
  145. if (!sawRunning) return
  146. const agent = ctx.agents.get(agentId)
  147. if (agent && agent.status !== 'idle') return // a turn is still running
  148. }
  149. // Let final output flush; track the timer so re-entry coalesces and HMR
  150. // disposal can cancel it before it exits the replacement process.
  151. if (exitTimer !== undefined) {
  152. return // exit already scheduled — coalesce re-entrant calls
  153. }
  154. exitTimer = setTimeout(() => { exit(0) }, 200)
  155. }
  156. const disposeStatusListener = ctx.on('agent/status', (subject, status) => {
  157. if (subject.id !== agentId) return
  158. if (status === 'running') sawRunning = true
  159. if (status === 'idle') maybeExit()
  160. })
  161. const activeQuestionItem = (pending: PendingQuestion): AskUserQuestionItem =>
  162. pending.request.questions[pending.questionIndex] as AskUserQuestionItem
  163. const renderQuestion = (pending: PendingQuestion): void => {
  164. const question = activeQuestionItem(pending)
  165. const options = question.options ?? []
  166. output.write('\n')
  167. output.write(question.header ? `[${question.header}] ${question.question}\n` : `${question.question}\n`)
  168. options.forEach((option, index) => {
  169. output.write(` ${index + 1}. ${option.label}\n`)
  170. if (option.description) output.write(` ${option.description}\n`)
  171. })
  172. output.write('> ')
  173. }
  174. const removeAbortListener = (pending: PendingQuestion): void => {
  175. pending.request.signal?.removeEventListener('abort', pending.onAbort)
  176. }
  177. const startNextQuestion = (): void => {
  178. if (activeQuestion !== undefined) return
  179. const pending = questionQueue.shift()
  180. if (pending === undefined) return
  181. // The queue never contains an aborted pending ask: the seam rejects an
  182. // already-aborted request synchronously, and queued asks attach their
  183. // abort listener before enqueueing.
  184. activeQuestion = pending
  185. renderQuestion(pending)
  186. }
  187. const disposeQuestion = (pending: PendingQuestion): void => {
  188. removeAbortListener(pending)
  189. pending.reject(new UserInteractionError('ask_user_question was interrupted before the user answered', 'ASK_ABORTED'))
  190. }
  191. const disposePendingQuestions = (): void => {
  192. if (activeQuestion !== undefined) {
  193. disposeQuestion(activeQuestion)
  194. activeQuestion = undefined
  195. }
  196. for (const pending of questionQueue.splice(0)) {
  197. disposeQuestion(pending)
  198. }
  199. }
  200. const finishQuestion = (pending: PendingQuestion): void => {
  201. activeQuestion = undefined
  202. removeAbortListener(pending)
  203. pending.resolve({ answers: pending.answers })
  204. output.write('\n')
  205. startNextQuestion()
  206. }
  207. const answerCurrentQuestion = (pending: PendingQuestion, answer: AskUserQuestionAnswerItem): void => {
  208. pending.answers.push(answer)
  209. pending.questionIndex += 1
  210. if (pending.questionIndex >= pending.request.questions.length) {
  211. finishQuestion(pending)
  212. return
  213. }
  214. renderQuestion(pending)
  215. }
  216. const selectedOptions = (text: string, options: AskUserQuestionOption[], multiSelect: boolean): OptionSelection => {
  217. if (text === '') return { kind: 'invalid' }
  218. if (!multiSelect) {
  219. if (!/^\d+$/.test(text)) return { kind: 'custom' }
  220. const selected = options[Number(text) - 1]
  221. return selected === undefined ? { kind: 'invalid' } : { kind: 'selected', options: [selected] }
  222. }
  223. const indices = text.split(/[,\s]+/).filter(Boolean)
  224. if (indices.length === 0) return { kind: 'invalid' }
  225. if (indices.some(part => !/^\d+$/.test(part))) return { kind: 'custom' }
  226. const uniqueIndices = [...new Set(indices)]
  227. const selected = uniqueIndices.map(part => options[Number(part) - 1])
  228. return selected.some(option => option === undefined)
  229. ? { kind: 'invalid' }
  230. : { kind: 'selected', options: selected as AskUserQuestionOption[] }
  231. }
  232. const answerQuestion = (line: string): void => {
  233. const pending = activeQuestion as PendingQuestion
  234. const question = activeQuestionItem(pending)
  235. const text = line.trim()
  236. const options = question.options ?? []
  237. const selection = options.length > 0
  238. ? selectedOptions(text, options, question.multiSelect ?? false)
  239. : { kind: text === '' ? 'invalid' : 'custom' } as OptionSelection
  240. if (selection.kind === 'selected') {
  241. answerCurrentQuestion(pending, { id: question.id, selected: selection.options.map(option => option.label) })
  242. return
  243. }
  244. if (selection.kind === 'custom' && text !== '') {
  245. answerCurrentQuestion(pending, { id: question.id, selected: [], custom: text })
  246. return
  247. }
  248. output.write(options.length > 0
  249. ? 'Please enter one of the option numbers'
  250. + (question.multiSelect ? ' (comma or space separated)' : '')
  251. + ' or a custom answer'
  252. + '.\n> '
  253. : 'Please enter an answer.\n> ')
  254. }
  255. const disposeUserInteractionProvider = ctx.userInteraction.registerProvider({
  256. ask(request) {
  257. if (disposed || stdinClosed) {
  258. return Promise.reject(
  259. new UserInteractionError('ask_user_question cannot be answered because stdin is closed', 'ASK_ABORTED'),
  260. )
  261. }
  262. return new Promise<AskUserQuestionAnswer>((resolve, reject) => {
  263. const pending: PendingQuestion = {
  264. request,
  265. questionIndex: 0,
  266. answers: [],
  267. resolve,
  268. reject,
  269. onAbort: () => {
  270. if (activeQuestion === pending) {
  271. activeQuestion = undefined
  272. disposeQuestion(pending)
  273. startNextQuestion()
  274. return
  275. }
  276. // If it is not active, this listener can only fire while the ask
  277. // remains queued; settled asks remove the listener first.
  278. questionQueue.splice(questionQueue.indexOf(pending), 1)
  279. disposeQuestion(pending)
  280. },
  281. }
  282. request.signal?.addEventListener('abort', pending.onAbort, { once: true })
  283. questionQueue.push(pending)
  284. startNextQuestion()
  285. })
  286. },
  287. })
  288. reader.on('line', (line) => {
  289. if (activeQuestion !== undefined) {
  290. answerQuestion(line)
  291. return
  292. }
  293. const text = line.trim()
  294. if (!text) return
  295. const agent = ctx.agents.get(agentId)
  296. if (!agent) {
  297. ctx.logger.error('ui-stdio: agent "%s" is not running', agentId)
  298. return
  299. }
  300. submittedWork = true
  301. if (agent.status === 'running') {
  302. agent.steer([{ type: 'text', text }])
  303. } else {
  304. agent.send([{ type: 'text', text }])
  305. }
  306. })
  307. reader.on('close', () => {
  308. // Fires for BOTH stdin EOF and plugin disposal (reader.close() below);
  309. // `disposed` guards teardown so HMR/dispose never exits the process.
  310. stdinClosed = true
  311. if (!disposed) disposePendingQuestions()
  312. maybeExit()
  313. })
  314. output.write(`${welcome}\n> `)
  315. return () => {
  316. disposed = true
  317. if (exitTimer !== undefined) clearTimeout(exitTimer)
  318. disposePendingQuestions()
  319. disposeUserInteractionProvider()
  320. disposeStatusListener()
  321. reader.close()
  322. }
  323. }, 'ui-stdio')
  324. }
  325. /**
  326. * Open the terminal channel once its configured agent exists. Generated stdio
  327. * projects boot the Cordis tree first and create or resume the agent from
  328. * developer code immediately afterward, so stdin must remain untouched until
  329. * the matching `agent/created` notification arrives.
  330. * @param ctx - the context supplying the agent registry and event stream.
  331. * @param config - presentation and target-agent configuration.
  332. * @param runtime - process-I/O seam.
  333. */
  334. export function mountStdio(ctx: Context, config: Config, runtime: StdioRuntime): void {
  335. const agentId = AgentId(config.agent ?? 'main')
  336. if (ctx.agents.get(agentId) !== undefined) {
  337. createStdioChat(ctx, config, runtime)
  338. return
  339. }
  340. const dispose = ctx.on('agent/created', (agent) => {
  341. if (agent.id !== agentId) return
  342. dispose()
  343. createStdioChat(ctx, config, runtime)
  344. })
  345. }
  346. /**
  347. * Cordis entry point. Binds the real `process` streams and delegates to
  348. * {@link mountStdio}; the indirection keeps the side-effecting handles out
  349. * of the testable core, which is why the unit suite drives `createStdioChat`
  350. * directly. This thin wrapper is exercised end-to-end by the keyless
  351. * Loader-path e2e smoke in `examples/echo-agent` (the real product entry).
  352. */
  353. /* v8 ignore start -- production stdio wiring; testable core is createStdioChat() (covered), exercised e2e by echo-agent keyless smoke */
  354. export function apply(ctx: Context, config: Config): void {
  355. mountStdio(ctx, config, {
  356. input: process.stdin,
  357. output: process.stdout,
  358. exit: code => process.exit(code),
  359. })
  360. }
  361. /* v8 ignore stop */