headless.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /**
  2. * `dsh -p "task"` — headless over the one shared composition: AppCLIEntry
  3. * boots the same base plus Web overlay as `dsh web` (port 0, so parallel runs never
  4. * collide), then in-process isomorphic injection (InProcessApiClient over
  5. * toFetchHandler(ctx.apiProxy), so the full carrier chain — wire
  6. * serialization, zod, SSE framing — really runs). The printed URL opens the
  7. * live session in a browser while the task runs. Runs one task turn, prints
  8. * the final assistant text, exits (completed → 0, else 1).
  9. */
  10. import { fileURLToPath } from 'node:url'
  11. import { InProcessApiClient, toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
  12. import type { MuxFrame } from '@deepseek-ai/dsh-host-apiproxy/api'
  13. import type { RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
  14. import type { SessionId } from '@deepseek-ai/dsh-session'
  15. import { AppCLIEntry } from './app-cli-entry.ts'
  16. import { createProcessShutdown } from './process-shutdown.ts'
  17. /** Outcome of one headless turn: aggregated final text plus the turn-end reason kind. */
  18. interface TurnOutcome {
  19. text: string
  20. reason: string
  21. }
  22. /** Unwrap an RpcResponse or fail loud: business errors print and exit 1 (shutdown first). */
  23. async function unwrap<T>(response: RpcResponse<T>, shutdown: () => Promise<void>): Promise<T> {
  24. if (response.result.ok) return response.result.value
  25. const { code, message } = response.result.error
  26. process.stderr.write(`dsh: ${code}: ${message}\n`)
  27. await shutdown()
  28. process.exit(1)
  29. }
  30. /**
  31. * Consume mux frames until the task turn ends, per the cli-demo runOneShot
  32. * correlation precedent: anchor on the first turn/start whose trigger kind is
  33. * 'message' (startup-injected turns are skipped), aggregate text from that
  34. * turn's assistant/message events (last one wins), finish on its turn/end.
  35. */
  36. async function consumeUntilTurnEnd(frames: AsyncIterable<RpcRequest<MuxFrame>>, sessionId: SessionId): Promise<TurnOutcome> {
  37. let targetTurn: number | undefined
  38. let text = ''
  39. try {
  40. for await (const frame of frames) {
  41. const payload = frame.payload
  42. if (payload.type === 'stream/error') {
  43. process.stderr.write(`dsh: stream error: ${payload.error.message}\n`)
  44. return { text, reason: 'error' }
  45. }
  46. if (payload.type !== 'session/event' || payload.sessionId !== sessionId) continue
  47. const event = payload.event
  48. if (targetTurn === undefined) {
  49. if (event.type === 'turn/start' && event.data.trigger.kind === 'message') targetTurn = event.data.turn
  50. continue
  51. }
  52. if (event.type === 'assistant/message' && event.data.turn === targetTurn) {
  53. const joined = event.data.message.content.filter(block => block.type === 'text').map(block => block.text).join('')
  54. if (joined !== '') text = joined
  55. }
  56. if (event.type === 'turn/end' && event.data.turn === targetTurn) {
  57. return { text, reason: event.data.reason.kind }
  58. }
  59. }
  60. } catch (error: unknown) {
  61. process.stderr.write(`dsh: event stream failed: ${String(error)}\n`)
  62. }
  63. return { text, reason: 'error' }
  64. }
  65. /**
  66. * Run one headless turn for `task` and exit (completed → 0, else 1). The task
  67. * is the non-empty prompt the argument adapter parsed from `-p`/`--prompt`
  68. * (the adapter rejects an empty task, so no guard is needed here).
  69. * @param task - the prompt text for the single turn.
  70. */
  71. export async function runHeadless(task: string): Promise<void> {
  72. // A missing DEEPSEEK_API_KEY throws here (plugin load is fail-loud, uncaught by design).
  73. const entry = new AppCLIEntry({
  74. configPath: fileURLToPath(new URL('../config/base.cordis.yml', import.meta.url)),
  75. overlayPath: fileURLToPath(new URL('../config/web.cordis.yml', import.meta.url)),
  76. dev: false,
  77. watchPersonalConfig: false,
  78. port: 0,
  79. })
  80. const { ctx, port } = await entry.run()
  81. // Normal completion and signals share one bounded drain. A signal received
  82. // during that drain escalates immediately instead of becoming a no-op.
  83. const shutdown = createProcessShutdown(async () => { await ctx.fiber.dispose() })
  84. process.on('SIGTERM', () => { shutdown.interrupt(143) })
  85. process.on('SIGINT', () => { shutdown.interrupt(130) })
  86. // The headless session is web-observable while it runs (same composition).
  87. process.stderr.write(`dsh: observing at http://127.0.0.1:${String(port)}\n`)
  88. const api = new InProcessApiClient(toFetchHandler(ctx.apiProxy))
  89. const created = await unwrap(await api.sessions.create({}), () => shutdown.shutdown(1))
  90. // Open the stream before prompting so no frame is lost — kept in this order
  91. // even though in-process delivery has no race, so the code survives a move
  92. // to a remote HTTP carrier unchanged.
  93. const abort = new AbortController()
  94. const frames = api.events.mux({}, abort.signal)
  95. const done = consumeUntilTurnEnd(frames, created.sessionId)
  96. await unwrap(await api.sessions.prompt({
  97. sessionId: created.sessionId,
  98. mode: 'queue',
  99. content: [{ type: 'text', text: task }],
  100. }), () => shutdown.shutdown(1))
  101. const outcome = await done
  102. process.stdout.write(outcome.text + '\n')
  103. abort.abort()
  104. await shutdown.shutdown(outcome.reason === 'completed' ? 0 : 1)
  105. }