index.ts 17 KB

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