index.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. /**
  2. * @deepseek-ai/dsh-headless — one-shot direct Agent driver. The bundle patch
  3. * rides over dsh-base without Host, HTTP, or browser plugins; this runner
  4. * creates one Agent through the core registry, drives the task to quiescence,
  5. * streams provider reasoning to stderr, flushes its Session, prints the final
  6. * assistant text to stdout, and exits.
  7. *
  8. * @module @deepseek-ai/dsh-headless
  9. */
  10. import { randomUUID } from 'node:crypto'
  11. import type { Context } from '@deepseek-ai/cordis'
  12. import z from '@deepseek-ai/schemastery'
  13. import { installModelSelection } from '@deepseek-ai/dsh-agent'
  14. import type { Agent, ModelSelectionRef } from '@deepseek-ai/dsh-agent'
  15. import type {} from '@deepseek-ai/dsh-agent-default-model'
  16. import { assertNever, createUserMessage } from '@deepseek-ai/dsh-llm'
  17. import { SessionId } from '@deepseek-ai/dsh-session'
  18. import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
  19. // Empty type imports carry the loader Context merge for the settlement await
  20. // and the cmdline Context merge for the appExit host value.
  21. import type {} from '@deepseek-ai/cordis-plugin-loader'
  22. import type {} from '@deepseek-ai/dsh-cmdline'
  23. /** Stable Cordis plugin name. */
  24. export const name = 'headless-runner'
  25. /** Core services required before the one-shot turn can start. */
  26. export const inject = ['agentDefaultModel', 'agents', 'sessions']
  27. /** Plugin config: the task resolved from this app's injected provider service. */
  28. export interface Config {
  29. /** The prompt text for the single run. */
  30. task: string
  31. }
  32. export const Config: z<Config> = z.object({
  33. task: z.string().required(),
  34. })
  35. /** Outcome of one owned run interval. */
  36. interface RunOutcome {
  37. text: string
  38. reason: SessionEvent<'turn/end'>['data']['reason'] | undefined
  39. }
  40. /** Process-facing effects of one run: output streams plus the launcher's bounded exit request. */
  41. interface HeadlessIo {
  42. stdout: { write(chunk: string): unknown }
  43. stderr: { write(chunk: string): unknown }
  44. /** Request process exit with `code` after the tree disposes. */
  45. exit(code: number): void
  46. }
  47. /** The process streams the runner writes to; tests substitute captures. */
  48. export const internals: { stdout: HeadlessIo['stdout']; stderr: HeadlessIo['stderr'] } = {
  49. stdout: process.stdout,
  50. stderr: process.stderr,
  51. }
  52. /** Aggregate the last assistant text and turn outcome in one owned interval. */
  53. function summarize(session: Session, firstSeq: number): RunOutcome {
  54. let started = false
  55. let text = ''
  56. let reason: SessionEvent<'turn/end'>['data']['reason'] | undefined
  57. const length = session.seq
  58. for (let seq = firstSeq; seq < length; seq++) {
  59. const event = session.eventAt(seq)
  60. if (event === undefined) {
  61. throw new Error(`headless summary cannot read seq ${String(seq)} below captured length ${String(length)}`)
  62. }
  63. if (event.type === 'turn/start') {
  64. started = true
  65. continue
  66. }
  67. if (!started) continue
  68. if (event.type === 'assistant/message') {
  69. const joined = event.data.message.content
  70. .filter(block => block.type === 'text')
  71. .map(block => block.text)
  72. .join('')
  73. if (joined !== '') text = joined
  74. }
  75. if (event.type === 'turn/end') reason = event.data.reason
  76. }
  77. return { text, reason }
  78. }
  79. /**
  80. * Project provider-reported reasoning from one owned run to stderr as it is
  81. * appended, while keeping final outcome derivation on the durable log.
  82. * @param ctx - plugin context carrying the Session event feed.
  83. * @param agent - the exact Agent whose reasoning belongs to this invocation.
  84. * @param stderr - progress output sink.
  85. * @returns a disposer that also terminates an unterminated reasoning line.
  86. */
  87. function streamReasoning(
  88. ctx: Context,
  89. agent: Agent,
  90. stderr: HeadlessIo['stderr'],
  91. ): () => void {
  92. let started = false
  93. let open = false
  94. let endsWithNewline = true
  95. const close = (): void => {
  96. if (!open) return
  97. if (!endsWithNewline) stderr.write('\n')
  98. open = false
  99. endsWithNewline = true
  100. }
  101. const dispose = ctx.on('session/event', (session, event) => {
  102. if (session !== agent.session) return
  103. if (event.type === 'turn/start') {
  104. close()
  105. started = true
  106. return
  107. }
  108. if (!started || event.type !== 'assistant/chunk') return
  109. const chunk = event.data.chunk
  110. switch (chunk.type) {
  111. case 'reasoning-delta':
  112. if (chunk.text === '') return
  113. if (!open) {
  114. stderr.write('dsh: reasoning:\n')
  115. open = true
  116. }
  117. stderr.write(chunk.text)
  118. endsWithNewline = chunk.text.endsWith('\n')
  119. return
  120. case 'block-start':
  121. if (chunk.blockType !== 'reasoning') close()
  122. return
  123. case 'block-end':
  124. if (chunk.block.type !== 'reasoning') close()
  125. return
  126. case 'usage':
  127. return
  128. case 'text-delta':
  129. case 'tool-call-delta':
  130. case 'finish':
  131. close()
  132. return
  133. /* v8 ignore next -- closed-union exhaustiveness guard */
  134. default:
  135. return assertNever(chunk, 'headless reasoning stream')
  136. }
  137. })
  138. return () => {
  139. dispose()
  140. close()
  141. }
  142. }
  143. /** Report an unexpected direct-driver failure and request a failing exit. */
  144. function fail(io: HeadlessIo, error: unknown): void {
  145. io.stderr.write(`dsh: ${error instanceof Error ? error.message : String(error)}\n`)
  146. io.exit(1)
  147. }
  148. /**
  149. * Run one task through a freshly created Agent and request process exit.
  150. * @param ctx - plugin context carrying the Agent, default model, Session, and launcher IO services.
  151. * @param task - one-shot task text.
  152. * @param io - process-facing effects.
  153. */
  154. async function run(ctx: Context, task: string, io: HeadlessIo): Promise<void> {
  155. // Loader siblings mount concurrently. Await the complete application before
  156. // creating an Agent so its scoped tools and adapters are not half-composed.
  157. await ctx.get('loader')?.await()
  158. const agents = ctx.get('agents')
  159. const defaultModel = ctx.get('agentDefaultModel')
  160. const sessions = ctx.get('sessions')
  161. // Early process shutdown can dispose the tree while settlement is pending.
  162. if (agents === undefined || defaultModel === undefined || sessions === undefined) return
  163. const selection = defaultModel.currentSelection()
  164. // This bundle composes no preset roster, so the model-facing rows sit in the
  165. // host plane and the agent reads them from the global layer. A deployment
  166. // that DOES configure one has to join it here first
  167. // (@deepseek-ai/dsh-agent-presets README, "Composing a child agent").
  168. const { agent } = await agents.create({
  169. sessionId: SessionId(`session-${randomUUID()}`),
  170. meta: { cwd: process.cwd() },
  171. agentOptions: { provider: selection.provider, model: selection.model },
  172. setup: (agentCtx) => {
  173. const selected: ModelSelectionRef = { current: selection, assembled: undefined }
  174. installModelSelection(agentCtx, selected)
  175. },
  176. })
  177. await agent.whenIdle()
  178. const firstSeq = agent.session.seq
  179. const stopReasoning = streamReasoning(ctx, agent, io.stderr)
  180. try {
  181. agent.followup(createUserMessage({
  182. content: [{ type: 'text', text: task }],
  183. source: { kind: 'user' },
  184. }))
  185. await agent.whenIdle()
  186. } finally {
  187. stopReasoning()
  188. }
  189. await sessions.flush(agent.session)
  190. const outcome = summarize(agent.session, firstSeq)
  191. io.stdout.write(outcome.text + '\n')
  192. if (outcome.reason?.kind === 'error') {
  193. io.stderr.write(`dsh: ${outcome.reason.error.code}: ${outcome.reason.error.message}\n`)
  194. }
  195. io.exit(outcome.reason?.kind === 'completed' ? 0 : 1)
  196. }
  197. /**
  198. * Mount the one-shot direct driver.
  199. * @param ctx - plugin context carrying core services and the launcher-provided exit request.
  200. * @param config - validated task config.
  201. */
  202. export function apply(ctx: Context, config: Config): void {
  203. // Read through the global service store, not the property proxy: appExit is
  204. // an optional host value, never an injected dependency.
  205. const exit = ctx.get('appExit')
  206. if (exit === undefined) {
  207. throw new Error('headless-runner: the launcher must provide ctx.appExit before the tree mounts')
  208. }
  209. const io: HeadlessIo = { stdout: internals.stdout, stderr: internals.stderr, exit }
  210. void run(ctx, config.task, io).catch((error: unknown) => { fail(io, error) })
  211. }