docs: align one-shot demo prose

This commit is contained in:
Tianyi Cui
2026-07-19 13:25:30 +08:00
parent dbe9e307b0
commit 89987f0ad4
15 changed files with 38 additions and 53 deletions
+2 -2
View File
@@ -28,7 +28,7 @@ packages/ @deepseek-ai/dsh-<pkg> workspaces at packages/<group>/<pkg>/
hooks/ Claude Code / Codex hook bridges + shared wire-protocol library
session-persistence/ persistence seam + JSONL/SQLite backends
ui/ ACP/stdio/TUI/JSON-RPC bridges; boot, approval, interaction plugins
examples/ demo bundles (agent-spine + stdio/ACP/JSON-RPC bins) leaves load
examples/ demo bundles (agent-spine + stdio/CLI/ACP/JSON-RPC bins) leaves load
support/ dev/test infrastructure packages
util/ zero-dependency utilities
python/ Python SDK and bundled runtime (see python/README.md)
@@ -47,7 +47,7 @@ pnpm install # pnpm workspaces, node ^22.19 || >=24
pnpm run test # vitest unit tests
pnpm run test:coverage # THE gating test run: per-file 100% coverage on packages/*/*/src
pnpm run test:e2e # real-API tests; self-skip without DEEPSEEK_API_KEY
pnpm run test:snapshot # keyless ACP/headless replay vs goldens; filter: -t <name>
pnpm run test:snapshot # keyless ACP/headless/TUI replay vs goldens; filter: -t <name>
pnpm run test:snapshot:record # re-record goldens (needs key)
pnpm run typecheck
pnpm run lint
+3 -3
View File
@@ -209,11 +209,11 @@ Source: [`packages/bash/bash-sandbox/src/index.ts:27`](../packages/bash/bash-san
## `@deepseek-ai/dsh-cli-demo`
```ts config-catalog
/** App config forwarded to the spine, pre-created agent, and JSONL backend. */
/** App config forwarded to the spine, configured agent, and JSONL backend. */
export interface Config {
/** Provider route for the `main` agent. */
/** Provider route for the configured agent. */
provider: string
/** Model name for the `main` agent; a matching adapter must be registered. */
/** Model name for the configured agent; a matching adapter must be registered. */
model: string
/** Deployment persona forwarded to the system-prompt plugin. */
persona?: string
+1 -1
View File
@@ -7,7 +7,7 @@ How this repo tests, tier by tier, and the rules that keep a green suite meaning
- **Unit** (`pnpm run test`): vitest over `packages|examples/*/tests/**/*.spec.ts`, colocated with what they test. Every registry gets an HMR-safety test (dispose the contributing fiber, assert cleanup). Prefer edge cases, error paths, event ordering, concurrency races, and permanent contract regressions (see `packages/core/agent-loop/tests/contract-regressions.spec.ts`).
- **Coverage gate** (`pnpm run test:coverage`): the gating run, per-file 100% on `packages/*/*/src`. An uncovered line is often dead code the gate is correctly flagging for deletion, not a missing test to bolt on. Line coverage is necessary, never sufficient — it proves lines ran, not that the feature works as shipped.
- **Real-API e2e** (`pnpm run test:e2e`): with-key tests against live provider APIs — the DeepSeek model plus provider-specific smokes that gate on their own keys (`EXA_API_KEY`, `PERPLEXITY_API_KEY`, …); each suite self-skips without its key so keyless CI stays green ([real-API e2e RFC](rfc/implemented/testing/2026-06-19-real-api-e2e-ci.md)).
- **Snapshot** (`pnpm run test:snapshot`): transport-specific keyless goldens cover external presentation. ACP suites boot the real example subprocess, replay a recorded session, and diff normalized stdout plus the re-persisted log ([ACP snapshot RFC](rfc/implemented/testing/2026-06-19-acp-snapshot-tests.md)); `examples/headless-agent` independently pins its `stream-json` event surface through the real one-shot subprocess. TUI completed journeys replay recorded primary/child JSONL through the real agent loop and tools before projecting ANSI into semantic terminal-state goldens; package-local snapshots retain transient renderer states, and a real PTY conversation covers the process boundary ([TUI snapshot RFC](rfc/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)). Use `pnpm run test:snapshot:record` when a model transcript must change and `pnpm run test:snapshot:refresh` when committed replay input remains correct; review every JSONL and golden diff. System-prompt/tool-schema content is pinned by ONE ACP scenario (`text-turn`) and tokenized in every other fixture, so a prompt or schema edit churns one committed line ([pinned-header RFC](rfc/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)).
- **Snapshot** (`pnpm run test:snapshot`): transport-specific keyless goldens cover external presentation. ACP suites boot the real example subprocess, replay a recorded session, and diff normalized JSON-RPC plus the re-persisted log ([ACP snapshot RFC](rfc/implemented/testing/2026-06-19-acp-snapshot-tests.md)); the headless suite independently pins `stream-json` through its real one-shot subprocess. TUI completed journeys replay recorded primary/child JSONL through the real agent loop and tools before projecting ANSI into semantic terminal-state goldens; package-local snapshots retain transient renderer states, and a real PTY conversation covers the process boundary ([TUI snapshot RFC](rfc/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)). Use `pnpm run test:snapshot:record` when a model transcript must change and `pnpm run test:snapshot:refresh` when committed replay input remains correct; review every JSONL and golden diff. System-prompt/tool-schema content is pinned by one ACP scenario (`text-turn`) and tokenized in every other fixture, so a prompt or schema edit churns one committed line ([pinned-header RFC](rfc/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)).
## The with-key policy: inference is cheap here
+1 -1
View File
@@ -25,7 +25,7 @@ Run the Code Mode overlay with `pnpm run demo:code-mode`, or pass `acp` for the
A non-interactive agent demo that accepts one positional task, runs one complete model/tool turn on the `@deepseek-ai/dsh-cli-demo` app, persists a fresh session, prints `text`, `json`, or `stream-json`, and exits.
Run with: `pnpm run demo:headless -- "task"` (needs `DEEPSEEK_API_KEY`). See [headless-agent/README.md](headless-agent/README.md) for the wire contract, mutation and token risks, and the headless-owned snapshot suite.
Run with: `pnpm run demo:headless -- "task"` (needs `DEEPSEEK_API_KEY`). See [headless-agent/README.md](headless-agent/README.md) for the output contract, safety boundaries, and snapshot suite.
## tui-agent
+1 -8
View File
@@ -13,14 +13,6 @@ pnpm run demo:repl
Type a coding task. The agent works through the `read`/`write`/`edit` filesystem tools for ordinary file operations and `bash` (+ the generic `task_output` / `task_list` / `task_kill` for background tasks) for shell commands, searches, and test runs, each in a fresh `bash -c` (the system prompt tells the model to pass `workdir` instead of `cd`). Both the fs tools and bash resolve relative paths against the session workspace. It can also delegate with `subagent`/`subagent_fork` and track multi-step work with `todo_write`.
```
> fix the failing test in /path/to/project
[main turn 1] (reasoning…)
[tool call] bash({"command": "node --test", "workdir": "/path/to/project"})
[tool result] … [exit code: 1]
```
The REPL renders reasoning, tool calls/results, and the latest todo list as line-oriented output suitable for terminals and pipes. Use `pnpm run demo:tui` for the interactive Markdown/card interface.
### Resuming a prior session
@@ -60,6 +52,7 @@ This example is a thin leaf `cordis.yml`: it picks the swappable backends, loads
| `stdio-agent` (`@deepseek-ai/dsh-stdio-demo`) | the app bundle: the agent-spine demo + JSONL persistence + the configured terminal channel + a pre-created `main` agent. This leaf fixes `ui.mode` to `readline`; `tui-agent` owns the corresponding TUI leaf |
| `subagent`, `subagent-spawn`, `subagent-fork` | the subagent provider registry plus the two in-process backends: a fresh child and a child seeded with the parent's completed-turn prefix |
| `tool-subagent`, `tool-subagent-fork` | two model-facing `dsh-tool-subagent` loads, each bound to a different provider and exposed under a distinct tool name (`subagent`, `subagent_fork`) |
| `workflow-workerthread`, `tool-workflow` | the worker-thread workflow engine and its model-facing `workflow` tool, with child calls routed through the spawn backend |
| `tool-todo` | the model-facing `todo_write` tool; writes the whole task list to the session log and renders as a persistent TUI plan or readline checklist |
| `fs-local`, `fs-policy`, `tool-fs` | the filesystem stack: the local `ctx.fs` provider, the read-before-write/edit policy gate (on the `fs/*` event gate), and the model-facing `read`/`write`/`edit` tools. Relative paths resolve against the session workspace |
+1 -1
View File
@@ -13,7 +13,7 @@ pnpm run demo:headless --output-format json -- "summarize the implementation"
pnpm run demo:headless --output-format stream-json -- "run the focused tests"
```
Exactly one nonblank positional task is required; quote tasks containing spaces. There is no `-p` flag. `text` prints the last text-bearing assistant message, `json` prints one DSH-native result record, and `stream-json` emits the parent `main` session's canonical task-turn events before that record. Child sessions surface only through parent tool events and results.
Exactly one nonblank positional task is required; quote tasks containing spaces. There is no `-p` flag. `text` prints the last text-bearing assistant message, `json` prints one DSH-native result record, and `stream-json` emits the top-level session's canonical task-turn events before that record. Child sessions surface only through parent tool events and results.
Each invocation creates and persists a fresh session, runs all model and tool steps in one turn, flushes, disposes, and exits. This is non-interactive automation: there is no prompt, approval, resume, second turn, or stdin context. The configured tools can mutate the launch workspace, run commands, spawn child agents, and consume provider tokens.
+2 -2
View File
@@ -3,7 +3,7 @@
# Headless Agent App Composition
The headless demo combines the real DeepSeek adapter and coding capabilities with the one-shot app package, format-pure stdout, and one fresh persisted main session.
The headless demo combines the real DeepSeek adapter and coding capabilities with the one-shot app package, format-pure stdout, and one fresh persisted top-level session.
```mermaid
flowchart LR
@@ -16,7 +16,7 @@ flowchart LR
cfg --> plugin_headless_cli_agent
plugin_headless_cli_agent --> bundle_agent_core["@deepseek-ai/dsh-agent-spine-demo"]
plugin_headless_cli_agent --> bundle_jsonl["@deepseek-ai/dsh-session-persistence-jsonl"]
plugin_headless_cli_agent --> frontdoor_cli["one-shot driver<br/>format-pure stdout<br/>pre-created main agent"]
plugin_headless_cli_agent --> frontdoor_cli["one-shot driver<br/>format-pure stdout<br/>fresh top-level agent"]
bundle_agent_core --> spine_llm["ctx.llm"]
bundle_agent_core --> spine_sessions["ctx.sessions"]
bundle_agent_core --> spine_tools["ctx.tools + tool-bash"]
-1
View File
@@ -13,7 +13,6 @@
- deepseek-v4-pro
- deepseek-v4-flash
# Local executor for the app bundle's bash tool.
- id: bash
name: '@deepseek-ai/dsh-bash-local'
config:
+7 -9
View File
@@ -1,6 +1,6 @@
# @deepseek-ai/dsh-cli-demo
Headless one-shot app and bin for running one agent task without a readline or editor client. The app composes [`@deepseek-ai/dsh-agent-spine-demo`](../agent-spine-demo/README.md), JSONL persistence, and one fresh `main` agent; the bin submits one task, waits through all model and tool steps, emits the selected result, disposes to quiescence, and exits.
Headless one-shot app and bin for running one agent task without a readline or editor client. It composes [`@deepseek-ai/dsh-agent-spine-demo`](../agent-spine-demo/README.md), JSONL persistence, and exactly one fresh top-level agent. The bin submits the task, waits for its durable turn ending, renders the selected output, disposes to quiescence, and exits.
The package mounts no console logger, readline UI, user-interaction service, or `ask_user_question` tool. Stdout is reserved for the selected output format; diagnostics use stderr.
@@ -8,8 +8,8 @@ The package mounts no console logger, readline UI, user-interaction service, or
| Key | Default | Routed to |
|---|---|---|
| `provider` | required | the pre-created `main` agent's provider route |
| `model` | required | the pre-created `main` agent's model |
| `provider` | required | the configured agent's provider route |
| `model` | required | the configured agent's model |
| `persona` | — | the deployment persona in `dsh-system-prompt` |
| `toolOrder` | lexicographic | explicit model-facing tool order in `dsh-system-prompt` |
| `tools` | `{ mode: 'native' }` | tool-registry presentation config through `dsh-agent-spine-demo` |
@@ -17,8 +17,6 @@ The package mounts no console logger, readline UI, user-interaction service, or
| `persistenceRoot` | `./.sessions` | JSONL session root |
| `workspaceContext` | required | workspace-instruction byte budget, or `false` to disable loading |
Each process creates a new session whose workspace cwd is the launch directory. The app has no resume setting.
## CLI contract
```sh
@@ -39,7 +37,7 @@ Loader configs with bare package specifiers require `node --expose-internals` or
- `text` writes the last assistant message containing text, followed by one newline.
- `json` writes one DSH-native result record: `{ type: "result", success, sessionId, turn, result, reason, usage? }`. `usage` sums every model step in the task turn.
- `stream-json` writes each canonical event from the `main` session's task turn as `{ type: "session_event", sessionId, event }`, then the same result record. Child-agent activity appears only through the parent tool events and results.
- `stream-json` writes each canonical event from the top-level session's task turn as `{ type: "session_event", sessionId, event }`, then the same result record. Child-agent activity appears only through the parent tool events and results.
Only `reason.kind === "completed"` exits successfully. Other durable turn endings still emit partial text or a result record, add a stderr diagnostic, and exit nonzero. Argument and boot failures leave stdout empty. SIGINT and SIGTERM cancel active work, await disposal, and exit 130 and 143 respectively.
@@ -53,12 +51,12 @@ The headless-agent leaf supplies local bash, filesystem, skill, subagent, workfl
### One-shot task turn
**What the model sees**: The positional task becomes one user message. Through `dsh-agent-spine-demo`, the `main` agent also receives configured workspace instructions and persona, the skill catalog, visible tool schemas, and retained tool results needed for later steps in the same turn.
**What the model sees**: The positional task becomes one user message. Through `dsh-agent-spine-demo`, the top-level agent also receives configured workspace instructions and persona, the skill catalog, visible tool schemas, and retained tool results needed for later steps in the same turn.
**Token effect**: The task, prompt sections, tool schemas, assistant output, and tool results consume tokens on each model step. JSON event streaming and final rendering add no model tokens; delegated child work has its own model usage and is not included in the parent result's `usage` total.
## Known Limitations and Deferred Work
- **One fresh main session per process** — there is no resume, second prompt, stdin context, or concurrent top-level session in this app.
- **One fresh top-level session per process** — its workspace cwd is the launch directory; there is no resume, second prompt, stdin context, or concurrent top-level session in this app.
- **No interactive question or approval provider** — tools that require a human answer cannot complete unless a different leaf composes a non-interactive provider with explicit policy.
- **Streaming is main-session-only** — child sessions are not flattened into the stream, and aggregate usage covers only model steps recorded on the parent task turn.
- **Streaming is top-level-session-only** — child sessions are not flattened into the stream, and aggregate usage covers only model steps recorded on the parent task turn.
+11 -14
View File
@@ -1,6 +1,6 @@
/**
* Covered command parser and one-turn driver for `dsh-cli-demo`. The executable
* entry only installs process signal handlers and delegates here.
* Command parser and one-turn driver for `dsh-cli-demo`. The executable wrapper
* owns process signals; this module owns output, durability, and cleanup.
* @module @deepseek-ai/dsh-cli-demo/cli
*/
@@ -44,9 +44,9 @@ export interface CliResult {
export interface OneShotOptions {
/** Exactly one nonblank user task. */
readonly task: string
/** Optional cancellation signal owned by the process wrapper. */
/** Optional signal that cancels the selected agent. */
readonly signal?: AbortSignal
/** Synchronous observer for each canonical event in the selected task turn. */
/** Synchronous task-turn observer; a throw cancels the agent and fails the run after flush. */
readonly onEvent?: (sessionId: string, event: SessionEvent) => void
}
@@ -91,12 +91,10 @@ class CliInterruptedError extends Error {
}
}
/** Convert an unknown thrown value to an Error without losing its text. */
function toError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error))
}
/** Render the reason carried by an AbortSignal. */
function interruptionReason(signal: AbortSignal): string {
return signal.reason === undefined ? 'interrupted' : String(signal.reason)
}
@@ -145,7 +143,6 @@ export function parseCliArgs(args: readonly string[]): CliCommand {
}
}
/** Add one model step's usage into a detached turn total. */
function addUsage(total: TokenUsage | undefined, step: TokenUsage): TokenUsage {
const next: TokenUsage = {
inputTokens: (total?.inputTokens ?? 0) + step.inputTokens,
@@ -157,7 +154,6 @@ function addUsage(total: TokenUsage | undefined, step: TokenUsage): TokenUsage {
return next
}
/** Select the text blocks from an assistant message, or undefined when it has none. */
function assistantText(event: Extract<SessionEvent, { type: 'assistant/message' }>): string | undefined {
const blocks = event.data.content.filter(block => block.type === 'text')
return blocks.length === 0 ? undefined : blocks.map(block => block.text).join('')
@@ -189,8 +185,11 @@ async function waitForStartupIdle(agent: Agent, signal?: AbortSignal): Promise<v
* Run one message-triggered turn on the configured top-level agent, aggregate its
* final text and model usage, wait for idle plus an explicit persistence flush,
* and return its durable ending. Only the selected agent's task turn reaches
* `onEvent`; startup injections and unrelated sessions are ignored.
* @param ctx - settled Loader root containing `ctx.agents` and `ctx.sessions`.
* `onEvent`; startup injections and unrelated sessions are ignored. The context
* must contain exactly one top-level agent. Signal abort cancels that agent; an
* abort before the correlated task turn rejects. An observer throw cancels the
* turn and is rethrown after the agent reaches idle and the session flushes.
* @param ctx - settled Loader root containing one agent plus `ctx.sessions`.
* @param options - task, optional cancellation, and optional stream observer.
* @returns the DSH-native result envelope after durable quiescence.
*/
@@ -291,7 +290,6 @@ export async function runOneShot(ctx: Context, options: OneShotOptions): Promise
}
}
/** Render one final result in the selected output encoding. */
function renderResult(outputFormat: OutputFormat, result: CliResult): string {
return outputFormat === 'text' ? `${result.result}\n` : `${JSON.stringify(result)}\n`
}
@@ -315,9 +313,8 @@ export function formatTurnFailure(reason: TurnEndReason): string {
}
/**
* Parse, boot, run, render, diagnose, and dispose one CLI invocation. Argument
* and boot failures never write stdout; all booted contexts are disposed before
* this promise resolves.
* Execute one CLI invocation. Argument and boot failures never write stdout;
* every booted context is disposed before this promise resolves.
* @param args - arguments after the executable name.
* @param runtime - optional injected process boundaries for tests and embedding.
* @returns the ordinary process exit code; the thin bin overrides it for Unix signals.
+5 -5
View File
@@ -1,6 +1,6 @@
/**
* Headless one-shot app composition: the default agent spine, JSONL session
* persistence, and one pre-created `main` agent. The CLI driver owns task
* persistence, and one fresh top-level agent. The CLI driver owns task
* submission and output; the app deliberately mounts no interactive or logging
* front door so stdout remains protocol-pure.
* @module @deepseek-ai/dsh-cli-demo
@@ -18,11 +18,11 @@ const DEFAULT_PERSISTENCE_ROOT = './.sessions'
export const name = 'cli-demo'
/** App config forwarded to the spine, pre-created agent, and JSONL backend. */
/** App config forwarded to the spine, configured agent, and JSONL backend. */
export interface Config {
/** Provider route for the `main` agent. */
/** Provider route for the configured agent. */
provider: string
/** Model name for the `main` agent; a matching adapter must be registered. */
/** Model name for the configured agent; a matching adapter must be registered. */
model: string
/** Deployment persona forwarded to the system-prompt plugin. */
persona?: string
@@ -51,7 +51,7 @@ export const Config: z<Config> = z.object({
})
/**
* Compose the UI-less spine, a fresh `main` agent rooted at the process cwd,
* Compose the UI-less spine, a fresh top-level agent rooted at the process cwd,
* and JSONL persistence. Swappable adapters, executors, and product tools stay
* in the leaf `cordis.yml`.
* @param ctx - app context that owns the composed child plugins.
@@ -57,7 +57,7 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi
private root: string
private coordinator: PersistenceCoordinator<number>
/** Runtime-only host-platform seam for directory-sync compatibility tests. */
/** Runtime host platform used to decide whether directory sync is supported. */
readonly internals: { platform: NodeJS.Platform } = { platform: process.platform }
constructor(ctx: Context, public config: Config) {
+1 -1
View File
@@ -2,7 +2,7 @@
A replay LLM plugin for keyless snapshot tests. It yields model streams reconstructed from a recorded **session JSONL** fixture, so a test can boot the real agent against a fixed model transcript with no API key. With `providers` configured it registers a replay-only adapter whose catalog is visible to clients such as ACP editors; without `providers` it installs the catch-all `llm/stream` waterfall used by tests that do not need discovery.
Its consumers are the ACP snapshot harness in `examples/acp-agent` and the `stream-json` snapshot in `examples/headless-agent`; each loads this plugin in place of a real LLM adapter. The package exists so its derive/parse/replay logic falls under the per-file 100% coverage gate on `packages/*/src` (the same logic, while it lived under `examples/`, was outside the gate).
Its consumers are the ACP snapshot harness in `examples/acp-agent` and the `stream-json` snapshot in `examples/headless-agent`; each loads this plugin in place of a real LLM adapter. Keeping derivation and replay here places that logic under the per-file 100% coverage gate on `packages/*/src`.
## How the fixture works
@@ -7,8 +7,6 @@
* zero-build dev path, resolving `@deepseek-ai/dsh-*` / `@cordisjs/*` through the tsconfig `paths`
* map) or from built `lib/` under plain Node (resolving bare packages through real `exports`, as an
* installed consumer does, while Node type-strips relative example-local TypeScript plugins).
* Consolidating that spawn glue here retires the copies in the ACP snapshot harness and the example
* e2e drivers (the `TODO(acp-test-harness)`).
*
* @module @deepseek-ai/dsh-loader-smoke
*/
+2 -2
View File
@@ -448,7 +448,7 @@ const APP_EXAMPLES = [
title: 'Headless Agent App Composition',
label: 'examples/headless-agent',
config: 'examples/headless-agent/cordis.yml',
summary: 'The headless demo combines the real DeepSeek adapter and coding capabilities with the one-shot app package, format-pure stdout, and one fresh persisted main session.',
summary: 'The headless demo combines the real DeepSeek adapter and coding capabilities with the one-shot app package, format-pure stdout, and one fresh persisted top-level session.',
},
{
id: 'cordis',
@@ -483,7 +483,7 @@ function renderAppExpansion(lines: string[], appNode: string, pluginName: string
: 'dsh-tui (TTY) / dsh-stdio (pipes)<br/>pre-created main agent'
lines.push(` ${appNode} --> ${nodeId('frontdoor', 'stdio')}["${frontDoor}"]`)
} else if (pluginName === '@deepseek-ai/dsh-cli-demo') {
lines.push(` ${appNode} --> ${nodeId('frontdoor', 'cli')}["one-shot driver<br/>format-pure stdout<br/>pre-created main agent"]`)
lines.push(` ${appNode} --> ${nodeId('frontdoor', 'cli')}["one-shot driver<br/>format-pure stdout<br/>fresh top-level agent"]`)
} else if (pluginName === '@deepseek-ai/dsh-acp-demo') {
lines.push(` ${appNode} --> ${nodeId('frontdoor', 'acp')}["@deepseek-ai/dsh-acp<br/>JSON-RPC stdio bridge<br/>sessions created by client"]`)
}