index.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /**
  2. * The stdio chat app: the default agent spine ({@link @deepseek-ai/dsh-agent-spine-demo}) plus the
  3. * coupled front-door cluster a terminal chat needs — TTY-selected pi-tui/readline
  4. * presentation, JSONL session persistence, the user-interaction seam with its
  5. * `ask_user_question` tool, and one pre-created agent whose exact shared
  6. * agent/session identity the selected UI drives under its `main` display label.
  7. * Swappable adapters, executors, optional tools, and HMR stay in the leaf. This
  8. * Loader plugin intentionally exposes named exports only; a default export
  9. * would hide its `Config` schema (see docs/postmortem/0001).
  10. * @module @deepseek-ai/dsh-stdio-demo
  11. */
  12. import type { Context } from 'cordis'
  13. import { randomUUID } from 'node:crypto'
  14. import ConsoleExporter from '@cordisjs/plugin-logger-console'
  15. import z from 'schemastery'
  16. import { SessionId } from '@deepseek-ai/dsh-session'
  17. import ToolRegistry, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools'
  18. import * as agentCore from '@deepseek-ai/dsh-agent-spine-demo'
  19. import * as workspaceContext from '@deepseek-ai/dsh-workspace-context'
  20. import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl'
  21. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  22. import * as toolAskUser from '@deepseek-ai/dsh-tool-ask-user'
  23. import * as uiStdio from '@deepseek-ai/dsh-stdio'
  24. import * as uiTui from '@deepseek-ai/dsh-tui'
  25. export const name = 'stdio-demo'
  26. const DEFAULT_PERSISTENCE_ROOT = './.sessions'
  27. const DEFAULT_WELCOME = 'ready.'
  28. /** Terminal front door selected by the app bundle. */
  29. export type TerminalMode = 'auto' | 'readline' | 'tui'
  30. /** App-level terminal selection with nested TUI presentation settings. */
  31. export interface UiConfig {
  32. /** Select a concrete front door or infer it from the process streams. */
  33. mode?: TerminalMode
  34. /** Settings forwarded only when the pi-tui front door is selected. */
  35. tui?: uiTui.TuiConfig
  36. }
  37. const terminalModeSchema = z.union(['auto', 'readline', 'tui'] as const).default('auto')
  38. /** Schemastery schema for app-level terminal selection. */
  39. export const UiConfigSchema: z<UiConfig> = z.object({
  40. mode: terminalModeSchema,
  41. tui: uiTui.TuiConfigSchema,
  42. })
  43. /**
  44. * Resolve the app's terminal front door.
  45. * @param config - app-level terminal selection.
  46. * @param isTTY - whether both process streams are interactive TTYs.
  47. * @returns the concrete UI package to mount.
  48. */
  49. export function resolveTerminalMode(config: UiConfig | undefined, isTTY: boolean): Exclude<TerminalMode, 'auto'> {
  50. const mode = config?.mode ?? 'auto'
  51. if (mode === 'auto') return isTTY ? 'tui' : 'readline'
  52. if (mode === 'tui' && !isTTY) {
  53. throw new Error('stdio-demo: TUI mode requires both stdin and stdout to be TTYs; use mode "readline" for pipes')
  54. }
  55. return mode
  56. }
  57. /**
  58. * App config: the swappable per-demo values, each routed to where the app wires
  59. * it. `provider`/`model`/`resumeSessionId` configure the pre-created `main` agent (through
  60. * {@link @deepseek-ai/dsh-agent-spine-demo}'s forwarded `agents` list); `persona` is
  61. * the deployment persona (forwarded to the system-prompt plugin); `toolOrder`
  62. * is the explicit model-facing tool order (forwarded to the system-prompt plugin);
  63. * fresh sessions use `process.cwd()` as their workspace cwd; resumed sessions
  64. * keep their persisted cwd. `persistenceRoot` is the JSONL backend's directory;
  65. * `welcome` is the UI banner and `ui` configures terminal mode/presentation.
  66. */
  67. export interface Config {
  68. /** Provider route for the `main` agent. */
  69. provider: string
  70. /** Model name for the `main` agent (must have a registered adapter). */
  71. model: string
  72. /** Bundled agent-loop concurrency cap; `1` is serial and omission uses its default. */
  73. maxParallelToolCalls?: number
  74. /** Deployment persona (the system-prompt plugin's `persona` config). */
  75. persona?: string
  76. /** Explicit model-facing tool order (the system-prompt plugin's `toolOrder` config; see dsh-system-prompt). */
  77. toolOrder?: string[]
  78. /** Tool-registry config — its presentation `mode` (forwarded through agent-spine-demo; see dsh-tools). */
  79. tools?: ToolsConfig
  80. /** DeepSeek Harness home directory exposed to bash and used for local skill discovery. */
  81. dshHome?: string
  82. /** Directory the JSONL session backend writes under. Defaults to `./.sessions`. */
  83. persistenceRoot?: string
  84. /** stdin-chat banner printed once on start. Defaults to `'ready.'`. */
  85. welcome?: string
  86. /** Terminal front-door selection and pi-tui presentation settings. */
  87. ui?: UiConfig
  88. /** Skill registry, local-provider, and model-facing consumer config forwarded to agent-spine-demo. */
  89. skills?: agentCore.SkillConfig
  90. /** Model-facing bash tool config forwarded through agent-core. */
  91. toolBash?: NonNullable<agentCore.Config['toolBash']>
  92. /** Generic background-task control-tool config forwarded through agent-core. */
  93. toolTasks?: NonNullable<agentCore.Config['toolTasks']>
  94. /**
  95. * If set, the pre-created agent RESUMES this persisted session id instead of
  96. * starting fresh. Sourced from an env var in the leaf `cordis.yml`
  97. * (`resumeSessionId: !!js process.env.RESUME_SESSION_ID`).
  98. */
  99. resumeSessionId?: string
  100. /** Controls automatic AGENTS.md/CLAUDE.md loading; configure a byte budget or set `false`. */
  101. workspaceContext: agentCore.Config['workspaceContext']
  102. }
  103. export const Config: z<Config> = z.object({
  104. provider: z.string().required(),
  105. model: z.string().required(),
  106. maxParallelToolCalls: z.number().step(1).min(1),
  107. persona: z.string(),
  108. // The array default is forced to undefined: ABSENT means "lexicographic
  109. // order" (the owning dsh-system-prompt schema does the same), while
  110. // schemastery's native [] default would read as an invalid configured list.
  111. toolOrder: z.array(z.string()).default(undefined as unknown as string[]),
  112. tools: ToolRegistry.Config,
  113. dshHome: z.string(),
  114. persistenceRoot: z.string().default(DEFAULT_PERSISTENCE_ROOT),
  115. welcome: z.string().default(DEFAULT_WELCOME),
  116. ui: UiConfigSchema,
  117. skills: agentCore.SkillConfigSchema,
  118. toolBash: agentCore.ToolBashConfigSchema,
  119. toolTasks: agentCore.ToolTasksConfigSchema,
  120. resumeSessionId: z.string(),
  121. workspaceContext: z.union([z.const(false), workspaceContext.Config]).required(),
  122. })
  123. /**
  124. * Compose the spine with one terminal front door. Persistence and user
  125. * interaction mount first; the selected UI then waits on the exact session id
  126. * and subscribes to config-start failures before agent-core starts it. Console
  127. * logging is readline-only because fullscreen output belongs to pi-tui. The
  128. * ask-user tool waits on the completed spine, and HMR remains a leaf concern.
  129. * @param ctx - context receiving the app's child plugins.
  130. * @param config - app configuration routed to the spine and front door.
  131. * @param isTTY - whether both process streams are interactive TTYs.
  132. */
  133. export function composeTerminalApp(ctx: Context, config: Config, isTTY: boolean): void {
  134. const resumeSessionId = config.resumeSessionId === '' ? undefined : config.resumeSessionId
  135. const sessionId = SessionId(resumeSessionId ?? `main-session-${randomUUID()}`)
  136. const mode = resolveTerminalMode(config.ui, isTTY)
  137. if (mode === 'readline') ctx.plugin(ConsoleExporter)
  138. ctx.plugin(SessionPersistenceJsonl, { root: config.persistenceRoot ?? DEFAULT_PERSISTENCE_ROOT })
  139. ctx.plugin(UserInteractionService)
  140. if (mode === 'tui') {
  141. ctx.plugin(uiTui, {
  142. ...config.ui?.tui,
  143. welcome: config.welcome ?? DEFAULT_WELCOME,
  144. sessionId,
  145. })
  146. } else {
  147. ctx.plugin(uiStdio, {
  148. welcome: config.welcome ?? DEFAULT_WELCOME,
  149. sessionId,
  150. })
  151. }
  152. ctx.plugin(agentCore, {
  153. ...agentCore.pickSpineConfig(config),
  154. agents: [{
  155. id: SessionId('main'),
  156. provider: config.provider,
  157. model: config.model,
  158. cwd: process.cwd(),
  159. ...resumeSessionId === undefined ? { sessionId } : { resumeSessionId: sessionId },
  160. }],
  161. })
  162. ctx.plugin(toolAskUser)
  163. }
  164. /** Compose the configured terminal front door with the agent app. */
  165. /* v8 ignore start -- production stream capability wiring; composeTerminalApp is unit-covered,
  166. and the coding-agent PTY smoke covers the interactive process path */
  167. export function apply(ctx: Context, config: Config): void {
  168. composeTerminalApp(ctx, config, process.stdin.isTTY && process.stdout.isTTY)
  169. }
  170. /* v8 ignore stop */