Merge remote-tracking branch 'origin/master' into cross-family-fs-sandbox

# Conflicts:
#	docs/config-catalog.md
#	docs/cordis-catalog/services.md
#	docs/module-graph.md
#	docs/rfc/implemented/feature/2026-07-06-sandbox.md
#	examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.golden.md
#	examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.golden.json
#	examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.golden.md
#	examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.golden.json
#	examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.golden.md
#	examples/acp-agent/tests/snapshots/escalation-approved/session.jsonl
#	examples/acp-agent/tests/snapshots/escalation-rejected/session.jsonl
#	examples/acp-agent/tests/snapshots/hook-cc-pretool-ask/session.jsonl
#	examples/acp-agent/tests/snapshots/permission-switching/session.jsonl
#	examples/acp-agent/tests/snapshots/permission-switching/system-prompt.golden.md
#	examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.golden.json
#	examples/acp-agent/tests/snapshots/skill-load/tool-schemas.golden.json
#	examples/acp-agent/tests/snapshots/text-turn/tool-schemas.golden.json
#	examples/acp-agent/tests/snapshots/workspace-edit/system-prompt.golden.md
#	examples/acp-agent/tests/snapshots/workspace-edit/tool-schemas.golden.json
#	packages/bash/bash-sandbox/src/index.ts
#	packages/bash/bash-sandbox/tests/bwrap.e2e.ts
#	packages/bash/bash-sandbox/tests/sandbox.spec.ts
#	packages/bash/bash-sandbox/tests/seatbelt.e2e.ts
#	packages/bash/bash/src/index.ts
#	packages/bash/tool-bash/package.json
#	packages/bash/tool-bash/src/index.ts
#	packages/bash/tool-bash/src/render.ts
#	packages/bash/tool-bash/tests/tools.spec.ts
#	packages/bash/tool-bash/tsconfig.json
#	pnpm-lock.yaml
#	scripts/verify-package-readme-model-experience.ts
This commit is contained in:
kingwl
2026-07-16 23:31:51 +08:00
242 changed files with 17052 additions and 2980 deletions

View File

@@ -4,7 +4,7 @@ Packages use the `@deepseek-ai/dsh-*` scope. Each is a Cordis `Service` subclass
## Hierarchy
Packages are grouped by modular role at `packages/<group>/<pkg>/`. The group directory is a pure container (no `package.json`); the package name stays `@deepseek-ai/dsh-<pkg>` regardless of group. **Each group README is the canonical per-package map** — package roles, ctx keys, and the product-vs-support split live there, next to the code.
Packages live at `packages/<group>/<pkg>/`; groups are containers, while names remain `@deepseek-ai/dsh-<pkg>`. **Each group README is the canonical package/ctx-key map.**
| Group | Role | Release expectation |
|---|---|---|
@@ -18,6 +18,7 @@ Packages are grouped by modular role at `packages/<group>/<pkg>/`. The group dir
| [`compact/`](compact/README.md) | Compaction capability family: the abstract seam + a basic backend (tool deferred) | Product — stable surface |
| [`context/`](context/README.md) | Opt-in request-context enrichment | Product — stable surface |
| [`subagent/`](subagent/README.md) | Subagent capability family: the provider-registry seam and the model-facing delegation tool | Product — stable surface |
| [`tasks/`](tasks/README.md) | Generic background-task runtime and model-facing `task_*` control tools | Product — stable surface |
| [`workflow/`](workflow/README.md) | Workflow capability family: the script-engine seam, the worker-thread engine, and the model-facing `workflow` tool | Product — stable surface |
| [`web/`](web/README.md) | Web capability family: the abstract seam, search/fetch provider impls, and the model-facing web tools | Product — stable surface |
| [`timeout/`](timeout/README.md) | Tool-call timeout policy: the `tools/execute` deadline enforcer | Product — stable surface |
@@ -27,12 +28,13 @@ Packages are grouped by modular role at `packages/<group>/<pkg>/`. The group dir
| [`hooks/`](hooks/README.md) | Hook bridges + the shared Claude Code / Codex wire-protocol library | Product — stable surface |
| [`session-persistence/`](session-persistence/README.md) | Persistence capability family: the seam + JSONL/SQLite backends | Product — stable surface |
| [`session-query/`](session-query/README.md) | Session retrieval family: logical corpus, surface records, and bounded exact reads | Product — stable surface |
| [`sdk/`](sdk/README.md) | Project SDK tooling | Product — stable surface |
| [`ui/`](ui/README.md) | Editor/client integration surfaces: ACP bridge, JSON-RPC SDK server, user-approval/user-interaction seams, ask-user tool | Product — stable surface |
| [`examples/`](examples/README.md) | Demo bundles (agent-spine + stdio/ACP/JSON-RPC bins) the leaves load | Support — example infra |
| [`support/`](support/README.md) | Support infrastructure (invariants, replay, Loader smokes) | Support — lower compatibility expectations |
| [`util/`](util/README.md) | Low-level zero-dependency utilities shared across groups (the `Branded<B>` primitive) | Support — small, stable, harness-dep-free |
The split is the point: a package's group says whether it is part of the product API or support/test/example infrastructure, so release and removal decisions do not treat every package as an equal public contract. New packages join an existing group; adding a new top-level group is a deliberate act (extend the group READMEs and this table).
Groups distinguish product API from support infrastructure. New packages join an existing group; a new group updates its README and this table.
## Dependencies

View File

@@ -7,6 +7,6 @@ The canonical three-package capability seam (see [capability seams](../../docs/r
| `bash/` | Abstract bash executor seam (interface + vocabulary; sandbox result facts carry the [`sandbox/`](../sandbox/README.md) seam's mode/enforcement vocabulary) | `ctx.bash` |
| `bash-local/` | Local-subprocess `BashExecutor` implementation | (registers `ctx.bash`) |
| `bash-sandbox/` | Sandbox-consuming `BashExecutor` (wraps every command argv via `ctx.sandbox`, stamps denial/enforcement facts; extends `bash-local`'s mechanics) | (registers `ctx.bash`) |
| `tool-bash/` | Model-facing `bash`/`bash_output`/`bash_kill` tool schemas | (registers on `ctx.tools`) |
| `tool-bash/` | Model-facing `bash` schema; background processes register with the generic [`tasks/`](../tasks/README.md) runtime | (registers on `ctx.tools`) |
The interface lives at `bash/bash/`. `bash-sandbox` replacing `bash-local` without touching the interface or the tool is the split doing exactly what it exists for — a leaf `cordis.yml` picks one executor entry, plus a `ctx.sandbox` provider entry for the confined one (see [the acp-agent example's default composition](../../examples/acp-agent/)).

View File

@@ -24,12 +24,12 @@ Design surveyed against the bash tools of Claude Code, OpenCode, Codex, and pi;
- **Spawn per call, no shell state** — every call is a fresh non-login `bash -c` (deterministic; no rc files). All four surveyed tools spawn per call. `XXX(stateful-shell)` in `src/run.ts` records the two proven stateful designs (Claude Code's cwd-only persistence; Codex's PTY exec sessions) for when real workflows demand them.
- **Process-group kills with escalation** — children are spawned `detached` (own process group); kills send SIGTERM to the group, then SIGKILL after the `graceMs` grace (default 3s — OpenCode's escalation; pipelines and subshells die with the parent). ESRCH is tolerated; daemons that re-parent away from the group can still survive — same caveat as the surveyed tools.
- **Tail-keep truncation + spill files** — output beyond `maxOutputBytes` keeps the in-memory TAIL (errors/results cluster at the end — pi/OpenCode rationale) while the FULL stream is appended to a temp file whose path is reported when available. If the final spill close reports a delayed writeback failure, the executor still returns the tail but withholds the path rather than advertising a possibly incomplete file.
- **Model-friendly environment** — ambient credential-shaped variables are removed before noninteractive terminal defaults and explicit caller entries are applied. Supplied stdin is written and closed; otherwise fd 0 is `/dev/null`. Trusted plugins use `env` and `stdin`, but the model-facing tool does not expose them. See the [bash stdin/env RFC](../../../docs/rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md).
- **Background tasks** — `start()` returns immediately, no timeout applies (Claude Code detaches timeouts when backgrounding), `readOutput()` is incremental with whole-stream byte offsets, and disposal kills everything. The spec's opaque `owner` token is stored on the tracked task and returned by `ownerOf(id)` — the executor never interprets it (the consumer's access policy does), and because it lives with the task here it survives a `tool-bash` HMR reload.
- **Model-friendly env + credential scrub** — `process.env` minus credential-shaped vars (`*KEY*`/`*SECRET*`/`*TOKEN*`), then `NO_COLOR=1 TERM=dumb PAGER=cat GIT_PAGER=cat` (Codex's hardcoded set) so pagers and ANSI color don't garble results. This scrub is the security control that keeps the harness's *ambient* credentials out of a spawned command. A spec's `env` is merged LAST (after the scrub), so a caller's explicit entry — a value it already holds — wins even on a credential-shaped name. The spec's `stdin`, when supplied, is written to the child and closed; with none supplied, fd 0 is `/dev/null` — the exact pre-seam default, so a command that probes stdin's file type is unaffected. Both `env`/`stdin` are set by in-process plugins (the hooks bridges); the model-facing tool doesn't expose them. See [the bash-stdin-env RFC](../../../docs/rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md).
- **Background processes** — `start()` returns a live `BashProcess` handle immediately, no timeout applies (Claude Code detaches timeouts when backgrounding), the handle's `readOutput()` is incremental with whole-stream byte offsets, and disposal kills every running process and awaits its exit. Everything task-shaped (ids, ownership, polling, notices) lives in the generic [`ctx.tasks` runtime](../../tasks/tasks/README.md), which the tool layer registers the handle with — this executor never sees a session or a registry.
## Model Experience
Indirectly, through `dsh-tool-bash`, which renders this executor's bounded stdout/stderr tails, background-task deltas and state, spill-file path, exact `Error: unknown bash task "<taskId>"` and `Error: aborted before spawn: <reason>` failures, and retains each resulting tool message until compaction.
Indirectly, through `dsh-tool-bash`, which renders this executor's bounded stdout/stderr tails, background-process deltas, spill-file paths, and infrastructure failures.
## Known Limitations and Deferred Work
@@ -38,6 +38,5 @@ Indirectly, through `dsh-tool-bash`, which renders this executor's bounded stdou
- **POSIX-only** — the `bash` binary, detached process groups, group kills, and SIGTERM→SIGKILL escalation are hardcoded; Windows is unsupported.
- **The credential scrub is a name heuristic** — `*KEY*`/`*SECRET*`/`*TOKEN*` only; differently-named secrets (e.g. `*PASSWORD*`) pass through, and a whitelist for over-scrubbed vars is noted future work.
- **Spill files are never deleted** — full-output recovery files (and the private per-process spill dir) accumulate under the OS tmpdir until something external cleans them.
- **Finished background tasks are never evicted** — they stay in the task map, retaining their in-memory output tails, until executor disposal.
The raw process handling lives in `src/run.ts`; `src/index.ts` is the service wiring.

View File

@@ -1,15 +1,14 @@
/**
* Local-subprocess implementation of the bash seam. Each call runs in its own
* process group, background tasks are tracked, and disposal kills and awaits
* them. Execution policy belongs in `tools/pre-execute` or a sandboxing
* executor, not this local process layer.
* Local-subprocess implementation of the bash executor seam. Each command runs
* as `bash -c` in its own process group; disposal kills and joins live groups.
* Execution policy belongs in `tools/pre-execute` or a sandboxing executor.
* @module @deepseek-ai/dsh-bash-local
*/
import { Context } from 'cordis'
import z from 'schemastery'
import { BashExecutor, BashTaskId } from '@deepseek-ai/dsh-bash'
import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskRead, OwnerToken } from '@deepseek-ai/dsh-bash'
import { BashExecutor } from '@deepseek-ai/dsh-bash'
import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult } from '@deepseek-ai/dsh-bash'
import { clampTimeout, deadline, timeoutOf } from '@deepseek-ai/dsh-timeout'
import { DEFAULT_GRACE_MS, runBash } from './run.ts'
import type { RunInternals, RunningBash } from './run.ts'
@@ -37,20 +36,9 @@ function assertPositiveFinite(name: string, value: number): void {
}
}
interface TrackedTask extends BashTask {
running: RunningBash
/** Whole-stream byte offsets already delivered via {@link LocalBashExecutor.readOutput}. */
stdoutOffset: number
stderrOffset: number
/** Opaque owner token from the {@link BashExecSpec} (the consumer's isolation key). */
owner: OwnerToken | undefined
}
/**
* Local-subprocess bash executor. Defaults follow the agent-tool survey
* consensus: 120s default / 600s max timeout (Claude Code, OpenCode), 64KB
* in-memory output with full-stream spill files (pi, OpenCode),
* process-group SIGTERM→SIGKILL kills with a 3s grace (OpenCode).
* Local bash executor with bounded output, spill files, and process-group
* `SIGTERM` to `SIGKILL` escalation.
*/
export class LocalBashExecutor extends BashExecutor {
static Config: z<Config> = z.object({
@@ -61,8 +49,8 @@ export class LocalBashExecutor extends BashExecutor {
graceMs: z.number().default(DEFAULT_GRACE_MS),
})
private tasks = new Map<BashTaskId, TrackedTask>()
private nextTaskId = 1
/** Live processes retained only so disposal can kill and join them. */
private live = new Map<BashProcess, RunningBash>()
/** Test seam: spill knobs forwarded to runBash. */
internals: RunInternals = {}
@@ -71,26 +59,21 @@ export class LocalBashExecutor extends BashExecutor {
constructor(ctx: Context, config: Config) {
super(ctx)
// schemastery (static Config) has already filled the defaulted fields;
// the cast records that runtime fact for exactOptionalPropertyTypes.
// Schemastery fills these fields before construction; the type does not encode that step.
this.config = config as ResolvedConfig
assertPositiveFinite('timeoutMs', this.config.timeoutMs)
assertPositiveFinite('maxTimeoutMs', this.config.maxTimeoutMs)
assertPositiveFinite('maxOutputBytes', this.config.maxOutputBytes)
assertPositiveFinite('graceMs', this.config.graceMs)
ctx.effect(() => async () => {
// Kill every live process group and WAIT for the processes to close so nothing outlives
// the fiber (HMR safety) — a TERM-trapping child is held until the SIGKILL escalation
// lands.
// Await closure so even a TERM-trapping child cannot outlive the fiber.
const pending: Promise<void>[] = []
for (const task of this.tasks.values()) {
if (task.status === 'running') {
task.status = 'killed'
task.running.kill()
pending.push(task.done)
}
for (const [proc, running] of this.live) {
proc.status = 'killed'
running.kill()
pending.push(proc.done)
}
this.tasks.clear()
this.live.clear()
await Promise.all(pending)
}, 'local bash teardown')
}
@@ -114,24 +97,16 @@ export class LocalBashExecutor extends BashExecutor {
workdir: request.workdir ?? this.config.cwd ?? process.cwd(),
timeoutMs,
...request.signal ? { signal: request.signal } : {},
// Carry stdin/env through verbatim — optional, no config default (absent
// means none). env merges AFTER the scrub in run.ts.
// Explicit environment values are merged after credential scrubbing in run.ts.
...request.stdin !== undefined ? { stdin: request.stdin } : {},
...request.env !== undefined ? { env: request.env } : {},
// Carry the owner through verbatim (required-but-nullable on the spec):
// the executor never interprets it — the consumer's access policy does.
owner: request.owner,
// Carry a sandbox-mode override through verbatim: this executor never
// confines, so the field is inert here (the seam contract) — a
// sandboxing subclass overrides resolve() to stamp its default instead.
// Local execution carries this override for sandboxing subclasses.
sandboxMode: request.sandboxMode,
}
}
async run(spec: BashExecSpec): Promise<BashRunResult> {
// One fused deadline drives both the timeout and upstream cancellation;
// runBash listens on d.signal and runs the SIGTERM→grace→SIGKILL kill.
// `using` clears the timer across the awaited process lifetime.
// One deadline combines timeout and upstream cancellation; disposal clears its timer.
using d = deadline(spec.signal, spec.timeoutMs, 'BASH_TIMEOUT')
const outcome = await runBash({
command: spec.command,
@@ -142,18 +117,14 @@ export class LocalBashExecutor extends BashExecutor {
stdin: spec.stdin,
env: spec.env,
}, this.internals).done
// Classify the FIRST abort reason: a BASH_TIMEOUT TimeoutReason means our timeout cut the
// command short; any other abort — an upstream cancel, or a foreign (outer) deadline's
// timeout under nesting — is aborted.
// Only this executor's timeout reason counts as timedOut; outer deadlines count as aborts.
const timedOut = timeoutOf(d.signal, 'BASH_TIMEOUT') !== undefined
const aborted = d.signal.aborted && !timedOut
return { ...outcome, timedOut, aborted, timeoutMs: spec.timeoutMs }
}
start(spec: BashExecSpec): BashTask {
// No timeout for background tasks (matches Claude Code, which detaches the timeout when
// backgrounding); callers stop tasks via kill() — or via spec.signal, which the seam
// contract honors for background runs too (runBash wires it to the group kill).
start(spec: BashExecSpec): BashProcess {
// Background runs ignore timeoutMs; callers stop them through kill() or spec.signal.
const running = runBash({
command: spec.command,
cwd: spec.workdir,
@@ -164,93 +135,66 @@ export class LocalBashExecutor extends BashExecutor {
env: spec.env,
}, this.internals)
const id = BashTaskId(`bash-${this.nextTaskId++}`)
const task: TrackedTask = {
id,
let stdoutOffset = 0
let stderrOffset = 0
const proc: BashProcess = {
status: 'running',
exitCode: null,
signal: null,
owner: spec.owner,
running,
stdoutOffset: 0,
stderrOffset: 0,
done: running.done.then((outcome) => {
// Abort-killed tasks report as killed, not completed. Background runs
// forward only the upstream signal (no timeout), so its aborted state
// is the authoritative "was this cancelled" signal.
if (task.status === 'running') task.status = spec.signal?.aborted === true ? 'killed' : 'completed'
task.exitCode = outcome.exitCode
task.signal = outcome.signal
this.notifyTaskDone(task)
// Any signal termination is killed, including a command signaling itself.
if (proc.status === 'running') {
proc.status = spec.signal?.aborted === true || outcome.signal !== null ? 'killed' : 'completed'
}
proc.exitCode = outcome.exitCode
proc.signal = outcome.signal
this.onProcessDone(proc, running.stderr.readFrom(0).text)
this.live.delete(proc)
}, (error: unknown) => {
// Spawn-level failure (bad workdir, …): the task never ran. String()
// suffices — runBash only rejects with Error instances.
task.status = 'killed'
task.running.stderr.push(Buffer.from(`spawn failed: ${String(error)}`))
this.notifyTaskDone(task)
// Background spawn failures settle as killed and surface through the read path.
proc.status = 'killed'
running.stderr.push(Buffer.from(`spawn failed: ${String(error)}`))
this.onProcessDone(proc, running.stderr.readFrom(0).text)
this.live.delete(proc)
}),
}
this.tasks.set(id, task)
return task
}
readOutput: (): BashProcessRead => {
const out = running.stdout.readFrom(stdoutOffset)
const err = running.stderr.readFrom(stderrOffset)
stdoutOffset = out.nextOffset
stderrOffset = err.nextOffset
get(id: BashTaskId): BashTask | undefined {
return this.tasks.get(id)
// Single newline between sections: stdout chunks usually end with one
// already; add it only when missing.
const separator = out.text.length > 0 && !out.text.endsWith('\n') ? '\n' : ''
const delta = out.text
+ (err.text.length > 0 ? `${separator}[stderr]\n${err.text}` : '')
return {
delta,
lossy: out.lossy || err.lossy,
...out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {},
...err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {},
}
},
kill: (): boolean => {
if (proc.status !== 'running') return false
proc.status = 'killed'
running.kill()
return true
},
}
this.live.set(proc, running)
return proc
}
/**
* Full collected stderr of a tracked task from stream start (bounded by the
* in-memory cap; bytes only in the spill file are not re-read). A protected
* seam for subclasses that classify a settled task's outcome — reading here
* does NOT advance the consumer's {@link readOutput} cursor. An unknown id
* (a task already dropped by disposal) reads as empty.
* Settlement hook for subclasses that attach execution facts to a process.
* Called after exit facts or spawn-failure output are stamped and before
* {@link BashProcess.done} resolves. The base implementation is intentionally
* empty.
* @param _proc - the settled process handle.
* @param _stderr - the process's retained stderr tail used by subclasses for settlement classification.
*/
protected collectedStderr(id: BashTaskId): string {
const task = this.tasks.get(id)
return task === undefined ? '' : task.running.stderr.readFrom(0).text
}
ownerOf(id: BashTaskId): OwnerToken | undefined {
// Unknown id and known-but-ownerless both read as undefined — the consumer
// treats undefined as "open" and a truly unknown id fails at readOutput/kill.
return this.tasks.get(id)?.owner
}
list(): BashTask[] {
return [...this.tasks.values()]
}
readOutput(id: BashTaskId): BashTaskRead {
const task = this.tasks.get(id)
if (!task) throw new Error(`unknown bash task "${id}"`)
const out = task.running.stdout.readFrom(task.stdoutOffset)
const err = task.running.stderr.readFrom(task.stderrOffset)
task.stdoutOffset = out.nextOffset
task.stderrOffset = err.nextOffset
// Single newline between sections: stdout chunks usually end with one
// already; add it only when missing.
const separator = out.text.length > 0 && !out.text.endsWith('\n') ? '\n' : ''
const delta = out.text
+ (err.text.length > 0 ? `${separator}[stderr]\n${err.text}` : '')
return {
task,
delta,
lossy: out.lossy || err.lossy,
...out.spillPath !== undefined ? { stdoutSpillPath: out.spillPath } : {},
...err.spillPath !== undefined ? { stderrSpillPath: err.spillPath } : {},
}
}
kill(id: BashTaskId): boolean {
const task = this.tasks.get(id)
if (!task) throw new Error(`unknown bash task "${id}"`)
if (task.status !== 'running') return false
task.status = 'killed'
task.running.kill()
return true
}
protected onProcessDone(_proc: BashProcess, _stderr: string): void {}
}
export default LocalBashExecutor

View File

@@ -1,11 +1,10 @@
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
import { BashTaskId } from '@deepseek-ai/dsh-bash'
import type { BashTaskRead } from '@deepseek-ai/dsh-bash'
import type { BashProcess } from '@deepseek-ai/dsh-bash'
const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-exec-spec-'))
@@ -18,36 +17,20 @@ async function setup(config: ConstructorParameters<typeof LocalBashExecutor>[1]
return { ctx, bash }
}
/** Poll until a pid no longer exists. */
async function waitGone(pid: number, timeoutMs = 5_000): Promise<void> {
/**
* Poll a handle's consuming readOutput until the ACCUMULATED delta contains
* `expected`; returns the accumulation (reads never re-deliver, so the caller
* gets everything produced up to the match).
*/
async function readUntil(proc: BashProcess, expected: string, timeoutMs = 5_000): Promise<string> {
const deadline = Date.now() + timeoutMs
let all = ''
while (Date.now() < deadline) {
try {
process.kill(pid, 0)
} catch {
return
}
all += proc.readOutput().delta
if (all.includes(expected)) return all
await new Promise(resolve => setTimeout(resolve, 20))
}
throw new Error(`pid ${pid} still alive after ${timeoutMs}ms`)
}
async function readUntil(
bash: LocalBashExecutor,
id: BashTaskId,
expected: string,
timeoutMs = 5_000,
): Promise<BashTaskRead> {
const deadline = Date.now() + timeoutMs
let last: BashTaskRead | undefined
let delta = ''
while (Date.now() < deadline) {
last = bash.readOutput(id)
delta += last.delta
if (delta.includes(expected)) return { ...last, delta }
await new Promise(resolve => setTimeout(resolve, 20))
}
throw new Error(`task ${id} output did not include ${JSON.stringify(expected)}; output was ${JSON.stringify(delta)}, last delta was ${JSON.stringify(last?.delta ?? '')}`)
throw new Error(`process output did not include ${JSON.stringify(expected)}; accumulated ${JSON.stringify(all)}`)
}
describe('LocalBashExecutor.run', () => {
@@ -90,15 +73,6 @@ describe('LocalBashExecutor.run', () => {
expect(() => bash.resolve({ command: 'true', timeoutMs: -1 })).toThrow(/request\.timeoutMs/)
})
it('kill escalation uses the configured graceMs (a TERM-trapping task dies by SIGKILL)', async () => {
const { bash } = await setup() // setup pins graceMs: 200 via config
const task = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo ready; while :; do sleep 60 & wait $!; done' }))
await readUntil(bash, task.id, 'ready\n')
bash.kill(task.id)
await task.done
expect(task.signal).toBe('SIGKILL')
})
it('per-call timeout takes precedence under the cap and kills on expiry', async () => {
const { bash } = await setup({ timeoutMs: 60_000 })
const result = await bash.run(bash.resolve({ command: 'sleep 60', timeoutMs: 100 }))
@@ -154,229 +128,183 @@ describe('LocalBashExecutor.run', () => {
})
})
describe('LocalBashExecutor background tasks', () => {
it('start returns immediately with a registered running task', async () => {
describe('LocalBashExecutor.start (background process handles)', () => {
it('start returns immediately with a running handle that settles as completed', async () => {
const { bash } = await setup()
const before = Date.now()
const task = bash.start(bash.resolve({ command: 'sleep 0.2; echo done' }))
const proc = bash.start(bash.resolve({ command: 'sleep 0.2; echo done' }))
expect(Date.now() - before).toBeLessThan(150)
expect(task.status).toBe('running')
expect(bash.get(task.id)).toBe(task)
expect(bash.list()).toContain(task)
await task.done
expect(task.status).toBe('completed')
expect(task.exitCode).toBe(0)
expect(proc.status).toBe('running')
await proc.done
expect(proc.status).toBe('completed')
expect(proc.exitCode).toBe(0)
})
it('assigns sequential ids', async () => {
it('threads stdin and extra env into a background process', async () => {
const { bash } = await setup()
const first = bash.start(bash.resolve({ command: 'true' }))
const second = bash.start(bash.resolve({ command: 'true' }))
expect(first.id).toBe('bash-1')
expect(second.id).toBe('bash-2')
await Promise.all([first.done, second.done])
})
it('threads stdin and extra env into a background task', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({
const proc = bash.start(bash.resolve({
command: 'cat; echo "[$DSH_BG_VAR]"',
stdin: 'bg-stdin\n',
env: { DSH_BG_VAR: 'bg-env' },
}))
const read = await readUntil(bash, task.id, '[bg-env]')
expect(read.delta).toContain('bg-stdin')
await task.done
expect(task.exitCode).toBe(0)
const output = await readUntil(proc, '[bg-env]')
expect(output).toContain('bg-stdin')
await proc.done
expect(proc.exitCode).toBe(0)
})
it('readOutput returns increments without re-delivery', async () => {
it('readOutput is consuming: increments are never re-delivered, and reads stay valid after exit', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({ command: 'echo first; sleep 1; echo second' }))
const first = await readUntil(bash, task.id, 'first\n')
expect(first.delta).toBe('first\n')
expect(first.lossy).toBe(false)
await task.done
const second = bash.readOutput(task.id)
const proc = bash.start(bash.resolve({ command: 'echo first; sleep 1; echo second' }))
const first = await readUntil(proc, 'first\n')
expect(first).toBe('first\n')
await proc.done
// Read-after-exit returns the remaining buffered output — once.
const second = proc.readOutput()
expect(second.delta).toBe('second\n')
const third = bash.readOutput(task.id)
expect(third.delta).toBe('')
expect(second.lossy).toBe(false)
expect(proc.readOutput().delta).toBe('')
})
it('readOutput marks stderr sections', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({ command: 'echo out; echo err >&2' }))
await task.done
const read = bash.readOutput(task.id)
expect(read.delta).toBe('out\n[stderr]\nerr\n')
const proc = bash.start(bash.resolve({ command: 'echo out; echo err >&2' }))
await proc.done
expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
})
it('readOutput reports stderr-only deltas without a leading newline', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({ command: 'echo err >&2' }))
await task.done
expect(bash.readOutput(task.id).delta).toBe('[stderr]\nerr\n')
const proc = bash.start(bash.resolve({ command: 'echo err >&2' }))
await proc.done
expect(proc.readOutput().delta).toBe('[stderr]\nerr\n')
})
it('readOutput flags lossy reads and reports spill paths', async () => {
it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
const { bash } = await setup()
const proc = bash.start(bash.resolve({ command: 'printf out; echo err >&2' }))
await proc.done
expect(proc.readOutput().delta).toBe('out\n[stderr]\nerr\n')
})
it('readOutput flags lossy reads and reports stdout spill paths', async () => {
const { bash } = await setup({ maxOutputBytes: 100 })
const task = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done' }))
await task.done
const read = bash.readOutput(task.id)
const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i; done' }))
await proc.done
const read = proc.readOutput()
// Window slid past offset 0 → lossy, spill path points at the full stream.
expect(read.lossy).toBe(true)
expect(read.stdoutSpillPath).toBeDefined()
})
it('readOutput throws for unknown ids', async () => {
const { bash } = await setup()
expect(() => bash.readOutput(BashTaskId('nope'))).toThrow(/unknown bash task "nope"/)
})
it('kill terminates the process group and reports status killed', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({ command: 'sleep 60' }))
expect(bash.kill(task.id)).toBe(true)
await task.done
expect(task.status).toBe('killed')
expect(task.signal).toBe('SIGTERM')
})
it('kill returns false for finished tasks and throws for unknown ids', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({ command: 'true' }))
await task.done
expect(bash.kill(task.id)).toBe(false)
expect(() => bash.kill(BashTaskId('nope'))).toThrow(/unknown bash task "nope"/)
})
it('notifies onTaskDone listeners on completion', async () => {
const { bash } = await setup()
const seen: [string, string][] = []
bash.onTaskDone(task => void seen.push([task.id, task.status]))
const task = bash.start(bash.resolve({ command: 'true' }))
await task.done
expect(seen).toEqual([[task.id, 'completed']])
})
it('notifies onTaskDone for killed tasks too', async () => {
const { bash } = await setup()
const listener = vi.fn()
bash.onTaskDone(listener)
const task = bash.start(bash.resolve({ command: 'sleep 60' }))
bash.kill(task.id)
await task.done
expect(listener).toHaveBeenCalledWith(task)
expect(task.status).toBe('killed')
})
it('marks tasks killed when the background spawn itself fails', async () => {
const { bash } = await setup()
const listener = vi.fn()
bash.onTaskDone(listener)
const task = bash.start(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))
await task.done
expect(task.status).toBe('killed')
expect(listener).toHaveBeenCalledWith(task)
expect(bash.readOutput(task.id).delta).toContain('spawn failed')
})
it('readOutput adds a separator only when stdout lacks a trailing newline', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({ command: 'printf out; echo err >&2' }))
await task.done
expect(bash.readOutput(task.id).delta).toBe('out\n[stderr]\nerr\n')
})
it('readOutput reports stderr spill paths', async () => {
const { bash } = await setup({ maxOutputBytes: 100 })
const task = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i >&2; done' }))
await task.done
const read = bash.readOutput(task.id)
const proc = bash.start(bash.resolve({ command: 'for i in $(seq 1 100); do printf "line-%04d\\n" $i >&2; done' }))
await proc.done
const read = proc.readOutput()
expect(read.lossy).toBe(true)
expect(read.stderrSpillPath).toBeDefined()
expect(read.delta).toContain('[stderr]')
})
it('disposing with already-finished tasks only kills the running ones', async () => {
it('kill() terminates the process group: true once, false after settlement', async () => {
const { bash } = await setup()
const proc = bash.start(bash.resolve({ command: 'sleep 60' }))
expect(proc.kill()).toBe(true)
await proc.done
expect(proc.status).toBe('killed')
expect(proc.signal).toBe('SIGTERM')
expect(proc.kill()).toBe(false)
})
it('kill() returns false for a naturally completed process', async () => {
const { bash } = await setup()
const proc = bash.start(bash.resolve({ command: 'true' }))
await proc.done
expect(proc.status).toBe('completed')
expect(proc.kill()).toBe(false)
})
it('kill escalation uses the configured graceMs (a TERM-trapping process dies by SIGKILL)', async () => {
const { bash } = await setup() // setup pins graceMs: 200 via config
// The child echoes AFTER arming the trap, so waiting for the marker
// guarantees SIGTERM is already ignored when the kill lands (a fixed sleep
// is load-flaky: a slow spawn would take the SIGTERM before the trap).
const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo armed; sleep 60' }))
await readUntil(proc, 'armed')
proc.kill()
await proc.done
expect(proc.status).toBe('killed')
expect(proc.signal).toBe('SIGKILL')
})
it('a spec.signal abort settles the handle as killed, not completed', async () => {
const { bash } = await setup()
const controller = new AbortController()
const proc = bash.start(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
controller.abort()
await proc.done
expect(proc.status).toBe('killed')
expect(proc.signal).toBe('SIGTERM')
})
it('a self-signal exit settles the handle as killed, not completed', async () => {
const { bash } = await setup()
const proc = bash.start(bash.resolve({ command: 'kill -TERM $$' }))
await proc.done
expect(proc.status).toBe('killed')
expect(proc.exitCode).toBeNull()
expect(proc.signal).toBe('SIGTERM')
})
it('a background spawn failure settles as killed with the error readable on stderr', async () => {
const { bash } = await setup()
const proc = bash.start(bash.resolve({ command: 'true', workdir: '/nonexistent-dsh' }))
// done resolves (never rejects) even though the process never ran.
await expect(proc.done).resolves.toBeUndefined()
expect(proc.status).toBe('killed')
expect(proc.readOutput().delta).toContain('spawn failed:')
})
})
describe('LocalBashExecutor disposal', () => {
it('disposing the fiber kills running processes and AWAITS their exit (no orphans, SIGKILL escalation included)', async () => {
const ctx = new Context()
const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
const bash = ctx.bash as LocalBashExecutor
bash.internals = { spillDir }
const finished = bash.start(bash.resolve({ command: 'true' }))
// The child prints its own pid ($$ = the detached bash group leader) so
// the test can probe liveness through the public read surface alone.
const proc = bash.start(bash.resolve({ command: 'trap \'\' TERM; echo $$; sleep 60' }))
const pid = Number((await readUntil(proc, '\n')).trim())
expect(Number.isInteger(pid) && pid > 0).toBe(true)
await fiber.dispose()
// Disposal itself waited: the pid must already be gone, no grace left —
// even for a TERM-trapping child held until the SIGKILL escalation landed.
expect(() => process.kill(pid, 0)).toThrow()
expect(proc.status).toBe('killed')
await proc.done
})
it('settled processes already left the live map: dispose does not touch them', async () => {
const ctx = new Context()
const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
const bash = ctx.bash as LocalBashExecutor
bash.internals = { spillDir }
const finished = bash.start(bash.resolve({ command: 'echo done' }))
await finished.done
expect(finished.status).toBe('completed')
const running = bash.start(bash.resolve({ command: 'sleep 60' }))
await fiber.dispose()
await running.done
// The teardown marks every LIVE entry killed; a settled process had
// already left the map, so its status stays completed.
expect(finished.status).toBe('completed')
expect(running.status).toBe('killed')
await running.done
expect(running.signal).toBe('SIGTERM')
expect(bash.list()).toEqual([])
})
it('disposing the executor fiber kills running tasks (no orphans)', async () => {
const ctx = new Context()
const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
const bash = ctx.bash as LocalBashExecutor
bash.internals = { spillDir }
const listener = vi.fn()
bash.onTaskDone(listener)
const task = bash.start(bash.resolve({ command: 'sleep 60' }))
const running = bash.get(task.id)!
await new Promise(resolve => setTimeout(resolve, 50))
// Grab the pid before dispose clears the registry.
const pid = (running as unknown as { running: { pid: number } }).running.pid
await fiber.dispose()
await waitGone(pid)
expect(bash.list()).toEqual([])
// Listener silenced by base-class teardown — no late notifications.
expect(listener).not.toHaveBeenCalled()
})
})
describe('executor cancellation, callback, and disposal contracts', () => {
it('start honors a pre-aborted or later-aborted AbortSignal', async () => {
const { bash } = await setup()
const controller = new AbortController()
const task = bash.start(bash.resolve({ command: 'sleep 60', signal: controller.signal }))
controller.abort()
await task.done
expect(task.status).toBe('killed')
expect(task.signal).toBe('SIGTERM')
})
it('a throwing onTaskDone listener does not reject task.done or starve later listeners', async () => {
const { bash } = await setup()
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
const second = vi.fn()
try {
bash.onTaskDone(() => { throw new Error('listener bug') })
bash.onTaskDone(second)
const task = bash.start(bash.resolve({ command: 'true' }))
await expect(task.done).resolves.toBeUndefined()
expect(second).toHaveBeenCalledWith(task)
expect(errorSpy).toHaveBeenCalled()
} finally {
errorSpy.mockRestore()
}
})
it('dispose AWAITS a TERM-trapping process (SIGKILL escalation included)', async () => {
const ctx = new Context()
const fiber = await ctx.plugin(LocalBashExecutor, { graceMs: 200 })
const bash = ctx.bash as LocalBashExecutor
bash.internals = { spillDir }
const task = bash.start(bash.resolve({ command: 'trap \'\' TERM; sleep 60' }))
await new Promise(resolve => setTimeout(resolve, 100))
const pid = (task as unknown as { running: { pid: number } }).running.pid
await fiber.dispose()
// Disposal itself waited: the pid must already be gone, no grace left.
expect(() => process.kill(pid, 0)).toThrow()
expect(task.status).toBe('killed')
})
})

View File

@@ -2,21 +2,23 @@
Sandbox-consuming implementation of the [`@deepseek-ai/dsh-bash`](../bash/) executor seam. Load it **instead of** `@deepseek-ai/dsh-bash-local`, together with a [`ctx.sandbox`](../../sandbox/sandbox/) provider (e.g. [`@deepseek-ai/dsh-sandbox-local`](../../sandbox/sandbox-local/)) — no alternate tool plugin is needed; `dsh-tool-bash` detects the executor's `sandboxMode` capability and adds the escalation fields.
The package root exports the default and named `SandboxBashExecutor` plugin plus its `Config`; quoting and result-classification helpers stay internal.
Every command is confined by handing the provider the exact `['bash', '-c', command]` argv this executor is about to spawn and spawning the returned (wrapped) argv instead. WHICH platform runner confines it — and whether one is usable at all (fail closed with a structured `SANDBOX_UNAVAILABLE` error, never a silent unconfined run) — is the provider's concern; this package owns the bash side only.
| Mode | File effects |
|---|---|
| `read-only` (default) | No writes anywhere (of `/dev`, only the `/dev/null` node is writable, so `>/dev/null` keeps working) |
| `workspace-write` | Writes only under `workspaceRoot` + `/tmp` (ephemeral under bwrap, the host `/tmp` under Landlock, `/private/tmp` plus the per-user temp dir under Seatbelt) |
| `danger-full-access` | No confinement; the provider is never consulted. Execution is `dsh-bash-local`'s verbatim — foreground results still carry `sandbox: { mode, denied: false }` (no `enforcement`: nothing was confined), background tasks carry no sandbox facts |
| `danger-full-access` | No confinement; the provider is never consulted. Foreground results carry `sandbox: { mode, denied: false }`; background process handles carry no sandbox facts. |
Semantics:
- **Denials are result facts.** A failed run whose stderr carries the selected backend's own denial dialect — the signatures the provider stamps on every wrap (EROFS text under bwrap, EACCES under Landlock, EPERM under Seatbelt) — is reported as `BashRunResult.sandbox.denied: true` (conservative classification, read from the collected stderr tail); every CONFINED run also carries the mode it executed under (`result.sandbox.mode`) and the provider's enforcement completeness (`result.sandbox.enforcement`: `full`, or `partial` on an older Landlock ABI).
- **Runner failures are sandbox failures, never task failures.** A failed run matching the wrap's `runnerFailureSignatures` (the runner's own error prefix — also what the shell prints for a missing runner) means the sandbox itself broke and the command NEVER RAN; the check outranks denial classification because a runner's error text can contain denial words. The foreground path re-throws it as the structured fail-closed `SANDBOX_UNAVAILABLE` error, with the runner's first stderr line as the cause; a settled background task stamps `task.sandbox.runnerFailed` instead (no error channel remains after settle), which `bash_output` renders as its own marker.
- **Config default, per-call override.** `resolve()` stamps the configured sandbox mode onto each spec unless an approved request supplies a wider mode. That override affects only its call or background task. `ctx.bash.sandboxMode` reports the default so the tool advertises escalation only when supported; results report the effective mode. The model learns standing mode only from tool/result facts, not a system-prompt announcement.
- **Runner failures are sandbox failures, never command failures.** Foreground execution throws `SANDBOX_UNAVAILABLE`; a settled background process stamps `process.sandbox.runnerFailed`, which the bash producer renders through generic `task_output`. Spawn failures also pass through settlement, so confined background handles retain their mode/enforcement facts and release per-process accounting.
- **Config-time default, per-call policy.** The DEFAULT mode is fixed by this entry's config for the executor's lifetime; `resolve()` stamps it onto every spec, and an explicit request-level `sandboxMode` override — set by the tool layer only for a call whose wider mode a human granted through `ctx.approval` ([the sandbox RFC § Escalation](../../../docs/rfc/implemented/feature/2026-07-06-sandbox.md)) — makes THAT call run, classify, and report under its own mode while every neighbor keeps the default (background facts are stamped per task at settle). The capability fact `ctx.bash.sandboxMode` reports the configured default so the tool layer advertises escalation only when this executor is mounted. The model learns of the sandbox only through result facts — the static bash tool description explains the denial marker; there is no current-mode statement in the system prompt.
- **File effects only.** Network and process visibility are deliberately not restricted — the mode vocabulary does not pretend to cover what the backend does not enforce.
- Process mechanics (spawn, process-group kills, output collection/spill, background tasks, credential scrub) are inherited verbatim from [`dsh-bash-local`](../bash-local/); the runner ladder, probes, and the per-platform Landlock launcher packages live with [`dsh-sandbox-local`](../../sandbox/sandbox-local/).
- Process mechanics (spawn, process-group kills, output collection/spill, background handles, credential scrub) are inherited from [`dsh-bash-local`](../bash-local/); runner selection lives in [`dsh-sandbox-local`](../../sandbox/sandbox-local/).
Deny-only at the seam: a denial is a reported fact, and this executor never negotiates permissions itself — the approval question lives in the tool layer (`dsh-tool-bash`), which drives the override this package honors.
@@ -56,5 +58,5 @@ The keyless consumer-integration proofs are `tests/bwrap.e2e.ts`, `tests/landloc
- **Confinement covers file effects only** — network access and process visibility are unchanged, so the modes are not a general-purpose security sandbox.
- **Denials are inferred from failed-command stderr** — backend signatures make the inference portable, but a matching application error can be classified as a denial and a denial omitted from the retained tail can be missed.
- **A background runner failure has no immediate error channel** — it is recorded on the settled task and surfaces when the caller polls with `bash_output`.
- **A background runner failure has no immediate error channel** — it is recorded on the settled process and surfaces when the caller reads the generic task with `task_output`.
- **`danger-full-access` deliberately bypasses `ctx.sandbox`** — it is an explicit unconfined mode, not a wider sandbox profile.

View File

@@ -0,0 +1,49 @@
/**
* Internal shell-quoting and sandbox-result classification helpers.
*
* @module @deepseek-ai/dsh-bash-sandbox/helpers
*/
import type { BashRunResult } from '@deepseek-ai/dsh-bash'
/**
* Quote one string as a single-quoted POSIX shell word.
* @param text - raw argv element to preserve through the outer shell parse.
* @returns the quoted shell word.
*/
export function shellQuote(text: string): string {
return `'${text.replaceAll("'", String.raw`'\''`)}'`
}
/**
* Classify a failed run against the selected backend's denial dialect.
* @param result - settled foreground run.
* @param signatures - case-insensitive denial substrings from the active wrap.
* @returns whether the failed run matches that denial dialect.
*/
export function classifyDenial(result: BashRunResult, signatures: readonly string[]): boolean {
return matchesSignature(result.exitCode, result.stderr.text, signatures)
}
/**
* Classify a failed run against the selected backend's runner-failure dialect.
* @param result - settled foreground run.
* @param signatures - case-insensitive runner-failure substrings from the active wrap.
* @returns whether the failed run matches that runner-failure dialect.
*/
export function classifyRunnerFailure(result: BashRunResult, signatures: readonly string[]): boolean {
return matchesSignature(result.exitCode, result.stderr.text, signatures)
}
/**
* Match a non-zero exit against case-insensitive stderr signatures.
* @param exitCode - process exit code; null means signal termination.
* @param stderr - collected stderr text.
* @param signatures - substrings identifying the selected backend's dialect.
* @returns whether this is a non-zero exit whose stderr matches a signature.
*/
export function matchesSignature(exitCode: number | null, stderr: string, signatures: readonly string[]): boolean {
if (exitCode === null || exitCode === 0) return false
const lowered = stderr.toLowerCase()
return signatures.some(signature => lowered.includes(signature.toLowerCase()))
}

View File

@@ -3,17 +3,18 @@
* `ctx.sandbox`, inherits local process mechanics, and reports the selected
* mode, enforcement, and denial facts. Runner failure means the command never
* ran: foreground calls throw `SANDBOX_UNAVAILABLE`, while settled background
* tasks carry `runnerFailed`. The tool owns approval and passes per-call modes.
* processes carry `runnerFailed`. The tool owns approval and passes per-call modes.
* @module @deepseek-ai/dsh-bash-sandbox
*/
import { Context } from 'cordis'
import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskId } from '@deepseek-ai/dsh-bash'
import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from '@deepseek-ai/dsh-bash'
import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
import type { ConfinedSandboxMode, SandboxEnforcement, SandboxMode } from '@deepseek-ai/dsh-sandbox'
import type {} from '@deepseek-ai/dsh-sandbox-policy'
import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
import type { Config as LocalConfig } from '@deepseek-ai/dsh-bash-local'
import { classifyDenial, classifyRunnerFailure, matchesSignature, shellQuote } from './helpers.ts'
/**
* Plugin config: the local executor's knobs, verbatim. The sandbox policy —
@@ -25,62 +26,13 @@ import type { Config as LocalConfig } from '@deepseek-ai/dsh-bash-local'
*/
export type Config = LocalConfig
/**
* Quote one string as a single-quoted POSIX shell word (embedded single
* quotes become `'\''`), so a wrapped argv element survives the outer
* `bash -c` re-parse byte-for-byte.
* @param text - the raw argv element to quote.
* @returns the single-quoted shell word.
*/
export function shellQuote(text: string): string {
return `'${text.replaceAll("'", String.raw`'\''`)}'`
}
/**
* Conservatively classify a nonzero, non-signal run using only the selected
* backend's denial signatures. Text inference may miss a denial or match
* unrelated stderr in that dialect; it never uses another backend's terms.
* @param result - the settled foreground run to classify.
* @param signatures - the active wrap's denial dialect, case-insensitive stderr substrings.
* @returns whether the run's failure reads as a sandbox denial.
*/
export function classifyDenial(result: BashRunResult, signatures: readonly string[]): boolean {
return matchesSignature(result.exitCode, result.stderr.text, signatures)
}
/**
* Classify a nonzero run using the selected backend's runner-failure
* signatures. Callers check this before denial because runner diagnostics may
* contain denial words; the command did not run.
* @param result - the settled foreground run to classify.
* @param signatures - the active wrap's runner-failure signatures,
* case-insensitive stderr substrings.
* @returns whether the run's failure reads as the runner itself failing.
*/
export function classifyRunnerFailure(result: BashRunResult, signatures: readonly string[]): boolean {
return matchesSignature(result.exitCode, result.stderr.text, signatures)
}
/**
* The classifier core shared by foreground results and settled background
* tasks: failed AND signature present. Lowercases BOTH sides — the seam
* declares its signatures case-insensitive, and producers compose them from
* runtime data of any case (an `argv0` path, `No such file or directory`).
*/
function matchesSignature(exitCode: number | null, stderr: string, signatures: readonly string[]): boolean {
if (exitCode === null || exitCode === 0) return false
const lowered = stderr.toLowerCase()
return signatures.some(signature => lowered.includes(signature.toLowerCase()))
}
/**
* Registers as `ctx.bash` in place of the local executor and requires a
* `ctx.sandbox` provider plus `ctx.sandboxPolicy`; the tool layer is
* unchanged. The policy default (mode + workspace root, from
* `ctx.sandboxPolicy`) is the fallback, while a session override or approved
* one-shot escalation may select each call's mode. The prompt does not state
* the standing mode; `result.sandbox` reports the mode and enforcement
* actually used.
* unchanged. The policy default (mode + workspace root) is the fallback,
* while a session override or approved one-shot escalation may select each
* call's mode. The prompt does not state the standing mode; `result.sandbox`
* reports the mode and enforcement actually used.
*/
export class SandboxBashExecutor extends LocalBashExecutor {
static inject = ['sandbox', 'sandboxPolicy']
@@ -92,11 +44,12 @@ export class SandboxBashExecutor extends LocalBashExecutor {
private readonly mode: SandboxMode
private readonly workspaceRoot: string
/**
* Per-task mode and wrap facts retained until settlement. Overlapping tasks
* may use different modes or provider facts, so one latest-wrap field would
* misclassify earlier completions.
* Per-process confinement facts retained until settlement. Providers may
* vary enforcement and diagnostic dialect between overlapping calls, so a
* shared latest-wrap value would classify a process against the wrong facts.
* Unconfined processes have no entry.
*/
private readonly taskFacts = new Map<BashTaskId, {
private readonly processFacts = new Map<BashProcess, {
mode: ConfinedSandboxMode
enforcement: SandboxEnforcement
denialSignatures: readonly string[]
@@ -145,39 +98,36 @@ export class SandboxBashExecutor extends LocalBashExecutor {
return { ...result, sandbox: { mode, denied: classifyDenial(result, confined.denialSignatures), enforcement: confined.enforcement } }
}
override start(spec: BashExecSpec): BashTask {
override start(spec: BashExecSpec): BashProcess {
// Same stamped-by-resolve invariant as run().
const mode = spec.sandboxMode as SandboxMode
if (mode === 'danger-full-access') return super.start(spec)
// Classification needs settled stderr. Store facts synchronously after
// spawn, before the earliest process completion can be observed.
// Install facts synchronously; promise settlement cannot run before start() returns.
const confined = this.confine(spec.command, mode)
const task = super.start({ ...spec, command: confined.command })
const proc = super.start({ ...spec, command: confined.command })
const { enforcement, denialSignatures, runnerFailureSignatures } = confined
this.taskFacts.set(task.id, { mode, enforcement, denialSignatures, runnerFailureSignatures })
return task
this.processFacts.set(proc, { mode, enforcement, denialSignatures, runnerFailureSignatures })
return proc
}
/**
* Stamp per-task sandbox facts before completion listeners and `done` settle.
* Full-access tasks have no facts; signal deaths are not denials.
* Stamp per-process sandbox facts before `done` settles. Full-access processes
* have no facts; signal deaths are not denials.
*/
protected override notifyTaskDone(task: BashTask): void {
const facts = this.taskFacts.get(task.id)
protected override onProcessDone(proc: BashProcess, stderr: string): void {
const facts = this.processFacts.get(proc)
if (facts !== undefined) {
this.taskFacts.delete(task.id)
const stderr = this.collectedStderr(task.id)
// Runner failure outranks denial. Background settlement has no throw
// channel, so this fact is its counterpart to the foreground exception.
const runnerFailed = matchesSignature(task.exitCode, stderr, facts.runnerFailureSignatures)
task.sandbox = {
this.processFacts.delete(proc)
// Runner failure outranks denial because its diagnostics may contain denial terms.
const runnerFailed = matchesSignature(proc.exitCode, stderr, facts.runnerFailureSignatures)
proc.sandbox = {
mode: facts.mode,
denied: !runnerFailed && matchesSignature(task.exitCode, stderr, facts.denialSignatures),
denied: !runnerFailed && matchesSignature(proc.exitCode, stderr, facts.denialSignatures),
enforcement: facts.enforcement,
...(runnerFailed ? { runnerFailed } : {}),
}
}
super.notifyTaskDone(task)
super.onProcessDone(proc, stderr)
}
/**

View File

@@ -5,8 +5,9 @@ import { homedir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { bwrapProfileArgs, LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import { LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
import { bwrapProfileArgs } from '@deepseek-ai/dsh-sandbox-local/src/profiles.ts'
import { SandboxBashExecutor } from '@deepseek-ai/dsh-bash-sandbox'
/**

View File

@@ -14,7 +14,8 @@ import type { BashRunResult, CollectedOutput } from '@deepseek-ai/dsh-bash'
import { SANDBOX_UNAVAILABLE, SandboxProvider, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
import type { ConfinedArgv, SandboxMode, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
import { classifyDenial, classifyRunnerFailure, SandboxBashExecutor, shellQuote } from '@deepseek-ai/dsh-bash-sandbox'
import { SandboxBashExecutor } from '@deepseek-ai/dsh-bash-sandbox'
import { classifyDenial, classifyRunnerFailure, shellQuote } from '../src/helpers.ts'
import type { Config } from '@deepseek-ai/dsh-bash-sandbox'
const spillDir = mkdtempSync(join(tmpdir(), 'dsh-bash-sandbox-spec-'))
@@ -37,9 +38,7 @@ const passthrough = (argv: readonly string[]): ConfinedArgv =>
/**
* Boot a context with a recording fake `ctx.sandbox` (behavior injectable
* per test), the shared `ctx.sandboxPolicy` (mode + workspaceRoot), and the
* executor under test on top of them. `mode`/`workspaceRoot` route to the
* policy service; the rest (cwd, graceMs, timeoutMs) to the executor.
* per test) and the executor under test on top of it.
*/
async function setup(
config: { mode?: SandboxMode; workspaceRoot?: string } & Config = {},
@@ -143,7 +142,7 @@ describe('danger-full-access', () => {
const task = bash.start(bash.resolve({ command: 'echo free-bg' }))
await task.done
expect(task.sandbox).toBeUndefined()
expect(bash.readOutput(task.id).delta).toContain('free-bg')
expect(task.readOutput().delta).toContain('free-bg')
expect(calls).toHaveLength(0)
})
})
@@ -195,7 +194,7 @@ describe('per-call sandboxMode override (the escalation mechanism)', () => {
const task = bash.start(bash.resolve({ command: 'echo bg-free', sandboxMode: 'danger-full-access' }))
await task.done
expect(task.sandbox).toBeUndefined()
expect(bash.readOutput(task.id).delta).toContain('bg-free')
expect(task.readOutput().delta).toContain('bg-free')
expect(calls).toHaveLength(0)
})
})
@@ -254,6 +253,20 @@ describe('result facts', () => {
})
describe('background sandbox facts', () => {
it('stamps facts and releases accounting when background spawn fails', async () => {
const { bash } = await setup()
const missingWorkdir = join(mkdtempSync(join(tmpdir(), 'dsh-sandbox-missing-cwd-')), 'missing')
const task = bash.start(bash.resolve({ command: 'true', workdir: missingWorkdir }))
await task.done
expect(task.status).toBe('killed')
expect(task.readOutput().delta).toContain('spawn failed:')
expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
const accounting = (bash as unknown as { processFacts: Map<unknown, unknown> }).processFacts
expect(accounting.size).toBe(0)
})
it('stamps a settled denial: nonzero exit + permission stderr under a confined mode', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({ command: 'echo "x: Permission denied" >&2; exit 1' }))
@@ -284,15 +297,6 @@ describe('background sandbox facts', () => {
expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full', runnerFailed: true })
})
it('completion listeners already see the stamped facts (stamp precedes notify)', async () => {
const { ctx, bash } = await setup({}, argv => ({ argv: [...argv], enforcement: 'partial', denialSignatures: UNIX_SIGNATURES, runnerFailureSignatures: RUNNER_FAILURE }))
const seen: unknown[] = []
ctx.bash.onTaskDone((task) => { seen.push(task.sandbox) })
const task = bash.start(bash.resolve({ command: 'echo "x: Permission denied" >&2; exit 1' }))
await task.done
expect(seen).toEqual([{ mode: 'read-only', denied: true, enforcement: 'partial' }])
})
it('overlapping background tasks keep their OWN wrap facts (per-task, not latest-wrap)', async () => {
// Facts belong to each wrap and may vary between calls. The slow task settles after the
// quick task starts; a shared latest-wrap field would classify and stamp it with the wrong
@@ -319,8 +323,8 @@ describe('background sandbox facts', () => {
const task = bash.start(bash.resolve({ command: 'echo "Permission denied" >&2; sleep 30' }))
// Let the stderr land before the kill so the classifier sees the
// signature and must still refuse it on the null exit code alone.
await vi.waitFor(() => { expect(bash.readOutput(task.id).delta).toContain('Permission denied') })
bash.kill(task.id)
await vi.waitFor(() => { expect(task.readOutput().delta).toContain('Permission denied') })
task.kill()
await task.done
expect(task.sandbox).toEqual({ mode: 'read-only', denied: false, enforcement: 'full' })
})

View File

@@ -5,8 +5,9 @@ import { homedir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { LocalSandboxProvider, seatbeltProfileArgs } from '@deepseek-ai/dsh-sandbox-local'
import { LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import { SandboxPolicyService } from '@deepseek-ai/dsh-sandbox-policy'
import { seatbeltProfileArgs } from '@deepseek-ai/dsh-sandbox-local/src/profiles.ts'
import { SandboxBashExecutor } from '@deepseek-ai/dsh-bash-sandbox'
/**

View File

@@ -1,6 +1,6 @@
# @deepseek-ai/dsh-bash
The **bash executor seam**: an abstract `BashExecutor` service (`ctx.bash`) defining WHAT a bash backend does — run commands, manage background tasks — without saying HOW.
The **bash executor seam**: an abstract `BashExecutor` service (`ctx.bash`) defining WHAT a bash backend does — run foreground commands and start background processes — without saying HOW. Task ids, ownership, collection, cancellation, and notices belong to the generic `ctx.tasks` runtime.
This package is the interface quarter of the bash capability, split so each concern can evolve (and be swapped) independently:
@@ -18,23 +18,20 @@ The split mirrors the LLM seam (`LlmService`/`LlmAdapter`) and the agent-tool su
| Member | Semantics |
|---|---|
| `run(spec)` | Foreground execution. Resolves when the command finishes. **Rejects only for infrastructure failures** (unusable workdir, missing shell, pre-aborted signal); nonzero exits, timeout kills, and abort kills resolve with a descriptive `BashRunResult`. |
| `start(spec)` | Background execution. Returns a `BashTask` handle immediately; **no timeout applies** (stop tasks via `kill`). |
| `get(id)` / `list()` | Task lookup. |
| `start(spec)` | Background execution. Returns a task-free `BashProcess` handle immediately; **no timeout applies**. The caller may adapt it into `ctx.tasks`. |
| `sandboxMode` | The capability fact for the tool layer: the default mode a SANDBOXING executor confines under (`undefined` in the base class — "this executor does not sandbox"). `dsh-tool-bash` reads it at registration to advertise the escalation fields only when the composition honors them. |
| `ownerOf(id)` | The opaque OWNER token recorded for a background task at `start` (from the spec's `owner`), or `undefined` for an unknown id OR a known-but-ownerless task. The executor stores/returns it verbatim and NEVER interprets it — the access POLICY lives in the consumer (`dsh-tool-bash`), which compares `ownerOf(id)` to the caller's token. Storing ownership here (disposed with the executor's fiber) is what makes it survive a consumer HMR reload. |
| `readOutput(id)` | **Incremental** output read — consecutive reads never re-deliver. Reads that lost data to buffer bounds flag `lossy` and point at full-stream spill files. Throws for unknown ids. |
| `kill(id)` | Kill a running task. Returns `false` when it already finished; throws for unknown ids. |
| `onTaskDone(listener)` | Completion listener (effect-based, disposer returned). Fires exactly once per task; never after the service is disposed. |
| `BashProcess.readOutput()` | **Incremental** output read — consecutive reads never re-deliver. Reads that lost data to buffer bounds flag `lossy` and point at full-stream spill files. |
| `BashProcess.kill()` | Kill the process group. Returns `false` when it already finished. |
Implementations subclass `BashExecutor`, implement the abstract methods, and call `notifyTaskDone(task)` on background completion. Disposal must kill every running task (no orphan processes) — see the HMR-safety tests.
Implementations subclass `BashExecutor` and implement the abstract methods. Disposal must kill every running process and await its exit — see the HMR-safety tests.
## Vocabulary
`BashExecRequest` (command, workdir?, timeoutMs?, signal?, stdin?, env?, owner?, sandboxMode?) resolves to `BashExecSpec` (command, workdir, timeoutMs, signal?, stdin?, env?, owner, sandboxMode) before execution; `owner` and `sandboxMode` are optional on the request and **required-but-nullable** on the resolved spec, so a forgotten one is a visible `undefined` rather than a silently-absent property. `sandboxMode` is the explicit per-call sandbox-policy input: an escalation grant a human just issued ([the sandbox RFC § Escalation](../../../docs/rfc/implemented/feature/2026-07-06-sandbox.md), which outranks) or the session's standing override ([the sandbox RFC § Per-session mode switching](../../../docs/rfc/implemented/feature/2026-07-06-sandbox.md)); a sandboxing executor's `resolve()` stamps its configured default when the request carries none, and a non-sandboxing executor carries the field verbatim and confines nothing.
`BashExecRequest` (command, workdir?, timeoutMs?, signal?, stdin?, env?, sandboxMode?) resolves to `BashExecSpec` (command, workdir, timeoutMs, signal?, stdin?, env?, sandboxMode) before execution. `sandboxMode` is optional on the request and required-but-nullable on the resolved spec: it carries an approved one-shot escalation or the session's standing override; a sandboxing executor stamps its configured default when absent, while a non-sandboxing executor carries the field and confines nothing.
The seam owns per-session sandbox overrides through the log-only `bash/sandbox-mode` event, `effectiveSandboxMode`, and `setSandboxMode`; writers preserve turn enclosure, and replay restores the last override. `BashTaskId` and `OwnerToken` are distinct brands. Foreground `run` returns exit, timeout, cancellation, output, and optional sandbox facts; background `start` and `readOutput` use task records. A sandboxing executor reports the executed mode, conservative denial classification, and enforcement completeness. See [core-data-structures/bash.md](../../../docs/core-data-structures/bash.md) for full shapes.
The seam also owns the per-session mode override vocabulary: the log-only `'bash/sandbox-mode'` session event, the pure `effectiveSandboxMode(events)` fold, and the `setSandboxMode(session, mode)` write path. `run()` returns `BashRunResult`; `start()` returns `BashProcess`, whose incremental read and kill methods are adapted by `dsh-tool-bash` into a generic task registration. A sandboxing executor stamps `BashSandboxInfo` on foreground results and settled process handles. See `src/types.ts` and [core-data-structures/bash.md](../../../docs/core-data-structures/bash.md).
`stdin` and `env` are set by in-process plugins (the hooks bridges, native plugins) to feed a hook command its JSON payload on stdin and its `CLAUDE_PROJECT_DIR`/`CLAUDE_PLUGIN_ROOT` env. The model-facing `dsh-tool-bash` tool does not expose them as parameters — a model already has equivalent power through shell syntax (`FOO=bar cmd`, a heredoc), so they would be redundant tool params. This is not a security boundary: the implementation's credential scrub (not these fields) is what keeps the harness's ambient secrets out of a spawned command. They are plain optionals on the resolved spec (unlike `owner`'s required-but-nullable): a missing one means "none", the safe default. See [the bash-stdin-env RFC](../../../docs/rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md).
`stdin` and `env` are set by in-process plugins (the hooks bridges, native plugins) to feed a hook command its JSON payload on stdin and its `CLAUDE_PROJECT_DIR`/`CLAUDE_PLUGIN_ROOT` env. The model-facing `dsh-tool-bash` tool does not expose them as parameters — a model already has equivalent power through shell syntax (`FOO=bar cmd`, a heredoc), so they would be redundant tool params. This is not a security boundary: the implementation's credential scrub (not these fields) is what keeps the harness's ambient secrets out of a spawned command. They are plain optionals on the resolved spec; a missing value means "none". See [the bash-stdin-env RFC](../../../docs/rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md).
## Model Experience

View File

@@ -22,12 +22,10 @@
],
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-brand": "^0.0.1",
"@deepseek-ai/dsh-sandbox": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"devDependencies": {
"@deepseek-ai/dsh-brand": "workspace:^",
"@deepseek-ai/dsh-sandbox": "workspace:^",
"cordis": "^4.0.0-rc.7"
}

View File

@@ -1,23 +1,22 @@
/**
* The bash executor seam (`ctx.bash`): an abstract service defining what a bash backend does —
* run commands, manage background tasks — without saying how.
* The `ctx.bash` executor seam for foreground commands and background process
* handles. Task ids, ownership, polling, and notices belong to
* `@deepseek-ai/dsh-tasks`, keeping executors independent of sessions.
* @module @deepseek-ai/dsh-bash
*/
import { Context, Service } from 'cordis'
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskId, BashTaskListener, BashTaskRead, OwnerToken } from './types.ts'
import type { BashExecRequest, BashExecSpec, BashProcess, BashRunResult } from './types.ts'
export { BashTaskId, OwnerToken } from './types.ts'
export type {
BashExecRequest,
BashExecSpec,
BashProcess,
BashProcessRead,
BashProcessStatus,
BashRunResult,
BashSandboxInfo,
BashTask,
BashTaskListener,
BashTaskRead,
BashTaskStatus,
CollectedOutput,
} from './types.ts'
@@ -28,34 +27,30 @@ declare module 'cordis' {
}
/**
* Registers one `ctx.bash` implementation. Runtime command failures resolve as
* {@link BashRunResult}; only infrastructure failures reject. Background starts
* return immediately without a timeout, report completion exactly once while
* live, and remain cancellable by signal or {@link kill}. Output reads are
* incremental and flag lost buffered data; disposal kills and awaits all tasks.
* Abstract bash execution service. Subclass, implement the abstract methods,
* and load the subclass as a plugin — it registers as `ctx.bash` (one
* implementation per context; loading a second throws, which is cordis'
* standard duplicate-service behavior).
*
* Implementations must honor these semantics:
* - {@link run} rejects only for infrastructure failures. Nonzero exits,
* timeout kills, and abort kills resolve with a {@link BashRunResult}.
* - {@link start} returns immediately; no timeout applies to background
* processes. `done` settles at process close and never rejects; spawn
* failures settle as `killed` with the error on stderr.
* - {@link BashProcess.readOutput} is incremental: consecutive reads never
* repeat output. Lossy reads report truncation and available spill files.
* - Disposal kills all running background processes and awaits their exit.
*/
export abstract class BashExecutor extends Service {
private listeners = new Set<BashTaskListener>()
private listenersClosed = false
constructor(ctx: Context) {
super(ctx, 'bash')
ctx.effect(() => () => {
// Close the listener registry before subclass teardown so late task
// completions (e.g. from kills issued during dispose) stay silent.
this.listenersClosed = true
this.listeners.clear()
}, 'bash listener teardown')
}
/**
* The sandbox mode this executor confines commands under BY DEFAULT, or `undefined` when it
* does not sandbox at all — the capability fact the tool and ACP layers read to advertise
* sandbox controls honestly.
* A session or call may override this default, so widening is evaluated per
* execution rather than encoded in this getter.
* @returns the configured default mode of a sandboxing executor;
* `undefined` for an executor that never confines.
* The sandbox mode this executor applies by default, or `undefined` when it
* does not sandbox commands.
* @returns the configured default sandbox mode, when supported.
*/
get sandboxMode(): SandboxMode | undefined {
return undefined
@@ -78,79 +73,11 @@ export abstract class BashExecutor extends Service {
abstract run(spec: BashExecSpec): Promise<BashRunResult>
/**
* Start a background task and return its handle immediately.
* Start a background process and return its handle immediately.
* @param spec - a resolved spec from {@link resolve}, never a raw request.
* @returns the live task handle; completion fires {@link onTaskDone}.
* @returns the live process handle (reads, kill, quiescence promise).
*/
abstract start(spec: BashExecSpec): BashTask
/**
* Look up a background task by id.
* @param id - the task id to look up.
* @returns the tracked task, or undefined for an id this executor never issued.
*/
abstract get(id: BashTaskId): BashTask | undefined
/**
* The opaque OWNER token recorded for a background task at {@link start} (from the {@link
* BashExecSpec}'s `owner`), or `undefined` for an unknown id OR a known-but-ownerless task.
* The executor stores the token without interpreting policy; keeping it here
* lets ownership survive a consumer-plugin reload.
* @param id - the background task id to look up ownership for.
* @returns the token recorded at start, verbatim; undefined for an unknown
* id or a known-but-ownerless task.
*/
abstract ownerOf(id: BashTaskId): OwnerToken | undefined
/**
* All tracked background tasks (insertion order).
* @returns every task this executor started, running or finished.
*/
abstract list(): BashTask[]
/**
* Read output produced since the previous read. Throws for unknown ids.
* @param id - the task to read from.
* @returns the incremental read; consecutive reads never re-deliver output.
*/
abstract readOutput(id: BashTaskId): BashTaskRead
/**
* Kill a running background task. Returns false when it had already
* finished (no-op). Throws for unknown ids.
* @param id - the task to kill.
* @returns true when this call killed it, false when it had already finished.
*/
abstract kill(id: BashTaskId): boolean
/**
* Register a background-task completion listener (disposed with the
* calling fiber). Listeners never fire after this service is disposed.
* @param listener - called exactly once per task completion.
* @returns the disposer that unregisters the listener.
*/
onTaskDone(listener: BashTaskListener): () => void {
const dispose = this.ctx.effect(() => {
this.listeners.add(listener)
return () => this.listeners.delete(listener)
}, 'bash.onTaskDone()')
return () => void dispose()
}
/** For implementations: notify listeners that `task` completed. Listener
* exceptions are contained (logged) — one bad listener must not reject
* `BashTask.done` or starve the listeners after it. */
protected notifyTaskDone(task: BashTask): void {
if (this.listenersClosed) return
for (const listener of this.listeners) {
try {
listener(task)
} catch (error: unknown) {
// Listener bugs are reported, never propagated into task.done.
console.error('bash onTaskDone listener threw:', error)
}
}
}
abstract start(spec: BashExecSpec): BashProcess
}
export default BashExecutor

View File

@@ -1,79 +1,24 @@
/**
* Execution vocabulary for the bash executor seam. Types only — the abstract
* service lives in `./index.ts`, implementations in sibling packages
* (`@deepseek-ai/dsh-bash-local` first).
*
* Execution types for the bash executor seam. Background task semantics belong
* to `@deepseek-ai/dsh-tasks`; this seam exposes only process handles.
* @module dsh-bash/types
*/
import type { Branded } from '@deepseek-ai/dsh-brand'
import type { SandboxEnforcement, SandboxMode } from '@deepseek-ai/dsh-sandbox'
/** Identifies one background task within an executor (generated `bash-N`). */
export type BashTaskId = Branded<'BashTaskId'>
/**
* Brand a string as a {@link BashTaskId}.
* @param id - the raw task-id string (the executor generates `bash-N`).
* @returns the same string, branded; no validation is performed.
*/
export function BashTaskId(id: string): BashTaskId {
return id as BashTaskId
}
/**
* A background task's opaque isolation key — the CONSUMER's owner identity, not
* the bash seam's. The executor stores and returns it verbatim and never
* interprets it; the access policy lives in the consumer (`dsh-tool-bash`),
* which is the single boundary that casts its own id vocabulary into one. A
* DISTINCT brand (not a `SessionId` alias) keeps the seam decoupled — a
* sandboxed/remote executor inherits no session dependency.
*/
export type OwnerToken = Branded<'OwnerToken'>
/**
* Brand a string as an {@link OwnerToken}. Only the consuming boundary
* (`dsh-tool-bash`) should cast its own id vocabulary in — see the type's doc.
* @param id - the consumer's raw owner identity (the tool layer passes the owning agent's session id).
* @returns the same string, branded; no validation is performed.
*/
export function OwnerToken(id: string): OwnerToken {
return id as OwnerToken
}
/**
* Sandbox facts for one foreground run — present on {@link BashRunResult} iff
* a sandboxing executor ran the command (an unsandboxed executor reports no
* `sandbox` field at all). Reported independently of `exitCode`/`signal`
* (orthogonal outcomes), so a caller can tell "the command failed on its own"
* from "the sandbox blocked a file operation". The mode/enforcement
* vocabulary lives on the `@deepseek-ai/dsh-sandbox` seam; this shape is the
* bash seam's result-fact carrier for it.
* Sandbox facts for one run, present iff a sandboxing executor handled it.
* Facts are reported independently of process exit status so callers can
* distinguish command failures from policy denials and runner failures.
*/
export interface BashSandboxInfo {
/** The mode the command actually ran under. */
mode: SandboxMode
/**
* True when the executor classifies this run's failure as the sandbox
* denying a file operation. The classification is CONSERVATIVE (a failed
* exit whose stderr carries a filesystem-permission signature) and reads
* the COLLECTED stderr — the bounded in-memory tail per
* {@link CollectedOutput} semantics, so a signature that survives only in a
* spill file is missed toward `denied: false`. A plain command failure
* keeps `denied: false` even under a sandboxed mode.
*/
/** Whether the sandbox denied a file operation. */
denied: boolean
/**
* How completely the runner enforced `mode`'s file effects — see
* {@link SandboxEnforcement}. Absent exactly when `mode` is
* `danger-full-access`: nothing is confined, so there is no enforcement to
* report.
*/
/** How completely the selected runner enforced the requested mode. */
enforcement?: SandboxEnforcement
/**
* The sandbox runner failed before executing the command. Set only on settled
* background tasks; foreground runs throw `SANDBOX_UNAVAILABLE` instead.
*/
/** Whether the sandbox runner failed before the command could run. */
runnerFailed?: boolean
}
@@ -109,30 +54,14 @@ export interface BashExecRequest {
* uses shell syntax like `FOO=bar cmd`).
*/
env?: Record<string, string> | undefined
/**
* Opaque OWNER token for a background task — the consumer's isolation key
* (the tool layer passes the owning agent's `session.header.id`). The
* executor stores it on the task and exposes it via {@link BashExecutor.ownerOf};
* the executor itself NEVER interprets it (no access policy lives in the
* seam — that is the consumer's job). Absent for foreground runs and for an
* ownerless background start (a non-agent caller).
*/
owner?: OwnerToken | undefined
/**
* Explicit per-call sandbox policy. The tool stamps a session override or a
* one-shot approved escalation, with the grant taking precedence. Sandboxing
* executors honor it for this call; non-sandboxing executors do not confine.
*/
/** Explicit per-call sandbox mode override. */
sandboxMode?: SandboxMode | undefined
}
/**
* A fully-resolved execution SPEC — exactly what {@link BashExecutor.run} /
* {@link BashExecutor.start} act on. `workdir` and `timeoutMs` are REQUIRED:
* defaulting and capping already happened in {@link BashExecutor.resolve}, so
* the executor never hides a `?? config` fallback (explicit > implicit). For
* background tasks, `start()` ignores `timeoutMs` (background runs have no
* timeout) — the field is still required because the type is shared.
* A resolved execution spec. {@link BashExecutor.resolve} fills and caps the
* required fields; {@link BashExecutor.start} ignores `timeoutMs` because
* background processes have no executor timeout.
*/
export interface BashExecSpec {
command: string
@@ -140,40 +69,14 @@ export interface BashExecSpec {
timeoutMs: number
/** Abort signal — implementations kill the command when it fires. */
signal?: AbortSignal | undefined
/**
* Bytes to write to the command's stdin (then close it), carried through
* verbatim from {@link BashExecRequest.stdin}. OPTIONAL on the resolved spec
* (unlike `owner`): it has no config default, so a missing one means "no
* stdin" — the safe, ordinary case — not a silent footgun, so it stays a
* plain optional rather than required-but-nullable (see the request field).
*/
/** Bytes to write to stdin before closing it; absent means no stdin. */
stdin?: string | undefined
/**
* Extra environment entries, carried through verbatim from
* {@link BashExecRequest.env} and merged by the implementation AFTER its
* credential scrub (an explicit entry wins even when its name matches the
* scrub pattern). OPTIONAL on the spec for the same reason as `stdin` — no
* config default, absent means "no extra env".
* Extra environment entries, merged after credential scrubbing so explicit
* values win; absent means no extra entries.
*/
env?: Record<string, string> | undefined
/**
* Opaque owner token, REQUIRED-but-nullable (mirrors `workdir`/`timeoutMs`
* being required on the resolved spec): {@link BashExecutor.resolve} carries
* the request's `owner` through, defaulting a missing one to `undefined`. A
* required field makes a forgotten owner a VISIBLE `undefined` rather than a
* silently-absent property that yields an unowned (cross-session-readable)
* task. `start()` stores it; `run()` (foreground) ignores it.
*/
owner: OwnerToken | undefined
/**
* The sandbox mode this call executes under, REQUIRED-but-nullable for the
* same visibility reason as `owner`. A sandboxing executor's `resolve()`
* stamps the effective mode (the request's explicit override, else its
* configured default) so `run()`/`start()` read the spec, never the config;
* a non-sandboxing executor carries the request value through verbatim and
* ignores it (`undefined` under such an executor means what its README says:
* unconfined execution).
*/
/** Resolved sandbox mode; ignored by executors that do not confine. */
sandboxMode: SandboxMode | undefined
}
@@ -201,42 +104,15 @@ export interface BashRunResult {
timeoutMs: number
stdout: CollectedOutput
stderr: CollectedOutput
/**
* Sandbox facts, present iff a sandboxing executor ran the command — an
* unsandboxed executor (e.g. `dsh-bash-local`) never sets it. See
* {@link BashSandboxInfo} for the `denied` classification semantics.
*/
/** Sandbox execution facts, absent for an unsandboxed executor. */
sandbox?: BashSandboxInfo
}
/** Lifecycle of a background task. */
export type BashTaskStatus = 'running' | 'completed' | 'killed'
/** Lifecycle of a background process. */
export type BashProcessStatus = 'running' | 'completed' | 'killed'
/** A tracked background task handle. */
export interface BashTask {
readonly id: BashTaskId
status: BashTaskStatus
/** Exit code once finished (null = killed by signal / still running). */
exitCode: number | null
/** Terminating signal name, when signal-killed. */
signal: NodeJS.Signals | null
/** Resolves when the underlying process closes (never rejects). */
readonly done: Promise<void>
/**
* Sandbox facts for this task's execution, stamped by a sandboxing executor
* once the task settles and BEFORE completion listeners are notified — an
* `onTaskDone` consumer and a `done` awaiter both see it. Denial
* classification runs against the settled task's collected stderr, so the
* field cannot exist earlier: absent while the task is running and under an
* executor that does not sandbox. See {@link BashSandboxInfo} for the
* `denied` semantics.
*/
sandbox?: BashSandboxInfo
}
/** One incremental {@link BashExecutor.readOutput} read. */
export interface BashTaskRead {
task: BashTask
/** One incremental {@link BashProcess.readOutput} read. */
export interface BashProcessRead {
/** Output produced since the previous read (stderr in a marked section). */
delta: string
/** True when truncation dropped unread bytes the delta cannot include. */
@@ -247,5 +123,31 @@ export interface BashTaskRead {
stderrSpillPath?: string
}
/** Completion callback for background tasks. */
export type BashTaskListener = (task: BashTask) => void
/**
* A background process handle returned by {@link BashExecutor.start}. It is the
* only access path; buffered output remains readable after exit. Executor
* disposal kills running processes and awaits {@link done}.
*/
export interface BashProcess {
/** Process lifecycle state (settled exactly once). */
status: BashProcessStatus
/** Exit code once finished (null = killed by signal / still running). */
exitCode: number | null
/** Terminating signal name, when signal-killed. */
signal: NodeJS.Signals | null
/** Resolves when the underlying process closes (never rejects — a spawn failure settles as `killed` with the error on stderr). */
readonly done: Promise<void>
/** Sandbox facts, stamped once a confined process settles. */
sandbox?: BashSandboxInfo
/**
* Read output produced since the previous read (consuming — consecutive
* reads never re-deliver). Reads that lost data flag `lossy` and point at
* full-stream spill files when available.
*/
readOutput(): BashProcessRead
/**
* Kill the process group. Returns false when it had already finished
* (no-op); idempotent.
*/
kill(): boolean
}

View File

@@ -1,150 +1,83 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { BashExecutor, BashTaskId, OwnerToken } from '@deepseek-ai/dsh-bash'
import type { BashExecRequest, BashExecSpec, BashRunResult, BashTask, BashTaskRead } from '@deepseek-ai/dsh-bash'
import { BashExecutor } from '@deepseek-ai/dsh-bash'
import type { BashExecRequest, BashExecSpec, BashProcess, BashProcessRead, BashRunResult } from '@deepseek-ai/dsh-bash'
/** Minimal concrete executor: records calls, lets tests drive completions. */
/**
* Minimal concrete executor: canned foreground results, a hand-built process
* handle. The seam is TASK-FREE (start returns a {@link BashProcess} handle;
* task semantics live in `ctx.tasks`), so this stub is all an implementation
* owes the abstract class.
*/
class StubExecutor extends BashExecutor {
tasks = new Map<BashTaskId, BashTask>()
private owners = new Map<BashTaskId, OwnerToken | undefined>()
resolve(request: BashExecRequest): BashExecSpec {
return {
command: request.command,
workdir: request.workdir ?? '/stub',
timeoutMs: request.timeoutMs ?? 1000,
...request.signal ? { signal: request.signal } : {},
owner: request.owner,
sandboxMode: request.sandboxMode,
}
}
async run(_spec: BashExecSpec): Promise<BashRunResult> {
async run(spec: BashExecSpec): Promise<BashRunResult> {
return {
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
timeoutMs: 1000,
timeoutMs: spec.timeoutMs,
stdout: { text: 'ok', truncated: false },
stderr: { text: '', truncated: false },
}
}
start(spec: BashExecSpec): BashTask {
const task: BashTask = {
id: BashTaskId(`stub-${this.tasks.size + 1}`),
start(): BashProcess {
const proc: BashProcess = {
status: 'running',
exitCode: null,
signal: null,
done: Promise.resolve(),
readOutput: (): BashProcessRead => ({ delta: '', lossy: false }),
kill: (): boolean => {
if (proc.status !== 'running') return false
proc.status = 'killed'
return true
},
}
this.tasks.set(task.id, task)
this.owners.set(task.id, spec.owner)
return task
return proc
}
get(id: BashTaskId): BashTask | undefined {
return this.tasks.get(id)
}
ownerOf(id: BashTaskId): OwnerToken | undefined {
return this.owners.get(id)
}
list(): BashTask[] {
return [...this.tasks.values()]
}
readOutput(id: BashTaskId): BashTaskRead {
const task = this.tasks.get(id)
if (!task) throw new Error(`unknown bash task "${id}"`)
return { task, delta: '', lossy: false }
}
kill(id: BashTaskId): boolean {
const task = this.tasks.get(id)
if (!task) throw new Error(`unknown bash task "${id}"`)
if (task.status !== 'running') return false
task.status = 'killed'
return true
}
/** Expose the protected notifier for tests. */
fire(task: BashTask): void {
this.notifyTaskDone(task)
}
}
async function setup() {
const ctx = new Context()
await ctx.plugin(StubExecutor)
// ctx.bash resolves to the registered implementation.
const bash = ctx.bash as StubExecutor
return { ctx, bash }
}
describe('BashExecutor service seam', () => {
it('registers as ctx.bash and serves the abstract API', async () => {
const { bash } = await setup()
const task = bash.start(bash.resolve({ command: 'sleep 1' }))
expect(bash.get(task.id)).toBe(task)
expect(bash.list()).toEqual([task])
expect(bash.kill(task.id)).toBe(true)
expect(bash.kill(task.id)).toBe(false)
const result = await bash.run(bash.resolve({ command: 'true' }))
expect(result.exitCode).toBe(0)
})
it('reports no default sandbox mode (composition truth: the base never confines)', async () => {
const { bash } = await setup()
expect(bash.sandboxMode).toBeUndefined()
})
it('onTaskDone delivers completions to registered listeners', async () => {
const { bash } = await setup()
const seen: string[] = []
bash.onTaskDone(task => void seen.push(task.id))
const task = bash.start(bash.resolve({ command: 'x' }))
bash.fire(task)
expect(seen).toEqual([task.id])
})
it('onTaskDone disposer unsubscribes the listener', async () => {
const { bash } = await setup()
const listener = vi.fn()
const dispose = bash.onTaskDone(listener)
dispose()
bash.fire(bash.start(bash.resolve({ command: 'x' })))
expect(listener).not.toHaveBeenCalled()
})
it('listeners registered from a fiber are removed on dispose (HMR safety)', async () => {
const { ctx, bash } = await setup()
const listener = vi.fn()
const fiber = await ctx.plugin(Object.assign((inner: Context) => {
inner.bash.onTaskDone(listener)
}, { inject: ['bash'] }))
bash.fire(bash.start(bash.resolve({ command: 'one' })))
expect(listener).toHaveBeenCalledTimes(1)
await fiber.dispose()
bash.fire(bash.start(bash.resolve({ command: 'two' })))
expect(listener).toHaveBeenCalledTimes(1)
})
it('silences listeners once the service fiber is disposed', async () => {
it('a concrete subclass registers as ctx.bash and serves the abstract API', async () => {
const ctx = new Context()
const fiber = await ctx.plugin(Object.assign(async (inner: Context) => {
await inner.plugin(StubExecutor)
}, {}))
const bash = ctx.bash as StubExecutor
const listener = vi.fn()
bash.onTaskDone(listener)
const task = bash.start(bash.resolve({ command: 'x' }))
await ctx.plugin(StubExecutor)
const spec = ctx.bash.resolve({ command: 'echo hi' })
expect(spec).toEqual({ command: 'echo hi', workdir: '/stub', timeoutMs: 1000, sandboxMode: undefined })
await fiber.dispose()
bash.fire(task)
expect(listener).not.toHaveBeenCalled()
const result = await ctx.bash.run(spec)
expect(result.exitCode).toBe(0)
expect(result.stdout.text).toBe('ok')
const proc = ctx.bash.start(spec)
expect(proc.status).toBe('running')
expect(proc.readOutput()).toEqual({ delta: '', lossy: false })
expect(proc.kill()).toBe(true)
expect(proc.kill()).toBe(false) // already settled → no-op
await proc.done
})
it('reports no default sandbox mode from the task-free base seam', async () => {
const ctx = new Context()
await ctx.plugin(StubExecutor)
expect(ctx.bash.sandboxMode).toBeUndefined()
})
it('loading a second implementation throws (one bash service per context — cordis standard)', async () => {
const ctx = new Context()
await ctx.plugin(StubExecutor)
class SecondExecutor extends StubExecutor {}
await expect(ctx.plugin(SecondExecutor)).rejects.toThrow(/service "bash" has been registered/)
})
})

View File

@@ -14,9 +14,6 @@
{
"path": "../../../vendor/cordis"
},
{
"path": "../../util/brand"
},
{
"path": "../../sandbox/sandbox"
}

View File

@@ -1,12 +1,12 @@
# @deepseek-ai/dsh-tool-bash
The model-facing bash tools — `bash`, `bash_output`, `bash_kill` — registered over the `ctx.bash` executor seam (`@deepseek-ai/dsh-bash`). This package owns schema and text shaping while process concerns stay behind the seam. Executor facts can change rendered results, and a sandboxing executor activates the escalation fields, without moving those presentation rules into the backend.
The model-facing `bash` tool registered over the `ctx.bash` executor seam. Foreground execution stays behind that seam; a background process handle is registered with the generic `ctx.tasks` runtime and controlled through `task_output`, `task_list`, and `task_kill` from `@deepseek-ai/dsh-tool-tasks`.
Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`); the plugin stays pending until `ctx.bash` exists (`inject: ['tools', 'bash', 'systemPrompt']`).
The package root exposes only the Cordis plugin contract (`name`, `inject`, `apply`); result rendering remains an implementation detail covered by same-package tests.
The package root exposes only the Cordis plugin contract (`name`, `inject`, `Config`, `apply`); result rendering and background-process adaptation remain implementation details covered by same-package tests.
The plugin also contributes the `tool:bash` prompt section (order 105) — the cross-call habit the per-tool descriptions cannot carry: check the `[exit code: N]` marker on every result and investigate failures before moving on. A sandboxing executor changes the `bash` schema and result markers but adds no mode statement or switch notice; see [Per-session mode](#per-session-mode-switching).
The plugin also contributes the `tool:bash` prompt section (order 105): check the `[exit code: N]` marker on every result and investigate failures before moving on.
## Tools
@@ -26,29 +26,15 @@ The plugin also contributes the `tool:bash` prompt section (order 105) — the c
Result text contains stdout, an optional `[stderr]` section, then applicable sandbox-denial, timeout, signal, exit-code, and truncation markers. Timeout is reported independently of final exit status; nonzero exit remains a model-interpreted result rather than `isError`. Truncation links a safe complete spill file or reports it unavailable. Only infrastructure failures such as spawn errors and aborts produce `isError`.
### `bash_output`
`task_id` → output produced **since the previous `bash_output` call** plus a status line (`running` / `completed, exit code: N` / `killed`). A settled task classified as a sandbox denial carries the same `[sandbox: file access denied under <mode> mode]` marker on every read that sees it (denials are only classifiable once the whole stderr has been collected). Reads that lost data to buffer bounds say so and point at the full-output spill file when one is safely available, otherwise `(unavailable)`.
### `bash_kill`
`task_id` → ask the executor to kill the background task. The concrete executor decides how to signal or stop the process; killing an already-finished task is a reported no-op, and unknown ids are errors.
### Task ownership (cross-session isolation)
The executor stores the spawning session id as the task's owner. `bash_output` and `bash_kill` reject a caller with a different session id; agent-less tasks remain unowned, while agent-less calls cannot access owned tasks. Storing ownership on the task prevents predictable global ids from crossing ACP sessions and preserves the fence across tool-plugin reloads. Completion notices remain effect-scoped and may be missed during a reload gap.
When `run_in_background` is true, this plugin preflights `ctx.tasks.start()` before spawning, registers the calling agent as owner, and adapts the returned `BashProcess` handle into generic cancel/done/incremental-output hooks. The task runtime owns ids, cross-session isolation, completion notices, waiting, and disposal cleanup; this plugin only maps bash exit/sandbox facts into task output and outcome detail. `enableRunInBackground: false` removes the parameter and rejects a forced background call at execution time.
## UI presentation
UI presentation is tool-owned through `presentCall` and `presentResult`. Foreground `bash` uses a terminal card whose title is the exact command and whose optional description is separate; cwd follows an explicit `workdir`—resolved by the bridge against the session when relative—or the session cwd. Its result carries raw output plus exit or signal data, and clients without terminal support receive a bridge-derived fenced console fallback. Background runs, spawn failures, `bash_output`, and `bash_kill` use generic cards. Presenters are pure and replay-safe; malformed older arguments fall back to generic rendering. See [`dsh-tools`](../../core/tools/) and [`dsh-acp`](../../ui/acp/) for card semantics.
## Background completion notices
When a task finishes, the plugin resolves its owner token to a live agent and injects a durable completion notice. If the owner no longer exists, the notice is dropped. Injection affects the next request but does not wake an idle agent, so the model must poll with `bash_output` when it needs completion promptly.
The tool owns its `presentCall`/`presentResult` render intent. A foreground call is a terminal card carrying command, description, cwd, raw output, and parsed exit status. A background start is a generic execute card because it returns only a task id; the generic `task_*` tools own their own cards. These presenters are pure and replay-safe.
## The tool builds its request from named args only
The seam supports trusted-plugin `stdin` and `env`, but the model-facing tool does not. It builds requests only from its declared arguments, signal, and owner; extra model keys are ignored. Shell syntax already provides equivalent command-level behavior, while the local executor's credential scrub protects ambient secrets. See the [stdin/env RFC](../../../docs/rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md).
The `BashExecRequest` seam carries optional `stdin` and `env`, used by trusted in-process plugins. This tool does **not** expose or forward them: it builds requests from named command/workdir/timeout/signal/sandbox fields only. This is not a trust boundary; the local executor's ambient credential scrub is the security control.
## Permissions and escalation
@@ -76,7 +62,7 @@ Check the [exit code: N] marker on every bash result; investigate failures befor
### Tool schemas
**What the model sees**: The model sees the generated [`bash`, `bash_output`, and `bash_kill` schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tool-bash). `sandbox_permissions` and `justification` augment `bash` only when the mounted executor advertises sandboxing. Agent-scoped tool restrictions can remove the definitions for that agent.
**What the model sees**: The model sees the generated [`bash` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-bash). `run_in_background` appears only when this producer enables it; `sandbox_permissions` and `justification` appear only when the mounted executor advertises sandboxing. Agent-scoped tool restrictions can remove the definition for that agent.
**Token effect**: Fixed schema cost on every request where the tools are visible; sandbox support adds the escalation fields and its conditional description paragraph.
@@ -88,19 +74,18 @@ Check the [exit code: N] marker on every bash result; investigate failures befor
### Background task context and results
**What the model sees**: Start returns exactly `started background task <taskId>`. Completion injects exactly `background bash task <taskId> finished <status>. Read its output with bash_output.` Reads return only the data-dependent delta or `(no new output)`, optionally `[some output was dropped from memory; full output: <paths-or-(unavailable)>]`, then exactly one of `[status: running]`, `[status: killed]`, `[status: killed by <signal>]`, or `[status: completed, exit code: <exitCode>]`. Kill returns `killed background task <taskId>` or `task <taskId> had already finished`.
**What the model sees**: Start returns exactly `started background task <taskId>`. This producer supplies incremental process output, optional `[some output was dropped from memory; full output: <paths-or-(unavailable)>]`, sandbox facts, and terminal detail such as `exit code: <exitCode>` or `signal: <signal>` to the generic task runtime. [`dsh-tool-tasks`](../../tasks/tool-tasks/README.md) owns the visible status line, completion notice, listing, and cancellation response.
**Token effect**: Start and status text is small; deltas are data-dependent. The completion notice and every tool result are retained until compaction, but polling does not repeat already-delivered output.
**Token effect**: The start acknowledgement is small and retained; collected output is data-dependent and bounded by the executor's stream buffers. Consuming reads do not repeat prior output.
### Tool errors
**What the model sees**: Validation and policy failures are normalized as `Error: <message>`. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got <value>`, `invalid escalation: sandbox_permissions requires a justification`, `invalid escalation: justification is only valid together with sandbox_permissions`, `invalid justification: expected a non-empty sentence`, `invalid task_id: expected a string, got <value>`, `task <taskId> belongs to another session`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, `sandbox escalation to "<mode>" is not strictly wider than this call's current "<mode>" mode`, the approval-availability/rejection/cancellation variants, and `command aborted`.
**What the model sees**: Validation and policy failures are normalized as `Error: <message>`. This package's stable messages are `invalid command: expected a non-empty string`, `invalid description: expected a non-empty string`, `invalid timeoutMs: expected a positive number, got <value>`, `invalid escalation: sandbox_permissions requires a justification`, `invalid escalation: justification is only valid together with sandbox_permissions`, `invalid justification: expected a non-empty sentence`, `background execution is disabled for this bash tool`, `background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`, `sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`, `sandbox escalation to "<mode>" is not strictly wider than this call's current "<mode>" mode`, the approval-availability/rejection/cancellation variants, and `command aborted`.
**Token effect**: Only the failing call adds these retained tokens; a rejected escalation does not add command output because the command does not run.
## Known Limitations and Deferred Work
- **Replay exit pills parse from result text** — output whose final line happens to be exactly `[exit code: N]` / `[killed by signal: …]` shows a wrong pill on session replay; a display-only known residual.
- **The bash tools opt out of `timeout-policy` budgets** — `bash` keeps the executor-owned `BASH_TIMEOUT` path and `bash_output`/`bash_kill` declare no budget, per [the tool-call timeout-policy RFC](../../../docs/rfc/implemented/architecture/2026-07-07-tool-call-timeout-policy.md).
- **Completion notices do not wake an idle agent** — they become durable context for the next request; a caller needing progress now must poll `bash_output` or send another message.
- **Tasks started outside an agent have no ownership fence** — their predictable ids are readable and killable by any caller; only agent-started tasks carry a session owner token.
- **The `bash` tool opts out of `timeout-policy` budgets** — it keeps the executor-owned `BASH_TIMEOUT` path, per [the tool-call timeout-policy RFC](../../../docs/rfc/implemented/architecture/2026-07-07-tool-call-timeout-policy.md).
- **Background processes have no executor timeout** — callers must use `task_kill`, or rely on owner/service disposal, when work no longer matters.

View File

@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-tool-bash",
"description": "Model-facing bash tools (bash, bash_output, bash_kill) over the DeepSeek Harness bash executor seam",
"description": "Model-facing bash tool with optional generic background-task and sandbox-escalation support",
"version": "0.0.1",
"private": true,
"type": "module",
@@ -23,28 +23,33 @@
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-agent": "^0.0.1",
"@deepseek-ai/dsh-user-approval": "^0.0.1",
"@deepseek-ai/dsh-bash": "^0.0.1",
"@deepseek-ai/dsh-llm": "^0.0.1",
"@deepseek-ai/dsh-sandbox": "^0.0.1",
"@deepseek-ai/dsh-sandbox-policy": "^0.0.1",
"@deepseek-ai/dsh-system-prompt": "^0.0.1",
"@deepseek-ai/dsh-tasks": "^0.0.1",
"@deepseek-ai/dsh-tools": "^0.0.1",
"@deepseek-ai/dsh-user-approval": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"dependencies": {
"schemastery": "^3.18.0"
},
"devDependencies": {
"@deepseek-ai/dsh-agent": "workspace:^",
"@deepseek-ai/dsh-agent-loop": "workspace:^",
"@deepseek-ai/dsh-user-approval": "workspace:^",
"@deepseek-ai/dsh-bash": "workspace:^",
"@deepseek-ai/dsh-bash-local": "workspace:^",
"@deepseek-ai/dsh-bash-sandbox": "workspace:^",
"@deepseek-ai/dsh-llm": "workspace:^",
"@deepseek-ai/dsh-sandbox": "workspace:^",
"@deepseek-ai/dsh-sandbox-local": "workspace:^",
"@deepseek-ai/dsh-sandbox-policy": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-system-prompt": "workspace:^",
"@deepseek-ai/dsh-tasks": "workspace:^",
"@deepseek-ai/dsh-tool-tasks": "workspace:^",
"@deepseek-ai/dsh-tools": "workspace:^",
"@deepseek-ai/dsh-user-approval": "workspace:^",
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -0,0 +1,27 @@
/**
* Generic-task adaptation for background bash process handles.
*
* @module @deepseek-ai/dsh-tool-bash/background
*/
import type { BashProcess } from '@deepseek-ai/dsh-bash'
/**
* Map a settled background process onto the generic task-outcome vocabulary:
* `killed` stays `killed` (detail: the signal when one is known), everything
* else is `completed` with the exit code as detail. A nonzero command exit is
* reported, not failed, exactly like the foreground rendering.
* @param proc - the settled process handle.
* @returns the outcome for the `ctx.tasks` registration.
*/
export function processOutcome(proc: BashProcess): { status: 'completed' | 'killed'; detail: string } {
// TODO(background-infrastructure-outcome): widen BashProcess with an explicit
// infrastructure-failure outcome, then map spawn failures and
// sandbox.runnerFailed to task `failed`. The current seam aliases a spawn
// failure with a signal-less kill and a runner failure with an ordinary
// wrapper exit; real nonzero command exits must remain `completed`.
if (proc.status === 'killed') {
return { status: 'killed', detail: proc.signal !== null ? `signal: ${proc.signal}` : 'killed before exit' }
}
return { status: 'completed', detail: `exit code: ${proc.exitCode ?? 0}` }
}

View File

@@ -1,96 +1,52 @@
/**
* The model-facing bash tools: `bash`, `bash_output`, `bash_kill`. Pure
* schema + text shaping — every process concern lives behind the `ctx.bash`
* executor seam (`@deepseek-ai/dsh-bash`), so sandbox/permission/remote
* executor implementations swap in without touching what the model sees.
*
* Background notifications: when a background task completes, a short notice
* is injected into the owning agent's session (`agent.inject()` — the
* documented context seam). Injection is durable context for the NEXT model
* request, not a wake-up: an idle agent stays idle until something sends a
* message, which is why the tool descriptions tell the model to poll with
* `bash_output`.
*
* Task ownership: a background task's OWNER is an opaque token — the owning
* agent's `session.header.id` — passed to the executor at spawn
* (`resolve({ …, owner })`) and stored ON THE TASK inside the executor
* (`@deepseek-ai/dsh-bash`'s `ownerOf(id)` seam), NOT in a plugin-local map.
* `bash_output`/`bash_kill` compare `ctx.bash.ownerOf(id)` to the caller's token
* and reject a task owned by a DIFFERENT session (`owner !== undefined && owner
* !== caller`); an unowned task (no token — started by a non-agent caller) is
* open to anyone. Task ids are global and predictable (`bash-1`, …); under
* multi-session ACP (RFC 011) this token check is the fence that stops one
* session's agent from reading or killing another session's background task.
*
* Storing the token on the task in the EXECUTOR (disposed with the `dsh-bash`
* fiber), rather than in this plugin, is what makes ownership survive a
* `tool-bash` HMR reload — a reload that reset a plugin-local map would orphan
* a task spawned before it. (The `onTaskDone` listener is still effect-scoped
* to this plugin's `apply`, so a
* completion landing during the reload gap still drops its one notice — the
* pre-existing reload-gap drop — but the ownership fence itself is HMR-proof.)
*
* Commands run with the executor's full authority unless a sandboxing
* executor (`@deepseek-ai/dsh-bash-sandbox`) confines them; per-call
* allow/deny/ask policy is the `tools/pre-execute` waterfall — see
* docs/architecture.md § Extension And Composition. Under a sandboxing
* executor this plugin also advertises the ESCALATION surface
* (`sandbox_permissions`/`justification` — the sandbox RFC § Escalation,
* docs/rfc/implemented/feature/2026-07-06-sandbox.md): a command the
* sandbox denied may be retried once under a strictly wider mode, resolved
* through `ctx.approval` BEFORE anything executes and failing closed on every
* unanswerable path. The fields exist only when the mounted executor reports
* a confining default (`ctx.bash.sandboxMode`) — a lever is never advertised
* that the composition cannot honor.
*
* Per-session mode switching (the sandbox RFC § Per-session mode switching): a session may carry a
* standing sandbox-mode override — the `sandbox/mode` event fold from
* `@deepseek-ai/dsh-bash` — which this plugin makes real at EXECUTION: each
* call is stamped `escalation grant > session override > executor default`.
* The prompt deliberately does NOT state the mode and no switch is narrated:
* the model learns the boundary from the denial marker (which names the mode
* it ran under) exactly when it matters, instead of preemptively refusing
* work a standing declaration would discourage.
* Model-facing `bash` tool over the `ctx.bash` executor seam. Background calls
* register process handles with `ctx.tasks`; their work uses task cancellation
* rather than the tool-call signal after an id is returned.
*
* TODO(permissions): deployment policy belongs in `tools/pre-execute` and
* sandboxing executors; see docs/architecture.md § Extending The Harness.
* @module @deepseek-ai/dsh-tool-bash
*/
import type { Context } from 'cordis'
import z from 'schemastery'
import { isAbsolute, resolve as resolvePath } from 'node:path'
import { defineTool } from '@deepseek-ai/dsh-tools'
import type { GenericCallView, TerminalCallView, ToolExecution, ToolResult, ToolResultView } from '@deepseek-ai/dsh-tools'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-system-prompt'
// Side-effect type import: declaration-merges `ctx.approval`, consumed
// opportunistically by the escalation gate (`ctx.get('approval')` — the seam
// stays optional at runtime, same pattern as dsh-tools' ask routing).
import type {} from '@deepseek-ai/dsh-tasks'
import type {} from '@deepseek-ai/dsh-user-approval'
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
import {
ESCALATION_TARGETS,
approveEscalation,
escalationHintMarker,
sandboxDenialMarker,
validateEscalationArgs,
} from '@deepseek-ai/dsh-sandbox'
import { ESCALATION_TARGETS, approveEscalation, validateEscalationArgs } from '@deepseek-ai/dsh-sandbox'
import { effectiveSandboxMode } from '@deepseek-ai/dsh-sandbox-policy'
import { BashTaskId, OwnerToken } from '@deepseek-ai/dsh-bash'
import type { BashTask } from '@deepseek-ai/dsh-bash'
import { parseExitStatus, renderResult } from './render.ts'
import { processOutcome } from './background.ts'
import { parseExitStatus, renderProcessRead, renderResult } from './render.ts'
export const name = 'tool-bash'
export const inject = ['tools', 'bash', 'systemPrompt']
/**
* Validate the constraints the SchemaSpec can't express. `defineTool` now
* validates parsed args against the SchemaSpec before `execute` runs (the
* arg-validation RFC), so type/required/enum checks are already done and `args`
* is the validated `InferArgs` shape here. What remains are value constraints
* the DSL has no vocabulary for: non-empty strings, a positive finite timeout,
* and the escalation pairing (`sandbox_permissions` and `justification` travel
* together — an approval prompt without a reason, or a reason driving nothing,
* is a malformed ask).
*/
/** Configures whether the model may background commands. */
export interface Config {
/** Expose `run_in_background` (default true); disabled calls are also rejected. */
enableRunInBackground?: boolean
}
export const Config: z<Config> = z.object({
enableRunInBackground: z.boolean().default(true),
})
/** Parsed tool args; execute validates value constraints absent from SchemaSpec. */
interface BashToolArgs {
command: string
description: string
timeoutMs?: number
workdir?: string
run_in_background?: boolean
sandbox_permissions?: string
justification?: string
}
function validateBashArgs(args: BashToolArgs): void {
if (args.command.trim().length === 0) {
throw new Error('invalid command: expected a non-empty string')
@@ -106,95 +62,38 @@ function validateBashArgs(args: BashToolArgs): void {
validateEscalationArgs(args.sandbox_permissions, args.justification)
}
/**
* Reject an empty `task_id`. Type and presence are guaranteed by the
* SchemaSpec validation (the arg-validation RFC); only the non-empty constraint, which the
* DSL can't express, is left to check here.
*/
function validateTaskId(value: string): BashTaskId {
if (value.length === 0) {
throw new Error(`invalid task_id: expected a string, got ${JSON.stringify(value)}`)
}
return BashTaskId(value)
}
/**
* The bash tool's validated argument shape — the base parameters plus the two
* escalation fields, which are ADVERTISED only when the mounted executor
* reports a confining default mode (absent from the schema otherwise, so the
* SchemaSpec validator rejects them before `execute` ever sees one).
*/
interface BashToolArgs {
command: string
description: string
timeoutMs?: number
workdir?: string
run_in_background?: boolean
sandbox_permissions?: string
justification?: string
}
/**
* The bash tool's static description. The base text is byte-stable regardless
* of composition (it is part of the pinned snapshot header); the escalation
* teaching rides only when the mounted executor actually honors the fields —
* it names the ONE sanctioned exception to the base text's "do not retry
* another way" rule. Its deference clause ("If the session states approval
* prompts are disabled…") points at the approval plugin's never-policy prompt
* sentence by meaning, not by parsed wording — a rendezvous kept working by
* that sentence continuing to open with the approvals-disabled claim.
*/
function bashDescription(escalationModes: readonly SandboxMode[]): string {
function bashDescription(backgroundEnabled: boolean, escalationModes: readonly SandboxMode[]): string {
const background = backgroundEnabled
? 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`.'
: 'Background execution is not available; long-running commands must finish within the timeout.'
const base = 'Execute a bash command (`bash -c`) and return its stdout/stderr. '
+ 'Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — '
+ 'pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. '
+ 'Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way (a background task reports the same marker via bash_output once it has finished). '
+ 'Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under <mode> mode]` — a policy denial, not a bug in the command; do not retry another way. '
+ 'Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. '
+ 'Set `run_in_background: true` for long-running commands: the call returns a task id immediately; '
+ 'poll it with `bash_output` and stop it with `bash_kill`.'
+ background
if (escalationModes.length === 0) return base
return base + ' Attempting a command the sandbox may deny is safe and expected: run it and read the '
+ 'marker rather than assuming the denial. When a command IS denied and a wider mode would let it '
+ 'succeed, escalate immediately in the SAME turn — the ONE sanctioned exception to a denial: retry '
+ 'marker rather than assuming the denial. When a command is denied and a wider mode would let it '
+ 'succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry '
+ 'the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) '
+ 'plus a one-sentence `justification`. Do not detour through chat to ask permission first — the '
+ 'approval prompt raised by that retry IS how the user consents. If the session states approval '
+ 'approval prompt raised by that retry is how the user consents. If the session states approval '
+ 'prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. '
+ 'Never escalate speculatively: ground the request in a real denial — normally the one THIS command '
+ 'Never escalate speculatively: ground the request in a real denial — normally the one this command '
+ 'just hit; escalating up front is fine only when this session already denied the same access. '
+ 'A rejected escalation is final for THAT command — stop and explain, never work around '
+ 'A rejected escalation is final for that command — stop and explain, never work around '
+ 'it — but it does not forbid attempting or escalating other commands later.'
}
// Pure tool-owned presentation used for both live events and replay.
/**
* Pending-state presentation for a `bash` call. The TITLE is the exact `command`
* — a `kind: 'execute'` card is rendered as a terminal whose header label IS the
* title, and an execute-kind card HIDES `rawInput` (Zed: `should_show_raw_input
* = !is_terminal_tool`), so the command must BE the title to be seen. This
* mirrors the reference ACP adapters (claude-agent-acp, codex-acp), which both
* use the bare command as an execute tool's title. The model-written
* `description` (a readable summary) rides as a `content` text block shown ABOVE
* the card. (Note: claude-agent-acp DROPS the description in terminal mode and
* shows only the card; surfacing it as a content block is a deliberate
* divergence here — we keep the human summary visible alongside the card.)
* `rawInput` still carries the bare command for non-execute UIs that DO render it.
*
* `terminal` marks the call so a capable UI renders a TERMINAL card — but ONLY a
* FOREGROUND run is a terminal: a `run_in_background` call returns a task id
* immediately (it never streams a terminal; its output is polled via
* `bash_output`), so it is NOT marked terminal and renders as an ordinary
* execute card. For a foreground run the `terminal.cwd` (header) is the model
* `workdir` when given — ABSOLUTE as-is, RELATIVE for the UI bridge to resolve
* against the session cwd; when omitted the bridge fills the session workspace
* cwd (this PURE presenter, args only, can't see it).
* Present foreground calls as terminals and background starts as generic cards.
* The command remains the title on both paths; foreground cwd is passed through
* for the bridge to resolve, while background descriptions remain card content.
*/
type BashCallArgs = { command: string; description: string; workdir?: string; run_in_background?: boolean }
function presentBashCall(args: BashCallArgs): GenericCallView | TerminalCallView {
// A background start is not an interactive terminal — a generic execute card
// with the command as rawInput and the description as a content block.
if (args.run_in_background === true) {
return {
card: 'generic',
@@ -204,8 +103,6 @@ function presentBashCall(args: BashCallArgs): GenericCallView | TerminalCallView
content: [{ type: 'text', text: args.description }],
}
}
// A foreground run IS a terminal: the command titles the card, the description
// renders above it, and the cwd (when the model gave a workdir) heads it.
return {
card: 'terminal',
title: args.command,
@@ -215,57 +112,24 @@ function presentBashCall(args: BashCallArgs): GenericCallView | TerminalCallView
}
/**
* Completed-state presentation for a `bash` call. Two parallel renderings of the
* same output: `terminal.output` for a UI that shows a terminal card (the run's
* stdout/stderr + status markers, exactly as the model sees them — the RAW text,
* newlines preserved, since a terminal renderer relies on exact bytes), and a
* fenced ```console `content` block as the fallback for a UI without terminal
* support (the fences are a UI-only affordance, so they live here, not in the
* model-facing result; the fenced body is trimmed of trailing blank lines for a
* tidy block). A capable UI also gets an exit-status pill from `terminal.exitCode`
* / `terminal.signal`, parsed from the status markers `renderResult` appended.
*
* Terminal output/exit is suppressed for results that are NOT a finished
* foreground run: a `run_in_background` start (`isBackground` — the text is a
* task-id ack, not a streamed run) and an `isError` result (a spawn failure or
* abort — there is no real process exit to pill, and the body is an error
* message, not `renderResult` output, so parsing it would be meaningless). Those
* return a `generic` result whose content is the fenced ```console block. A
* finished foreground run returns a `terminal` result carrying the RAW output
* and the parsed exit status; the BRIDGE derives the fenced fallback from
* `output` for a UI without terminal support, so the tool does not double-encode
* it. A non-text result (unexpected for bash) falls through to `undefined`.
* Present completed foreground output as a terminal; background acknowledgements
* and execution errors use generic fenced output without an exit-status pill.
*/
function presentBashResult(args: unknown, result: ToolResult): ToolResultView | undefined {
const block = result.content.length === 1 ? result.content[0] : undefined
if (block === undefined || block.type !== 'text') return undefined
const raw = block.text
const isBackground = typeof args === 'object' && args !== null && (args as { run_in_background?: unknown }).run_in_background === true
// A background ack or an errored run is not a real terminal exit: render the
// fenced ```console fallback as generic content (no exit pill).
// Background acknowledgements and errors have no terminal exit status.
if (isBackground || result.isError) {
return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] }
}
// A finished foreground run: RAW output + parsed exit for the terminal card.
// The bridge derives the no-capability fenced fallback from `output`.
return { card: 'terminal', output: raw, ...parseExitStatus(raw) }
}
/** Pending-state presentation for `bash_output`/`bash_kill` (background-task tools). */
function presentTaskCall(verb: string, args: { task_id: string }): GenericCallView {
return { card: 'generic', title: `${verb} background task ${args.task_id}`, kind: 'execute', rawInput: args.task_id }
}
/**
* Resolve the working directory for a bash call. Precedence: an explicit model
* `workdir` wins; otherwise default to the calling agent's session cwd
* (`session.header.cwd`) so each ACP session's commands run in ITS workspace,
* not the server's launch dir. A RELATIVE model `workdir` is resolved against
* the session cwd (the tool tells the model to pass `workdir` instead of `cd`,
* so a relative one should be relative to the session's root, not `process.cwd()`).
* Returns `undefined` when neither is available (no agent / headerless session /
* no session cwd) — the executor then applies its own config/`process.cwd()`
* default, preserving today's non-ACP behavior.
* Resolve an explicit workdir first, making a relative one session-cwd-relative;
* otherwise use the session cwd and leave executor defaulting as the fallback.
*/
function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent }): string | undefined {
const sessionCwd = exec.agent?.session.header.cwd
@@ -276,102 +140,11 @@ function resolveWorkdir(modelWorkdir: string | undefined, exec: { agent?: Agent
return modelWorkdir
}
/** Status line for background task reads. */
function statusLine(task: BashTask): string {
switch (task.status) {
case 'running': return '[status: running]'
case 'killed': return `[status: killed${task.signal !== null ? ` by ${task.signal}` : ''}]`
case 'completed': return `[status: completed, exit code: ${task.exitCode ?? 0}]`
}
}
export function apply(ctx: Context): void {
// The bash tools' cross-call HABIT, which the per-tool descriptions cannot
// carry (they describe one call each): the exit-code marker is only useful
// if the model actually checks it every time.
ctx.systemPrompt.section({
name: 'tool:bash',
order: 105,
text: 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.',
})
/**
* The caller's owner TOKEN — the owning agent's `session.header.id`, or
* `undefined` for a non-agent caller. Read `session.header.id` (NOT
* `session.id`): every other subsystem keys off the header id (the ACP bridge,
* both persistence backends), and the sibling `resolveWorkdir` already reads
* `session.header.cwd`, so using `session.id` here would be the asymmetry smell
* the conventions flag. The two are equal in production, but the header is the
* canonical identity.
*/
const callerToken = (exec: { agent?: Agent }): OwnerToken | undefined =>
exec.agent ? OwnerToken(exec.agent.session.header.id) : undefined
/**
* Authorize a `bash_output`/`bash_kill` call against the task's stored owner
* token. Rejects when the task HAS an owner and it differs from the caller's
* token — using `!== undefined` semantics, NOT truthiness, so an empty-string
* token is still a real owner (never treated as unowned). An unowned task
* (`ownerOf` returns `undefined`) is allowed; a truly unknown id is also
* `undefined` here and then fails loudly at the subsequent
* `readOutput`/`kill` ("unknown bash task"). The conservative no-agent caller
* (`callerToken` undefined) cannot match an owned task and is rejected.
*/
const assertTaskAccess = (taskId: BashTaskId, exec: { agent?: Agent }): void => {
const owner = ctx.bash.ownerOf(taskId)
if (owner !== undefined && owner !== callerToken(exec)) {
throw new Error(`task ${taskId} belongs to another session`)
}
}
// Background completion → inject a notice into the owning agent's session.
// Find the live agent by its session id token via the agent registry, read
// opportunistically with `ctx.get('agents')` (NOT `ctx.agents`/static inject):
// this listener runs from `task.done.then` on the bash fiber — a foreign
// fiber — where the `ctx.agents` property proxy would throw through the
// traceable shadow; `ctx.get(name)` is the topology-independent lookup. No
// registry mounted (`undefined`) → drop the notice. Match on
// `agent.session.header.id`, NOT the registry key: a config agent's id differs
// from its session id, and the owner token IS the session id.
ctx.bash.onTaskDone((task) => {
const ownerToken = ctx.bash.ownerOf(task.id)
if (ownerToken === undefined) return
const agent = ctx.get('agents')?.list().find(a => OwnerToken(a.session.header.id) === ownerToken)
if (!agent) return
try {
agent.inject(
[{ type: 'text', text: `background bash task ${task.id} finished ${statusLine(task)}. Read its output with bash_output.` }],
{ source: { kind: 'plugin', plugin: 'tool-bash' } },
)
} catch (error: unknown) {
// The ONE expected failure: the agent was disposed between task
// completion and this injection (ReactLoopAgent.inject throws
// `agent "<id>" is disposed`). That race is benign — drop the notice.
// Anything else is a real bug and must surface, not be swallowed.
if (error instanceof Error && error.message.includes('is disposed')) return
throw error
}
})
// The escalation surface exists whenever the mounted executor confines.
// Its enum is the closed target vocabulary, deliberately NOT cut down by
// the configured default: a session may switch to a narrower effective mode
// while sharing this globally registered schema. Strict widening therefore
// belongs to the per-call check below. An executor swap restarts this fiber
// (static inject) and re-registers the schema.
export function apply(ctx: Context, config: Config): void {
const backgroundEnabled = config.enableRunInBackground ?? true
const defaultMode = ctx.bash.sandboxMode
const escalationModes: readonly SandboxMode[] = defaultMode === undefined ? [] : ESCALATION_TARGETS
/**
* The session's standing mode override for an ordinary (non-escalating)
* call: the `sandbox/mode` fold of the calling agent's log, stamped
* onto the request so EXECUTION follows the same effective mode the prompt
* section states. Weakest precedence — an escalation grant (freshly
* approved for exactly this call) outranks it, and without either the
* executor's `resolve()` applies its configured default. Undefined for a
* non-sandboxing executor (nothing honors it) and for agent-less callers
* (no session to fold).
*/
const sessionOverride = (exec: ToolExecution): SandboxMode | undefined =>
defaultMode === undefined || exec.agent === undefined ? undefined : effectiveSandboxMode(exec.agent.session.events)
@@ -382,9 +155,9 @@ export function apply(ctx: Context): void {
* {@link approveEscalation}. This tool contributes only the composition
* guard (the fields are unadvertised without a sandboxing executor, yet
* schema validation checks advertised keys only, so an unadvertised
* `sandbox_permissions` still reaches execute) and the channel closure over
* `ctx.approval` — consumed opportunistically (`ctx.get`, the dsh-tools
* ask-routing pattern) so a deployment without it degrades per call.
* `sandbox_permissions` still reaches execute) and the approval ingredients
* — the seam is consumed opportunistically (`ctx.get`) so a deployment
* without it degrades per call.
*/
const approveBashEscalation = (mode: string, justification: string, exec: ToolExecution): Promise<SandboxMode> => {
if (escalationModes.length === 0) {
@@ -403,9 +176,16 @@ export function apply(ctx: Context): void {
)
}
// Cross-call guidance belongs in the prompt rather than one-call schema prose.
ctx.systemPrompt.section({
name: 'tool:bash',
order: 105,
text: 'Check the [exit code: N] marker on every bash result; investigate failures before moving on.',
})
ctx.tools.register(defineTool({
name: 'bash',
description: bashDescription(escalationModes),
description: bashDescription(backgroundEnabled, escalationModes),
parameters: {
command: { type: 'string', required: true, description: 'The bash command to execute.' },
description: {
@@ -417,117 +197,69 @@ export function apply(ctx: Context): void {
},
timeoutMs: { type: 'number', description: 'Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry.' },
workdir: { type: 'string', description: 'Working directory for this command. Defaults to the session workspace; a relative path is resolved against it.' },
run_in_background: { type: 'boolean', description: 'Run in the background and return a task id immediately. No timeout applies.' },
...backgroundEnabled ? {
run_in_background: { type: 'boolean' as const, description: 'Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies.' },
} : {},
...escalationModes.length > 0 ? {
sandbox_permissions: {
type: 'string' as const,
enum: [...escalationModes],
description: 'The wider sandbox mode this command needs. Only valid as a one-shot retry '
+ 'of a command the sandbox just denied; requires justification and user approval.',
description: 'The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.',
},
justification: {
type: 'string' as const,
description: 'Required with sandbox_permissions: one sentence for the user explaining '
+ 'why this exact command needs the wider access.',
description: 'Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access.',
},
} : {},
},
async execute(args: BashToolArgs, exec) {
validateBashArgs(args)
// `description` is display/logging metadata only (surfaced to UIs via
// the tool/call session event); it is intentionally NOT forwarded to
// ctx.bash and has no effect on execution.
// An escalating call resolves approval BEFORE anything executes; every
// non-grant outcome throws its distinct error text and runs nothing.
// (validateBashArgs pinned the pairing, so the double narrow is exact.)
// An ordinary call carries the session's standing override instead —
// grant > session override > executor default (see sessionOverride).
// Description is display metadata; workdir defaults to the caller's session.
const sandboxMode = args.sandbox_permissions !== undefined && args.justification !== undefined
? await approveBashEscalation(args.sandbox_permissions, args.justification, exec)
: sessionOverride(exec)
// Default the workdir to the calling agent's session cwd so each ACP
// session runs in its own workspace (see resolveWorkdir); an explicit
// model workdir still wins.
const workdir = resolveWorkdir(args.workdir, exec)
const request = {
command: args.command,
...workdir !== undefined ? { workdir } : {},
...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {},
...exec.signal ? { signal: exec.signal } : {},
...sandboxMode !== undefined ? { sandboxMode } : {},
}
if (args.run_in_background === true) {
// Stamp the owner token (the agent's session id) onto the spec so the
// executor stores it on the task — the isolation fence for bash_output/
// bash_kill. Foreground runs pass no owner (they finish inline; nothing
// to fence).
const task = ctx.bash.start(ctx.bash.resolve({ ...request, owner: callerToken(exec) }))
return [{ type: 'text', text: `started background task ${task.id}` }]
// Undeclared keys are allowed, so schema omission also needs enforcement.
if (!backgroundEnabled) {
throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)')
}
const tasks = ctx.get('tasks')
if (tasks === undefined) {
throw new Error('background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks')
}
// Reject pre-start cancellation; returned tasks use their own lifecycle.
if (exec.signal?.aborted) throw new Error('command aborted')
// Task preflight finishes before the starter can spawn a process.
const id = tasks.start({
kind: 'bash',
label: args.command,
...exec.agent ? { owner: exec.agent } : {},
run: () => {
const proc = ctx.bash.start(ctx.bash.resolve(request))
return {
cancel: () => void proc.kill(),
done: proc.done.then(() => processOutcome(proc)),
readOutput: () => renderProcessRead(proc.readOutput(), proc.sandbox, escalationModes),
}
},
})
return [{ type: 'text', text: `started background task ${id}` }]
}
const result = await ctx.bash.run(ctx.bash.resolve(request))
const result = await ctx.bash.run(ctx.bash.resolve({
...request,
...exec.signal ? { signal: exec.signal } : {},
}))
if (result.aborted) throw new Error('command aborted')
return [{ type: 'text', text: renderResult(result, escalationModes) }]
},
presentCall: presentBashCall,
presentResult: presentBashResult,
}))
ctx.tools.register(defineTool({
name: 'bash_output',
description: 'Read new output from a background bash task started with `bash` + `run_in_background`. '
+ 'Returns only output produced since the previous bash_output call, plus the task status. '
+ 'Tasks keep running while you do other work; poll again later for more output.',
parameters: {
task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
},
// execute is synchronous (registry reads + string shaping) but the
// ToolDefinition contract wants a Promise — hence resolve(), not async.
execute(args, exec) {
const id = validateTaskId(args.task_id)
assertTaskAccess(id, exec)
const read = ctx.bash.readOutput(id)
let text = read.delta.length > 0 ? read.delta : '(no new output)'
if (read.lossy) {
const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((p): p is string => p !== undefined)
const fullOutput = paths.length > 0 ? paths.join(', ') : '(unavailable)'
text += `\n[some output was dropped from memory; full output: ${fullOutput}]`
}
text += `\n${statusLine(read.task)}`
if (read.task.sandbox?.runnerFailed) {
// The sandbox RUNNER itself failed — the command never ran. The
// foreground path surfaces this as the structured SANDBOX_UNAVAILABLE
// error; a settled task's read carries the marker instead.
text += `\n[sandbox: the sandbox runner itself failed under ${read.task.sandbox.mode} mode — the command did not run; this is a sandbox problem, not a command failure]`
} else if (read.task.sandbox?.denied) {
// Mirrors the foreground result marker (and its same-turn escalation
// hint). Background denials are only classifiable once the task
// settles (the classifier needs the whole stderr), so the marker
// rides every read that sees the settled task.
text += `\n${sandboxDenialMarker(read.task.sandbox.mode)}`
if (escalationModes.length > 0) {
text += `\n${escalationHintMarker('command')}`
}
}
return Promise.resolve([{ type: 'text', text }])
},
presentCall: args => presentTaskCall('Read output from', args),
}))
ctx.tools.register(defineTool({
name: 'bash_kill',
description: 'Ask the executor to kill a running background bash task by task id.',
parameters: {
task_id: { type: 'string', required: true, description: 'Task id returned by the bash tool.' },
},
execute(args, exec) {
const id = validateTaskId(args.task_id)
assertTaskAccess(id, exec)
const killed = ctx.bash.kill(id)
return Promise.resolve([{
type: 'text',
text: killed ? `killed background task ${id}` : `task ${id} had already finished`,
}])
},
presentCall: args => presentTaskCall('Kill', args),
}))
}

View File

@@ -4,7 +4,7 @@
* @module @deepseek-ai/dsh-tool-bash/render
*/
import type { BashRunResult, CollectedOutput } from '@deepseek-ai/dsh-bash'
import type { BashProcessRead, BashRunResult, BashSandboxInfo, CollectedOutput } from '@deepseek-ai/dsh-bash'
import type { SandboxMode } from '@deepseek-ai/dsh-sandbox'
import { escalationHintMarker, sandboxDenialMarker } from '@deepseek-ai/dsh-sandbox'
@@ -16,7 +16,7 @@ function streamText(output: CollectedOutput): string {
/**
* Shape one finished run into the text the model sees: stdout, then a marked
* stderr section, then exit-status markers. Non-zero exits are REPORTED, not
* stderr section, then exit-status markers. Non-zero exits are reported, not
* errored — the model decides how to react; only infrastructure failures
* (spawn errors, aborts) surface as isError results.
* @param result - the completed foreground run from the executor.
@@ -41,23 +41,15 @@ export function renderResult(
if (body.length === 0) body = '(no output)'
const markers: string[] = []
// The sandbox marker precedes the exit-status markers so `[exit code: N]`
// stays the LAST line (exitStatus() anchors its parse there). Denial is a
// reported fact like timeout: the model decides how to react.
// Keep the exit marker last because parseExitStatus anchors there.
if (result.sandbox?.denied) {
markers.push(sandboxDenialMarker(result.sandbox.mode))
// The same-turn nudge lives at the decision point: only when this
// composition advertises the fields (a lever is never hinted that the
// schema does not offer), and inside the sandbox marker family so the
// exit-code marker stays the last line.
// Hint only when the composition exposes escalation, before the final exit marker.
if (escalationModes.length > 0) {
markers.push(escalationHintMarker('command'))
}
}
// Timeout is reported independently of how the process actually ended: a
// command can trap SIGTERM and exit 0 after our timer fired (e.g.
// `trap "exit 0" TERM; sleep 60`), giving timedOut:true / exitCode:0 /
// signal:null — the model must still see that the command was cut short.
// A command may trap SIGTERM and exit 0 after timeout; still report interruption.
if (result.timedOut) markers.push(`[timed out after ${result.timeoutMs}ms]`)
if (result.signal !== null) {
markers.push(`[killed by signal: ${result.signal}]`)
@@ -70,6 +62,38 @@ export function renderResult(
return body + markers.join('\n')
}
/**
* Shape one background-process read into the `task_output` delta the model
* sees: the incremental delta, plus the lossy-read notice (with full-stream
* spill paths) when in-memory truncation dropped unread bytes. Empty-delta
* rendering (`(no new output)`) is the generic control surface's job.
* @param read - one incremental read from the process handle.
* @param sandbox - settled sandbox facts, when this was a confined process.
* @param escalationModes - escalation targets advertised by this composition.
* @returns the delta text with any loss or sandbox notice appended.
*/
export function renderProcessRead(
read: BashProcessRead,
sandbox?: BashSandboxInfo,
escalationModes: readonly SandboxMode[] = [],
): string {
const notices: string[] = []
if (read.lossy) {
const paths = [read.stdoutSpillPath, read.stderrSpillPath].filter((path): path is string => path !== undefined)
notices.push(`[some output was dropped from memory; full output: ${paths.length > 0 ? paths.join(', ') : '(unavailable)'}]`)
}
if (sandbox?.runnerFailed) {
notices.push(`[sandbox: the sandbox runner itself failed under ${sandbox.mode} mode — the command did not run; this is a sandbox problem, not a command failure]`)
} else if (sandbox?.denied) {
notices.push(sandboxDenialMarker(sandbox.mode))
if (escalationModes.length > 0) {
notices.push(escalationHintMarker('command'))
}
}
if (notices.length === 0) return read.delta
return `${read.delta}${read.delta.length > 0 && !read.delta.endsWith('\n') ? '\n' : ''}${notices.join('\n')}`
}
/**
* Recover the structured exit status from a rendered {@link renderResult}
* string — the inverse of the status markers it appends. A killed marker

View File

@@ -7,15 +7,17 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import ToolRegistry from '@deepseek-ai/dsh-tools'
import AgentRegistry, { AgentId } from '@deepseek-ai/dsh-agent'
import AgentLoop, { ReactLoopAgent } from '@deepseek-ai/dsh-agent-loop'
import TaskService from '@deepseek-ai/dsh-tasks'
import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks'
import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
import { BashTaskId } from '@deepseek-ai/dsh-bash'
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
/**
* Full-loop integration: a scripted mock model drives the REAL bash tool
* through the agent loop, exercising the same seams a live model would
* (tool/call + tool/result session events, agent.inject notifications).
* (tool/call + tool/result session events, the generic `ctx.tasks` runtime,
* agent.inject completion notices).
*/
async function harness(adapter: MockAdapter) {
const ctx = new Context()
@@ -25,6 +27,8 @@ async function harness(adapter: MockAdapter) {
await ctx.plugin(ToolRegistry)
await ctx.plugin(AgentRegistry)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(TaskService)
await ctx.plugin(ToolTasks)
await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
await ctx.plugin(ToolBash)
ctx.llm.registerAdapter(['mock'], adapter)
@@ -67,6 +71,16 @@ function resultText(event: SessionEvent): string {
.join('')
}
/** Poll until `predicate` holds (background settlement races turn end). */
async function pollUntil(predicate: () => boolean, timeoutMs = 5_000): Promise<void> {
const deadline = Date.now() + timeoutMs
while (Date.now() < deadline) {
if (predicate()) return
await new Promise(resolve => setTimeout(resolve, 20))
}
throw new Error(`condition not met within ${timeoutMs}ms`)
}
describe('bash tool through the agent loop', () => {
it('foreground: model calls bash, sees the result, replies', async () => {
const adapter = new MockAdapter([
@@ -116,46 +130,41 @@ describe('bash tool through the agent loop', () => {
expect(resultText(toolResult)).toContain('[exit code: 9]')
})
it('background: start → poll → completion notice lands as context/message', async () => {
it('background: start ack → completion notice as context/message → task_output collects it', async () => {
// The task id is deterministic (a fresh TaskService counts per kind from 1),
// so the script can name `bash-1` without threading a generated id.
const adapter = new MockAdapter([
toolCallResponse('call-1', 'bash', { command: 'echo bg-ok', description: 'test command', run_in_background: true }),
// Each harness owns a fresh BashLocal service, whose first task id is
// deterministically bash-1. Keep the scripted call faithful to what the
// model sent; tool arguments are immutable once execution policy begins.
toolCallResponse('call-2', 'bash_output', { task_id: 'bash-1' }, undefined),
textResponse('Started it in the background.'),
toolCallResponse('call-2', 'task_output', { task_id: 'bash-1' }),
textResponse('Background task finished.'),
])
let taskId = ''
const ctx = await harness(adapter)
const agent = ctx.agentLoop.create(AgentId('it-bg'), { model: 'mock' })
// Capture the generated id so the deterministic fixture is checked against
// the real executor instead of silently assuming it.
ctx.on('session/event', (_session, event) => {
if (event.type === 'tool/result' && taskId === '') {
const match = /task (bash-\d+)/.exec(resultText(event))
if (match) taskId = match[1]!
}
})
agent.send([{ type: 'text', text: 'run echo bg-ok in the background' }])
await waitForIdle(ctx, agent)
expect(taskId).toBe('bash-1')
const firstResult = findEvent(events(agent), 'tool/result')
expect(firstResult.data.isError).toBe(false)
expect(resultText(firstResult)).toBe('started background task bash-1')
// Wait for the background task itself (completion may race turn end).
const task = ctx.bash.get(BashTaskId(taskId))
if (!task) throw new Error(`task ${taskId} not registered`)
await task.done
const log = events(agent)
const firstResult = findEvent(log, 'tool/result')
expect(resultText(firstResult)).toBe(`started background task ${taskId}`)
const notice = findEvent(log, 'context/message')
// The task settles on its own; the tool-tasks notice listener injects a
// durable context/message into the owning agent's session (settlement may
// race turn end, so poll for it).
await pollUntil(() => events(agent).some(event => event.type === 'context/message'))
const notice = findEvent(events(agent), 'context/message')
expect(notice.data.content.some(
block => block.type === 'text' && block.text.includes(`background bash task ${taskId} finished`),
block => block.type === 'text' && block.text.includes('background task bash-1 (bash: echo bg-ok) finished'),
)).toBe(true)
expect(notice.data.source).toEqual({ kind: 'plugin', plugin: 'tool-bash' })
expect(notice.data.source).toEqual({ kind: 'plugin', plugin: 'tool-tasks' })
// The next turn collects the output through the generic task tool.
agent.send([{ type: 'text', text: 'collect it' }])
await waitForIdle(ctx, agent)
const readResult = findEvent(events(agent), 'tool/result', 'last')
expect(readResult.data.isError).toBe(false)
expect(resultText(readResult)).toContain('bg-ok')
expect(resultText(readResult)).toContain('[status: completed, exit code: 0]')
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -14,6 +14,12 @@
{
"path": "../../../vendor/cordis"
},
{
"path": "../../../vendor/schemastery"
},
{
"path": "../../llm/llm"
},
{
"path": "../../core/tools"
},
@@ -23,6 +29,9 @@
{
"path": "../../bash/bash"
},
{
"path": "../../tasks/tasks"
},
{
"path": "../../core/system-prompt"
},

View File

@@ -84,17 +84,11 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
key: 'bash',
summary: 'Registers one `ctx.bash` implementation.',
summary: 'Abstract bash execution service.',
methods: [
'abstract resolve(request: BashExecRequest): BashExecSpec',
'abstract run(spec: BashExecSpec): Promise<BashRunResult>',
'abstract start(spec: BashExecSpec): BashTask',
'abstract get(id: BashTaskId): BashTask | undefined',
'abstract ownerOf(id: BashTaskId): OwnerToken | undefined',
'abstract list(): BashTask[]',
'abstract readOutput(id: BashTaskId): BashTaskRead',
'abstract kill(id: BashTaskId): boolean',
'onTaskDone(listener: BashTaskListener): () => void',
'abstract start(spec: BashExecSpec): BashProcess',
],
},
{
@@ -219,6 +213,20 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
'async assemble(context: AssembleContext = {}): Promise<PromptAssembly>',
],
},
{
key: 'tasks',
summary: 'The `tasks` service: the runtime-global background task registry.',
methods: [
'start(spec: TaskStart): TaskId',
'list(caller?: Agent): TaskSnapshot[]',
'get(id: TaskId, caller?: Agent): TaskSnapshot',
'read(id: TaskId, caller?: Agent): TaskRead',
'kill(id: TaskId, caller?: Agent, reason?: string): \'requested\' | \'already-finished\'',
'async wait(id: TaskId, timeoutMs: number, caller?: Agent, signal?: AbortSignal): Promise<TaskSnapshot>',
'onTaskDone(listener: TaskDoneListener): () => void',
'attachSurface(name: string): () => void',
],
},
{
key: 'tools',
summary: 'Tool registry and execution pipeline.',
@@ -564,11 +572,23 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'BashExecRequest',
declaration: 'export interface BashExecRequest {\n command: string;\n workdir?: string | undefined;\n timeoutMs?: number | undefined;\n signal?: AbortSignal | undefined;\n stdin?: string | undefined;\n env?: Record<string, string> | undefined;\n owner?: OwnerToken | undefined;\n sandboxMode?: SandboxMode | undefined;\n}',
declaration: 'export interface BashExecRequest {\n command: string;\n workdir?: string | undefined;\n timeoutMs?: number | undefined;\n signal?: AbortSignal | undefined;\n stdin?: string | undefined;\n env?: Record<string, string> | undefined;\n sandboxMode?: SandboxMode | undefined;\n}',
},
{
name: 'BashExecSpec',
declaration: 'export interface BashExecSpec {\n command: string;\n workdir: string;\n timeoutMs: number;\n signal?: AbortSignal | undefined;\n stdin?: string | undefined;\n env?: Record<string, string> | undefined;\n owner: OwnerToken | undefined;\n sandboxMode: SandboxMode | undefined;\n}',
declaration: 'export interface BashExecSpec {\n command: string;\n workdir: string;\n timeoutMs: number;\n signal?: AbortSignal | undefined;\n stdin?: string | undefined;\n env?: Record<string, string> | undefined;\n sandboxMode: SandboxMode | undefined;\n}',
},
{
name: 'BashProcess',
declaration: 'export interface BashProcess {\n status: BashProcessStatus;\n exitCode: number | null;\n signal: NodeJS.Signals | null;\n readonly done: Promise<void>;\n sandbox?: BashSandboxInfo;\n readOutput(): BashProcessRead;\n kill(): boolean;\n}',
},
{
name: 'BashProcessRead',
declaration: 'export interface BashProcessRead {\n delta: string;\n lossy: boolean;\n stdoutSpillPath?: string;\n stderrSpillPath?: string;\n}',
},
{
name: 'BashProcessStatus',
declaration: 'export type BashProcessStatus = \'running\' | \'completed\' | \'killed\';',
},
{
name: 'BashRunResult',
@@ -578,26 +598,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'BashSandboxInfo',
declaration: 'export interface BashSandboxInfo {\n mode: SandboxMode;\n denied: boolean;\n enforcement?: SandboxEnforcement;\n runnerFailed?: boolean;\n}',
},
{
name: 'BashTask',
declaration: 'export interface BashTask {\n readonly id: BashTaskId;\n status: BashTaskStatus;\n exitCode: number | null;\n signal: NodeJS.Signals | null;\n readonly done: Promise<void>;\n sandbox?: BashSandboxInfo;\n}',
},
{
name: 'BashTaskId',
declaration: 'export type BashTaskId = Branded<\'BashTaskId\'>;',
},
{
name: 'BashTaskListener',
declaration: 'export type BashTaskListener = (task: BashTask) => void;',
},
{
name: 'BashTaskRead',
declaration: 'export interface BashTaskRead {\n task: BashTask;\n delta: string;\n lossy: boolean;\n stdoutSpillPath?: string;\n stderrSpillPath?: string;\n}',
},
{
name: 'BashTaskStatus',
declaration: 'export type BashTaskStatus = \'running\' | \'completed\' | \'killed\';',
},
{
name: 'Branded',
declaration: 'export type Branded<B extends string> = string & {\n readonly [BRAND]: B;\n};',
@@ -750,10 +750,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'MessageSourceMap',
declaration: 'export interface MessageSourceMap {\n user: {\n kind: \'user\';\n };\n plugin: {\n kind: \'plugin\';\n plugin: string;\n };\n}',
},
{
name: 'OwnerToken',
declaration: 'export type OwnerToken = Branded<\'OwnerToken\'>;',
},
{
name: 'PresetOption',
declaration: 'export interface PresetOption {\n value: string;\n name: string;\n description?: string;\n}',
@@ -930,6 +926,46 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'SurfaceOp',
declaration: 'export type SurfaceOp = \'append\' | {\n op: \'replace\';\n start: number;\n end: number;\n};',
},
{
name: 'TaskDoneListener',
declaration: 'export type TaskDoneListener = (snapshot: TaskSnapshot, owner: Agent | undefined) => void | PromiseLike<void>;',
},
{
name: 'TaskHooks',
declaration: 'export interface TaskHooks {\n cancel(reason?: string): void;\n done: Promise<TaskOutcome>;\n readOutput?(): string;\n}',
},
{
name: 'TaskId',
declaration: 'export type TaskId = Branded<\'TaskId\'>;',
},
{
name: 'TaskKind',
declaration: 'export type TaskKind = TaskKindMap[keyof TaskKindMap];',
},
{
name: 'TaskKindMap',
declaration: 'export interface TaskKindMap {\n bash: \'bash\';\n subagent: \'subagent\';\n}',
},
{
name: 'TaskOutcome',
declaration: 'export interface TaskOutcome {\n status: \'completed\' | \'killed\' | \'failed\';\n detail?: string;\n output?: string;\n}',
},
{
name: 'TaskRead',
declaration: 'export interface TaskRead {\n text: string;\n snapshot: TaskSnapshot;\n}',
},
{
name: 'TaskSnapshot',
declaration: 'export interface TaskSnapshot {\n id: TaskId;\n kind: TaskKind;\n label: string;\n ownerSession?: SessionId;\n status: TaskStatus;\n detail?: string;\n startedAt: number;\n finishedAt?: number;\n reported: boolean;\n}',
},
{
name: 'TaskStart',
declaration: 'export interface TaskStart {\n kind: TaskKind;\n label: string;\n owner?: Agent;\n run(): TaskHooks;\n}',
},
{
name: 'TaskStatus',
declaration: 'export type TaskStatus = \'running\' | \'stopping\' | \'completed\' | \'killed\' | \'failed\';',
},
{
name: 'TerminalCallView',
declaration: 'export interface TerminalCallView {\n card: \'terminal\';\n title: string;\n description?: string;\n cwd?: string;\n}',

View File

@@ -58,7 +58,7 @@ Everything that goes beyond "call the model, run the tools, repeat" belongs to p
- Hooks and policy: the relevant `agent/*` checkpoints plus the guarded `tools/pre-execute``tools/execute``tools/post-execute``tools/result` pipeline; exact signatures and modes live in the [generated event catalog](../../../docs/cordis-catalog/events.md)
- Compaction: `agent/pre-step`
- Sandbox, permission, plan mode: `tools/pre-execute` for extensible deny/ask, `tools.guard()` for monotonic owner policy, `tools/post-execute` for result decisions, and `tools/result` for final observation
- Sub-agents: implemented outside the loop as `ctx.subagents` providers; in-process providers use `ctx.agents.create()` and owned `AgentHandle` teardown, while child streaming/progress and background/poll collection remain deferred.
- Sub-agents: implemented outside the loop as `ctx.subagents` providers; in-process providers use `ctx.agents.create()` and owned `AgentHandle` teardown, while generic [`ctx.tasks`](../../tasks/tasks/) plus [`dsh-tool-subagent`](../../subagent/tool-subagent/) own background collection.
- Persistence: `session/event` + `session/flush`
- UI: `session/event` (assistant token stream, boundaries, tool activity) + `agent/*` control events (`agent/status`, `agent/created`/`agent/disposed`)

View File

@@ -30,6 +30,22 @@ function fixture(files: Record<string, string>): string {
const make = (content: string): string => fixture({ 'index.ts': content })
describe('verify-export-jsdoc functions and consts', () => {
it('limits packages without src/* exports to declarations reachable from package entrypoints', () => {
const root = fixture({
'index.ts': "export { publicFn } from './internal.ts'\n",
'internal.ts': `
export function publicFn(value: string): string { return value }
export function hiddenFn(value: string): string { return value }
`,
})
writeFileSync(join(root, 'packages/group/fix/package.json'), JSON.stringify({
exports: { '.': { types: './lib/types/index.d.ts', default: './lib/index.js' } },
}))
const violations = collectExportJsdocViolations(root)
expect(violations).toHaveLength(1)
expect(violations.every(violation => violation.includes('publicFn'))).toBe(true)
})
it('accepts a fully documented surface', () => {
expect(collectExportJsdocViolations(make(`
/**

View File

@@ -23,7 +23,7 @@ describe('gen-tool-catalog collectToolCatalog', () => {
it('boots every shipped tool package and harvests its model-facing schemas', async () => {
const catalog = await collectToolCatalog()
const names = catalog.flatMap(entry => entry.schemas.map(s => s.name)).sort()
expect(names).toEqual(['ask_user_question', 'bash', 'bash_kill', 'bash_output', 'cordis_inspect', 'cordis_mount', 'cordis_unmount', 'edit', 'read', 'run_code', 'skill', 'subagent', 'todo_write', 'web_fetch', 'web_search', 'workflow', 'write'])
expect(names).toEqual(['ask_user_question', 'bash', 'cordis_inspect', 'cordis_mount', 'cordis_unmount', 'edit', 'read', 'run_code', 'skill', 'subagent', 'task_kill', 'task_list', 'task_output', 'todo_write', 'web_fetch', 'web_search', 'workflow', 'write'])
// Every tool carries a JSON-Schema `parameters` object (what the model sees).
for (const entry of catalog) {
for (const schema of entry.schemas) {

View File

@@ -30,6 +30,8 @@ Because the package wires no logger entry, an ACP leaf has **nothing to get wron
| `toolOrder` | — | explicit model-facing tool order (a name list with one `'<unlisted-tools>'` rest entry; absent — lexicographic; an unregistered name fails each turn at prompt assembly), routed to `dsh-system-prompt` |
| `tools` | `{ mode: 'native' }` | tool-registry presentation config (`native` / `code` / `both`), routed through `dsh-agent-spine-demo` |
| `skills` | owner defaults | registry-cache, local-provider, and model-facing skill-tool config, routed through `dsh-agent-spine-demo` |
| `toolBash` | owner defaults | model-facing bash config routed through `dsh-agent-spine-demo`, including bash's producer-local `enableRunInBackground` |
| `toolTasks` | owner defaults | generic `task_output` wait bounds routed through `dsh-agent-spine-demo` |
| `persistenceRoot` | `./.sessions` | the JSONL backend's root directory |
The leaf supplies the swappable backends: an LLM adapter (`llm-deepseek` for the real model, `llm-replay` for keyless snapshot replay) and a bash executor.

View File

@@ -41,6 +41,10 @@ export interface Config {
persistenceRoot?: string
/** Skill registry, local-provider, and model-facing consumer config forwarded to agent-spine-demo. */
skills?: agentCore.SkillConfig
/** Model-facing bash tool config forwarded through agent-core. */
toolBash?: NonNullable<agentCore.Config['toolBash']>
/** Generic background-task control-tool config forwarded through agent-core. */
toolTasks?: NonNullable<agentCore.Config['toolTasks']>
}
// Each front door owns a complete, directly readable config schema; extracting
@@ -58,6 +62,8 @@ export const Config: z<Config> = z.object({
// apply() fallback through one named constant while retaining both boundaries.
persistenceRoot: z.string().default('./.sessions'),
skills: agentCore.SkillConfigSchema,
toolBash: agentCore.ToolBashConfigSchema,
toolTasks: agentCore.ToolTasksConfigSchema,
})
/* jscpd:ignore-end */
@@ -74,6 +80,8 @@ export function apply(ctx: Context, config: Config): void {
...config.toolOrder !== undefined ? { toolOrder: config.toolOrder } : {},
...config.tools !== undefined ? { tools: config.tools } : {},
...config.skills !== undefined ? { skills: config.skills } : {},
...config.toolBash !== undefined ? { toolBash: config.toolBash } : {},
...config.toolTasks !== undefined ? { toolTasks: config.toolTasks } : {},
})
ctx.plugin(UserInteractionService)
ctx.plugin(SessionPersistenceJsonl, { root: config.persistenceRoot ?? './.sessions' })

View File

@@ -19,8 +19,9 @@ import * as acpAgent from '../src/index.ts'
* ACP operations end-to-end) is the keyless bin smoke in `load-path.e2e.ts`;
* this spec asserts the composition and the persistenceRoot default branch.
*/
async function mount(config: acpAgent.Config): Promise<Context> {
async function mount(config: acpAgent.Config, withBash = false): Promise<Context> {
const ctx = new Context()
if (withBash) ctx.provide('bash', { sandboxMode: undefined })
await ctx.plugin(acpAgent, config)
// The bundle mounts its children inside apply() (not awaited there); let their
// fibers settle so the spine services are ready.
@@ -112,6 +113,19 @@ describe('dsh-acp-demo composition', () => {
await ctx.fiber.dispose()
})
it('forwards bundled tool config into agent-core', async () => {
const ctx = await mount({
model: 'mock',
toolBash: { enableRunInBackground: false },
toolTasks: { waitTimeoutMs: 7, maxWaitTimeoutMs: 11 },
skills: await isolatedSkillsConfig(),
}, true)
const bash = ctx.tools.schemas().find(tool => tool.name === 'bash')
expect(Object.keys((bash!.parameters as { properties: Record<string, unknown> }).properties))
.not.toContain('run_in_background')
await ctx.fiber.dispose()
})
it('exposes its plugin shape', () => {
expect(acpAgent.name).toBe('acp-demo')
expect(acpAgent.Config).toBeDefined()
@@ -134,7 +148,7 @@ describe('dsh-acp-demo composition', () => {
})
}
const assembly = await ctx.get('systemPrompt')!.assemble()
expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'skill'])
expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'skill', 'task_kill', 'task_list', 'task_output'])
await ctx.fiber.dispose()
})

View File

@@ -17,9 +17,11 @@ Read this package for the whole plugin tree and its composition order.
@deepseek-ai/dsh-skill skill provider registry
@deepseek-ai/dsh-skill-local local filesystem skill provider
@deepseek-ai/dsh-agent agent registry + agent/* event vocabulary
@deepseek-ai/dsh-invariants runtime event-contract assertions
@deepseek-ai/dsh-tool-bash the model-facing bash/bash_output/bash_kill schemas
@deepseek-ai/dsh-tasks generic background-task registry
@deepseek-ai/dsh-invariants dev-mode event-contract assertions
@deepseek-ai/dsh-tool-bash the model-facing bash schema
@deepseek-ai/dsh-tool-skill session-prefix skill catalog + model-facing loader schema
@deepseek-ai/dsh-tool-tasks task_output/task_list/task_kill schemas + completion notices
@deepseek-ai/dsh-agent-loop THE concrete loop (gets the forwarded `agents`)
(dsh-system-prompt gets the forwarded `persona`)
```
@@ -39,11 +41,12 @@ This is the [interface/implementation/consumer seam](../../../docs/rfc/implement
```ts
import type { Config } from '@deepseek-ai/dsh-agent-spine-demo'
// { agents?, persona?, toolOrder?, tools?, skills? } — the schema intersects the owner schemas,
// { agents?, persona?, toolOrder?, tools?, skills?, toolBash?, toolTasks? }
// The schema intersects the owner schemas,
// so validation and defaulting can never drift from the owners.
```
The bundle FORWARDS each field to the child that owns it: `agents` to `agent-loop` (default `[]`), so each app supplies its own pre-created agents — a stdio app pre-creates a `main`; the ACP app pre-creates none (it creates agents on demand at `session/new`) — `persona` and `toolOrder` to `dsh-system-prompt`; `tools` to the tool registry for its presentation mode; and `skills.registry`, `skills.local`, and `skills.tool` to the skill registry, local provider, and model-facing consumer. Forwarding is exactly why the owners can live in the shared spine even though the apps disagree on what to configure.
The bundle FORWARDS each field to the child that owns it: `agents` to `agent-loop` (default `[]`), so each app supplies its own pre-created agents — a stdio app pre-creates a `main`; the ACP app pre-creates none (it creates agents on demand at `session/new`) — `persona` and `toolOrder` to `dsh-system-prompt`; `tools` to the tool registry for its presentation mode; `skills.registry`, `skills.local`, and `skills.tool` to the skill registry, local provider, and model-facing consumer; and `toolBash`/`toolTasks` to the two model-facing tool plugins the bundle owns. `toolBash.enableRunInBackground` controls only the bash producer, while `toolTasks` controls generic `task_output` wait bounds; independently loaded producers keep their own config. Forwarding is exactly why the owners can live in the shared spine even though the apps disagree on what to configure.
## Why a code bundle, not a shared YAML include

View File

@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-agent-spine-demo",
"description": "The default executor-less/UI-less agent spine as one Cordis bundle plugin (timer + llm + sessions + system-prompt + tools + skills + agents + invariants + tool-bash + tool-skill + agent-loop)",
"description": "The default executor-less/UI-less agent spine as one Cordis bundle plugin (timer + llm + sessions + system-prompt + tools + skills + agents + tasks + invariants + tool-bash + tool-skill + tool-tasks + agent-loop)",
"version": "0.0.1",
"private": true,
"type": "module",
@@ -31,8 +31,10 @@
"@deepseek-ai/dsh-skill": "^0.0.1",
"@deepseek-ai/dsh-skill-local": "^0.0.1",
"@deepseek-ai/dsh-system-prompt": "^0.0.1",
"@deepseek-ai/dsh-tasks": "^0.0.1",
"@deepseek-ai/dsh-tool-bash": "^0.0.1",
"@deepseek-ai/dsh-tool-skill": "^0.0.1",
"@deepseek-ai/dsh-tool-tasks": "^0.0.1",
"@deepseek-ai/dsh-tools": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
@@ -46,8 +48,10 @@
"@deepseek-ai/dsh-skill": "workspace:^",
"@deepseek-ai/dsh-skill-local": "workspace:^",
"@deepseek-ai/dsh-system-prompt": "workspace:^",
"@deepseek-ai/dsh-tasks": "workspace:^",
"@deepseek-ai/dsh-tool-bash": "workspace:^",
"@deepseek-ai/dsh-tool-skill": "workspace:^",
"@deepseek-ai/dsh-tool-tasks": "workspace:^",
"@deepseek-ai/dsh-tools": "workspace:^",
"cordis": "^4.0.0-rc.7"
},

View File

@@ -1,7 +1,8 @@
/**
* Default executor-less, UI-less agent spine. It bundles the common services,
* concrete loop, local skill provider, and model-facing bash/skill consumers;
* deployments still choose the LLM adapter, bash executor, and presentation.
* background-task registry and controls, concrete loop, local skill provider,
* and model-facing bash/skill consumers; deployments still choose the LLM
* adapter, bash executor, and presentation.
* The plugin intentionally exposes named exports only because Loader default
* unwrapping would discard its `Config` schema (see docs/postmortem/0001).
* @module @deepseek-ai/dsh-agent-spine-demo
@@ -17,9 +18,11 @@ import ToolRegistry, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools
import SkillService, { type Config as SkillRegistryConfig } from '@deepseek-ai/dsh-skill'
import * as SkillLocal from '@deepseek-ai/dsh-skill-local'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import TaskService from '@deepseek-ai/dsh-tasks'
import * as invariants from '@deepseek-ai/dsh-invariants'
import * as toolBash from '@deepseek-ai/dsh-tool-bash'
import * as toolSkill from '@deepseek-ai/dsh-tool-skill'
import * as toolTasks from '@deepseek-ai/dsh-tool-tasks'
import AgentLoop, { type Config as AgentLoopConfig } from '@deepseek-ai/dsh-agent-loop'
export const name = 'agent-spine-demo'
@@ -35,13 +38,19 @@ export interface SkillConfig {
}
/**
* Bundle config: each field forwarded verbatim to the child that owns it — `agents` to the
* agent loop (an app that pre-creates no agents, like the ACP bridge, omits it),
* `persona` and `toolOrder` to the system-prompt plugin (the deployment's persona section and
* the explicit model-facing tool order), the `tools` object to the tool registry (its
* presentation `mode`), and `skills` to the skill registry/local provider/tool consumer.
* The schema intersects the owners' schemas, which supply defaults for every
* optional input and keep validation from drifting.
* Bundle config: each field forwarded verbatim to the child that owns it —
* `agents` to the agent loop (an app that pre-creates no agents, like the ACP
* bridge, simply omits it), `persona` and `toolOrder` to the system-prompt
* plugin (the deployment's persona section and the explicit model-facing tool
* order), the `tools` object to the tool registry (its presentation `mode`),
* and `toolBash`/`toolTasks` to the two model-facing tool plugins this bundle
* owns. Producer opt-in stays producer-local: `toolBash` configures bash only;
* future background-capable tools remain independently composed plugins.
* Every field is optional INPUT here because each owner's schema
* supplies the default (`[]` / `''` / absent — lexicographic / `native`); the
* schema is the INTERSECTION of the owners' own schemas (the registry's
* nested under its `tools` key), so validation and defaulting can never
* drift from them.
*/
export interface Config {
/** The agent-loop `agents` list (see dsh-agent-loop's `Config`). */
@@ -54,6 +63,10 @@ export interface Config {
tools?: ToolsConfig
/** Skill registry, local provider, and model-facing consumer config. */
skills?: SkillConfig
/** Model-facing bash tool config, including this producer's background opt-in. */
toolBash?: toolBash.Config
/** Generic background-task control-tool wait bounds. */
toolTasks?: toolTasks.Config
}
/** The skill config schema exported for app packages that forward `skills`. */
@@ -63,11 +76,22 @@ export const SkillConfigSchema: z<SkillConfig> = z.object({
tool: toolSkill.Config,
})
/** The bash-tool config schema exported for app packages that forward `toolBash`. */
export const ToolBashConfigSchema: z<toolBash.Config> = toolBash.Config
/** The task-control-tool config schema exported for app packages that forward `toolTasks`. */
export const ToolTasksConfigSchema: z<toolTasks.Config> = toolTasks.Config
/** Intersect the owners' schemas so validation + defaulting stay identical. */
export const Config = z.intersect([
AgentLoop.Config,
SystemPrompt.Config,
z.object({ tools: ToolRegistry.Config, skills: SkillConfigSchema }),
z.object({
tools: ToolRegistry.Config,
skills: SkillConfigSchema,
toolBash: ToolBashConfigSchema,
toolTasks: ToolTasksConfigSchema,
}),
]) as unknown as z<Config>
/**
@@ -92,8 +116,10 @@ export function apply(ctx: Context, config: Config): void {
ctx.plugin(SkillService, config.skills?.registry ?? {})
ctx.plugin(SkillLocal, config.skills?.local ?? {})
ctx.plugin(AgentRegistry)
ctx.plugin(TaskService)
ctx.plugin(invariants)
ctx.plugin(toolBash)
ctx.plugin(toolBash, config.toolBash ?? {})
ctx.plugin(toolSkill, config.skills?.tool ?? {})
ctx.plugin(toolTasks, config.toolTasks ?? {})
ctx.plugin(AgentLoop, { agents: config.agents ?? [] })
}

View File

@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
@@ -7,7 +7,13 @@ import Loader from '@cordisjs/plugin-loader'
import { TOOL_ORDER_REST } from '@deepseek-ai/dsh-system-prompt'
import * as agentCore from '../src/index.ts'
import { AgentId, agentEvents, type Agent } from '@deepseek-ai/dsh-agent'
import type { Message } from '@deepseek-ai/dsh-llm'
import { CallId, type Message } from '@deepseek-ai/dsh-llm'
declare module '@deepseek-ai/dsh-tasks' {
interface TaskKindMap {
probe: 'probe'
}
}
async function composePrefix(ctx: Context, cwd: string): Promise<Message[]> {
const agent = { session: { header: { cwd } } } as unknown as Agent
@@ -28,12 +34,13 @@ async function composePrefix(ctx: Context, cwd: string): Promise<Message[]> {
* Loader-path guard (export shape, `unwrapExports`) is the app packages' keyless
* bin smokes; here we assert the composition + config forwarding.
*/
async function mount(config?: agentCore.Config): Promise<Context> {
async function mount(config?: agentCore.Config, withBash = false): Promise<Context> {
const oldDshHome = process.env.DSH_HOME
const oldAgentsHome = process.env.DSH_AGENTS_HOME
process.env.DSH_HOME = await mkdtemp(join(tmpdir(), 'dsh-agent-spine-demo-home-'))
process.env.DSH_AGENTS_HOME = await mkdtemp(join(tmpdir(), 'dsh-agent-spine-demo-agents-'))
const ctx = new Context()
if (withBash) ctx.provide('bash', { sandboxMode: undefined })
try {
await ctx.plugin(agentCore, config)
// The bundle mounts its children inside apply() (not awaited there); let their
@@ -86,6 +93,7 @@ describe('dsh-agent-spine-demo bundle', () => {
expect(ctx.get('tools')).toBeDefined()
expect(ctx.get('skills')).toBeDefined()
expect(ctx.get('agents')).toBeDefined()
expect(ctx.get('tasks')).toBeDefined()
expect(ctx.get('agentLoop')).toBeDefined()
await ctx.fiber.dispose()
})
@@ -153,6 +161,33 @@ describe('dsh-agent-spine-demo bundle', () => {
await ctx.fiber.dispose()
})
it('forwards its bundled tool configs to tool-bash and tool-tasks', async () => {
const ctx = await mount({
toolBash: { enableRunInBackground: false },
toolTasks: { waitTimeoutMs: 7, maxWaitTimeoutMs: 11 },
}, true)
const bash = ctx.tools.schemas().find(tool => tool.name === 'bash')
expect(bash).toBeDefined()
expect(Object.keys((bash!.parameters as { properties: Record<string, unknown> }).properties))
.not.toContain('run_in_background')
const id = ctx.tasks.start({
kind: 'probe',
label: 'config forwarding probe',
run: () => ({ cancel: () => {}, done: Promise.resolve({ status: 'completed' }) }),
})
const wait = vi.spyOn(ctx.tasks, 'wait')
await ctx.tools.execute({
callId: CallId('task-config-forwarding'),
name: 'task_output',
arguments: { task_id: id, wait: true },
})
expect(wait).toHaveBeenCalledWith(id, 7, undefined, undefined)
await ctx.fiber.dispose()
})
it('uses the default skill config when apply is called directly without skills', async () => {
await withIsolatedSkillHomes(async () => {
const ctx = new Context()
@@ -177,7 +212,7 @@ describe('dsh-agent-spine-demo bundle', () => {
})
}
const assembly = await ctx.get('systemPrompt')!.assemble()
expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'skill'])
expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'skill', 'task_kill', 'task_list', 'task_output'])
await ctx.fiber.dispose()
})

View File

@@ -11,9 +11,6 @@
{
"path": "../../../vendor/cordis"
},
{
"path": "../../../vendor/schemastery"
},
{
"path": "../../../vendor/timer"
},
@@ -52,6 +49,12 @@
},
{
"path": "../../bash/tool-bash"
},
{
"path": "../../tasks/tasks"
},
{
"path": "../../tasks/tool-tasks"
}
]
}

View File

@@ -30,6 +30,8 @@ The leaf `cordis.yml` supplies only the **swappable backends** — an LLM adapte
| `toolOrder` | — | explicit model-facing tool order (a name list with one `'<unlisted-tools>'` rest entry; absent — lexicographic; an unregistered name fails each turn at prompt assembly), routed to `dsh-system-prompt` |
| `tools` | `{ mode: 'native' }` | tool-registry presentation config (`native` / `code` / `both`), routed through `dsh-agent-spine-demo` |
| `skills` | owner defaults | registry-cache, local-provider, and model-facing skill-tool config, routed through `dsh-agent-spine-demo` |
| `toolBash` | owner defaults | model-facing bash config routed through `dsh-agent-spine-demo`, including bash's producer-local `enableRunInBackground` |
| `toolTasks` | owner defaults | generic `task_output` wait bounds routed through `dsh-agent-spine-demo` |
| `persistenceRoot` | `./.sessions` | the JSONL backend's root directory |
| `welcome` | `ready.` | the stdin-chat banner |
| `resumeSessionId` | — | resume a persisted session id instead of starting fresh (sourced from an env var in the leaf) |

View File

@@ -48,6 +48,10 @@ export interface Config {
welcome?: string
/** Skill registry, local-provider, and model-facing consumer config forwarded to agent-spine-demo. */
skills?: agentCore.SkillConfig
/** Model-facing bash tool config forwarded through agent-core. */
toolBash?: NonNullable<agentCore.Config['toolBash']>
/** Generic background-task control-tool config forwarded through agent-core. */
toolTasks?: NonNullable<agentCore.Config['toolTasks']>
/**
* If set, the `main` agent RESUMES this persisted session id instead of
* starting fresh. Sourced from an env var in the leaf `cordis.yml`
@@ -69,6 +73,8 @@ export const Config: z<Config> = z.object({
persistenceRoot: z.string().default('./.sessions'),
welcome: z.string().default('ready.'),
skills: agentCore.SkillConfigSchema,
toolBash: agentCore.ToolBashConfigSchema,
toolTasks: agentCore.ToolTasksConfigSchema,
resumeSessionId: z.string(),
})
@@ -92,6 +98,8 @@ export function apply(ctx: Context, config: Config): void {
...config.resumeSessionId !== undefined ? { resumeSessionId: SessionId(config.resumeSessionId) } : {},
}],
...config.skills !== undefined ? { skills: config.skills } : {},
...config.toolBash !== undefined ? { toolBash: config.toolBash } : {},
...config.toolTasks !== undefined ? { toolTasks: config.toolTasks } : {},
})
ctx.plugin(SessionPersistenceJsonl, { root: config.persistenceRoot ?? './.sessions' })
ctx.plugin(UserInteractionService)

View File

@@ -15,8 +15,9 @@ import * as stdioAgent from '../src/index.ts'
* keyless echo smoke; this tier pins the export shape because an inject-less app could otherwise
* survive namespace collapse while silently losing its schema.
*/
async function mount(config: stdioAgent.Config): Promise<Context> {
async function mount(config: stdioAgent.Config, withBash = false): Promise<Context> {
const ctx = new Context()
if (withBash) ctx.provide('bash', { sandboxMode: undefined })
await ctx.plugin(stdioAgent, config)
// The app mounts its children inside apply() (not awaited there); let their
// fibers settle so the spine services + the pre-created agent are ready.
@@ -126,6 +127,19 @@ describe('dsh-stdio-demo app', () => {
await ctx.fiber.dispose()
})
it('forwards bundled tool config into agent-core', async () => {
const ctx = await mount({
model: 'mock',
toolBash: { enableRunInBackground: false },
toolTasks: { waitTimeoutMs: 7, maxWaitTimeoutMs: 11 },
skills: await isolatedSkillsConfig(),
}, true)
const bash = ctx.tools.schemas().find(tool => tool.name === 'bash')
expect(Object.keys((bash!.parameters as { properties: Record<string, unknown> }).properties))
.not.toContain('run_in_background')
await ctx.fiber.dispose()
})
it('exposes its name and Config schema', () => {
expect(stdioAgent.name).toBe('stdio-demo')
expect(stdioAgent.Config).toBeDefined()
@@ -148,7 +162,7 @@ describe('dsh-stdio-demo app', () => {
})
}
const assembly = await ctx.get('systemPrompt')!.assemble()
expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'ask_user_question', 'skill'])
expect(assembly.tools.map(tool => tool.name)).toEqual(['zulu', 'alpha', 'ask_user_question', 'skill', 'task_kill', 'task_list', 'task_output'])
await ctx.fiber.dispose()
})

View File

@@ -25,7 +25,6 @@ function recordingBash(run: (spec: BashExecSpec) => Promise<BashRunResult>): {
...request.signal ? { signal: request.signal } : {},
...request.stdin !== undefined ? { stdin: request.stdin } : {},
...request.env !== undefined ? { env: request.env } : {},
owner: request.owner,
sandboxMode: request.sandboxMode,
}
},

View File

@@ -2,6 +2,8 @@
Local implementation of the [`dsh-sandbox`](../sandbox/) seam. It selects and caches one platform runner: Linux prefers a working `bwrap` then Landlock; macOS uses Seatbelt. Multiple candidates are probed in order, while a sole candidate is selected directly.
The package root exports the default and named `LocalSandboxProvider` plugin, `Config`, and its public test-injection seam; platform profile builders stay internal.
Unsupported platforms and unusable runners fail closed with `SANDBOX_UNAVAILABLE`; execution never silently falls through unconfined. Each wrap carries runner-failure signatures so consumers can distinguish a broken sandbox from a command failure. The [sandbox RFC](../../../docs/rfc/implemented/feature/2026-07-06-sandbox.md) owns selection rationale and profile differences.
Policy is per call; the provider stores only the mechanism and cached runner verdict. Each wrap reports enforcement completeness plus backend-specific denial and runner-failure signatures. `runnerCommand` is an operator assertion of a bwrap-shaped runner and skips probes, but missing or unexecutable commands still fail closed at execution. Because its mechanism is unknown, it carries both Linux denial dialects. `probeTimeoutMs` bounds functional probes. The [sandbox RFC](../../../docs/rfc/implemented/feature/2026-07-06-sandbox.md) owns selection and failure semantics.

View File

@@ -7,14 +7,13 @@
*/
import { spawnSync } from 'node:child_process'
import { realpathSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { grantArgs as landlockGrantArgs, LAUNCHER_BIN, launcherPath as landlockLauncherPath, probe as defaultProbeLandlock } from 'node-addon-landlock-run'
import { LAUNCHER_BIN, launcherPath as landlockLauncherPath, probe as defaultProbeLandlock } from 'node-addon-landlock-run'
import { Context } from 'cordis'
import z from 'schemastery'
import { assertNever } from '@deepseek-ai/dsh-llm'
import { SandboxProvider, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
import type { ConfinedArgv, ConfinedSandboxMode, SandboxEnforcement, SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import { bwrapProfileArgs, landlockProfileArgs, seatbeltProfileArgs } from './profiles.ts'
/** Plugin config. All optional — `static Config` supplies the defaults. */
export interface Config {
@@ -38,77 +37,6 @@ export interface Config {
probeTimeoutMs?: number
}
/**
* Build a bwrap profile: the host is read-only with fresh `/dev` and `/proc`;
* workspace-write overlays writable temp and workspace mounts. PID and network
* isolation are intentionally outside the file-effect policy.
*
* @param policy - the file-effect policy to express as bwrap arguments.
* @returns the bwrap profile arguments (before the trailing `--` + argv).
*/
export function bwrapProfileArgs(policy: SandboxPolicy): string[] {
const args = ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--die-with-parent']
if (policy.mode === 'workspace-write') {
args.push('--tmpfs', '/tmp')
args.push('--bind', policy.workspaceRoot, policy.workspaceRoot)
}
return args
}
/**
* Build Landlock grants for the same file policy without synthetic mounts.
* Read-only grants only `/dev/null` for writes; workspace-write also grants the
* host temp root and workspace.
*
* @param policy - the file-effect policy to express as launcher grants.
* @returns the launcher grant arguments (before `--` + argv).
*/
export function landlockProfileArgs(policy: SandboxPolicy): string[] {
const readWrite = ['/dev/null']
if (policy.mode === 'workspace-write') {
readWrite.push('/tmp', policy.workspaceRoot)
}
return landlockGrantArgs({ readOnly: ['/'], readWrite })
}
/**
* Resolve a granted root to the path the kernel actually sees. Seatbelt path
* filters match the CANONICAL path (symlinks resolved), and the roots this
* profile grants are symlinked on every macOS: `/tmp` is `/private/tmp` and
* the user temp dir lives under `/var` → `/private/var` — an as-spelled
* grant would match nothing.
*/
function canonicalPath(path: string): string {
try {
return realpathSync(path)
} catch {
// An unresolved grant matches nothing until the named path exists; keep its spelling.
return path
}
}
/** Quote one path as an SBPL string literal (backslashes and double quotes escaped). */
function sbplString(path: string): string {
return `"${path.replaceAll('\\', String.raw`\\`).replaceAll('"', String.raw`\"`)}"`
}
/**
* Build a Seatbelt profile that denies file writes then allows `/dev/null` and,
* for workspace-write, the canonical workspace, host temp, and per-user macOS
* temp roots. Network and process visibility remain unrestricted.
*
* @param policy - the file-effect policy to express as an SBPL profile.
* @returns the `sandbox-exec` arguments (`-p` + profile, before `--` + argv).
*/
export function seatbeltProfileArgs(policy: SandboxPolicy): string[] {
const forms = ['(version 1)', '(allow default)', '(deny file-write*)', `(allow file-write* (literal ${sbplString('/dev/null')}))`]
if (policy.mode === 'workspace-write') {
const roots = [...new Set([policy.workspaceRoot, '/tmp', tmpdir()].map(canonicalPath))]
forms.push(`(allow file-write* ${roots.map(root => `(subpath ${sbplString(root)})`).join(' ')})`)
}
return ['-p', forms.join(' ')]
}
/** Probe whether `bwrap` can create the profile; the provider caches the bounded result. */
function defaultProbeBwrap(timeoutMs: number): boolean {
const probe = spawnSync('bwrap', ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--die-with-parent', '--', 'true'], {

View File

@@ -0,0 +1,67 @@
/**
* Internal platform-profile builders for the local sandbox provider.
*
* @module @deepseek-ai/dsh-sandbox-local/profiles
*/
import { realpathSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { grantArgs as landlockGrantArgs } from 'node-addon-landlock-run'
import type { SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
/**
* Build the bwrap profile arguments for one file-effect policy.
* @param policy - file-effect policy to express as bwrap mounts.
* @returns profile arguments before the trailing separator and command argv.
*/
export function bwrapProfileArgs(policy: SandboxPolicy): string[] {
const args = ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--die-with-parent']
if (policy.mode === 'workspace-write') {
args.push('--tmpfs', '/tmp')
args.push('--bind', policy.workspaceRoot, policy.workspaceRoot)
}
return args
}
/**
* Build the Landlock launcher grants for one file-effect policy.
* @param policy - file-effect policy to express as Landlock allow-list grants.
* @returns launcher grant arguments before the trailing separator and command argv.
*/
export function landlockProfileArgs(policy: SandboxPolicy): string[] {
const readWrite = ['/dev/null']
if (policy.mode === 'workspace-write') {
readWrite.push('/tmp', policy.workspaceRoot)
}
return landlockGrantArgs({ readOnly: ['/'], readWrite })
}
/** Resolve a granted root to the canonical path the Seatbelt kernel sees. */
function canonicalPath(path: string): string {
try {
return realpathSync(path)
} catch {
// Missing or unreadable roots stay as spelled; an unresolved root grants
// nothing until it exists, which is the conservative outcome.
return path
}
}
/** Quote one path as an SBPL string literal. */
function sbplString(path: string): string {
return `"${path.replaceAll('\\', String.raw`\\`).replaceAll('"', String.raw`\"`)}"`
}
/**
* Build the sandbox-exec arguments and SBPL profile for one policy.
* @param policy - file-effect policy to express as an SBPL profile.
* @returns sandbox-exec arguments before the trailing separator and command argv.
*/
export function seatbeltProfileArgs(policy: SandboxPolicy): string[] {
const forms = ['(version 1)', '(allow default)', '(deny file-write*)', `(allow file-write* (literal ${sbplString('/dev/null')}))`]
if (policy.mode === 'workspace-write') {
const roots = [...new Set([policy.workspaceRoot, '/tmp', tmpdir()].map(canonicalPath))]
forms.push(`(allow file-write* ${roots.map(root => `(subpath ${sbplString(root)})`).join(' ')})`)
}
return ['-p', forms.join(' ')]
}

View File

@@ -6,7 +6,8 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import { bwrapProfileArgs, LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import { LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import { bwrapProfileArgs } from '../src/profiles.ts'
/**
* Keyless backend integration through `confine()` and a real bwrap process. With no rung forced,

View File

@@ -15,12 +15,10 @@ import { Context } from 'cordis'
import { SANDBOX_UNAVAILABLE, SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
import type { SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import {
bwrapProfileArgs,
landlockProfileArgs,
LocalSandboxProvider,
seatbeltProfileArgs,
} from '@deepseek-ai/dsh-sandbox-local'
import type { Config } from '@deepseek-ai/dsh-sandbox-local'
import { bwrapProfileArgs, landlockProfileArgs, seatbeltProfileArgs } from '../src/profiles.ts'
const RO: SandboxPolicy = { mode: 'read-only', workspaceRoot: '/ws' }
const WW: SandboxPolicy = { mode: 'workspace-write', workspaceRoot: '/ws' }

View File

@@ -6,7 +6,8 @@ import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import type { SandboxPolicy } from '@deepseek-ai/dsh-sandbox'
import { LocalSandboxProvider, seatbeltProfileArgs } from '@deepseek-ai/dsh-sandbox-local'
import { LocalSandboxProvider } from '@deepseek-ai/dsh-sandbox-local'
import { seatbeltProfileArgs } from '../src/profiles.ts'
/**
* Keyless backend integration through `confine()` and a real macOS Seatbelt process, with Linux

15
packages/sdk/README.md Normal file
View File

@@ -0,0 +1,15 @@
# SDK packages
Developer tooling for creating, editing, building, and running DeepSeek Harness projects.
The [feature RFC](../../docs/rfc/proposed/feature/2026-07-14-sdk-developer-projects.md) owns the developer workflow; the [architecture RFC](../../docs/rfc/proposed/architecture/2026-07-15-sdk-project-editing-architecture.md) owns the package and project-editing boundaries.
| Package | Role |
|---|---|
| [`helper`](helper/README.md) | Project aggregate, edit session, builtin features, project documents, templates, package managers, and prompt abstraction |
| [`scripts`](scripts/README.md) | The `dsh-sdk` launcher: `start`, `dev`, `build`, and interactive `config` |
| [`create-sdk`](create-sdk/README.md) | The `npm create @deepseek-ai/sdk` initializer |
`@deepseek-ai/create-sdk` is the one package-name exception to the repository's `@deepseek-ai/dsh-*` rule: npm's scoped initializer convention requires that name for `npm create @deepseek-ai/sdk`.
Generated projects keep `cordis.yml` as the only runtime plugin tree. `dsh-sdk dev` adds TypeScript and local-workspace resolution around that same file; it does not create a development-only config.

View File

@@ -0,0 +1,19 @@
# `@deepseek-ai/create-sdk`
Interactive initializer for `npm create @deepseek-ai/sdk [directory]`. Directory/name/description have visible editable defaults. A tree picker selects features and configures finite options with Right/Left navigation; secret text follows only for selected options. Local plugin creation is one none/plugin/tool choice.
The supported package surface is the `create-sdk` bin. The package root exports no symbols, and workflow, bin, source, and package-manifest subpaths are not exported.
The initializer rejects every existing target path, creates one `SdkProject` edit session, validates and commits it, then asks whether to install NPM dependencies and build. Install or build failures keep the generated project and print a retry command.
Public flags are `[directory]`, `--description`, `--provider`, `--base-url`, `--api-key`, `--model`, `--interface`, `--pm`, and `--install`/`--no-install`. Flags prefill matching questions, but creation always requires a TTY.
The provider choice is DeepSeek or a custom endpoint backed by `llm-pi-ai`. DeepSeek asks only for an API key and uses the public endpoint plus `deepseek-v4-flash`; custom also asks for a base URL. An empty key requires confirmation and creates a commented empty `.env` variable so provider startup fails clearly until it is filled. Existing plugin defaults are omitted; required SDK presets remain typed against the owning package's Config.
## Model Experience
Indirectly, through the generated project composition and its selected runtime plugins.
## Known Limitations and Deferred Work
- **TTY-only creation** — flags prefill questions, but the wizard still requires an interactive terminal before it writes a project.

View File

@@ -0,0 +1,37 @@
{
"name": "@deepseek-ai/create-sdk",
"description": "Create a DeepSeek Harness SDK project with npm create @deepseek-ai/sdk",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"bin": {
"create-sdk": "lib/bin.js"
},
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
}
},
"files": [
"lib/index.js",
"lib/bin.js",
"lib/assets",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"src"
],
"license": "BSD-3-Clause",
"dependencies": {
"@deepseek-ai/dsh-helper": "workspace:^",
"commander": "^15.0.0"
},
"peerDependencies": {
"cordis": "^4.0.0-rc.7"
},
"devDependencies": {
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -0,0 +1,84 @@
/**
* Commander adapter for the create-sdk command surface.
*
* @module @deepseek-ai/create-sdk/args
*/
import { Command, Option } from 'commander'
import type { PackageManagerName, RunInterface } from '@deepseek-ai/dsh-helper'
/** Parsed create command flags before interactive resolution. */
export interface CreateArgs {
directory?: string
description?: string
provider?: 'deepseek' | 'custom'
baseURL?: string
apiKey?: string
model?: string
runInterface?: RunInterface
packageManager?: PackageManagerName
install?: boolean
linkWorkspace?: boolean
help: boolean
}
interface CommanderCreateOptions {
description?: string
provider?: 'deepseek' | 'custom'
baseUrl?: string
apiKey?: string
model?: string
interface?: RunInterface
pm?: PackageManagerName
install?: boolean
linkWorkspace?: boolean
help?: boolean
}
function createProgram(): Command {
return new Command()
.name('create-sdk')
.description('Create a DeepSeek Harness SDK project')
.helpOption(false)
.showHelpAfterError(false)
.exitOverride()
.configureOutput({
/* v8 ignore next -- the command wrapper renders the package-owned usage template */
writeOut: () => {},
/* v8 ignore next -- Commander output is deliberately suppressed; errors are returned to the bin wrapper */
writeErr: () => {},
})
.argument('[directory]')
.option('-h, --help')
.option('--description <text>')
.addOption(new Option('--provider <name>').choices(['deepseek', 'custom']))
.option('--base-url <url>')
.option('--api-key <key>')
.option('--model <name>')
.addOption(new Option('--interface <name>').choices(['acp', 'stdio', 'embed']))
.addOption(new Option('--pm <name>').choices(['npm', 'pnpm', 'yarn']))
.addOption(new Option('--install').default(undefined))
.addOption(new Option('--no-install').default(undefined))
.option('--link-workspace')
}
/** Parse create-sdk positionals/options through Commander into a domain-neutral value. */
export function parseCreateArgs(argv: readonly string[]): CreateArgs {
const program = createProgram()
program.parse([...argv], { from: 'user' })
const options = program.opts<CommanderCreateOptions>()
const directory = program.processedArgs[0] as string | undefined
return {
...directory === undefined ? {} : { directory },
...options.description === undefined ? {} : { description: options.description },
...options.provider === undefined ? {} : { provider: options.provider },
...options.baseUrl === undefined ? {} : { baseURL: options.baseUrl },
...options.apiKey === undefined ? {} : { apiKey: options.apiKey },
...options.model === undefined ? {} : { model: options.model },
...options.interface === undefined ? {} : { runInterface: options.interface },
...options.pm === undefined ? {} : { packageManager: options.pm },
...options.install === undefined ? {} : { install: options.install },
...options.linkWorkspace ? { linkWorkspace: true } : {},
help: options.help ?? false,
}
}

View File

@@ -0,0 +1,10 @@
#!/usr/bin/env node
/**
* Self-executing create-sdk command.
*
* @module @deepseek-ai/create-sdk/bin
*/
import { runCreateCommand } from './command.ts'
process.exitCode = await runCreateCommand()

View File

@@ -0,0 +1,111 @@
/**
* Internal create-sdk command composition used by the package bin.
*
* @module @deepseek-ai/create-sdk/command
*/
import { readFile } from 'node:fs/promises'
import {
ClackPromptPort,
PromptCancelledError,
type PackageManagerVersionProbe,
type PromptPort,
} from '@deepseek-ai/dsh-helper'
import { parseCreateArgs } from './args.ts'
import { CreateWizard, type ResolvedCreateRequest } from './create-wizard.ts'
import { scaffoldProject, type ScaffoldResult } from './project-scaffolder.ts'
import { CREATE_TEMPLATES, packageManagerTemplateModel } from './templates/create-templates.ts'
/** Process and terminal slice used by the initializer. */
export interface CreateCommandContext {
cwd: string
stdin: NodeJS.ReadStream
stdout: NodeJS.WriteStream
stderr: NodeJS.WriteStream
releaseVersion?: string
versionProbe?: PackageManagerVersionProbe
port?: PromptPort
setup?: (request: ResolvedCreateRequest) => Promise<void>
}
/** Read this initializer package's release version in source and built layouts. */
export async function readCreateSdkVersion(): Promise<string> {
const manifest = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')) as { version?: unknown }
/* v8 ignore next -- this package's checked-in manifest always carries its version */
if (typeof manifest.version !== 'string') throw new Error('create-sdk package version is missing')
return manifest.version
}
/** Resolve, write, optionally install, and build one new project. */
export async function createProject(
argv: readonly string[],
context: CreateCommandContext,
): Promise<ScaffoldResult | undefined> {
const args = parseCreateArgs(argv)
if (args.help) {
context.stdout.write(CREATE_TEMPLATES.usage.render({}))
return undefined
}
if (!context.port && (!context.stdin.isTTY || !context.stdout.isTTY)) {
throw new Error('create-sdk requires an interactive TTY')
}
const wizard = new CreateWizard({
args,
/* v8 ignore next -- production TTY wiring is exercised by the built-bin smoke */
port: context.port ?? new ClackPromptPort(context.stdin, context.stdout),
cwd: context.cwd,
releaseVersion: context.releaseVersion ?? await readCreateSdkVersion(),
...context.versionProbe ? { versionProbe: context.versionProbe } : {},
})
const resolved = await wizard.run()
const result = await scaffoldProject(resolved.directory, resolved.request)
context.stdout.write(CREATE_TEMPLATES.created.render({
name: resolved.request.name,
directory: resolved.directory,
}))
if (resolved.install) {
try {
if (context.setup) await context.setup(resolved)
else {
await resolved.request.packageManager.install(resolved.directory)
await resolved.request.packageManager.build(resolved.directory)
}
} catch (error) {
context.stderr.write(CREATE_TEMPLATES.setupFailure.render({
directory: resolved.directory,
error: String(error),
...packageManagerTemplateModel(resolved.request.packageManager),
}))
throw error
}
}
context.stdout.write(CREATE_TEMPLATES.nextSteps.render({
directory: resolved.directory,
setupRequired: !resolved.install,
...packageManagerTemplateModel(resolved.request.packageManager),
}))
return result
}
/** Run the create command with process defaults and convert cancellation to a clean exit. */
export async function runCreateCommand(
argv: readonly string[] = process.argv.slice(2),
context: CreateCommandContext = {
cwd: process.cwd(),
stdin: process.stdin,
stdout: process.stdout,
stderr: process.stderr,
},
): Promise<number> {
try {
await createProject(argv, context)
return 0
} catch (error) {
if (error instanceof PromptCancelledError) {
context.stderr.write('create-sdk: cancelled\n')
return 1
}
context.stderr.write(`create-sdk: ${error instanceof Error ? error.message : String(error)}\n`)
return 1
}
}

View File

@@ -0,0 +1,205 @@
/**
* Static create-sdk question sequence; dynamic feature/plugin loops remain
* in the wizard orchestrator.
*
* @module @deepseek-ai/create-sdk/create-questions
*/
import { existsSync } from 'node:fs'
import { basename, resolve } from 'node:path'
import {
ConfirmQuestion,
SecretQuestion,
SelectQuestion,
TextQuestion,
requireAnswer,
type PromptPort,
type Question,
type RunInterface,
} from '@deepseek-ai/dsh-helper'
import type { CreateArgs } from './args.ts'
/** Answers that establish project identity and feature applicability. */
export interface ProjectAnswers {
directory: string
name: string
description: string
provider: 'deepseek' | 'custom'
baseURL: string
apiKey: string
model: string
runInterface: RunInterface
}
interface ProjectAnswerState extends Partial<ProjectAnswers> {
readonly args: CreateArgs
readonly cwd: string
}
interface WizardStep<TState> {
run(port: PromptPort, state: TState): Promise<void>
}
function questionStep<TState, TValue>(options: {
question: (state: TState) => Question<TValue>
when?: (state: TState) => boolean
prefilled?: (state: TState) => TValue | undefined
apply: (state: TState, value: TValue) => void
}): WizardStep<TState> {
return {
async run(port, state) {
if (options.when && !options.when(state)) return
const value = requireAnswer(await options.question(state).resolve(port, options.prefilled?.(state)))
options.apply(state, value)
},
}
}
/** Validate one required text answer. */
function nonEmpty(value: string): string | undefined {
return value.trim().length === 0 ? 'A value is required' : undefined
}
function packageName(value: string): string | undefined {
if (!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(value)) {
return 'Use a lowercase npm package name'
}
return undefined
}
function projectDirectory(value: string, cwd: string): string | undefined {
const empty = nonEmpty(value)
if (empty) return empty
return existsSync(resolve(cwd, value)) ? 'Target already exists' : undefined
}
const API_KEY_STEP: WizardStep<ProjectAnswerState> = {
async run(port, state) {
let prefilled = state.args.apiKey
while (true) {
const apiKey = requireAnswer(await new SecretQuestion({
id: 'apiKey',
message: state.provider === 'custom' ? 'Custom provider API key' : 'DeepSeek API key',
}).resolve(port, prefilled))
if (apiKey.length > 0) {
state.apiKey = apiKey
return
}
const keepEmpty = requireAnswer(await new ConfirmQuestion({
id: 'apiKey.empty',
message: 'Keep the API key empty and fill .env later?',
initialValue: false,
tone: 'warning',
}).resolve(port))
if (keepEmpty) {
state.apiKey = ''
return
}
prefilled = undefined
}
},
}
const PROJECT_QUESTION_STEPS: readonly WizardStep<ProjectAnswerState>[] = [
questionStep({
question: state => new TextQuestion({
id: 'directory',
message: 'Where should the project be created?',
placeholder: 'my-agent',
defaultValue: 'my-agent',
validate: value => projectDirectory(value, state.cwd),
}),
prefilled: state => state.args.directory,
apply: (state, value) => { state.directory = resolve(state.cwd, value) },
}),
questionStep({
question: (state) => {
/* v8 ignore next -- the preceding directory step always populates this state */
if (!state.directory) throw new Error('directory must resolve before package name')
return new TextQuestion({
id: 'name',
message: 'Package name',
placeholder: basename(state.directory),
defaultValue: basename(state.directory),
validate: packageName,
})
},
apply: (state, value) => { state.name = value },
}),
questionStep({
question: (state) => {
/* v8 ignore next -- the preceding package-name step always populates this state */
if (!state.name) throw new Error('package name must resolve before description')
return new TextQuestion({
id: 'description',
message: 'Project description',
placeholder: `A DeepSeek Harness agent named ${state.name}`,
defaultValue: `A DeepSeek Harness agent named ${state.name}`,
validate: nonEmpty,
})
},
prefilled: state => state.args.description,
apply: (state, value) => { state.description = value },
}),
questionStep({
question: () => new SelectQuestion<'deepseek' | 'custom'>({
id: 'provider',
message: 'Model provider',
options: [
{ value: 'deepseek', label: 'DeepSeek' },
{ value: 'custom', label: 'Custom endpoint (pi-ai)' },
],
initialValue: 'deepseek',
}),
prefilled: state => state.args.provider,
apply: (state, value) => { state.provider = value },
}),
questionStep({
question: () => new TextQuestion({
id: 'baseURL', message: 'Custom provider base URL', validate: nonEmpty,
}),
when: state => state.provider === 'custom' || state.args.baseURL !== undefined,
prefilled: state => state.args.baseURL,
apply: (state, value) => { state.baseURL = value },
}),
API_KEY_STEP,
questionStep({
question: () => new SelectQuestion<RunInterface>({
id: 'interface',
message: 'Run interface',
options: [
{ value: 'acp', label: 'ACP server' },
{ value: 'stdio', label: 'Terminal REPL' },
{ value: 'embed', label: 'Embedded context' },
],
initialValue: 'stdio',
}),
prefilled: state => state.args.runInterface,
apply: (state, value) => { state.runInterface = value },
}),
]
function completeAnswers(state: ProjectAnswerState): ProjectAnswers {
const keys = ['directory', 'name', 'description', 'provider', 'baseURL', 'apiKey', 'model', 'runInterface'] as const
for (const key of keys) {
/* v8 ignore next -- the fixed step list above populates every key or throws/cancels first */
if (state[key] === undefined) throw new Error(`create question did not resolve ${key}`)
}
return state as ProjectAnswerState & ProjectAnswers
}
/** Run the fixed project-context sequence in declaration order. */
export async function collectProjectAnswers(
port: PromptPort,
args: CreateArgs,
cwd: string,
): Promise<ProjectAnswers> {
const state: ProjectAnswerState = {
args,
cwd,
baseURL: args.baseURL ?? '',
model: args.model ?? 'deepseek-v4-flash',
}
for (const step of PROJECT_QUESTION_STEPS) await step.run(port, state)
return completeAnswers(state)
}

View File

@@ -0,0 +1,222 @@
/**
* Declarative create questions with dynamic feature and plugin orchestration.
*
* @module @deepseek-ai/create-sdk/create-wizard
*/
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
FeatureConfigurator,
ConfirmQuestion,
LocalPluginBlueprint,
NpmPackageManager,
SelectQuestion,
featureId,
createBuiltinRegistry,
createPackageManager,
inferPackageManagerName,
probePackageManagerVersion,
requireAnswer,
type FeatureRegistry,
type FeatureSelection,
type LocalPluginKind,
type PackageManager,
type PackageManagerName,
type PackageManagerVersionProbe,
type ProjectCreationRequest,
type ProjectProfile,
type PromptPort,
} from '@deepseek-ai/dsh-helper'
import type { CreateArgs } from './args.ts'
import { collectProjectAnswers, type ProjectAnswers } from './create-questions.ts'
import { CREATE_TEMPLATES, packageManagerTemplateModel } from './templates/create-templates.ts'
/** Fully resolved initializer request and post-create choice. */
export interface ResolvedCreateRequest {
directory: string
request: ProjectCreationRequest
install: boolean
}
/** Create-specific orchestration around declarative questions and dynamic selections. */
export class CreateWizard {
private readonly args: CreateArgs
private readonly port: PromptPort
private readonly cwd: string
private readonly releaseVersion: string
private readonly versionProbe: PackageManagerVersionProbe
private readonly userAgent: string
private readonly linkWorkspaceRoot: string | undefined
/** Bind parsed args and infrastructure to one wizard run. */
constructor(options: {
args: CreateArgs
port: PromptPort
cwd?: string
releaseVersion: string
versionProbe?: PackageManagerVersionProbe
userAgent?: string
}) {
this.args = options.args
this.port = options.port
this.cwd = resolve(options.cwd ?? process.cwd())
this.releaseVersion = options.releaseVersion
this.versionProbe = options.versionProbe ?? probePackageManagerVersion
/* v8 ignore next -- pnpm supplies npm_config_user_agent while direct invocations may omit it */
this.userAgent = options.userAgent ?? process.env.npm_config_user_agent ?? ''
this.linkWorkspaceRoot = options.args.linkWorkspace
? fileURLToPath(new URL('../../../../', import.meta.url))
: undefined
}
/** Collect all answers before constructing any project files. */
async run(): Promise<ResolvedCreateRequest> {
const answers = await this.collectProjectAnswers()
const profile = this.provisionalProfile(answers)
const registry = createBuiltinRegistry(profile)
const features = await this.collectFeatures(profile, registry, answers)
const localPlugins = await this.collectPlugins()
const { manager, install } = await this.collectPackageManager()
return {
directory: answers.directory,
install,
request: {
name: answers.name,
description: answers.description,
runtime: { model: answers.model },
packageManager: manager,
releaseVersion: this.releaseVersion,
...this.linkWorkspaceRoot ? { linkWorkspaceRoot: this.linkWorkspaceRoot } : {},
features,
localPlugins,
},
}
}
private async collectProjectAnswers(): Promise<ProjectAnswers> {
return collectProjectAnswers(this.port, this.args, this.cwd)
}
private provisionalProfile(answers: ProjectAnswers): ProjectProfile {
return {
name: answers.name,
description: answers.description,
runtime: { model: answers.model },
runInterface: answers.runInterface,
packageManager: new NpmPackageManager('10.0.0'),
releaseVersion: this.releaseVersion,
...this.linkWorkspaceRoot ? { linkWorkspaceRoot: this.linkWorkspaceRoot } : {},
}
}
private async collectFeatures(
profile: ProjectProfile,
registry: FeatureRegistry,
answers: ProjectAnswers,
): Promise<FeatureSelection[]> {
const configurator = new FeatureConfigurator(this.port)
const selections: FeatureSelection[] = [
{
id: featureId('provider'),
options: [answers.provider],
...answers.baseURL ? { values: { baseURL: answers.baseURL } } : {},
secrets: { apiKey: answers.apiKey },
},
{ id: featureId('spine'), options: ['default'] },
{ id: featureId('app'), options: [answers.runInterface] },
]
const configurable = registry.all().filter(feature => feature.id === 'bash'
|| feature.id === 'persistence'
|| (!feature.required && feature.isApplicable(profile)))
const selected = [...requireAnswer(await this.port.nestedMultiselect({
message: 'Select features',
options: configurable.map((feature) => {
const nested = feature.mode !== 'single'
const defaults = new Set(feature.defaultOptions(profile))
return {
value: feature.id,
label: feature.summary,
required: feature.required,
default: feature.required || feature.id === 'hmr' || feature.id === 'fs' || feature.id === 'todo'
|| feature.id === 'skill',
...nested ? {
choiceMode: feature.mode === 'multiple' ? 'multiple' as const : 'exclusive' as const,
choices: feature.options.map(option => ({
value: option.id,
label: option.label,
default: defaults.has(option.id),
})),
} : {},
}
}),
}))]
for (const { value: id } of [...selected]) {
const feature = registry.get(id)
for (const suggestedId of feature.suggests) {
if (selected.some(item => item.value === suggestedId)) continue
const suggested = registry.get(suggestedId)
const add = requireAnswer(await new ConfirmQuestion({
id: `${feature.id}.${suggested.id}`,
message: `Add the recommended ${suggested.summary.toLowerCase()} for ${feature.summary.toLowerCase()}?`,
initialValue: true,
}).resolve(this.port))
if (add) selected.push({ value: suggested.id, choices: suggested.defaultOptions(profile) })
}
}
const fixed = new Set(selections.map(selection => selection.id))
const choices = new Map<FeatureSelection['id'], readonly string[] | undefined>()
for (const feature of registry.all()) {
if (feature.required && feature.isApplicable(profile) && !fixed.has(feature.id)) {
choices.set(feature.id, feature.defaultOptions(profile))
}
}
for (const choice of selected) {
choices.set(choice.value, choice.choices.length > 0 ? choice.choices : undefined)
}
for (const [id, options] of choices) {
selections.push(await configurator.configure(
registry.get(id),
profile,
undefined,
options,
))
}
return selections
}
private async collectPlugins(): Promise<LocalPluginBlueprint[]> {
const kind = requireAnswer(await new SelectQuestion<LocalPluginKind | 'none'>({
id: 'plugins.kind',
message: 'Local plugin',
options: [
{ value: 'none', label: 'No local plugin' },
{ value: 'plugin', label: 'Cordis plugin' },
{ value: 'tool', label: 'Model-facing tool' },
],
initialValue: 'none',
}).resolve(this.port))
return kind === 'none' ? [] : [new LocalPluginBlueprint(kind, kind)]
}
private async collectPackageManager(): Promise<{ manager: PackageManager; install: boolean }> {
const inferred = inferPackageManagerName(this.args.packageManager, this.userAgent)
const name = requireAnswer(await new SelectQuestion<PackageManagerName>({
id: 'packageManager',
message: 'Package manager',
options: [
{ value: 'npm', label: 'npm' },
{ value: 'pnpm', label: 'pnpm' },
{ value: 'yarn', label: 'Yarn' },
],
initialValue: inferred ?? 'npm',
}).resolve(this.port, inferred))
const manager = createPackageManager(name, await this.versionProbe(name, this.cwd))
const install = requireAnswer(await new ConfirmQuestion({
id: 'install',
message: CREATE_TEMPLATES.installQuestion.render(packageManagerTemplateModel(manager)).trimEnd(),
initialValue: true,
}).resolve(this.port, this.args.install))
return { manager, install }
}
}

View File

@@ -0,0 +1,7 @@
/**
* The create-sdk package is a CLI initializer; its library entry exports no symbols.
*
* @module @deepseek-ai/create-sdk
*/
export {}

View File

@@ -0,0 +1,41 @@
/**
* Project creation use case over the shared SDK aggregate and edit session.
*
* @module @deepseek-ai/create-sdk/project-scaffolder
*/
import { stat } from 'node:fs/promises'
import {
SdkProject,
createBuiltinRegistry,
type ChangeSet,
type ProjectCreationRequest,
} from '@deepseek-ai/dsh-helper'
/** Result of writing one new SDK project. */
export interface ScaffoldResult {
project: SdkProject
changes: ChangeSet
}
/** Create a project entirely in memory, then validate and commit it once. */
export async function scaffoldProject(root: string, request: ProjectCreationRequest): Promise<ScaffoldResult> {
let targetExists = true
try {
await stat(root)
} catch (error) {
/* v8 ignore else -- the other arm requires a filesystem permission/IO fault from stat */
if ((error as NodeJS.ErrnoException).code === 'ENOENT') targetExists = false
/* v8 ignore next -- paired with the ignored defensive stat-error arm above */
else throw error
}
if (targetExists) throw new Error(`target already exists: ${root}`)
const project = SdkProject.create(root, request)
const registry = createBuiltinRegistry(project.profile)
const edit = project.edit(registry)
for (const selection of request.features) {
edit.installFeature(registry.get(selection.id), selection)
}
for (const plugin of request.localPlugins) edit.addPlugin(plugin)
return edit.commit()
}

View File

@@ -0,0 +1 @@
Created {{name}} in {{directory}}

View File

@@ -0,0 +1 @@
Run {{packageManager}} {{installArgs}} and then build the project?

View File

@@ -0,0 +1,5 @@
{{#if setupRequired}}
Next: cd {{directory}} && {{packageManager}} {{installArgs}} && {{packageManager}} {{buildArgs}} && {{packageManager}} start
{{else}}
Next: cd {{directory}} && {{packageManager}} start
{{/if}}

View File

@@ -0,0 +1,2 @@
Project files are ready, but setup failed: {{error}}
Retry: cd {{directory}} && {{packageManager}} {{installArgs}} && {{packageManager}} {{buildArgs}}

View File

@@ -0,0 +1,11 @@
Usage: create-sdk [directory] [options]
Options:
--description <text>
--provider <deepseek|custom>
--base-url <url>
--api-key <key>
--model <name>
--interface <acp|stdio|embed>
--pm <npm|pnpm|yarn>
--install / --no-install

View File

@@ -0,0 +1,59 @@
/**
* Package-owned terminal templates for create-sdk.
*
* @module @deepseek-ai/create-sdk/templates/create-templates
*/
import {
TextTemplate,
type PackageManager,
type PackageManagerName,
} from '@deepseek-ai/dsh-helper'
interface CreatedTemplateModel {
name: string
directory: string
}
interface NextStepsTemplateModel extends PackageManagerTemplateModel {
directory: string
setupRequired: boolean
}
interface SetupFailureTemplateModel extends PackageManagerTemplateModel {
directory: string
error: string
}
/** Package-manager execution data consumed by create-sdk templates. */
export interface PackageManagerTemplateModel {
packageManager: PackageManagerName
installArgs: string
buildArgs: string
}
/**
* Map package-manager execution data into terminal-template fields.
* @param manager - selected package-manager strategy.
* @returns executable name and operation arguments.
*/
export function packageManagerTemplateModel(manager: PackageManager): PackageManagerTemplateModel {
return {
packageManager: manager.name,
installArgs: manager.installCommand().join(' '),
buildArgs: manager.buildCommand().join(' '),
}
}
/** Compiled create-sdk terminal templates. */
export const CREATE_TEMPLATES = {
usage: TextTemplate.fromFile<Record<string, never>>(new URL('./assets/usage.txt.tpl', import.meta.url)),
created: TextTemplate.fromFile<CreatedTemplateModel>(new URL('./assets/created.txt.tpl', import.meta.url)),
nextSteps: TextTemplate.fromFile<NextStepsTemplateModel>(new URL('./assets/next-steps.txt.tpl', import.meta.url)),
setupFailure: TextTemplate.fromFile<SetupFailureTemplateModel>(
new URL('./assets/setup-failure.txt.tpl', import.meta.url),
),
installQuestion: TextTemplate.fromFile<PackageManagerTemplateModel>(
new URL('./assets/install-question.txt.tpl', import.meta.url),
),
} as const

View File

@@ -0,0 +1,28 @@
import { execFile } from 'node:child_process'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import { describe, expect, it } from 'vitest'
const execFileAsync = promisify(execFile)
const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
const createBin = join(repoRoot, 'packages/sdk/create-sdk/lib/bin.js')
const scriptsBin = join(repoRoot, 'packages/sdk/scripts/lib/bin.js')
describe.skipIf(!existsSync(createBin) || !existsSync(scriptsBin))(
'SDK built artifacts',
() => {
it('runs the published dsh-sdk bin help path under plain Node', async () => {
const result = await execFileAsync(process.execPath, [scriptsBin, '--help'], { encoding: 'utf8' })
expect(result.stdout).toContain('Usage: dsh-sdk <command>')
expect(result.stderr).toBe('')
})
it('runs the published create-sdk bin help path under plain Node', async () => {
const result = await execFileAsync(process.execPath, [createBin, '--help'], { encoding: 'utf8' })
expect(result.stdout).toContain('Usage: create-sdk [directory]')
expect(result.stderr).toBe('')
})
},
)

View File

@@ -0,0 +1,398 @@
import { describe, expect, it } from 'vitest'
import {
featureId,
createPackageManager,
type NestedMultiSelectValue,
type PromptPort,
} from '@deepseek-ai/dsh-helper'
import type {
ConfirmPromptRequest,
MultiSelectPromptRequest,
NestedMultiSelectRequest,
PromptOutcome,
SecretPromptRequest,
SelectPromptRequest,
TextPromptRequest,
} from '../../helper/src/questions/prompt-port.ts'
import { parseCreateArgs } from '../src/args.ts'
import { CreateWizard } from '../src/create-wizard.ts'
import { CREATE_TEMPLATES, packageManagerTemplateModel } from '../src/templates/create-templates.ts'
class RecordingPort implements PromptPort {
readonly transcript: unknown[] = []
readonly #answers: unknown[]
constructor(answers: unknown[]) { this.#answers = [...answers] }
answer<T>(record: unknown): Promise<PromptOutcome<T>> {
this.transcript.push(record)
return Promise.resolve({ status: 'answered', value: this.#answers.shift() as T })
}
text(request: TextPromptRequest): Promise<PromptOutcome<string>> {
return this.answer({
kind: 'text',
message: request.message,
defaultValue: request.defaultValue,
initialValue: request.initialValue,
})
}
secret(request: SecretPromptRequest): Promise<PromptOutcome<string>> {
return this.answer({ kind: 'secret', message: request.message })
}
select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> {
return this.answer({
kind: 'select', message: request.message, options: request.options.map(option => option.label),
initialValue: request.initialValue,
})
}
multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> {
return this.answer({
kind: 'multiselect', message: request.message, options: request.options.map(option => option.label),
initialValues: request.initialValues,
})
}
confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> {
return this.answer({ kind: 'confirm', message: request.message, initialValue: request.initialValue })
}
nestedMultiselect<TValue, TChoice>(
request: NestedMultiSelectRequest<TValue, TChoice>,
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
return this.answer({
kind: 'nested-multiselect',
message: request.message,
options: request.options.map(option => ({
label: option.label,
required: option.required,
default: option.default,
choices: option.choices?.map(choice => choice.label),
})),
})
}
}
describe('create-sdk terminal contract', () => {
it('renders package-manager-specific setup commands', () => {
const model = packageManagerTemplateModel(createPackageManager('yarn', '4.0.0'))
expect(CREATE_TEMPLATES.installQuestion.render(model)).toBe('Run yarn install and then build the project?\n')
expect(CREATE_TEMPLATES.setupFailure.render({
directory: '/workspace/agent',
error: 'offline',
...model,
})).toContain('yarn install && yarn build')
})
it('pins the full unresolved question order and completion messages', async () => {
const port = new RecordingPort([
'my-agent',
'my-agent',
'Snapshot agent',
'deepseek',
'secret-key',
'acp',
[
{ value: featureId('persistence'), choices: ['jsonl'] },
{ value: featureId('hmr'), choices: [] },
{ value: featureId('web'), choices: ['exa'] },
{ value: featureId('workflow'), choices: [] },
],
true,
'exa-key',
'none',
'npm',
false,
])
const resolved = await new CreateWizard({
args: parseCreateArgs([]),
port,
cwd: '/workspace',
releaseVersion: '0.0.1',
userAgent: '',
versionProbe: async () => '10.0.0',
}).run()
expect({
prompts: port.transcript,
result: {
directory: resolved.directory,
name: resolved.request.name,
manager: resolved.request.packageManager.name,
install: resolved.install,
features: resolved.request.features.map(item => ({ id: item.id, options: item.options })),
},
messages: {
created: CREATE_TEMPLATES.created.render({
name: resolved.request.name,
directory: resolved.directory,
}),
next: CREATE_TEMPLATES.nextSteps.render({
directory: resolved.directory,
setupRequired: false,
...packageManagerTemplateModel(resolved.request.packageManager),
}),
failure: CREATE_TEMPLATES.setupFailure.render({
directory: resolved.directory,
error: String(new Error('offline')),
...packageManagerTemplateModel(resolved.request.packageManager),
}),
},
}).toMatchInlineSnapshot(`
{
"messages": {
"created": "Created my-agent in /workspace/my-agent
",
"failure": "Project files are ready, but setup failed: Error: offline
Retry: cd /workspace/my-agent && npm install && npm run build
",
"next": "Next: cd /workspace/my-agent && npm start
",
},
"prompts": [
{
"defaultValue": "my-agent",
"initialValue": undefined,
"kind": "text",
"message": "Where should the project be created?",
},
{
"defaultValue": "my-agent",
"initialValue": undefined,
"kind": "text",
"message": "Package name",
},
{
"defaultValue": "A DeepSeek Harness agent named my-agent",
"initialValue": undefined,
"kind": "text",
"message": "Project description",
},
{
"initialValue": "deepseek",
"kind": "select",
"message": "Model provider",
"options": [
"DeepSeek",
"Custom endpoint (pi-ai)",
],
},
{
"kind": "secret",
"message": "DeepSeek API key",
},
{
"initialValue": "stdio",
"kind": "select",
"message": "Run interface",
"options": [
"ACP server",
"Terminal REPL",
"Embedded context",
],
},
{
"kind": "nested-multiselect",
"message": "Select features",
"options": [
{
"choices": [
"Local executor",
"Sandboxed executor",
],
"default": true,
"label": "Command execution",
"required": true,
},
{
"choices": [
"JSONL files",
"SQLite database",
],
"default": true,
"label": "Durable session storage",
"required": true,
},
{
"choices": undefined,
"default": true,
"label": "Hot-module reload",
"required": false,
},
{
"choices": undefined,
"default": true,
"label": "Read, write, and edit local files",
"required": false,
},
{
"choices": undefined,
"default": true,
"label": "Model-facing task tracking",
"required": false,
},
{
"choices": undefined,
"default": true,
"label": "Local skill discovery",
"required": false,
},
{
"choices": [
"DeepSeek search",
"Exa search",
"Perplexity search",
"Fetch only",
],
"default": false,
"label": "Web search and fetch tools",
"required": false,
},
{
"choices": [
"Fresh child agent",
"Fork parent history",
],
"default": false,
"label": "Delegate work to child agents",
"required": false,
},
{
"choices": undefined,
"default": false,
"label": "Scripted multi-agent workflows",
"required": false,
},
{
"choices": undefined,
"default": false,
"label": "Automatic context compaction",
"required": false,
},
{
"choices": [
"Claude Code hooks",
"Codex hooks",
],
"default": false,
"label": "Run Claude Code or Codex hooks",
"required": false,
},
{
"choices": undefined,
"default": false,
"label": "Loop-hygiene reminders",
"required": false,
},
{
"choices": undefined,
"default": false,
"label": "Tool timeout policy",
"required": false,
},
{
"choices": undefined,
"default": false,
"label": "Ask the user from the model loop",
"required": false,
},
],
},
{
"initialValue": true,
"kind": "confirm",
"message": "Add the recommended tool timeout policy for web search and fetch tools?",
},
{
"kind": "secret",
"message": "Exa API key",
},
{
"initialValue": "none",
"kind": "select",
"message": "Local plugin",
"options": [
"No local plugin",
"Cordis plugin",
"Model-facing tool",
],
},
{
"initialValue": "npm",
"kind": "select",
"message": "Package manager",
"options": [
"npm",
"pnpm",
"Yarn",
],
},
{
"initialValue": true,
"kind": "confirm",
"message": "Run npm install and then build the project?",
},
],
"result": {
"directory": "/workspace/my-agent",
"features": [
{
"id": "provider",
"options": [
"deepseek",
],
},
{
"id": "spine",
"options": [
"default",
],
},
{
"id": "app",
"options": [
"acp",
],
},
{
"id": "bash",
"options": [
"local",
],
},
{
"id": "persistence",
"options": [
"jsonl",
],
},
{
"id": "hmr",
"options": [
"default",
],
},
{
"id": "web",
"options": [
"exa",
],
},
{
"id": "workflow",
"options": [
"workerthread",
],
},
{
"id": "timeout-policy",
"options": [
"default",
],
},
],
"install": false,
"manager": "npm",
"name": "my-agent",
},
}
`)
})
})

View File

@@ -0,0 +1,502 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { PassThrough, Writable } from 'node:stream'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
LocalPluginBlueprint,
featureId,
NpmPackageManager,
type NestedMultiSelectValue,
type PromptPort,
} from '@deepseek-ai/dsh-helper'
import type {
ConfirmPromptRequest,
MultiSelectPromptRequest,
NestedMultiSelectRequest,
PromptOutcome,
SecretPromptRequest,
SelectPromptRequest,
TextPromptRequest,
} from '../../helper/src/questions/prompt-port.ts'
import { parseCreateArgs } from '../src/args.ts'
import {
createProject,
readCreateSdkVersion,
runCreateCommand,
type CreateCommandContext,
} from '../src/command.ts'
import { CreateWizard } from '../src/create-wizard.ts'
import { scaffoldProject } from '../src/project-scaffolder.ts'
class ScriptedPort implements PromptPort {
readonly requests: string[] = []
readonly #answers: unknown[]
constructor(answers: unknown[]) {
this.#answers = [...answers]
}
answer<T>(message: string): Promise<PromptOutcome<T>> {
this.requests.push(message)
const value = this.#answers.shift()
return Promise.resolve(value === ScriptedPort.cancel
? { status: 'cancelled' }
: { status: 'answered', value: value as T })
}
async text(request: TextPromptRequest): Promise<PromptOutcome<string>> {
const outcome = await this.answer<string>(request.message)
if (outcome.status === 'cancelled') return outcome
const value = outcome.value || request.defaultValue || ''
const diagnostic = request.validate?.(value)
if (diagnostic) throw new Error(diagnostic)
return { status: 'answered', value }
}
secret(request: SecretPromptRequest): Promise<PromptOutcome<string>> { return this.answer(request.message) }
select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> { return this.answer(request.message) }
multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> {
return this.answer(request.message)
}
confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> { return this.answer(request.message) }
nestedMultiselect<TValue, TChoice>(
request: NestedMultiSelectRequest<TValue, TChoice>,
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
return this.answer(request.message)
}
static readonly cancel = Symbol('cancel')
}
const temporary: string[] = []
const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
interface GeneratedPackageManifest {
scripts?: Record<string, string>
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
}
interface GeneratedTsConfig {
compilerOptions: {
types?: readonly string[]
}
}
function parseGeneratedPackageManifest(text: string): GeneratedPackageManifest {
return JSON.parse(text) as GeneratedPackageManifest
}
function parseGeneratedTsConfig(text: string): GeneratedTsConfig {
return JSON.parse(text) as GeneratedTsConfig
}
function commandContext(
cwd: string,
port?: PromptPort,
setup?: CreateCommandContext['setup'],
): CreateCommandContext & { readStdout: () => string; readStderr: () => string } {
let stdout = ''
let stderr = ''
const input = Object.assign(new PassThrough(), { isTTY: true }) as unknown as NodeJS.ReadStream
const output = Object.assign(new Writable({
write(chunk, _encoding, callback) { stdout += String(chunk); callback() },
}), { isTTY: true }) as unknown as NodeJS.WriteStream
const error = new Writable({
write(chunk, _encoding, callback) { stderr += String(chunk); callback() },
}) as unknown as NodeJS.WriteStream
return {
cwd,
stdin: input,
stdout: output,
stderr: error,
releaseVersion: '0.0.1',
versionProbe: async () => '10.0.0',
...port ? { port } : {},
...setup ? { setup } : {},
readStdout: () => stdout,
readStderr: () => stderr,
}
}
afterEach(async () => {
await Promise.all(temporary.splice(0).map(path => rm(path, { recursive: true, force: true })))
})
describe('create arguments', () => {
it('parses public options and the private repository link mode', () => {
expect(parseCreateArgs([
'agent', '--description=demo', '--provider', 'deepseek', '--base-url=https://api.example',
'--api-key', 'key', '--model=m', '--interface', 'acp', '--pm=pnpm', '--no-install',
'--link-workspace',
])).toEqual({
directory: 'agent',
description: 'demo',
provider: 'deepseek',
baseURL: 'https://api.example',
apiKey: 'key',
model: 'm',
runInterface: 'acp',
packageManager: 'pnpm',
install: false,
linkWorkspace: true,
help: false,
})
expect(parseCreateArgs(['--link-workspace']).linkWorkspace).toBe(true)
expect(() => parseCreateArgs(['--link-packages-workspace'])).toThrow("unknown option '--link-packages-workspace'")
expect(parseCreateArgs(['--provider=custom']).provider).toBe('custom')
expect(parseCreateArgs(['--help']).help).toBe(true)
expect(() => parseCreateArgs(['--interface=bad'])).toThrow('Allowed choices are acp, stdio, embed')
expect(() => parseCreateArgs(['--unknown'])).toThrow("unknown option '--unknown'")
expect(() => parseCreateArgs(['one', 'two'])).toThrow('too many arguments')
})
it('validates empty directories and package names', async () => {
const root = await mkdtemp(join(tmpdir(), 'create-validation-'))
temporary.push(root)
await expect(new CreateWizard({
args: parseCreateArgs(['']), port: new ScriptedPort([]), cwd: root,
releaseVersion: '0.0.1', versionProbe: async () => '10.0.0',
}).run()).rejects.toThrow('A value is required')
await expect(new CreateWizard({
args: parseCreateArgs(['agent']), port: new ScriptedPort(['Invalid Name']), cwd: root,
releaseVersion: '0.0.1', versionProbe: async () => '10.0.0',
}).run()).rejects.toThrow('lowercase npm package name')
})
it('rejects an existing target before asking project questions', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'create-existing-target-'))
temporary.push(cwd)
await mkdir(join(cwd, 'taken'))
const port = new ScriptedPort([])
const wizard = new CreateWizard({
args: parseCreateArgs(['taken']),
port,
cwd,
releaseVersion: '0.0.1',
versionProbe: async () => '10.0.0',
})
await expect(wizard.run()).rejects.toThrow('directory: Target already exists')
expect(port.requests).toEqual([])
})
})
describe('CreateWizard and scaffolder', () => {
it('asks only unresolved questions in requirement-safe order', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'create-wizard-'))
temporary.push(cwd)
const port = new ScriptedPort([
'my-agent',
[
{ value: featureId('persistence'), choices: ['sqlite'] },
{ value: featureId('hmr'), choices: [] },
{ value: featureId('fs'), choices: [] },
{ value: featureId('web'), choices: ['exa'] },
],
false,
'exa-key',
'tool',
])
const args = parseCreateArgs([
'my-agent',
'--description=demo',
'--provider=deepseek',
'--api-key=deepseek-key',
'--model=deepseek-v4-flash',
'--interface=stdio',
'--pm=npm',
'--no-install',
'--link-workspace',
])
const resolved = await new CreateWizard({
args,
port,
cwd,
releaseVersion: '0.0.1',
versionProbe: async () => '10.0.0',
}).run()
expect(port.requests).toEqual([
'Package name',
'Select features',
'Add the recommended tool timeout policy for web search and fetch tools?',
'Exa API key',
'Local plugin',
])
expect(resolved.install).toBe(false)
expect(resolved.request.packageManager.name).toBe('npm')
expect(resolved.request.linkWorkspaceRoot).toBe(repoRoot)
expect(resolved.request.localPlugins[0]).toMatchObject({ name: 'tool', kind: 'tool' })
expect(resolved.request.features.find(item => item.id === 'web')).toMatchObject({
options: ['exa'], secrets: { apiKey: 'exa-key' },
})
expect(resolved.request.features.find(item => item.id === 'hmr')).toMatchObject({ options: ['default'] })
})
it('writes the project once and refuses every existing target', async () => {
const root = await mkdtemp(join(tmpdir(), 'create-scaffold-'))
temporary.push(root)
const request = {
name: 'agent',
description: 'demo',
runtime: { model: 'deepseek-v4-flash' },
packageManager: new NpmPackageManager('10.0.0'),
releaseVersion: '0.0.1',
features: [
{ id: featureId('provider'), options: ['deepseek'], secrets: { apiKey: 'key' } },
{ id: featureId('bash'), options: ['local'] },
{ id: featureId('app'), options: ['embed'] },
{ id: featureId('persistence'), options: ['jsonl'] },
],
localPlugins: [new LocalPluginBlueprint('plugin', 'plugin')],
}
const target = join(root, 'project')
const result = await scaffoldProject(target, request)
expect(result.changes.changedFiles).toContain('README.md')
const index = await readFile(join(target, 'index.ts'), 'utf8')
expect(index).toContain('SdkBootContext')
expect(index).toContain('ctx.agents.create')
expect(index).toContain('agentOptions: { model: "deepseek-v4-flash" }')
const tsconfig = parseGeneratedTsConfig(await readFile(join(target, 'tsconfig.base.json'), 'utf8'))
const manifest = parseGeneratedPackageManifest(await readFile(join(target, 'package.json'), 'utf8'))
expect(tsconfig.compilerOptions.types).toEqual(['node'])
expect(manifest.scripts).toEqual({
dev: 'dsh-sdk dev index.ts',
build: 'dsh-sdk build',
typecheck: 'tsc -b',
start: 'dsh-sdk start index.js',
config: 'dsh-sdk config',
})
expect(manifest.dependencies).not.toHaveProperty('node-addon-require-builtin')
expect(manifest.devDependencies?.['@types/node']).toBe('^22.20.0')
expect(await readFile(join(target, 'plugins/plugin/src/index.ts'), 'utf8')).toContain('export function apply')
const cordis = await readFile(join(target, 'cordis.yml'), 'utf8')
expect(cordis).toMatch(/^- id:/)
expect(cordis).not.toMatch(/^\[/)
const occupied = join(root, 'occupied')
await mkdir(occupied)
await expect(scaffoldProject(occupied, request)).rejects.toThrow('already exists')
await writeFile(join(occupied, 'keep'), 'x')
await expect(scaffoldProject(occupied, request)).rejects.toThrow('already exists')
})
it('installs workflow requirements before validating the next feature', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'create-workflow-requires-'))
temporary.push(cwd)
const port = new ScriptedPort([
'workflow-agent',
[
{ value: featureId('persistence'), choices: ['jsonl'] },
{ value: featureId('workflow'), choices: [] },
],
'none',
])
const resolved = await new CreateWizard({
args: parseCreateArgs([
'workflow-agent', '--description=test', '--provider=deepseek', '--api-key=key',
'--interface=embed', '--pm=npm', '--no-install',
]),
port,
cwd,
releaseVersion: '0.0.1',
versionProbe: async () => '10.0.0',
}).run()
const result = await scaffoldProject(resolved.directory, resolved.request)
expect(result.project.cordis.entry('subagent-spawn')).toBeDefined()
expect(result.project.cordis.entry('tool-subagent')).toBeDefined()
})
it('confirms an empty provider key and leaves a documented .env placeholder', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'create-empty-key-'))
temporary.push(cwd)
const port = new ScriptedPort([
'empty-key-agent',
'',
true,
[{ value: featureId('persistence'), choices: ['jsonl'] }],
'none',
])
const resolved = await new CreateWizard({
args: parseCreateArgs([
'empty-key-agent', '--description=test', '--provider=deepseek',
'--interface=embed', '--pm=npm', '--no-install',
]),
port,
cwd,
releaseVersion: '0.0.1',
versionProbe: async () => '10.0.0',
}).run()
await scaffoldProject(resolved.directory, resolved.request)
expect(await readFile(join(resolved.directory, '.env'), 'utf8')).toBe(
'# Required before start; an empty value makes provider startup fail.\nDEEPSEEK_API_KEY=\n',
)
expect(port.requests).toContain('Keep the API key empty and fill .env later?')
})
it('collects custom provider inputs, retries an empty key, and accepts a recommendation', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'create-custom-inputs-'))
temporary.push(cwd)
const port = new ScriptedPort([
'custom-agent',
'test custom provider',
'custom',
'https://provider.example/v1',
'', false, 'custom-key',
'embed',
[
{ value: featureId('persistence'), choices: ['jsonl'] },
{ value: featureId('web'), choices: ['deepseek'] },
],
true,
'none',
'npm',
false,
])
const resolved = await new CreateWizard({
args: parseCreateArgs(['custom-agent']),
port,
cwd,
releaseVersion: '0.0.1',
versionProbe: async () => '10.0.0',
userAgent: '',
}).run()
expect(resolved.request.features.find(item => item.id === 'provider')).toMatchObject({
options: ['custom'], values: { baseURL: 'https://provider.example/v1' }, secrets: { apiKey: 'custom-key' },
})
expect(resolved.request.features.some(item => item.id === 'timeout-policy')).toBe(true)
})
it('does not re-suggest an already selected feature', async () => {
const cwd = await mkdtemp(join(tmpdir(), 'create-selected-suggestion-'))
temporary.push(cwd)
const port = new ScriptedPort([
'agent',
[
{ value: featureId('persistence'), choices: ['jsonl'] },
{ value: featureId('web'), choices: ['deepseek'] },
{ value: featureId('timeout-policy'), choices: ['default'] },
],
'none',
])
const resolved = await new CreateWizard({
args: parseCreateArgs([
'agent', '--description=test', '--provider=deepseek', '--api-key=key',
'--interface=embed', '--pm=npm', '--no-install',
]),
port,
cwd,
releaseVersion: '0.0.1',
versionProbe: async () => '10.0.0',
}).run()
expect(resolved.request.features.filter(item => item.id === 'timeout-policy')).toHaveLength(1)
})
it('uses process defaults when constructor infrastructure is omitted', async () => {
const name = `default-infra-${String(process.pid)}`
const port = new ScriptedPort([
name, [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
])
const resolved = await new CreateWizard({
args: parseCreateArgs([
name, '--description=test', '--provider=deepseek', '--api-key=key',
'--interface=embed', '--pm=npm', '--no-install',
]),
port,
releaseVersion: '0.0.1',
}).run()
expect(resolved.request.packageManager.name).toBe('npm')
})
it('reads the release batch from the initializer package', async () => {
await expect(readCreateSdkVersion()).resolves.toBe('0.0.1')
})
})
describe('create command composition', () => {
const argv = (directory: string, install: boolean): string[] => [
directory, '--description=test', '--provider=deepseek', '--api-key=key',
'--interface=embed', '--pm=npm', install ? '--install' : '--no-install',
]
it('prints help before requiring a TTY and rejects non-interactive creation', async () => {
const root = await mkdtemp(join(tmpdir(), 'create-command-help-'))
temporary.push(root)
const context = commandContext(root)
context.stdin.isTTY = false
context.stdout.isTTY = false
await expect(createProject(['--help'], context)).resolves.toBeUndefined()
expect(context.readStdout()).toContain('Usage: create-sdk')
expect(context.readStdout()).not.toContain('--link-workspace')
await expect(createProject(argv('agent', false), context)).rejects.toThrow('interactive TTY')
context.stdin.isTTY = true
await expect(createProject(argv('agent', false), context)).rejects.toThrow('interactive TTY')
})
it('creates through an injected prompt port and delegates optional setup', async () => {
const root = await mkdtemp(join(tmpdir(), 'create-command-success-'))
temporary.push(root)
const port = new ScriptedPort([
'agent', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
])
let setupDirectory = ''
const context = commandContext(root, port, async (request) => { setupDirectory = request.directory })
const result = await createProject(argv('agent', true), context)
expect(result?.project.root).toBe(join(root, 'agent'))
expect(setupDirectory).toBe(join(root, 'agent'))
expect(context.readStdout()).toContain('Created agent')
expect(context.readStdout()).toContain('Next: cd')
const noInstall = commandContext(root, new ScriptedPort([
'next', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
]))
await expect(createProject(argv('next', false), noInstall)).resolves.toBeDefined()
expect(noInstall.readStdout()).toContain('npm install && npm run build && npm start')
})
it('uses the package manager setup path when no setup override is supplied', async () => {
const root = await mkdtemp(join(tmpdir(), 'create-command-default-setup-'))
temporary.push(root)
const port = new ScriptedPort([
'agent', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
])
const install = vi.spyOn(NpmPackageManager.prototype, 'install').mockResolvedValue()
const build = vi.spyOn(NpmPackageManager.prototype, 'build').mockResolvedValue()
const context = commandContext(root, port)
delete context.releaseVersion
delete context.versionProbe
await createProject(argv('agent', true), context)
expect(install).toHaveBeenCalledOnce()
expect(build).toHaveBeenCalledOnce()
install.mockRestore()
build.mockRestore()
})
it('reports setup failures after preserving generated files', async () => {
const root = await mkdtemp(join(tmpdir(), 'create-command-failure-'))
temporary.push(root)
const port = new ScriptedPort([
'agent', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
])
const context = commandContext(root, port, async () => { throw new Error('offline') })
await expect(createProject(argv('agent', true), context)).rejects.toThrow('offline')
expect(context.readStderr()).toContain('Project files are ready, but setup failed')
expect(context.readStderr()).toContain('npm install && npm run build')
const stringFailure = commandContext(root, new ScriptedPort([
'next', [{ value: featureId('persistence'), choices: ['jsonl'] }], 'none',
]), async () => { throw 'offline-string' })
await expect(runCreateCommand(argv('next', true), stringFailure)).resolves.toBe(1)
expect(stringFailure.readStderr()).toContain('offline-string')
})
it('maps cancellation and ordinary errors to command exit codes', async () => {
const root = await mkdtemp(join(tmpdir(), 'create-command-exit-'))
temporary.push(root)
const cancelled = commandContext(root, new ScriptedPort([ScriptedPort.cancel]))
await expect(runCreateCommand([], cancelled)).resolves.toBe(1)
expect(cancelled.readStderr()).toContain('cancelled')
const invalid = commandContext(root)
await expect(runCreateCommand(['--unknown'], invalid)).resolves.toBe(1)
expect(invalid.readStderr()).toContain('unknown option')
const help = commandContext(root)
await expect(runCreateCommand(['--help'], help)).resolves.toBe(0)
})
})

View File

@@ -0,0 +1,112 @@
import { execFile } from 'node:child_process'
import { existsSync } from 'node:fs'
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import { afterEach, describe, expect, it } from 'vitest'
import {
LocalPluginBlueprint,
featureId,
createPackageManager,
type PackageManagerName,
} from '@deepseek-ai/dsh-helper'
import { scrubEnvironment } from '../../helper/src/package-managers/package-manager.ts'
import { scaffoldProject } from '../src/project-scaffolder.ts'
const execFileAsync = promisify(execFile)
const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
const builtScripts = join(repoRoot, 'packages/sdk/scripts/lib/bin.js')
const temporary: string[] = []
afterEach(async () => {
await Promise.all(temporary.splice(0).map(path => rm(path, { recursive: true, force: true })))
})
async function managerVersion(name: PackageManagerName): Promise<string | undefined> {
try {
return (await execFileAsync(name, ['--version'], { encoding: 'utf8' })).stdout.trim()
} catch {
// An unavailable optional manager skips only its own live-link case.
return undefined
}
}
const managers: PackageManagerName[] = ['npm', 'pnpm', 'yarn']
describe.skipIf(!existsSync(builtScripts))('live-linked generated projects', () => {
for (const name of managers) {
it(`${name}: installs the local closure and resolves plugin TypeScript in dev`, async (context) => {
const version = await managerVersion(name)
if (!version) {
context.skip()
return
}
const parent = await mkdtemp(join(tmpdir(), `dsh-link-${name}-`))
const root = join(parent, 'project')
temporary.push(parent)
const manager = createPackageManager(name, version)
await scaffoldProject(root, {
name: `linked-${name}`,
description: 'link e2e',
runtime: { model: 'deepseek-v4-flash' },
packageManager: manager,
releaseVersion: '0.0.1',
linkWorkspaceRoot: repoRoot,
features: [
{ id: featureId('provider'), options: ['deepseek'], secrets: { apiKey: 'test-key' } },
{ id: featureId('bash'), options: ['local'] },
{ id: featureId('app'), options: ['embed'] },
{ id: featureId('persistence'), options: ['jsonl'] },
],
localPlugins: [new LocalPluginBlueprint('probe', 'plugin')],
})
await writeFile(join(root, 'plugins/probe/src/index.ts'), `
import { writeFileSync } from 'node:fs'
import type { Context } from 'cordis'
export const name = 'probe'
export function apply(_ctx: Context): void {
writeFileSync(new URL('../../../plugin-loaded', import.meta.url), 'loaded\\n')
}
`)
const cacheRoot = join(tmpdir(), 'dsh-sdk-link-cache', name)
const commandEnvironment = {
...scrubEnvironment(),
COREPACK_HOME: join(cacheRoot, 'corepack'),
XDG_CACHE_HOME: join(cacheRoot, 'cache'),
XDG_DATA_HOME: join(cacheRoot, 'data'),
npm_config_cache: join(cacheRoot, 'npm'),
pnpm_config_store_dir: join(cacheRoot, 'pnpm-store'),
}
await execFileAsync(name, manager.installCommand(), {
cwd: root,
env: commandEnvironment,
encoding: 'utf8',
timeout: 120_000,
})
await execFileAsync(name, manager.buildCommand(), {
cwd: root,
env: commandEnvironment,
encoding: 'utf8',
timeout: 120_000,
})
expect(existsSync(join(root, 'index.js'))).toBe(true)
expect(existsSync(join(root, 'plugins/probe/lib/index.js'))).toBe(true)
const dshSdk = join(root, 'node_modules/@deepseek-ai/dsh-scripts/lib/bin.js')
const run = await execFileAsync(process.execPath, [dshSdk, 'dev', 'index.ts'], {
cwd: root,
env: { ...commandEnvironment, DEEPSEEK_API_KEY: 'test-key' },
encoding: 'utf8',
timeout: 30_000,
})
expect(run.stderr).not.toContain('without inject')
expect(await readFile(join(root, 'plugin-loaded'), 'utf8')).toBe('loaded\n')
const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8')) as {
dependencies: Record<string, string>
}
expect(manifest.dependencies.cordis).toMatch(name === 'npm' ? /^file:/ : name === 'pnpm' ? /^link:/ : /^portal:/)
expect(manifest.dependencies).not.toHaveProperty('node-addon-require-builtin')
}, 180_000)
}
})

View File

@@ -0,0 +1,12 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": ["src"],
"references": [
{ "path": "../helper" },
{ "path": "../../../vendor/cordis" }
]
}

View File

@@ -0,0 +1,14 @@
import { defineConfig } from 'tsdown'
/** Bundle the library and create bin, then mirror package-owned terminal templates. */
export default defineConfig({
entry: ['lib/types/index.js', 'lib/types/bin.js'],
outDir: 'lib',
format: ['esm'],
platform: 'node',
target: 'es2024',
fixedExtension: false,
dts: false,
clean: false,
copy: [{ from: 'src/templates/assets/*', to: 'lib/assets' }],
})

View File

@@ -0,0 +1,23 @@
# `@deepseek-ai/dsh-helper`
Shared project domain and infrastructure for `create-sdk` and `dsh-sdk config`. `SdkProject` is a read-only snapshot; `ProjectEditSession` is the only mutation and commit boundary. The [SDK architecture RFC](../../../docs/rfc/proposed/architecture/2026-07-15-sdk-project-editing-architecture.md) owns the rationale.
The package owns the builtin typed-spec catalog, provider/app behavior entities, structured project file objects, helper-owned project templates, the shared typed `TextTemplate` renderer, package-manager strategies, local-plugin blueprints, typed questions, and the clack prompt adapter. It never boots a Cordis application.
All business and document validation completes before commit writes any affected file. Commit detects external edits made after the session opened, but deliberately provides no cross-file rollback after writing starts.
Builtin features are provider, bash, app, persistence, HMR, filesystem, todo, skill, web, subagent, workflow, compaction, hooks, repeat-tool guard, timeout policy, and ask-user. The catalog owns feature options, required and non-default Cordis plugin config, feature requirements, resource contribution, and round-trip markers; create and config use the same registry and configurator.
`SdkProject.open()` requires only readable root `package.json` and `cordis.yml`. A Cordis config entry anchors feature installation; a package present only through a linked NPM dependency closure leaves the feature absent. Once an owned Cordis config entry exists, an incomplete resource shape is `inconsistent` and cannot be modified automatically.
`.env.example` follows the currently selected features. `.env` is append-only: helper may add a missing differently named variable, but never updates or removes existing content.
The package root explicitly exports only the objects consumed by `create-sdk` and `dsh-scripts`; internal modules have no `src/*` or package-manifest subpath export.
## Model Experience
None, as the project domain edits files and never mounts a live agent or model request.
## Known Limitations and Deferred Work
- **Commit is not transactional across files** — external edits are detected before each write, but a later failure does not roll back files already written.

View File

@@ -0,0 +1,45 @@
{
"name": "@deepseek-ai/dsh-helper",
"description": "Domain model and infrastructure for creating and editing DeepSeek Harness SDK projects",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "lib/index.js",
"types": "lib/types/index.d.ts",
"exports": {
".": {
"types": "./lib/types/index.d.ts",
"default": "./lib/index.js"
}
},
"files": [
"lib/index.js",
"lib/assets",
"lib/types/**/*.d.ts",
"lib/types/**/*.d.ts.map",
"src"
],
"license": "BSD-3-Clause",
"dependencies": {
"@clack/core": "^1.4.3",
"@clack/prompts": "^1.7.0",
"handlebars": "^4.7.9",
"jsonc-parser": "^3.3.1",
"yaml": "^2.9.0"
},
"peerDependencies": {
"@deepseek-ai/dsh-brand": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"devDependencies": {
"@deepseek-ai/dsh-brand": "workspace:^",
"@deepseek-ai/dsh-compact-basic": "workspace:^",
"@deepseek-ai/dsh-hooks-claude": "workspace:^",
"@deepseek-ai/dsh-hooks-codex": "workspace:^",
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^",
"@deepseek-ai/dsh-session-persistence-sqlite": "workspace:^",
"@deepseek-ai/dsh-tool-subagent": "workspace:^",
"@deepseek-ai/dsh-tool-web": "workspace:^",
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -0,0 +1,190 @@
/**
* Comment-preserving Cordis YAML document and `!!js` expression value.
*
* @module @deepseek-ai/dsh-helper/documents/cordis-yaml-file
*/
import {
Document, isMap, isSeq, parseDocument, visit, YAMLMap, YAMLSeq,
type ScalarTag,
} from 'yaml'
import { ProjectFile, withTrailingNewline } from './project-file.ts'
/** Explicit JavaScript expression serialized with Cordis' `!!js` YAML tag. */
export class JsExpression {
/** Expression source evaluated by the Cordis include loader. */
readonly source: string
/** Create an expression value. */
constructor(source: string) {
if (source.trim().length === 0) throw new Error('JavaScript expression must not be empty')
this.source = source
}
/** Return expression source for YAML scalar stringification. */
toString(): string {
return this.source
}
}
const JS_EXPRESSION_TAG: ScalarTag = {
tag: 'tag:yaml.org,2002:js',
identify: value => value instanceof JsExpression,
resolve: value => new JsExpression(value),
stringify: item => String(item.value),
}
/** Plain domain representation of one top-level Cordis config entry. */
export interface CordisConfigEntry {
id: string
name: string
config?: Record<string, unknown>
disabled?: boolean
}
function parseYaml(text: string): Document.Parsed {
const document = parseDocument(text, {
customTags: [JS_EXPRESSION_TAG],
keepSourceTokens: true,
prettyErrors: true,
})
if (document.errors.length > 0) {
throw new Error(`invalid cordis.yml: ${document.errors.map(error => error.message).join('; ')}`)
}
if (!isSeq(document.contents)) throw new Error('invalid cordis.yml: root must be a sequence')
visit(document, { Collection: (_key, collection) => { collection.flow = false } })
return document
}
function entryFromValue(value: unknown): CordisConfigEntry {
/* v8 ignore next -- entries() calls this only after requiring a YAMLMap, whose JSON value is an object */
if (value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error('invalid cordis.yml entry: expected an object')
}
const entry = value as Record<string, unknown>
if (typeof entry.id !== 'string' || entry.id.length === 0) {
throw new Error('invalid cordis.yml entry: id must be a non-empty string')
}
if (typeof entry.name !== 'string' || entry.name.length === 0) {
throw new Error(`invalid cordis.yml entry ${entry.id}: name must be a non-empty string`)
}
if (entry.config !== undefined
&& (entry.config === null || Array.isArray(entry.config) || typeof entry.config !== 'object')) {
throw new Error(`invalid cordis.yml entry ${entry.id}: plugin config must be an object`)
}
if (entry.disabled !== undefined && typeof entry.disabled !== 'boolean') {
throw new Error(`invalid cordis.yml entry ${entry.id}: disabled must be boolean`)
}
return {
id: entry.id,
name: entry.name,
...entry.config !== undefined ? { config: entry.config as Record<string, unknown> } : {},
...entry.disabled !== undefined ? { disabled: entry.disabled } : {},
}
}
/** Editable top-level cordis.yml using YAML's document API. */
export class CordisYamlFile extends ProjectFile {
private readonly document: Document.Parsed
private constructor(document: Document.Parsed, originalText?: string) {
super('cordis.yml', originalText)
this.document = document
}
/** Create an empty Cordis config entry list. */
static create(): CordisYamlFile {
return new CordisYamlFile(parseYaml('[]\n'))
}
/** Parse an existing cordis.yml while retaining comments and scalar styles. */
static parse(text: string): CordisYamlFile {
return new CordisYamlFile(parseYaml(text), text)
}
/** Clone through YAML text so the edit session owns an independent AST. */
override clone(): CordisYamlFile {
return new CordisYamlFile(parseYaml(this.serialize()), this.originalText)
}
private sequence(): YAMLSeq {
/* v8 ignore next -- parseYaml and create both establish a sequence root */
if (!isSeq(this.document.contents)) throw new Error('cordis.yml root is not a sequence')
return this.document.contents
}
private entryNode(id: string): YAMLMap | undefined {
for (const item of this.sequence().items) {
if (!isMap(item)) continue
if (item.get('id') === id) return item
}
return undefined
}
/** Return defensive plain entry values in file order. */
entries(): CordisConfigEntry[] {
return this.sequence().items.map((item) => {
if (!isMap(item)) throw new Error('invalid cordis.yml: every entry must be a mapping')
return entryFromValue(item.toJSON())
})
}
/** Find one entry by stable id. */
entry(id: string): CordisConfigEntry | undefined {
return this.entries().find(entry => entry.id === id)
}
/** Add one new top-level entry, rejecting duplicate ids. */
addEntry(entry: CordisConfigEntry, commentedExample?: string): void {
if (this.entryNode(entry.id)) throw new Error(`Cordis config entry already exists: ${entry.id}`)
const node = this.document.createNode(entry)
if (commentedExample) node.comment = commentedExample.split('\n').map(line => ` ${line}`).join('\n')
this.sequence().items.push(node)
}
/** Remove an entry by id and report whether it existed. */
removeEntry(id: string): boolean {
const sequence = this.sequence()
const index = sequence.items.findIndex(item => isMap(item) && item.get('id') === id)
if (index < 0) return false
sequence.items.splice(index, 1)
return true
}
/** Enable or disable an entry through the Loader-native field. */
setDisabled(id: string, disabled: boolean): void {
const node = this.entryNode(id)
if (!node) throw new Error(`Cordis config entry does not exist: ${id}`)
if (disabled) node.set('disabled', true)
else node.delete('disabled')
}
/** Replace only owned plugin config keys while retaining unknown user keys. */
updateOwnedConfig(id: string, ownedKeys: readonly string[], next: Record<string, unknown>): void {
const entry = this.entryNode(id)
if (!entry) throw new Error(`Cordis config entry does not exist: ${id}`)
let config: unknown = entry.get('config', true)
if (config === undefined || config === null) {
config = new YAMLMap()
entry.set('config', config)
}
if (!isMap(config)) throw new Error(`Cordis config entry ${id} plugin config is not a mapping`)
for (const key of ownedKeys) config.delete(key)
for (const [key, value] of Object.entries(next)) config.set(key, this.document.createNode(value))
if (config.items.length === 0) entry.delete('config')
}
/** Validate ids, names, plugin config maps, and id uniqueness. */
override validate(): void {
const seen = new Set<string>()
for (const entry of this.entries()) {
if (seen.has(entry.id)) throw new Error(`duplicate Cordis config entry id: ${entry.id}`)
seen.add(entry.id)
}
}
/** Serialize through the YAML document while retaining untouched trivia. */
override serialize(): string {
return withTrailingNewline(this.document.toString({ lineWidth: 0 }))
}
}

View File

@@ -0,0 +1,111 @@
/**
* Ownership-aware, line-preserving dotenv document.
*
* @module @deepseek-ai/dsh-helper/documents/env-file
*/
import { ProjectFile, withTrailingNewline } from './project-file.ts'
interface ParsedVariable {
index: number
value: string
}
const VARIABLE = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/
const VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
/** `.env` appends missing variables; `.env.example` supports managed replacement and removal. */
export class EnvFile extends ProjectFile {
private readonly lines: string[]
private constructor(relativePath: '.env' | '.env.example', lines: string[], originalText?: string) {
super(relativePath, originalText, relativePath === '.env' ? 0o600 : undefined)
this.lines = [...lines]
}
/** Create an empty environment file. */
static create(relativePath: '.env' | '.env.example'): EnvFile {
return new EnvFile(relativePath, [])
}
/** Parse an existing environment file without rewriting unknown lines. */
static parse(relativePath: '.env' | '.env.example', text: string): EnvFile {
const normalized = text.replace(/\n$/, '')
return new EnvFile(relativePath, normalized.length === 0 ? [] : normalized.split('\n'), text)
}
/** Clone the current line model. */
override clone(): EnvFile {
return new EnvFile(this.relativePath as '.env' | '.env.example', this.lines, this.originalText)
}
private variables(): Map<string, ParsedVariable[]> {
const values = new Map<string, ParsedVariable[]>()
this.lines.forEach((line, index) => {
const match = VARIABLE.exec(line)
if (!match) return
const name = match[1]
const value = match[2]
/* v8 ignore next -- both captures are mandatory in VARIABLE */
if (name === undefined || value === undefined) return
const occurrences = values.get(name) ?? []
occurrences.push({ index, value })
values.set(name, occurrences)
})
return values
}
/** Read the effective value; append-only `.env` accepts duplicates and uses the last declaration. */
get(name: string): string | undefined {
const occurrences = this.variables().get(name) ?? []
if (this.relativePath === '.env.example' && occurrences.length > 1) {
throw new Error(`${this.relativePath} contains duplicate variable ${name}`)
}
return occurrences.at(-1)?.value
}
/** Add or replace one SDK-managed `.env.example` variable while preserving unrelated lines. */
set(name: string, value: string): void {
if (this.relativePath !== '.env.example') throw new Error('.env is append-only')
if (!VARIABLE_NAME.test(name)) throw new Error(`invalid environment variable name: ${name}`)
const occurrences = this.variables().get(name) ?? []
if (occurrences.length > 1) throw new Error(`${this.relativePath} contains duplicate variable ${name}`)
const line = `${name}=${value}`
if (occurrences[0]) this.lines[occurrences[0].index] = line
else this.lines.push(line)
}
/** Append a missing `.env` variable and optional comment without changing any existing declaration. */
append(name: string, value: string, comment?: string): boolean {
if (this.relativePath !== '.env') throw new Error('.env.example is SDK-managed')
if (!VARIABLE_NAME.test(name)) throw new Error(`invalid environment variable name: ${name}`)
if (comment !== undefined && (!comment || comment.includes('\n'))) {
throw new Error('environment comment must be one non-empty line')
}
if (this.variables().has(name)) return false
if (comment) this.lines.push(`# ${comment}`)
this.lines.push(`${name}=${value}`)
return true
}
/** Remove one SDK-managed `.env.example` variable while retaining every other line. */
remove(name: string): void {
if (this.relativePath !== '.env.example') throw new Error('.env is append-only')
const occurrences = this.variables().get(name) ?? []
if (occurrences.length > 1) throw new Error(`${this.relativePath} contains duplicate variable ${name}`)
if (occurrences[0]) this.lines.splice(occurrences[0].index, 1)
}
/** Validate the managed placeholder file; append-only `.env` accepts duplicate declarations. */
override validate(): void {
if (this.relativePath === '.env') return
for (const [name, occurrences] of this.variables()) {
if (occurrences.length > 1) throw new Error(`${this.relativePath} contains duplicate variable ${name}`)
}
}
/** Serialize all retained lines with one trailing newline. */
override serialize(): string {
return withTrailingNewline(this.lines.join('\n'))
}
}

View File

@@ -0,0 +1,169 @@
/**
* Structured package.json document owned by an SDK project.
*
* @module @deepseek-ai/dsh-helper/documents/package-json-file
*/
import { ProjectFile, withTrailingNewline } from './project-file.ts'
/** NPM dependency sections managed by the SDK. */
export type NpmDependencySection = 'dependencies' | 'devDependencies'
/** JSON shape retained by {@link PackageJsonFile}. */
export interface PackageManifest {
name?: string
version?: string
private?: boolean
description?: string
type?: string
packageManager?: string
scripts?: Record<string, string>
dependencies?: Record<string, string>
devDependencies?: Record<string, string>
workspaces?: string[]
resolutions?: Record<string, string>
[key: string]: unknown
}
function parseManifest(text: string): PackageManifest {
let value: unknown
try {
value = JSON.parse(text)
} catch (error) {
throw new Error(`invalid package.json: ${String(error)}`)
}
if (value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error('invalid package.json: root must be an object')
}
return value as PackageManifest
}
function sortedRecord(value: Record<string, string>): Record<string, string> {
return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)))
}
/** Editable, deterministic package.json representation. */
export class PackageJsonFile extends ProjectFile {
private readonly manifest: PackageManifest
private constructor(manifest: PackageManifest, originalText?: string) {
super('package.json', originalText)
this.manifest = structuredClone(manifest)
}
/** Create a new package manifest from a complete rendered template. */
static create(text: string): PackageJsonFile {
return new PackageJsonFile(parseManifest(text))
}
/** Parse an existing package.json document. */
static parse(text: string): PackageJsonFile {
return new PackageJsonFile(parseManifest(text), text)
}
/** Clone this document and its nested manifest data. */
override clone(): PackageJsonFile {
return new PackageJsonFile(this.manifest, this.originalText)
}
/** Return a defensive copy of the manifest. */
value(): Readonly<PackageManifest> {
return structuredClone(this.manifest)
}
/** Set one package script. */
setScript(name: string, command: string): void {
this.manifest.scripts ??= {}
this.manifest.scripts[name] = command
}
/** Read one package script. */
script(name: string): string | undefined {
return this.manifest.scripts?.[name]
}
/** Remove one package script. */
removeScript(name: string): void {
delete this.manifest.scripts?.[name]
}
/** Set one NPM dependency in its runtime or development section. */
setNpmDependency(section: NpmDependencySection, name: string, spec: string): void {
this.manifest[section] ??= {}
this.manifest[section][name] = spec
}
/** Remove one NPM dependency from a section. */
removeNpmDependency(section: NpmDependencySection, name: string): void {
delete this.manifest[section]?.[name]
}
/** Read an NPM dependency spec from either managed section. */
npmDependency(name: string): { section: NpmDependencySection; spec: string } | undefined {
for (const section of ['dependencies', 'devDependencies'] as const) {
const spec = this.manifest[section]?.[name]
if (spec !== undefined) return { section, spec }
}
return undefined
}
/** Return all managed NPM dependency names. */
npmDependencyNames(): string[] {
return [...new Set([
...Object.keys(this.manifest.dependencies ?? {}),
...Object.keys(this.manifest.devDependencies ?? {}),
])].sort()
}
/** Add a package-manager workspace glob. */
addWorkspace(pattern: string): void {
const workspaces = this.manifest.workspaces ??= []
if (!workspaces.includes(pattern)) workspaces.push(pattern)
}
/** Set or remove the packageManager field. */
setPackageManager(value: string | undefined): void {
if (value === undefined) delete this.manifest.packageManager
else this.manifest.packageManager = value
}
/** Pin a Yarn resolution used by live-link projects. */
setResolution(name: string, spec: string): void {
this.manifest.resolutions ??= {}
this.manifest.resolutions[name] = spec
}
/** Validate the fields the SDK relies on. */
override validate(): void {
if (!this.manifest.name || typeof this.manifest.name !== 'string') {
throw new Error('package.json name must be a non-empty string')
}
for (const section of ['scripts', 'dependencies', 'devDependencies'] as const) {
const value: unknown = this.manifest[section]
if (value === undefined) continue
if (value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error(`package.json ${section} must be an object`)
}
for (const [key, item] of Object.entries(value)) {
if (typeof item !== 'string' || item.length === 0) {
throw new Error(`package.json ${section}.${key} must be a non-empty string`)
}
}
}
if (this.manifest.workspaces !== undefined
&& (!Array.isArray(this.manifest.workspaces) || this.manifest.workspaces.some(item => typeof item !== 'string'))) {
throw new Error('package.json workspaces must be an array of strings')
}
}
/** Serialize with deterministic managed maps and two-space JSON formatting. */
override serialize(): string {
const value: PackageManifest = structuredClone(this.manifest)
if (this.manifest.scripts) value.scripts = sortedRecord(this.manifest.scripts)
if (this.manifest.dependencies) value.dependencies = sortedRecord(this.manifest.dependencies)
if (this.manifest.devDependencies) value.devDependencies = sortedRecord(this.manifest.devDependencies)
if (this.manifest.workspaces) value.workspaces = [...this.manifest.workspaces].sort()
if (this.manifest.resolutions) value.resolutions = sortedRecord(this.manifest.resolutions)
return withTrailingNewline(JSON.stringify(value, null, 2))
}
}

View File

@@ -0,0 +1,96 @@
/**
* Structured pnpm workspace configuration for generated SDK projects.
*
* @module @deepseek-ai/dsh-helper/documents/pnpm-workspace-file
*/
import {
isMap, isScalar, isSeq, parseDocument,
type Document, type Scalar, type YAMLMap, type YAMLSeq,
} from 'yaml'
import { ProjectFile, withTrailingNewline } from './project-file.ts'
function parseYaml(text: string): Document.Parsed {
const document = parseDocument(text, { keepSourceTokens: true, prettyErrors: true })
if (document.errors.length > 0) {
throw new Error(`invalid pnpm-workspace.yaml: ${document.errors.map(error => error.message).join('; ')}`)
}
if (!isMap(document.contents)) throw new Error('pnpm-workspace.yaml root must be an object')
return document
}
/** Generated pnpm-workspace.yaml model. */
export class PnpmWorkspaceFile extends ProjectFile {
private readonly document: Document.Parsed
private constructor(document: Document.Parsed, originalText?: string) {
super('pnpm-workspace.yaml', originalText)
this.document = document
}
/** Create a pnpm workspace document. */
static create(): PnpmWorkspaceFile {
const document = new PnpmWorkspaceFile(parseYaml('{}\n'))
document.mapping().set('packages', document.document.createNode([]))
document.mapping().set('allowBuilds', document.document.createNode({ esbuild: true }))
return document
}
/** Parse the workspace fields the SDK owns while retaining all other YAML. */
static parse(text: string): PnpmWorkspaceFile {
const document = new PnpmWorkspaceFile(parseYaml(text), text)
document.packageSequence()
const autoInstallPeers = document.mapping().get('autoInstallPeers')
if (autoInstallPeers !== undefined && typeof autoInstallPeers !== 'boolean') {
throw new Error('pnpm-workspace.yaml autoInstallPeers must be boolean')
}
return document
}
/** Clone the complete comment-preserving workspace document. */
override clone(): PnpmWorkspaceFile {
return new PnpmWorkspaceFile(parseYaml(this.serialize()), this.originalText)
}
/** Add one package workspace glob. */
addPackage(pattern: string): void {
const packages = this.packageSequence()
if (packages.items.some(item => item.value === pattern)) return
packages.add(this.document.createNode(pattern))
}
/** Disable registry peer auto-installation for live-link projects. */
disableAutoInstallPeers(): void {
this.mapping().set('autoInstallPeers', false)
}
/** Validate workspace globs. */
override validate(): void {
for (const pattern of this.packageValues()) {
if (pattern.trim().length === 0) throw new Error('pnpm workspace pattern must not be empty')
}
}
/** Serialize the workspace while retaining unknown settings and comments. */
override serialize(): string {
return withTrailingNewline(this.document.toString({ lineWidth: 0 }))
}
private mapping(): YAMLMap {
/* v8 ignore next -- parseYaml and create both establish a mapping root */
if (!isMap(this.document.contents)) throw new Error('pnpm-workspace.yaml root must be an object')
return this.document.contents
}
private packageSequence(): YAMLSeq<Scalar<string>> {
const packages = this.mapping().get('packages', true)
if (!isSeq(packages) || packages.items.some(item => !isScalar(item) || typeof item.value !== 'string')) {
throw new Error('pnpm-workspace.yaml packages must be an array of strings')
}
return packages as YAMLSeq<Scalar<string>>
}
private packageValues(): string[] {
return this.packageSequence().items.map(item => item.value)
}
}

View File

@@ -0,0 +1,64 @@
/**
* Base abstraction for one file in an SDK project snapshot.
*
* @module @deepseek-ai/dsh-helper/documents/project-file
*/
/** Return text with exactly one trailing newline. */
export function withTrailingNewline(text: string): string {
return text.replace(/\n*$/, '') + '\n'
}
/** One cloneable, validatable project file. */
export abstract class ProjectFile {
/** Project-relative POSIX path. */
readonly relativePath: string
/** Text observed when the document entered the snapshot; absent for a new file. */
readonly originalText: string | undefined
/** Permission bits used only when the file is first created. */
readonly createMode: number | undefined
protected constructor(relativePath: string, originalText?: string, createMode?: number) {
if (relativePath.startsWith('/') || relativePath.split('/').includes('..')) {
throw new Error(`project document path must stay inside the project: ${relativePath}`)
}
this.relativePath = relativePath
this.originalText = originalText
this.createMode = createMode
}
/** Clone the document for an isolated edit session. */
abstract clone(): ProjectFile
/** Validate the document's complete current state. */
abstract validate(): void
/** Serialize the complete current file. */
abstract serialize(): string
}
/** Immutable complete-text file used by one-shot artifacts. */
export class TextProjectFile extends ProjectFile {
private readonly text: string
/** Create a complete-text project document. */
constructor(relativePath: string, text: string, originalText?: string) {
super(relativePath, originalText)
this.text = withTrailingNewline(text)
}
/** Clone this immutable document. */
override clone(): TextProjectFile {
return new TextProjectFile(this.relativePath, this.text, this.originalText)
}
/** Complete text artifacts have no extra structural validation. */
override validate(): void {}
/** Return the complete artifact text. */
override serialize(): string {
return this.text
}
}

View File

@@ -0,0 +1,89 @@
/**
* Comment-preserving root tsconfig editor for local plugin references.
*
* @module @deepseek-ai/dsh-helper/documents/tsconfig-file
*/
import { applyEdits, modify, parse, type ParseError } from 'jsonc-parser'
import { ProjectFile, withTrailingNewline } from './project-file.ts'
const FORMAT = { insertSpaces: true, tabSize: 2, eol: '\n' }
function parseConfig(text: string): Record<string, unknown> {
const errors: ParseError[] = []
const value: unknown = parse(text, errors, { allowTrailingComma: true, disallowComments: false })
if (errors.length > 0 || value === null || Array.isArray(value) || typeof value !== 'object') {
throw new Error('tsconfig.json is not a valid JSONC object')
}
return value as Record<string, unknown>
}
/** Root tsconfig document edited with jsonc-parser patches. */
export class TsConfigFile extends ProjectFile {
private text: string
private constructor(text: string, originalText?: string) {
super('tsconfig.json', originalText)
this.text = withTrailingNewline(text)
}
/** Create the root project-reference config. */
static create(): TsConfigFile {
return new TsConfigFile(JSON.stringify({
extends: './tsconfig.base.json',
compilerOptions: { noEmit: true },
include: ['index.ts'],
references: [],
}, null, 2))
}
/** Parse an existing root tsconfig. */
static parse(text: string): TsConfigFile {
parseConfig(text)
return new TsConfigFile(text, text)
}
/** Clone the current JSONC text. */
override clone(): TsConfigFile {
return new TsConfigFile(this.text, this.originalText)
}
/** Add one project reference while retaining comments and formatting. */
addReference(path: string): void {
const value = parseConfig(this.text)
const references = value.references
if (references !== undefined && !Array.isArray(references)) {
throw new Error('tsconfig.json references must be an array')
}
const typed = (references ?? []) as unknown[]
for (const item of typed) {
if (item === null || Array.isArray(item) || typeof item !== 'object' || typeof (item as { path?: unknown }).path !== 'string') {
throw new Error('tsconfig.json references must contain { path: string } objects')
}
}
if (typed.some(item => (item as { path: string }).path === path)) return
this.text = applyEdits(this.text, modify(
this.text,
['references', typed.length],
{ path },
{ formattingOptions: FORMAT, isArrayInsertion: true },
))
}
/** Validate JSONC and the project-reference shape. */
override validate(): void {
const value = parseConfig(this.text)
if (value.references === undefined) return
if (!Array.isArray(value.references)) throw new Error('tsconfig.json references must be an array')
for (const item of value.references) {
if (item === null || Array.isArray(item) || typeof item !== 'object' || typeof (item as { path?: unknown }).path !== 'string') {
throw new Error('tsconfig.json references must contain { path: string } objects')
}
}
}
/** Return patched JSONC text. */
override serialize(): string {
return withTrailingNewline(this.text)
}
}

View File

@@ -0,0 +1,126 @@
/**
* Required run-interface app feature.
*
* @module @deepseek-ai/dsh-helper/features/builtin/app
*/
import { featureId } from '../../ids.ts'
import type { ProjectProfile } from '../../project/types.ts'
import {
createAppPackageScripts,
createAppProjectArtifacts,
createProjectTemplateContext,
} from '../../templates/project-template.ts'
import {
FeatureOption,
ExclusiveOptionFeature,
} from '../feature.ts'
import { ProjectContribution, type ProjectResource } from '../resources.ts'
import {
npmCordisConfigEntry,
optionalString,
ownedTextFile,
packageScript,
requiredString,
} from './helpers.ts'
const ID = featureId('app')
function appProjectResources(
profile: ProjectProfile,
runInterface: 'acp' | 'stdio' | 'embed',
): readonly ProjectResource[] {
const context = createProjectTemplateContext(profile, runInterface)
const scripts = createAppPackageScripts(context)
return [
...createAppProjectArtifacts(context).map(document => (
ownedTextFile(ID, document.relativePath, document.serialize())
)),
packageScript(ID, 'dev', scripts.dev),
packageScript(ID, 'start', scripts.start),
]
}
class AppOption extends FeatureOption {
override readonly id: 'acp' | 'stdio' | 'embed'
override readonly label: string
constructor(id: 'acp' | 'stdio' | 'embed', label: string) {
super()
this.id = id
this.label = label
}
/** Identify options by their unique front door, not the shared interaction service. */
override markerConfigEntries(): readonly { id: string; name: string }[] {
switch (this.id) {
case 'acp': return [{ id: 'acp', name: '@deepseek-ai/dsh-acp' }]
case 'stdio': return [{ id: 'stdio', name: '@deepseek-ai/dsh-stdio' }]
case 'embed': return []
}
}
/** Embed is identified by the configured loop with no external front door. */
override matchesConfigEntries(entries: readonly { id: string; name: string }[], profile: ProjectProfile): boolean {
if (this.id !== 'embed') return super.matchesConfigEntries(entries, profile)
return entries.some(entry => entry.id === 'agent-loop' && entry.name === '@deepseek-ai/dsh-agent-loop')
&& !entries.some(entry => entry.name === '@deepseek-ai/dsh-acp' || entry.name === '@deepseek-ai/dsh-stdio')
}
override contribution(profile: ProjectProfile): ProjectContribution {
switch (this.id) {
case 'acp':
return new ProjectContribution([
...appProjectResources(profile, this.id),
...npmCordisConfigEntry(ID, {
id: 'user-interaction',
name: '@deepseek-ai/dsh-user-interaction',
}),
...npmCordisConfigEntry(ID, {
id: 'acp',
name: '@deepseek-ai/dsh-acp',
config: { model: profile.runtime.model },
}, ['model'], config => requiredString(config, 'model')),
])
case 'stdio':
return new ProjectContribution([
...appProjectResources(profile, this.id),
...npmCordisConfigEntry(ID, {
id: 'user-interaction',
name: '@deepseek-ai/dsh-user-interaction',
}),
...npmCordisConfigEntry(ID, {
id: 'stdio',
name: '@deepseek-ai/dsh-stdio',
config: {
welcome: 'agent REPL ready. Give it a coding task.',
agent: 'main',
},
}, ['welcome', 'agent'], config => [
...optionalString(config, 'welcome'),
...requiredString(config, 'agent'),
]),
])
case 'embed':
return new ProjectContribution(appProjectResources(profile, this.id))
}
}
}
/** Required app selection represented by acp, stdio, or embed options. */
export class AppFeature extends ExclusiveOptionFeature {
override readonly id = ID
override readonly summary = 'Run interface'
override readonly required = true
override readonly requires = [featureId('spine')]
override readonly options = [
new AppOption('acp', 'ACP server'),
new AppOption('stdio', 'Terminal REPL'),
new AppOption('embed', 'Embedded context'),
]
/** Default to the profile's already selected front door. */
override defaultOptions(profile: ProjectProfile): readonly string[] {
return [profile.runInterface]
}
}

View File

@@ -0,0 +1,111 @@
/**
* Small resource constructors shared by builtin feature modules.
*
* @module @deepseek-ai/dsh-helper/features/builtin/helpers
*/
import type { CordisConfigEntry } from '../../documents/cordis-yaml-file.ts'
import { TextProjectFile } from '../../documents/project-file.ts'
import { resourceKey } from '../../ids.ts'
import type {
CordisConfigEntryResource,
EnvironmentResource,
OwnedFileResource,
NpmDependencyResource,
PackageScriptResource,
} from '../resources.ts'
/** Create a runtime NPM dependency resource. */
function npmDependency(_owner: string, name: string): NpmDependencyResource {
return {
kind: 'npm-dependency',
key: resourceKey(`npm-dependency:${name}`),
name,
section: 'dependencies',
}
}
/** Create a feature-owned package script that is replaceable only while unchanged. */
export function packageScript(_owner: string, name: string, command: string): PackageScriptResource {
return {
kind: 'package-script',
key: resourceKey(`package-script:${name}`),
name,
command,
removeOnlyWhenUnchanged: true,
}
}
/** Create a Cordis config entry resource with explicitly owned config keys. */
export function cordisConfigEntry(
_owner: string,
value: CordisConfigEntry,
ownedConfigKeys: readonly string[] = Object.keys(value.config ?? {}),
validateConfig?: CordisConfigEntryResource['validateConfig'],
): CordisConfigEntryResource {
return {
kind: 'cordis-config-entry',
key: resourceKey(`cordis-config-entry:${value.id}`),
entry: value,
ownedConfigKeys,
...validateConfig ? { validateConfig } : {},
}
}
/** Couple one bare-package Cordis config entry to its mandatory runtime NPM dependency. */
export function npmCordisConfigEntry(
owner: string,
value: CordisConfigEntry,
ownedConfigKeys: readonly string[] = Object.keys(value.config ?? {}),
validateConfig?: CordisConfigEntryResource['validateConfig'],
): readonly [NpmDependencyResource, CordisConfigEntryResource] {
return [
npmDependency(owner, value.name),
cordisConfigEntry(owner, value, ownedConfigKeys, validateConfig),
]
}
/** Create a secret/environment binding resource. */
export function environment(
_owner: string,
name: string,
value: string | undefined,
comment?: string,
): EnvironmentResource {
return {
kind: 'environment',
key: resourceKey(`environment:${name}`),
name,
...value === undefined ? {} : { value },
exampleValue: '',
...comment === undefined ? {} : { comment },
}
}
/** Create an owned complete-text file that is removable only while unchanged. */
export function ownedTextFile(_owner: string, path: string, text: string): OwnedFileResource {
return {
kind: 'owned-file',
key: resourceKey(`file:${path}`),
document: new TextProjectFile(path, text),
removeOnlyWhenUnchanged: true,
}
}
/** Validate a config key as a string when present. */
export function optionalString(config: Readonly<Record<string, unknown>>, key: string): string[] {
return config[key] === undefined || typeof config[key] === 'string' ? [] : [`${key} must be a string`]
}
/** Validate a config key as a non-empty string when required. */
export function requiredString(config: Readonly<Record<string, unknown>>, key: string): string[] {
return typeof config[key] === 'string' && config[key].length > 0 ? [] : [`${key} must be a non-empty string`]
}
/** Validate a config key as an array of strings. */
export function stringArray(config: Readonly<Record<string, unknown>>, key: string): string[] {
const value = config[key]
return Array.isArray(value) && value.every(item => typeof item === 'string')
? []
: [`${key} must be an array of strings`]
}

View File

@@ -0,0 +1,367 @@
/**
* Ordered builtin feature catalog: behavior entities only where project
* context changes the contribution, typed specs everywhere else.
*
* @module @deepseek-ai/dsh-helper/features/builtin
*/
import type { BasicCompactConfig } from '@deepseek-ai/dsh-compact-basic'
import type { Config as ClaudeHooksConfig } from '@deepseek-ai/dsh-hooks-claude'
import type { Config as CodexHooksConfig } from '@deepseek-ai/dsh-hooks-codex'
import type { Config as JsonlConfig } from '@deepseek-ai/dsh-session-persistence-jsonl'
import type { Config as SqliteConfig } from '@deepseek-ai/dsh-session-persistence-sqlite'
import type { Config as ToolSubagentConfig } from '@deepseek-ai/dsh-tool-subagent'
import type { Config as ToolWebConfig } from '@deepseek-ai/dsh-tool-web'
import type { ProjectProfile } from '../../project/types.ts'
import { defineFeatures } from '../define-feature.ts'
import { FeatureRegistry } from '../registry.ts'
import { AppFeature } from './app.ts'
import { ProviderFeature } from './provider.ts'
import { SpineFeature } from './spine.ts'
const compactPreset = {
contextWindow: 128_000,
thresholdRatio: 0.8,
retainTokens: 20_480,
summarizationModel: '',
maxTokens: 8_192,
compactionRetries: 1,
} satisfies BasicCompactConfig
/**
* Build and definition-check the complete builtin set for one project profile.
* @param profile - project context used to validate conditional contributions.
* @returns ordered builtin feature registry.
*/
export function createBuiltinRegistry(profile: ProjectProfile): FeatureRegistry {
return new FeatureRegistry(defineFeatures([
new ProviderFeature(),
new SpineFeature(),
{
id: 'bash',
summary: 'Command execution',
mode: 'exclusive',
required: true,
baseResources: [{ kind: 'npm-cordis-config-entry', id: 'tool-bash', package: '@deepseek-ai/dsh-tool-bash' }],
options: [
{
id: 'local',
label: 'Local executor',
default: true,
resources: [{ kind: 'npm-cordis-config-entry', id: 'bash', package: '@deepseek-ai/dsh-bash-local' }],
},
{
id: 'sandbox',
label: 'Sandboxed executor',
resources: [
{ kind: 'npm-cordis-config-entry', id: 'sandbox', package: '@deepseek-ai/dsh-sandbox-local' },
{
kind: 'npm-cordis-config-entry',
id: 'bash',
package: '@deepseek-ai/dsh-bash-sandbox',
commentedExample: `Uncomment to allow writes under the project workspace.
config:
mode: workspace-write
workspaceRoot: !!js process.cwd()`,
},
],
},
],
},
new AppFeature(),
{
id: 'persistence',
summary: 'Durable session storage',
mode: 'exclusive',
required: true,
options: [
{
id: 'jsonl',
label: 'JSONL files',
default: true,
resources: [{
kind: 'npm-cordis-config-entry',
id: 'session-persistence',
package: '@deepseek-ai/dsh-session-persistence-jsonl',
config: { root: './.sessions' } satisfies JsonlConfig,
}],
},
{
id: 'sqlite',
label: 'SQLite database',
resources: [{
kind: 'npm-cordis-config-entry',
id: 'session-persistence',
package: '@deepseek-ai/dsh-session-persistence-sqlite',
config: { path: './.sessions/sessions.sqlite' } satisfies SqliteConfig,
}],
},
],
},
{
id: 'hmr',
summary: 'Hot-module reload',
mode: 'single',
options: [{
id: 'default',
label: 'Cordis HMR',
default: true,
resources: [{ kind: 'npm-cordis-config-entry', id: 'hmr', package: '@cordisjs/plugin-hmr' }],
}],
},
{
id: 'fs',
summary: 'Read, write, and edit local files',
mode: 'single',
options: [{
id: 'local',
label: 'Local filesystem',
default: true,
resources: [
{ kind: 'npm-cordis-config-entry', id: 'fs-local', package: '@deepseek-ai/dsh-fs-local' },
{ kind: 'npm-cordis-config-entry', id: 'fs-policy', package: '@deepseek-ai/dsh-fs-policy' },
{ kind: 'npm-cordis-config-entry', id: 'tool-fs', package: '@deepseek-ai/dsh-tool-fs' },
],
}],
},
{
id: 'todo',
summary: 'Model-facing task tracking',
mode: 'single',
options: [{
id: 'default',
label: 'todo_write tool',
default: true,
resources: [{ kind: 'npm-cordis-config-entry', id: 'tool-todo', package: '@deepseek-ai/dsh-tool-todo' }],
}],
},
{
id: 'skill',
summary: 'Local skill discovery',
mode: 'single',
options: [{
id: 'default',
label: 'Local skills and skill tool',
default: true,
resources: [
{ kind: 'npm-cordis-config-entry', id: 'skill', package: '@deepseek-ai/dsh-skill' },
{ kind: 'npm-cordis-config-entry', id: 'skill-local', package: '@deepseek-ai/dsh-skill-local' },
{ kind: 'npm-cordis-config-entry', id: 'tool-skill', package: '@deepseek-ai/dsh-tool-skill' },
],
}],
},
{
id: 'web',
summary: 'Web search and fetch tools',
mode: 'exclusive',
suggests: ['timeout-policy'],
baseResources: [
{ kind: 'npm-cordis-config-entry', id: 'web', package: '@deepseek-ai/dsh-web' },
{ kind: 'npm-cordis-config-entry', id: 'web-fetch-local', package: '@deepseek-ai/dsh-web-fetch-local' },
],
options: [
{
id: 'deepseek',
label: 'DeepSeek search',
default: true,
markers: [{ id: 'web-search-deepseek', name: '@deepseek-ai/dsh-web-search-deepseek' }],
resources: [
{ kind: 'npm-cordis-config-entry', id: 'web-search-deepseek', package: '@deepseek-ai/dsh-web-search-deepseek' },
{ kind: 'npm-cordis-config-entry', id: 'tool-web', package: '@deepseek-ai/dsh-tool-web' },
],
},
{
id: 'exa',
label: 'Exa search',
secrets: [{ id: 'apiKey', environment: 'EXA_API_KEY', message: 'Exa API key', required: true }],
markers: [{ id: 'web-search-exa', name: '@deepseek-ai/dsh-web-search-exa' }],
resources: [
{ kind: 'npm-cordis-config-entry', id: 'web-search-exa', package: '@deepseek-ai/dsh-web-search-exa' },
{ kind: 'npm-cordis-config-entry', id: 'tool-web', package: '@deepseek-ai/dsh-tool-web' },
],
},
{
id: 'perplexity',
label: 'Perplexity search',
secrets: [{
id: 'apiKey',
environment: 'PERPLEXITY_API_KEY',
message: 'Perplexity API key',
required: true,
}],
markers: [{ id: 'web-search-perplexity', name: '@deepseek-ai/dsh-web-search-perplexity' }],
resources: [
{
kind: 'npm-cordis-config-entry',
id: 'web-search-perplexity',
package: '@deepseek-ai/dsh-web-search-perplexity',
},
{ kind: 'npm-cordis-config-entry', id: 'tool-web', package: '@deepseek-ai/dsh-tool-web' },
],
},
{
id: 'fetch-only',
label: 'Fetch only',
markers: [{ id: 'tool-web', name: '@deepseek-ai/dsh-tool-web', config: { search: false } }],
resources: [{
kind: 'npm-cordis-config-entry',
id: 'tool-web',
package: '@deepseek-ai/dsh-tool-web',
config: { search: false } satisfies ToolWebConfig,
}],
},
],
},
{
id: 'subagent',
summary: 'Delegate work to child agents',
mode: 'multiple',
baseResources: [{ kind: 'npm-cordis-config-entry', id: 'subagent', package: '@deepseek-ai/dsh-subagent' }],
options: [
{
id: 'spawn',
label: 'Fresh child agent',
default: true,
resources: [
{ kind: 'npm-cordis-config-entry', id: 'subagent-spawn', package: '@deepseek-ai/dsh-subagent-spawn' },
{
kind: 'npm-cordis-config-entry',
id: 'tool-subagent',
package: '@deepseek-ai/dsh-tool-subagent',
config: { provider: 'spawn' } satisfies ToolSubagentConfig,
},
],
},
{
id: 'fork',
label: 'Fork parent history',
resources: [
{ kind: 'npm-cordis-config-entry', id: 'subagent-fork', package: '@deepseek-ai/dsh-subagent-fork' },
{
kind: 'npm-cordis-config-entry',
id: 'tool-subagent-fork',
package: '@deepseek-ai/dsh-tool-subagent',
config: { provider: 'fork', toolName: 'subagent_fork' } satisfies ToolSubagentConfig,
},
],
},
],
},
{
id: 'workflow',
summary: 'Scripted multi-agent workflows',
mode: 'single',
options: [{
id: 'workerthread',
label: 'Worker thread engine',
default: true,
requires: [{ id: 'subagent', options: ['spawn'] }],
resources: [
{
kind: 'npm-cordis-config-entry',
id: 'workflow-workerthread',
package: '@deepseek-ai/dsh-workflow-workerthread',
},
{ kind: 'npm-cordis-config-entry', id: 'tool-workflow', package: '@deepseek-ai/dsh-tool-workflow' },
],
}],
},
{
id: 'compact',
summary: 'Automatic context compaction',
mode: 'single',
options: [{
id: 'basic',
label: 'Basic compaction',
default: true,
resources: [{
kind: 'npm-cordis-config-entry',
id: 'compact-basic',
package: '@deepseek-ai/dsh-compact-basic',
config: compactPreset,
}],
}],
},
{
id: 'hooks',
summary: 'Run Claude Code or Codex hooks',
mode: 'multiple',
requires: [{ id: 'bash' }],
options: [
{
id: 'claude',
label: 'Claude Code hooks',
default: true,
resources: [
{
kind: 'npm-cordis-config-entry',
id: 'hooks-claude',
package: '@deepseek-ai/dsh-hooks-claude',
config: { configPath: './hooks.json' } satisfies ClaudeHooksConfig,
},
{ kind: 'owned-file', path: 'hooks.json', text: '{}' },
],
},
{
id: 'codex',
label: 'Codex hooks',
resources: [
{
kind: 'npm-cordis-config-entry',
id: 'hooks-codex',
package: '@deepseek-ai/dsh-hooks-codex',
config: { configPath: './codex-hooks.json' } satisfies CodexHooksConfig,
},
{ kind: 'owned-file', path: 'codex-hooks.json', text: '{}' },
],
},
],
},
{
id: 'guard',
summary: 'Loop-hygiene reminders',
mode: 'single',
options: [{
id: 'repeat-tool',
label: 'Repeat-tool reminders',
default: true,
resources: [{
kind: 'npm-cordis-config-entry',
id: 'repeat-tool-guard',
package: '@deepseek-ai/dsh-repeat-tool-guard',
}],
}],
},
{
id: 'timeout-policy',
summary: 'Tool timeout policy',
mode: 'single',
options: [{
id: 'default',
label: 'Timeout policy',
default: true,
resources: [{
kind: 'npm-cordis-config-entry',
id: 'timeout-policy',
package: '@deepseek-ai/dsh-timeout-policy',
}],
}],
},
{
id: 'ask-user',
summary: 'Ask the user from the model loop',
mode: 'single',
supportedInterfaces: ['acp', 'stdio'],
options: [{
id: 'default',
label: 'ask_user_question tool',
default: true,
resources: [{
kind: 'npm-cordis-config-entry',
id: 'tool-ask-user',
package: '@deepseek-ai/dsh-tool-ask-user',
}],
}],
},
]), profile)
}

View File

@@ -0,0 +1,111 @@
/**
* Required hand-rolled DeepSeek and custom pi-ai provider behavior.
*
* @module @deepseek-ai/dsh-helper/features/builtin/provider
*/
import { JsExpression } from '../../documents/cordis-yaml-file.ts'
import { featureId } from '../../ids.ts'
import type { FeatureSelection, ProjectProfile } from '../../project/types.ts'
import {
FeatureOption,
ExclusiveOptionFeature,
type FeatureProjectView,
} from '../feature.ts'
import { ProjectContribution } from '../resources.ts'
import { npmCordisConfigEntry, environment } from './helpers.ts'
const ID = featureId('provider')
const DEFAULT_MODEL = 'deepseek-v4-flash'
const API_KEY_COMMENT = 'Required before start; an empty value makes provider startup fail.'
class DeepSeekOption extends FeatureOption {
override readonly id = 'deepseek'
override readonly label = 'DeepSeek'
override readonly secrets = [{
id: 'apiKey',
environment: 'DEEPSEEK_API_KEY',
message: 'DeepSeek API key',
required: true,
}]
override contribution(_profile: ProjectProfile, secrets: Readonly<Record<string, string>>): ProjectContribution {
return new ProjectContribution([
...npmCordisConfigEntry(ID, {
id: 'llm-deepseek',
name: '@deepseek-ai/dsh-llm-deepseek',
config: { apiKey: new JsExpression('process.env.DEEPSEEK_API_KEY') },
}, ['apiKey', 'baseURL', 'models']),
environment(ID, 'DEEPSEEK_API_KEY', secrets.apiKey, API_KEY_COMMENT),
])
}
}
class CustomOption extends FeatureOption {
override readonly id = 'custom'
override readonly label = 'Custom endpoint (pi-ai)'
override readonly secrets = [{
id: 'apiKey',
environment: 'DEEPSEEK_API_KEY',
message: 'Custom provider API key',
required: true,
}]
override readonly inputs = [{
id: 'baseURL',
message: 'Custom provider base URL',
}]
override contribution(_profile: ProjectProfile, secrets: Readonly<Record<string, string>>): ProjectContribution {
return new ProjectContribution([
...npmCordisConfigEntry(ID, {
id: 'llm-pi-ai',
name: '@deepseek-ai/dsh-llm-pi-ai',
config: { apiKey: new JsExpression('process.env.DEEPSEEK_API_KEY') },
}, ['apiKey', 'baseURL', 'models']),
environment(ID, 'DEEPSEEK_API_KEY', secrets.apiKey, API_KEY_COMMENT),
])
}
}
/** Required provider feature with DeepSeek and custom pi-ai options. */
export class ProviderFeature extends ExclusiveOptionFeature {
override readonly id = ID
override readonly summary = 'Model provider'
override readonly required = true
override readonly options = [new DeepSeekOption(), new CustomOption()]
/** Prefer the hand-rolled adapter and its public endpoint defaults. */
override defaultOptions(): readonly string[] {
return ['deepseek']
}
/** Recover literal endpoint overrides from either provider entry. */
override readSelection(project: FeatureProjectView, selection: FeatureSelection): FeatureSelection {
const base = super.readSelection(project, selection)
const entry = project.cordisConfigEntries().find(item => item.id === 'llm-deepseek' || item.id === 'llm-pi-ai')
const baseURL = entry?.config?.baseURL
return typeof baseURL === 'string' ? { ...base, values: { baseURL } } : base
}
/** Apply explicit endpoint/model overrides while omitting provider defaults. */
override contribution(selection: FeatureSelection, profile: ProjectProfile): ProjectContribution {
const contribution = super.contribution(selection, profile)
const baseURL = selection.values?.baseURL
if (baseURL !== undefined && typeof baseURL !== 'string') throw new Error('provider baseURL must be a string')
return new ProjectContribution(contribution.resources.map((resource) => {
if (resource.kind !== 'cordis-config-entry' || (resource.entry.id !== 'llm-deepseek'
&& resource.entry.id !== 'llm-pi-ai')) return resource
return {
...resource,
entry: {
...resource.entry,
config: {
...resource.entry.config,
...baseURL ? { baseURL } : {},
...profile.runtime.model === DEFAULT_MODEL ? {} : { models: [profile.runtime.model] },
},
},
}
}))
}
}

View File

@@ -0,0 +1,55 @@
/**
* Required agent-spine feature expressed as top-level Cordis config entries.
*
* @module @deepseek-ai/dsh-helper/features/builtin/spine
*/
import { featureId } from '../../ids.ts'
import type { ProjectProfile } from '../../project/types.ts'
import { loadHelperTemplate } from '../../templates/template-assets.ts'
import { FeatureOption, FixedFeature } from '../feature.ts'
import { ProjectContribution } from '../resources.ts'
import { npmCordisConfigEntry, requiredString } from './helpers.ts'
const ID = featureId('spine')
const PERSONA = loadHelperTemplate<Record<string, never>>('persona.txt.tpl').render({}).trimEnd()
function emptyAgentsDiagnostics(config: Readonly<Record<string, unknown>>): string[] {
const agents = config.agents
if (!Array.isArray(agents)) return ['agents must be an array']
return agents.length === 0 ? [] : ['agents must be empty']
}
class SpineOption extends FeatureOption {
override readonly id = 'default'
override readonly label = 'Default agent spine'
override contribution(_profile: ProjectProfile): ProjectContribution {
return new ProjectContribution([
...npmCordisConfigEntry(ID, { id: 'timer', name: '@cordisjs/plugin-timer' }),
...npmCordisConfigEntry(ID, { id: 'llm', name: '@deepseek-ai/dsh-llm' }),
...npmCordisConfigEntry(ID, { id: 'session', name: '@deepseek-ai/dsh-session' }),
...npmCordisConfigEntry(ID, {
id: 'system-prompt',
name: '@deepseek-ai/dsh-system-prompt',
config: { persona: PERSONA },
}, ['persona'], config => requiredString(config, 'persona')),
...npmCordisConfigEntry(ID, { id: 'tools', name: '@deepseek-ai/dsh-tools' }, []),
...npmCordisConfigEntry(ID, { id: 'agent', name: '@deepseek-ai/dsh-agent' }),
...npmCordisConfigEntry(ID, { id: 'invariants', name: '@deepseek-ai/dsh-invariants' }),
...npmCordisConfigEntry(ID, {
id: 'agent-loop',
name: '@deepseek-ai/dsh-agent-loop',
config: { agents: [] },
}, ['agents'], emptyAgentsDiagnostics),
])
}
}
/** Required providerless agent spine without a composition bundle entry. */
export class SpineFeature extends FixedFeature {
override readonly id = ID
override readonly summary = 'Agent runtime spine'
override readonly required = true
override readonly options = [new SpineOption()]
}

View File

@@ -0,0 +1,286 @@
/**
* Typed declarative definitions for features whose behavior is entirely
* the shared resource lifecycle.
*
* @module @deepseek-ai/dsh-helper/features/define-feature
*/
import type { CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
import { TextProjectFile } from '../documents/project-file.ts'
import { featureId, resourceKey, type FeatureId } from '../ids.ts'
import type { FeatureSelection, ProjectProfile, RunInterface } from '../project/types.ts'
import {
Feature,
FeatureOption,
type FeatureRequirement,
type FeatureSecret,
} from './feature.ts'
import { ProjectContribution, type ProjectResource } from './resources.ts'
/** Static NPM dependency in a declarative feature. */
interface NpmDependencySpec {
kind: 'npm-dependency'
name: string
section?: 'dependencies' | 'devDependencies'
}
/** Bare-package Cordis config entry that also contributes its NPM dependency. */
interface NpmCordisConfigEntrySpec {
kind: 'npm-cordis-config-entry'
id: string
package: string
config?: Readonly<Record<string, unknown>>
ownedConfigKeys?: readonly string[]
commentedExample?: string
}
/** Relative or absolute file Cordis config entry with no NPM dependency. */
interface FileCordisConfigEntrySpec {
kind: 'file-cordis-config-entry'
id: string
path: string
config?: Readonly<Record<string, unknown>>
ownedConfigKeys?: readonly string[]
commentedExample?: string
}
/** Static complete file owned by one feature option. */
interface OwnedFileSpec {
kind: 'owned-file'
path: string
text: string
removeOnlyWhenUnchanged?: boolean
}
/** Resource forms that require no feature-specific imperative code. */
type FeatureResourceSpec =
| NpmDependencySpec
| NpmCordisConfigEntrySpec
| FileCordisConfigEntrySpec
| OwnedFileSpec
/** Cordis config entry identity and optional plugin-config subset that identifies an option. */
interface FeatureOptionMarkerSpec {
id: string
name: string
config?: Readonly<Record<string, unknown>>
}
/** Declarative requirement converted to branded domain identity at the boundary. */
interface FeatureRequirementSpec {
id: string
options?: readonly string[]
}
/** One static option inside a typed feature definition. */
interface FeatureOptionSpec {
id: string
label: string
default?: boolean
resources: readonly FeatureResourceSpec[]
secrets?: readonly FeatureSecret[]
markers?: readonly FeatureOptionMarkerSpec[]
requires?: readonly FeatureRequirementSpec[]
}
/** Complete declarative feature definition. */
export interface FeatureSpec {
id: string
summary: string
mode: 'single' | 'exclusive' | 'multiple'
options: readonly FeatureOptionSpec[]
baseResources?: readonly FeatureResourceSpec[]
required?: boolean
requires?: readonly FeatureRequirementSpec[]
suggests?: readonly string[]
supportedInterfaces?: readonly RunInterface[]
}
function sameShape(expected: unknown, actual: unknown): boolean {
if (expected === null || actual === null) return expected === actual
if (Array.isArray(expected)) {
return Array.isArray(actual) && (expected.length === 0 || actual.every(item => sameShape(expected[0], item)))
}
if (typeof expected !== 'object') return typeof expected === typeof actual
if (typeof actual !== 'object' || Array.isArray(actual)) return false
return Object.entries(expected as Record<string, unknown>).every(
([key, value]) => sameShape(value, (actual as Record<string, unknown>)[key]),
)
}
function configDiagnostics(
expected: Readonly<Record<string, unknown>> | undefined,
): ((config: Readonly<Record<string, unknown>>) => readonly string[]) | undefined {
if (!expected || Object.keys(expected).length === 0) return undefined
return config => Object.entries(expected).flatMap(([key, value]) => sameShape(value, config[key])
? []
: [`${key} has an incompatible value shape`])
}
function resourcesFromSpec(spec: FeatureResourceSpec): ProjectResource[] {
switch (spec.kind) {
case 'npm-dependency':
return [{
kind: 'npm-dependency',
key: resourceKey(`npm-dependency:${spec.name}`),
name: spec.name,
section: spec.section ?? 'dependencies',
}]
case 'npm-cordis-config-entry':
case 'file-cordis-config-entry': {
const config = spec.config ? { ...spec.config } : undefined
const validateConfig = configDiagnostics(config)
const name = spec.kind === 'npm-cordis-config-entry' ? spec.package : spec.path
return [
...spec.kind === 'npm-cordis-config-entry'
? [{
kind: 'npm-dependency' as const,
key: resourceKey(`npm-dependency:${spec.package}`),
name: spec.package,
section: 'dependencies' as const,
}]
: [],
{
kind: 'cordis-config-entry',
key: resourceKey(`cordis-config-entry:${spec.id}`),
entry: {
id: spec.id,
name,
...config ? { config } : {},
},
ownedConfigKeys: spec.ownedConfigKeys ?? Object.keys(config ?? {}),
...spec.commentedExample ? { commentedExample: spec.commentedExample } : {},
...validateConfig ? { validateConfig } : {},
},
]
}
case 'owned-file':
return [{
kind: 'owned-file',
key: resourceKey(`file:${spec.path}`),
document: new TextProjectFile(spec.path, spec.text),
removeOnlyWhenUnchanged: spec.removeOnlyWhenUnchanged ?? true,
}]
}
}
function isSubset(expected: Readonly<Record<string, unknown>>, actual: Readonly<Record<string, unknown>>): boolean {
return Object.entries(expected).every(([key, value]) => Object.is(actual[key], value))
}
class DefinedFeatureOption extends FeatureOption {
override readonly id: string
override readonly label: string
override readonly secrets: readonly FeatureSecret[]
private readonly spec: FeatureOptionSpec
constructor(spec: FeatureOptionSpec) {
super()
this.spec = spec
this.id = spec.id
this.label = spec.label
this.secrets = spec.secrets ?? []
}
override contribution(_profile: ProjectProfile, secrets: Readonly<Record<string, string>>): ProjectContribution {
return new ProjectContribution([
...this.spec.resources.flatMap(resourcesFromSpec),
...this.secrets.map(secret => ({
kind: 'environment' as const,
key: resourceKey(`environment:${secret.environment}`),
name: secret.environment,
...secrets[secret.id] === undefined ? {} : { value: secrets[secret.id] },
exampleValue: '',
})),
])
}
override markerConfigEntries(): readonly Pick<CordisConfigEntry, 'id' | 'name'>[] {
const markers = this.spec.markers ?? this.spec.resources.flatMap((resource) => {
switch (resource.kind) {
case 'npm-cordis-config-entry': return [{ id: resource.id, name: resource.package }]
case 'file-cordis-config-entry': return [{ id: resource.id, name: resource.path }]
default: return []
}
})
return markers.map(marker => ({ id: marker.id, name: marker.name }))
}
override matchesConfigEntries(entries: readonly CordisConfigEntry[]): boolean {
const markers = this.spec.markers
if (!markers) return this.markerConfigEntries().some(marker => entries.some(
entry => entry.id === marker.id && entry.name === marker.name,
))
return markers.some(marker => entries.some(entry => entry.id === marker.id
&& entry.name === marker.name
&& (!marker.config || isSubset(marker.config, entry.config ?? {}))))
}
}
/** Feature entity backed by a typed static definition. */
class DefinedFeature extends Feature {
override readonly id: FeatureId
override readonly summary: string
override readonly mode: FeatureSpec['mode']
override readonly options: readonly FeatureOption[]
override readonly required: boolean
override readonly requires: readonly FeatureId[]
override readonly suggests: readonly FeatureId[]
override readonly supportedInterfaces: readonly RunInterface[]
private readonly spec: FeatureSpec
/** Validate and materialize one declarative definition. */
constructor(spec: FeatureSpec) {
super()
this.spec = spec
this.id = featureId(spec.id)
this.summary = spec.summary
this.mode = spec.mode
this.options = spec.options.map(option => new DefinedFeatureOption(option))
const defaultCount = spec.options.filter(option => option.default).length
if (spec.mode === 'single' && (spec.options.length !== 1 || defaultCount !== 1)) {
throw new Error(`single feature ${spec.id} requires one default option`)
}
if (spec.mode === 'exclusive' && defaultCount !== 1) {
throw new Error(`exclusive feature ${spec.id} requires exactly one default option`)
}
if (spec.mode === 'multiple' && defaultCount === 0) {
throw new Error(`multiple feature ${spec.id} requires at least one default option`)
}
this.required = spec.required ?? false
this.requires = (spec.requires ?? []).map(requirement => featureId(requirement.id))
this.suggests = (spec.suggests ?? []).map(featureId)
this.supportedInterfaces = spec.supportedInterfaces ?? ['acp', 'stdio', 'embed']
}
override defaultOptions(): readonly string[] {
return this.spec.options.filter(option => option.default).map(option => option.id)
}
override baseContribution(): ProjectContribution {
return new ProjectContribution((this.spec.baseResources ?? []).flatMap(resourcesFromSpec))
}
override requirements(selection: FeatureSelection): readonly FeatureRequirement[] {
const selected = new Set(selection.options)
return [
...(this.spec.requires ?? []),
...this.spec.options.filter(option => selected.has(option.id)).flatMap(option => option.requires ?? []),
].map(requirement => ({
id: featureId(requirement.id),
...requirement.options ? { options: requirement.options } : {},
}))
}
}
/** Construct the shared lifecycle entity from a typed declarative definition. */
export function defineFeature(spec: FeatureSpec): Feature {
return new DefinedFeature(spec)
}
/** Materialize one ordered catalog containing static specs and behavior entities. */
export function defineFeatures(definitions: readonly (Feature | FeatureSpec)[]): Feature[] {
return definitions.map(definition => definition instanceof Feature
? definition
: defineFeature(definition))
}

View File

@@ -0,0 +1,104 @@
/**
* Shared option and secret question flow for create and config.
*
* @module @deepseek-ai/dsh-helper/features/feature-configurator
*/
import type { Feature } from './feature.ts'
import type { FeatureSelection, ProjectProfile } from '../project/types.ts'
import type { PromptPort } from '../questions/prompt-port.ts'
import { requireAnswer } from '../questions/prompt-port.ts'
import { MultiSelectQuestion, SecretQuestion, SelectQuestion, TextQuestion } from '../questions/question.ts'
/** Resolve one feature selection without knowing which workflow requested it. */
export class FeatureConfigurator {
private readonly port: PromptPort
/** Bind the configurator to the shared prompt boundary. */
constructor(port: PromptPort) {
this.port = port
}
/**
* Ask option and input questions, preserving current secrets on empty input.
* @param feature - feature whose options and inputs are collected.
* @param profile - target project context.
* @param current - currently installed selection, when configuring.
* @param prefilledOptions - options already chosen by a tree picker.
* @param prefilledSecrets - non-interactive secret values supplied by creation.
* @returns normalized selection with captured values and secrets.
*/
async configure(
feature: Feature,
profile: ProjectProfile,
current?: FeatureSelection,
prefilledOptions?: readonly string[],
prefilledSecrets: Readonly<Record<string, string>> = {},
): Promise<FeatureSelection> {
let options: readonly string[]
switch (feature.mode) {
case 'single':
options = feature.defaultOptions(profile)
break
case 'exclusive': {
const initialValue = current?.options[0] ?? feature.defaultOptions(profile)[0]
if (initialValue === undefined) throw new Error(`feature ${feature.id} has no default option`)
const question = new SelectQuestion({
id: `${feature.id}.option`,
message: `Choose ${feature.summary.toLowerCase()}`,
options: feature.options.map(option => ({ value: option.id, label: option.label })),
initialValue,
})
const prefilled = prefilledOptions?.[0]
options = [requireAnswer(await question.resolve(this.port, prefilled))]
break
}
case 'multiple': {
const question = new MultiSelectQuestion({
id: `${feature.id}.options`,
message: `Choose ${feature.summary.toLowerCase()}`,
options: feature.options.map(option => ({ value: option.id, label: option.label })),
initialValues: current?.options ?? feature.defaultOptions(profile),
required: true,
})
options = requireAnswer(await question.resolve(this.port, prefilledOptions))
break
}
}
const selected: FeatureSelection = {
id: feature.id,
options,
}
const values: Record<string, string> = {}
for (const input of feature.valueInputs(selected, profile)) {
const existing = current?.values?.[input.id]
if (existing !== undefined && typeof existing !== 'string') {
throw new Error(`${feature.id}.${input.id} current value must be a string`)
}
const question = new TextQuestion({
id: `${feature.id}.${input.id}`,
message: input.message,
...existing === undefined ? {} : { initialValue: existing },
validate: value => value.trim().length === 0 ? 'A value is required' : undefined,
})
values[input.id] = requireAnswer(await question.resolve(this.port))
}
const base: FeatureSelection = Object.keys(values).length === 0
? selected
: { ...selected, values }
const secrets = { ...current?.secrets }
for (const secret of feature.secrets(base, profile)) {
const existing = secrets[secret.id]
const question = new SecretQuestion({
id: `${feature.id}.${secret.id}`,
message: existing === undefined ? secret.message : `${secret.message} (leave empty to keep current)`,
validate: value => secret.required && existing === undefined && value.length === 0
? 'A value is required'
: undefined,
})
const answer = requireAnswer(await question.resolve(this.port, prefilledSecrets[secret.id]))
if (answer.length > 0) secrets[secret.id] = answer
}
return Object.keys(secrets).length === 0 ? base : { ...base, secrets }
}
}

View File

@@ -0,0 +1,345 @@
/**
* Stateful builtin feature and option domain objects.
*
* @module @deepseek-ai/dsh-helper/features/feature
*/
import type { CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
import type { PackageManifest } from '../documents/package-json-file.ts'
import type { FeatureId } from '../ids.ts'
import type { FeatureSelection, ProjectProfile, RunInterface } from '../project/types.ts'
import { ProjectContribution, type CordisConfigEntryResource, type ProjectResource } from './resources.ts'
/** Read-only project surface used by feature inspection. */
export interface FeatureProjectView {
readonly profile: ProjectProfile
cordisConfigEntries(): readonly CordisConfigEntry[]
packageManifest(): Readonly<PackageManifest>
hasDocument(path: string): boolean
readEnvironment(path: '.env' | '.env.example', name: string): string | undefined
}
/** Installation state visible to create/config workflows. */
type FeatureInstallationState = 'absent' | 'enabled' | 'disabled' | 'inconsistent'
/** Result of round-tripping one feature from a project snapshot. */
export interface FeatureInstallation {
id: FeatureId
state: FeatureInstallationState
options: readonly string[]
selection?: FeatureSelection
diagnostics: readonly string[]
}
/** One final-state requirement on another builtin feature. */
export interface FeatureRequirement {
id: FeatureId
options?: readonly string[]
}
/** One secret captured into an environment binding rather than Cordis plugin config. */
export interface FeatureSecret {
id: string
environment: string
message: string
required: boolean
}
/** One visible string value requested only by options that own it. */
export interface FeatureValueInput {
id: string
message: string
}
/** One selectable behavior option owned by a feature. */
export abstract class FeatureOption {
abstract readonly id: string
abstract readonly label: string
readonly secrets: readonly FeatureSecret[] = []
readonly inputs: readonly FeatureValueInput[] = []
/** Contribute this option's project resources. */
abstract contribution(profile: ProjectProfile, secrets: Readonly<Record<string, string>>): ProjectContribution
/** Every Cordis config entry package owned by this option during inspection. */
ownedConfigEntries(profile: ProjectProfile): readonly Pick<CordisConfigEntry, 'id' | 'name'>[] {
return this.contribution(profile, {}).resources
.filter((resource): resource is CordisConfigEntryResource => resource.kind === 'cordis-config-entry')
.map(resource => ({ id: resource.entry.id, name: resource.entry.name }))
}
/** Cordis config entry identities that distinguish this option during inspection. */
markerConfigEntries(profile: ProjectProfile): readonly Pick<CordisConfigEntry, 'id' | 'name'>[] {
return this.ownedConfigEntries(profile)
}
/** Whether current owned Cordis config entries identify this option. */
matchesConfigEntries(entries: readonly CordisConfigEntry[], profile: ProjectProfile): boolean {
return this.markerConfigEntries(profile).some(marker => entries.some(
entry => entry.id === marker.id && entry.name === marker.name,
))
}
}
/** How a feature's options compose. */
export type FeatureOptionMode = 'single' | 'exclusive' | 'multiple'
function packageNames(resources: readonly ProjectResource[]): Set<string> {
return new Set(resources
.filter((resource): resource is CordisConfigEntryResource => resource.kind === 'cordis-config-entry')
.map(resource => resource.entry.name))
}
function configDiagnostics(resource: CordisConfigEntryResource, entry: CordisConfigEntry): string[] {
/* v8 ignore next -- entries without validators have no diagnostics to compute */
if (!resource.validateConfig) return []
return [...resource.validateConfig(entry.config ?? {})].map(message => `${entry.id}: ${message}`)
}
/** A behavior-owning builtin feature with shallow option composition. */
export abstract class Feature {
/** Stable registry identity. */
abstract readonly id: FeatureId
/** User-facing feature summary. */
abstract readonly summary: string
/** Option-selection rule. */
abstract readonly mode: FeatureOptionMode
/** Available behavior options. */
abstract readonly options: readonly FeatureOption[]
/** Whether every valid project must enable this feature. */
readonly required: boolean = false
/** Unconditional feature requirements. */
readonly requires: readonly FeatureId[] = []
/** Features recommended during creation. */
readonly suggests: readonly FeatureId[] = []
/** Front doors under which this feature is meaningful. */
readonly supportedInterfaces: readonly RunInterface[] = ['acp', 'stdio', 'embed']
/**
* Options selected when installation has no override.
* @param profile - project context controlling applicable defaults.
* @returns selected option ids.
*/
abstract defaultOptions(profile: ProjectProfile): readonly string[]
/**
* Shared resources present for every installed option set.
* @param _profile - project context available to behavior features.
* @returns shared project contribution.
*/
baseContribution(_profile: ProjectProfile): ProjectContribution {
return new ProjectContribution([])
}
/**
* Additional final-state requirements depending on selected options.
* @param _selection - normalized feature selection.
* @returns required features and option constraints.
*/
requirements(_selection: FeatureSelection): readonly FeatureRequirement[] {
return this.requires.map(id => ({ id }))
}
/**
* Whether the feature may be selected for this project front door.
* @param profile - project context to check.
* @returns whether the feature applies.
*/
isApplicable(profile: ProjectProfile): boolean {
return this.supportedInterfaces.includes(profile.runInterface)
}
/**
* Validate and normalize one requested option set.
* @param selection - requested feature and options.
* @param profile - project context for applicability and defaults.
* @returns deduplicated, sorted selection.
*/
normalizeSelection(selection: FeatureSelection, profile: ProjectProfile): FeatureSelection {
if (selection.id !== this.id) throw new Error(`selection ${selection.id} does not belong to feature ${this.id}`)
if (!this.isApplicable(profile)) {
throw new Error(`feature ${this.id} is not available for ${profile.runInterface}`)
}
const available = new Set(this.options.map(option => option.id))
const options = [...new Set(selection.options.length > 0 ? selection.options : this.defaultOptions(profile))]
for (const option of options) {
if (!available.has(option)) throw new Error(`unknown ${this.id} option: ${option}`)
}
if (this.mode === 'single' && (options.length !== 1 || this.options.length !== 1)) {
throw new Error(`feature ${this.id} has one fixed option`)
}
if (this.mode === 'exclusive' && options.length !== 1) {
throw new Error(`feature ${this.id} requires exactly one option`)
}
if (this.mode === 'multiple' && options.length === 0) {
throw new Error(`feature ${this.id} requires at least one option`)
}
return { ...selection, options: options.sort() }
}
/**
* Build the complete selected resource contribution.
* @param selection - selected options and captured inputs.
* @param profile - target project context.
* @returns merged base and option resources.
*/
contribution(selection: FeatureSelection, profile: ProjectProfile): ProjectContribution {
const normalized = this.normalizeSelection(selection, profile)
const selected = this.selectedOptions(normalized)
.map(option => option.contribution(profile, normalized.secrets ?? {}))
return ProjectContribution.merge(this.baseContribution(profile), ...selected)
}
/**
* All secret definitions required by one selected option set.
* @param selection - selected options.
* @param profile - target project context.
* @returns selected secret definitions.
*/
secrets(selection: FeatureSelection, profile: ProjectProfile): readonly FeatureSecret[] {
const normalized = this.normalizeSelection(selection, profile)
return this.selectedOptions(normalized).flatMap(option => option.secrets)
}
/**
* All visible value definitions required by one selected option set.
* @param selection - selected options.
* @param profile - target project context.
* @returns selected visible-input definitions.
*/
valueInputs(selection: FeatureSelection, profile: ProjectProfile): readonly FeatureValueInput[] {
const normalized = this.normalizeSelection(selection, profile)
return this.selectedOptions(normalized).flatMap(option => option.inputs)
}
private selectedOptions(selection: FeatureSelection): readonly FeatureOption[] {
return selection.options.map((id) => {
const option = this.options.find(candidate => candidate.id === id)
/* v8 ignore next -- normalizeSelection already membership-checks every selected id */
if (!option) throw new Error(`unknown ${this.id} option: ${id}`)
return option
})
}
/**
* Recover input and secret values after structural inspection.
* @param project - project snapshot being inspected.
* @param selection - structurally detected selection.
* @returns selection enriched with readable values.
*/
readSelection(project: FeatureProjectView, selection: FeatureSelection): FeatureSelection {
const secrets = Object.fromEntries(this.secrets(selection, project.profile).flatMap((secret) => {
const value = project.readEnvironment('.env', secret.environment)
return value === undefined ? [] : [[secret.id, value]]
}))
return Object.keys(secrets).length === 0 ? selection : { ...selection, secrets }
}
/**
* Inspect current files and reject any partial or ambiguous owned shape.
* @param project - project snapshot to inspect.
* @returns installation state, selection, and diagnostics.
*/
inspect(project: FeatureProjectView): FeatureInstallation {
const profile = project.profile
const allPackages = new Set<string>()
for (const option of this.options) {
for (const entry of option.ownedConfigEntries(profile)) allPackages.add(entry.name)
}
for (const name of packageNames(this.baseContribution(profile).resources)) allPackages.add(name)
const configEntries = project.cordisConfigEntries()
const ownedConfigEntries = configEntries.filter(entry => allPackages.has(entry.name))
const options = this.options
.filter(option => option.matchesConfigEntries(configEntries, profile))
.map(option => option.id)
if (ownedConfigEntries.length === 0 && options.length === 0) {
return { id: this.id, state: 'absent', options: [], diagnostics: [] }
}
let selection: FeatureSelection
try {
selection = this.normalizeSelection({ id: this.id, options }, profile)
} catch (error) {
return { id: this.id, state: 'inconsistent', options, diagnostics: [String(error)] }
}
selection = this.readSelection(project, selection)
const expected = this.contribution(selection, profile)
const expectedEntries = expected.resources
.filter((resource): resource is CordisConfigEntryResource => resource.kind === 'cordis-config-entry')
const diagnostics: string[] = []
for (const resource of expectedEntries) {
const actual = ownedConfigEntries.find(entry => entry.id === resource.entry.id && entry.name === resource.entry.name)
if (!actual) diagnostics.push(`missing Cordis config entry ${resource.entry.id} (${resource.entry.name})`)
else diagnostics.push(...configDiagnostics(resource, actual))
}
for (const actual of ownedConfigEntries) {
if (!expectedEntries.some(resource => resource.entry.id === actual.id && resource.entry.name === actual.name)) {
diagnostics.push(`unexpected owned Cordis config entry ${actual.id} (${actual.name})`)
}
}
const manifest = project.packageManifest()
for (const resource of expected.resources) {
switch (resource.kind) {
case 'npm-dependency':
if (!manifest[resource.section]?.[resource.name]) {
diagnostics.push(`missing package.json ${resource.section} entry ${resource.name}`)
}
break
case 'package-script':
if (!manifest.scripts?.[resource.name]) {
diagnostics.push(`missing package.json script ${resource.name}`)
}
break
case 'owned-file':
if (!project.hasDocument(resource.document.relativePath)) diagnostics.push(`missing owned file ${resource.document.relativePath}`)
break
case 'environment':
try {
if (project.readEnvironment('.env.example', resource.name) === undefined) {
diagnostics.push(`missing .env.example variable ${resource.name}`)
}
} catch (error) {
diagnostics.push(String(error))
}
break
case 'cordis-config-entry': break
}
}
const disabled = ownedConfigEntries.map(entry => entry.disabled === true)
if (disabled.some(Boolean) && disabled.some(value => !value)) {
diagnostics.push('owned Cordis config entries have mixed enabled states')
}
if (diagnostics.length > 0) {
return { id: this.id, state: 'inconsistent', options, diagnostics }
}
return {
id: this.id,
state: ownedConfigEntries.length > 0 && disabled.every(Boolean) ? 'disabled' : 'enabled',
options,
selection,
diagnostics: [],
}
}
}
/** Fixed one-option feature base. */
export abstract class FixedFeature extends Feature {
override readonly mode = 'single'
/** Select the sole option. */
override defaultOptions(): readonly string[] {
const option = this.options[0]
if (!option) throw new Error(`simple feature ${this.id} has no option`)
return [option.id]
}
}
/** Mutually exclusive option feature base. */
export abstract class ExclusiveOptionFeature extends Feature {
override readonly mode = 'exclusive'
}
/** Additive multi-option feature base. */
export abstract class MultiOptionFeature extends Feature {
override readonly mode = 'multiple'
}

View File

@@ -0,0 +1,87 @@
/**
* Builtin feature registry and definition-time conflict checks.
*
* @module @deepseek-ai/dsh-helper/features/registry
*/
import type { FeatureId, ResourceKey } from '../ids.ts'
import type { ProjectProfile } from '../project/types.ts'
import type { Feature, FeatureProjectView } from './feature.ts'
import type { CordisConfigEntryResource } from './resources.ts'
/** Compile-time builtin feature collection. */
export class FeatureRegistry {
private readonly features = new Map<FeatureId, Feature>()
/** Register and validate a complete builtin set. */
constructor(features: readonly Feature[], validationProfile: ProjectProfile) {
const owners = new Map<ResourceKey, FeatureId>()
for (const feature of features) {
if (this.features.has(feature.id)) throw new Error(`duplicate feature id: ${feature.id}`)
this.features.set(feature.id, feature)
const validationInterface = feature.supportedInterfaces[0]
if (!validationInterface) throw new Error(`feature ${feature.id} supports no run interface`)
const selections = feature.options.map(option => ({ id: feature.id, options: [option.id] }))
for (const selection of selections) {
const contribution = feature.contribution(selection, {
...validationProfile,
runInterface: validationInterface,
})
for (const resource of contribution.resources) {
const owner = owners.get(resource.key)
if (owner && owner !== feature.id) {
throw new Error(`resource ${resource.key} is declared by both ${owner} and ${feature.id}`)
}
owners.set(resource.key, feature.id)
}
}
}
}
/**
* Return all builtins in display order.
* @returns all registered features.
*/
all(): readonly Feature[] {
return [...this.features.values()]
}
/**
* Resolve one builtin or fail loud.
* @param id - stable feature identity.
* @returns registered feature.
*/
get(id: FeatureId): Feature {
const feature = this.features.get(id)
if (!feature) throw new Error(`unknown feature: ${id}`)
return feature
}
/**
* Inspect every applicable builtin in display order.
* @param project - project view to inspect.
* @returns installation snapshots for applicable features.
*/
inspect(project: FeatureProjectView): ReturnType<Feature['inspect']>[] {
return this.all()
.filter(feature => feature.isApplicable(project.profile))
.map(feature => feature.inspect(project))
}
/**
* Resolve the builtin that owns a Cordis package name for this profile.
* @param name - Loader package name.
* @param profile - project context controlling applicability.
* @returns owning feature, if the package is builtin-owned.
*/
ownerOfPackage(name: string, profile: ProjectProfile): Feature | undefined {
return this.all().find((feature) => {
if (!feature.isApplicable(profile)) return false
const selections = feature.options.map(option => ({ id: feature.id, options: [option.id] }))
return selections.some(selection => feature.contribution(selection, profile).resources.some(
(resource): resource is CordisConfigEntryResource => resource.kind === 'cordis-config-entry'
&& resource.entry.name === name,
))
})
}
}

View File

@@ -0,0 +1,97 @@
/**
* Resource vocabulary contributed by builtin SDK features.
*
* @module @deepseek-ai/dsh-helper/features/resources
*/
import type { CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
import type { ProjectFile } from '../documents/project-file.ts'
import type { ResourceKey } from '../ids.ts'
/** Runtime or development NPM dependency contribution. */
export interface NpmDependencyResource {
kind: 'npm-dependency'
key: ResourceKey
name: string
section: 'dependencies' | 'devDependencies'
}
/** Feature-owned package script. */
export interface PackageScriptResource {
kind: 'package-script'
key: ResourceKey
name: string
command: string
removeOnlyWhenUnchanged: boolean
}
/** Owned Cordis config entry plus the config keys safe to update in place. */
export interface CordisConfigEntryResource {
kind: 'cordis-config-entry'
key: ResourceKey
entry: CordisConfigEntry
ownedConfigKeys: readonly string[]
commentedExample?: string
validateConfig?: (config: Readonly<Record<string, unknown>>) => readonly string[]
}
/** Environment variable reference and dotenv material. */
export interface EnvironmentResource {
kind: 'environment'
key: ResourceKey
name: string
value?: string
exampleValue: string
comment?: string
}
/** Feature-exclusive complete file. */
export interface OwnedFileResource {
kind: 'owned-file'
key: ResourceKey
document: ProjectFile
removeOnlyWhenUnchanged: boolean
}
/** Any resource a feature can add to a project. */
export type ProjectResource =
| NpmDependencyResource
| PackageScriptResource
| CordisConfigEntryResource
| EnvironmentResource
| OwnedFileResource
/** Complete resource contribution for one selected feature state. */
export class ProjectContribution {
readonly resources: readonly ProjectResource[]
/** Validate and retain one feature-owned resource set. */
constructor(resources: readonly ProjectResource[]) {
const seen = new Set<ResourceKey>()
for (const resource of resources) {
if (seen.has(resource.key)) throw new Error(`duplicate contribution resource key: ${resource.key}`)
seen.add(resource.key)
}
this.resources = resources
}
/** Merge base and option contributions by stable key. */
static merge(...contributions: readonly ProjectContribution[]): ProjectContribution {
const resources = new Map<ResourceKey, ProjectResource>()
for (const contribution of contributions) {
for (const resource of contribution.resources) {
const previous = resources.get(resource.key)
if (previous && JSON.stringify(previous) !== JSON.stringify(resource)) {
throw new Error(`resource ${resource.key} has conflicting definitions inside one feature`)
}
resources.set(resource.key, resource)
}
}
return new ProjectContribution([...resources.values()])
}
/** Index resources by stable key. */
byKey(): ReadonlyMap<ResourceKey, ProjectResource> {
return new Map(this.resources.map(resource => [resource.key, resource]))
}
}

View File

@@ -0,0 +1,31 @@
/**
* Branded identities owned by the SDK project domain.
*
* @module @deepseek-ai/dsh-helper/ids
*/
import type { Branded } from '@deepseek-ai/dsh-brand'
/** Stable identity of a builtin SDK feature. */
export type FeatureId = Branded<'FeatureId'>
/**
* Construct a feature identity from its registry key.
* @param value - lowercase kebab-case registry key.
* @returns branded feature identity.
*/
export function featureId(value: string): FeatureId {
if (!/^[a-z][a-z0-9-]*$/.test(value)) {
throw new Error(`invalid feature id: ${JSON.stringify(value)}`)
}
return value as FeatureId
}
/** Stable identity of a resource contributed to an SDK project. */
export type ResourceKey = Branded<'ResourceKey'>
/** Construct a resource key from its owner-qualified value. */
export function resourceKey(value: string): ResourceKey {
if (value.length === 0) throw new Error('resource key must not be empty')
return value as ResourceKey
}

View File

@@ -0,0 +1,45 @@
/**
* Shared domain and infrastructure for DeepSeek Harness SDK project tooling.
*
* @module @deepseek-ai/dsh-helper
*/
export { featureId } from './ids.ts'
export { TextTemplate } from './templates/text-template.ts'
export type {
FeatureSelection,
ProjectCreationRequest,
ProjectProfile,
RunInterface,
} from './project/types.ts'
export type { ChangeSet, ProjectCommitResult } from './project/change-set.ts'
export { SdkProject } from './project/sdk-project.ts'
export {
NodeCommandRunner,
NpmPackageManager,
createPackageManager,
inferPackageManagerName,
probePackageManagerVersion,
} from './package-managers/package-manager.ts'
export type {
CommandRunner,
PackageManager,
PackageManagerName,
PackageManagerVersionProbe,
} from './package-managers/package-manager.ts'
export { LocalPluginBlueprint } from './plugins/local-plugin-blueprint.ts'
export type { LocalPluginKind } from './plugins/local-plugin-blueprint.ts'
export type { Feature, FeatureInstallation } from './features/feature.ts'
export type { FeatureRegistry } from './features/registry.ts'
export { FeatureConfigurator } from './features/feature-configurator.ts'
export { createBuiltinRegistry } from './features/builtin/index.ts'
export { PromptCancelledError, requireAnswer } from './questions/prompt-port.ts'
export type { NestedMultiSelectValue, PromptPort } from './questions/prompt-port.ts'
export {
ConfirmQuestion,
SecretQuestion,
SelectQuestion,
TextQuestion,
} from './questions/question.ts'
export type { Question } from './questions/question.ts'
export { ClackPromptPort } from './questions/clack-prompt-port.ts'

View File

@@ -0,0 +1,137 @@
/**
* Repository package discovery and NPM dependency-closure rewriting for live links.
*
* @module @deepseek-ai/dsh-helper/package-managers/link-workspace
*/
import { readFile, readdir } from 'node:fs/promises'
import { existsSync, realpathSync } from 'node:fs'
import { basename, dirname, join, relative, resolve, sep } from 'node:path'
import type { PackageJsonFile, PackageManifest } from '../documents/package-json-file.ts'
import { PnpmWorkspaceFile } from '../documents/pnpm-workspace-file.ts'
import type { ProjectFile } from '../documents/project-file.ts'
import type { PackageManager } from './package-manager.ts'
interface WorkspacePackage {
directory: string
manifest: PackageManifest
}
function posixPath(path: string): string {
return path.split(sep).join('/')
}
function canonicalPath(path: string): string {
let existing = resolve(path)
const suffix: string[] = []
while (!existsSync(existing)) {
const parent = dirname(existing)
/* v8 ignore next -- every absolute path reaches the existing filesystem root */
if (parent === existing) throw new Error(`cannot resolve an existing ancestor for ${path}`)
suffix.unshift(basename(existing))
existing = parent
}
return resolve(realpathSync(existing), ...suffix)
}
async function packageDirectories(root: string): Promise<string[]> {
const result: string[] = []
for (const vendor of await readdir(join(root, 'vendor'), { withFileTypes: true })) {
if (vendor.isDirectory()) result.push(join(root, 'vendor', vendor.name))
}
for (const group of await readdir(join(root, 'packages'), { withFileTypes: true })) {
if (!group.isDirectory()) continue
for (const pkg of await readdir(join(root, 'packages', group.name), { withFileTypes: true })) {
if (pkg.isDirectory()) result.push(join(root, 'packages', group.name, pkg.name))
}
}
return result
}
/** Index of repository packages used by `--link-workspace`. */
export class LinkWorkspace {
readonly root: string
private readonly packages: Map<string, WorkspacePackage>
private constructor(root: string, packages: Map<string, WorkspacePackage>) {
this.root = root
this.packages = packages
}
/** Scan vendor and package workspaces from a repository root. */
static async open(root: string): Promise<LinkWorkspace> {
const absolute = resolve(root)
const packages = new Map<string, WorkspacePackage>()
for (const directory of await packageDirectories(absolute)) {
let manifest: PackageManifest
try {
manifest = JSON.parse(await readFile(join(directory, 'package.json'), 'utf8')) as PackageManifest
} catch (error) {
throw new Error(`cannot read linked package at ${directory}: ${String(error)}`)
}
if (!manifest.name || typeof manifest.name !== 'string') continue
if (packages.has(manifest.name)) throw new Error(`duplicate linked package name: ${manifest.name}`)
packages.set(manifest.name, { directory, manifest })
}
if (!packages.has('cordis') || !packages.has('@deepseek-ai/dsh-scripts')) {
throw new Error(`not a DeepSeek Harness repository root: ${absolute}`)
}
return new LinkWorkspace(absolute, packages)
}
/** Expand direct NPM dependencies through all repository-local NPM dependency edges. */
closure(names: Iterable<string>): string[] {
const pending = [...names]
const result = new Set<string>()
while (pending.length > 0) {
const name = pending.pop()
if (!name || result.has(name)) continue
const pkg = this.packages.get(name)
/* v8 ignore next -- closure() only returns names present in this package map */
if (!pkg) continue
result.add(name)
const edges = {
...pkg.manifest.dependencies,
...pkg.manifest.peerDependencies as Record<string, string> | undefined,
}
for (const dependencyName of Object.keys(edges)) {
if (this.packages.has(dependencyName) && !result.has(dependencyName)) pending.push(dependencyName)
}
}
return [...result].sort()
}
/** Rewrite the full local closure to manager-specific live-link specs. */
apply(
projectRoot: string,
manifest: PackageJsonFile,
manager: PackageManager,
documents: readonly ProjectFile[],
): void {
const canonicalProjectRoot = canonicalPath(projectRoot)
const names = this.closure(manifest.npmDependencyNames())
for (const name of names) {
const pkg = this.packages.get(name)
/* v8 ignore next -- closure() only returns names present in this package map */
if (!pkg) continue
const relativePath = posixPath(relative(canonicalProjectRoot, realpathSync(pkg.directory)))
const spec = manager.linkSpec(relativePath)
const current = manifest.npmDependency(name)
manifest.setNpmDependency(current?.section ?? 'dependencies', name, spec)
if (manager.name === 'yarn') manifest.setResolution(name, spec)
}
if (manager.name === 'pnpm') {
const workspace = documents.find((item): item is PnpmWorkspaceFile => item instanceof PnpmWorkspaceFile)
if (!workspace) throw new Error('pnpm link mode requires pnpm-workspace.yaml')
workspace.disableAutoInstallPeers()
}
}
/** Resolve a package directory for diagnostics and tests. */
packageDirectory(name: string): string | undefined {
const directory = this.packages.get(name)?.directory
return directory
? resolve(dirname(directory), directory.split(sep).at(-1) as string)
: undefined
}
}

View File

@@ -0,0 +1,280 @@
/**
* Package-manager strategies for SDK project workspaces and child commands.
*
* @module @deepseek-ai/dsh-helper/package-managers/package-manager
*/
import { execFile, spawn } from 'node:child_process'
import { promisify } from 'node:util'
import type { PackageJsonFile } from '../documents/package-json-file.ts'
import { PnpmWorkspaceFile } from '../documents/pnpm-workspace-file.ts'
import type { ProjectFile } from '../documents/project-file.ts'
/** Supported generated-project package managers. */
export type PackageManagerName = 'npm' | 'pnpm' | 'yarn'
/** Result from one child package-manager process. */
export interface CommandResult {
exitCode: number | null
signal: NodeJS.Signals | null
}
/** Injectable subprocess boundary used by package-manager strategies. */
export interface CommandRunner {
/** Run one executable without a shell and await process exit. */
run(command: string, args: readonly string[], cwd: string): Promise<CommandResult>
}
/** Injectable package-manager version probe used by project creation. */
export type PackageManagerVersionProbe = (name: PackageManagerName, cwd: string) => Promise<string>
const execFileAsync = promisify(execFile)
/**
* Read a manager version without forwarding ambient credentials.
* @param name - package-manager executable.
* @param cwd - working directory used for resolution.
* @returns trimmed version output.
*/
export async function probePackageManagerVersion(name: PackageManagerName, cwd: string): Promise<string> {
try {
const { stdout } = await execFileAsync(name, ['--version'], {
cwd,
env: scrubEnvironment(),
encoding: 'utf8',
})
const version = stdout.trim()
if (!version) throw new Error('empty version output')
return version
} catch (error) {
throw new Error(`cannot run ${name} --version: ${String(error)}`)
}
}
/** Remove credential-shaped environment variables from spawned commands. */
export function scrubEnvironment(environment: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
return Object.fromEntries(Object.entries(environment).filter(([name]) => !/(?:KEY|SECRET|TOKEN)/i.test(name)))
}
/** Node child-process command runner with inherited stdio and quiescent completion. */
export class NodeCommandRunner implements CommandRunner {
/** Spawn one child and settle only after its exit. */
run(command: string, args: readonly string[], cwd: string): Promise<CommandResult> {
return new Promise((resolve, reject) => {
const child = spawn(command, [...args], {
cwd,
env: scrubEnvironment(),
stdio: 'inherit',
shell: false,
})
child.once('error', reject)
child.once('exit', (exitCode, signal) => { resolve({ exitCode, signal }) })
})
}
}
function major(version: string): number {
const match = /^(\d+)/.exec(version)
if (!match?.[1]) throw new Error(`invalid package manager version: ${JSON.stringify(version)}`)
return Number(match[1])
}
/** Behavior owned by one generated-project package manager. */
export abstract class PackageManager {
/** Manager executable and project identity. */
abstract readonly name: PackageManagerName
/** Detected concrete manager version. */
readonly version: string
constructor(version: string) {
this.version = version
}
/** Validate the detected version against this SDK's supported floor. */
abstract validateVersion(): void
/**
* Configure root manifest fields and return manager-specific files.
* @param manifest - generated root manifest to update.
* @returns manager-specific companion documents.
*/
abstract configureWorkspace(manifest: PackageJsonFile): ProjectFile[]
/**
* Build the NPM dependency spec for a local workspace plugin.
* @returns manager-specific local NPM dependency spec.
*/
abstract localPluginSpec(): string
/**
* Resolve a repository live-link NPM dependency.
* @param relativePath - relative path from generated project to package.
* @returns manager-specific NPM dependency spec.
*/
abstract linkSpec(relativePath: string): string
/**
* Build install command arguments.
* @returns arguments following the manager executable.
*/
installCommand(): readonly string[] {
return ['install']
}
/**
* Build project-build command arguments.
* @returns arguments following the manager executable.
*/
buildCommand(): readonly string[] {
return ['run', 'build']
}
/**
* Run NPM dependency installation and fail on non-zero or signalled exit.
* @param cwd - generated project directory.
* @param runner - optional subprocess boundary.
*/
async install(cwd: string, runner: CommandRunner = new NodeCommandRunner()): Promise<void> {
await this.runChecked(runner, this.installCommand(), cwd, 'install')
}
/**
* Run the project build and fail on non-zero or signalled exit.
* @param cwd - generated project directory.
* @param runner - optional subprocess boundary.
*/
async build(cwd: string, runner: CommandRunner = new NodeCommandRunner()): Promise<void> {
await this.runChecked(runner, this.buildCommand(), cwd, 'build')
}
private async runChecked(runner: CommandRunner, args: readonly string[], cwd: string, operation: string): Promise<void> {
const result = await runner.run(this.name, args, cwd)
if (result.signal !== null) {
throw new Error(`${this.name} ${operation} was killed by ${result.signal}`)
}
if (result.exitCode !== 0) {
throw new Error(`${this.name} ${operation} exited with code ${String(result.exitCode)}`)
}
}
}
/** npm workspace behavior. */
export class NpmPackageManager extends PackageManager {
override readonly name = 'npm'
/** npm 10 is the supported floor at the repository's Node floor. */
override validateVersion(): void {
if (major(this.version) < 10) throw new Error(`npm >=10 is required, got ${this.version}`)
}
/** Configure package.json workspaces; npm needs no companion file. */
override configureWorkspace(manifest: PackageJsonFile): ProjectFile[] {
manifest.addWorkspace('plugins/*')
manifest.setPackageManager(undefined)
return []
}
/** npm resolves workspace packages through its ordinary wildcard. */
override localPluginSpec(): string {
return '*'
}
/** npm live links use file NPM dependencies. */
override linkSpec(relativePath: string): string {
return `file:${relativePath}`
}
}
/** pnpm workspace behavior. */
export class PnpmPackageManager extends PackageManager {
override readonly name = 'pnpm'
/** pnpm 10 is the supported floor for strict NPM dependency-build policy. */
override validateVersion(): void {
if (major(this.version) < 10) throw new Error(`pnpm >=10 is required, got ${this.version}`)
}
/** Configure packageManager and a structured pnpm workspace file. */
override configureWorkspace(manifest: PackageJsonFile): ProjectFile[] {
manifest.setPackageManager(`pnpm@${this.version}`)
const workspace = PnpmWorkspaceFile.create()
workspace.addPackage('plugins/*')
return [workspace]
}
/** pnpm uses its explicit workspace protocol. */
override localPluginSpec(): string {
return 'workspace:*'
}
/** pnpm live links use link NPM dependencies. */
override linkSpec(relativePath: string): string {
return `link:${relativePath}`
}
}
/** Yarn Berry-compatible workspace behavior. */
export class YarnPackageManager extends PackageManager {
override readonly name = 'yarn'
/** Yarn classic is excluded because the generated project relies on modern workspaces. */
override validateVersion(): void {
if (major(this.version) < 2) throw new Error(`Yarn >=2 is required, got ${this.version}`)
}
/** Configure packageManager and package.json workspaces. */
override configureWorkspace(manifest: PackageJsonFile): ProjectFile[] {
manifest.addWorkspace('plugins/*')
manifest.setPackageManager(`yarn@${this.version}`)
return []
}
/** Modern Yarn uses the workspace protocol. */
override localPluginSpec(): string {
return 'workspace:*'
}
/** Yarn live links use portal NPM dependencies to preserve package identity. */
override linkSpec(relativePath: string): string {
return `portal:${relativePath}`
}
/** Yarn runs scripts without the `run` token. */
override buildCommand(): readonly string[] {
return ['build']
}
}
/**
* Construct and validate one package-manager strategy.
* @param name - selected manager.
* @param version - detected concrete version.
* @returns validated strategy.
*/
export function createPackageManager(name: PackageManagerName, version: string): PackageManager {
let manager: PackageManager
switch (name) {
case 'npm': manager = new NpmPackageManager(version); break
case 'pnpm': manager = new PnpmPackageManager(version); break
case 'yarn': manager = new YarnPackageManager(version); break
}
manager.validateVersion()
return manager
}
/**
* Infer a package manager from an explicit choice or npm user-agent value.
* @param explicit - explicit CLI selection.
* @param userAgent - npm-compatible user-agent string.
* @returns selected or inferred manager name.
*/
export function inferPackageManagerName(
explicit: PackageManagerName | undefined,
userAgent: string | undefined = process.env.npm_config_user_agent,
): PackageManagerName | undefined {
if (explicit) return explicit
const token = userAgent?.split(' ')[0]?.split('/')[0]
if (token === 'npm' || token === 'pnpm' || token === 'yarn') return token
return undefined
}

View File

@@ -0,0 +1,123 @@
/**
* Source blueprints for local Cordis plugins generated under `plugins/*`.
*
* @module @deepseek-ai/dsh-helper/plugins/local-plugin-blueprint
*/
import { TextProjectFile } from '../documents/project-file.ts'
import type { CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
import { resolveNpmDependency } from '../project/npm-dependency-policy.ts'
import { loadHelperTemplate } from '../templates/template-assets.ts'
/** Supported generated local-plugin shapes. */
export type LocalPluginKind = 'plugin' | 'tool'
function kebab(value: string): string {
const result = value.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
if (!result || !/^[a-z]/.test(result)) throw new Error(`invalid local plugin name: ${JSON.stringify(value)}`)
return result
}
function packageName(projectName: string, pluginName: string): string {
if (projectName.startsWith('@')) {
const separator = projectName.indexOf('/')
if (separator > 1 && separator < projectName.length - 1) {
return `${projectName.slice(0, separator)}/${projectName.slice(separator + 1)}-${pluginName}`
}
}
return `${projectName}-${pluginName}`
}
interface LocalPluginTemplateContext {
pluginName: string
toolName: string
toolTitle: string
}
const PLUGIN_SOURCE = loadHelperTemplate<LocalPluginTemplateContext>('local-plugin.ts.tpl')
const TOOL_SOURCE = loadHelperTemplate<LocalPluginTemplateContext>('local-tool.ts.tpl')
const PLUGIN_TSDOWN = loadHelperTemplate<LocalPluginTemplateContext>('local-plugin-tsdown.config.ts.tpl')
/** One local plugin's derived package, source, build, and runtime entry. */
export class LocalPluginBlueprint {
/** Normalized local package and Cordis config entry name. */
readonly name: string
/** Generated plugin source shape. */
readonly kind: LocalPluginKind
/** Normalize and validate one local plugin request. */
constructor(name: string, kind: LocalPluginKind) {
this.name = kebab(name)
this.kind = kind
}
/** Root-relative plugin directory. */
get directory(): string {
return `plugins/${this.name}`
}
/**
* Derive an npm package name from the root project identity.
* @param projectName - generated root package name.
* @returns local plugin package name.
*/
packageName(projectName: string): string {
return packageName(projectName, this.name)
}
/**
* Build the runtime Cordis config entry for this local package.
* @param projectName - generated root package name.
* @returns Loader entry referencing the local package.
*/
cordisConfigEntry(projectName: string): CordisConfigEntry {
return { id: this.name, name: this.packageName(projectName) }
}
/**
* Render the complete local package files.
* @param projectName - generated root package name.
* @param releaseVersion - SDK dependency version.
* @returns local manifest, configs, and source documents.
*/
documents(projectName: string, releaseVersion: string): TextProjectFile[] {
const name = this.packageName(projectName)
const toolName = this.name.replaceAll('-', '_')
const cordisSpec = resolveNpmDependency('cordis', 'devDependencies', releaseVersion).spec
const manifest = {
name,
version: '0.0.0',
private: true,
type: 'module',
main: 'lib/index.js',
types: 'lib/index.d.ts',
exports: { '.': { types: './lib/index.d.ts', default: './lib/index.js' } },
peerDependencies: {
...this.kind === 'tool' ? { '@deepseek-ai/dsh-tools': `^${releaseVersion}` } : {},
cordis: cordisSpec,
},
devDependencies: {
cordis: cordisSpec,
},
}
const tsconfig = {
extends: '../../tsconfig.base.json',
compilerOptions: { rootDir: 'src', outDir: 'lib/types' },
include: ['src'],
}
const context: LocalPluginTemplateContext = {
pluginName: this.name,
toolName,
toolTitle: toolName.replaceAll('_', ' '),
}
return [
new TextProjectFile(`${this.directory}/package.json`, JSON.stringify(manifest, null, 2)),
new TextProjectFile(`${this.directory}/tsconfig.json`, JSON.stringify(tsconfig, null, 2)),
new TextProjectFile(`${this.directory}/tsdown.config.ts`, PLUGIN_TSDOWN.render(context)),
new TextProjectFile(
`${this.directory}/src/index.ts`,
(this.kind === 'tool' ? TOOL_SOURCE : PLUGIN_SOURCE).render(context),
),
]
}
}

View File

@@ -0,0 +1,26 @@
/**
* Result summary for one SDK project edit session.
*
* @module @deepseek-ai/dsh-helper/project/change-set
*/
import type { FeatureId } from '../ids.ts'
/** Immutable description of committed or pending project changes. */
export interface ChangeSet {
addedFeatures: readonly FeatureId[]
enabledFeatures: readonly FeatureId[]
disabledFeatures: readonly FeatureId[]
configuredFeatures: readonly FeatureId[]
addedPlugins: readonly string[]
enabledPlugins: readonly string[]
disabledPlugins: readonly string[]
changedFiles: readonly string[]
npmDependenciesChanged: boolean
}
/** Result of committing one project edit session. */
export interface ProjectCommitResult<TProject> {
project: TProject
changes: ChangeSet
}

View File

@@ -0,0 +1,62 @@
/**
* NPM dependency baseline and version policy for generated SDK projects.
*
* @module @deepseek-ai/dsh-helper/project/npm-dependency-policy
*/
import type { NpmDependencySection } from '../documents/package-json-file.ts'
/** One NPM dependency spec selected by the SDK release policy. */
export interface ResolvedNpmDependency {
section: NpmDependencySection
spec: string
}
/** NPM dependency maps rendered into a newly created root package.json. */
export interface BaselineNpmDependencies {
dependencies: Readonly<Record<string, string>>
devDependencies: Readonly<Record<string, string>>
}
const EXTERNAL_NPM_DEPENDENCY_SPECS: Readonly<Record<string, string>> = {
'@cordisjs/plugin-hmr': '^1.0.15',
'@cordisjs/plugin-timer': '^1.1.2',
'@types/node': '^22.20.0',
cordis: '^4.0.0-rc.7',
tsdown: '^0.22.2',
tsx: '^4.22.4',
typescript: '^6.0.3',
}
const BASELINE_NPM_DEPENDENCY_NAMES: Readonly<Record<NpmDependencySection, readonly string[]>> = {
dependencies: ['@deepseek-ai/dsh-scripts', 'cordis'],
devDependencies: ['@types/node', 'tsdown', 'tsx', 'typescript'],
}
/** Resolve one package to its generated-project section and version spec. */
export function resolveNpmDependency(
name: string,
requestedSection: NpmDependencySection,
releaseVersion: string,
): ResolvedNpmDependency {
if (name.startsWith('@deepseek-ai/dsh-')) {
return { section: requestedSection, spec: `^${releaseVersion}` }
}
const spec = EXTERNAL_NPM_DEPENDENCY_SPECS[name]
if (spec) return { section: requestedSection, spec }
throw new Error(`no generated-project NPM dependency policy for ${name}`)
}
/** Build the root package.json NPM dependency maps from the shared version policy. */
export function baselineNpmDependencies(releaseVersion: string): BaselineNpmDependencies {
return {
dependencies: Object.fromEntries(BASELINE_NPM_DEPENDENCY_NAMES.dependencies.map((name) => {
const dependency = resolveNpmDependency(name, 'dependencies', releaseVersion)
return [name, dependency.spec]
})),
devDependencies: Object.fromEntries(BASELINE_NPM_DEPENDENCY_NAMES.devDependencies.map((name) => {
const dependency = resolveNpmDependency(name, 'devDependencies', releaseVersion)
return [name, dependency.spec]
})),
}
}

View File

@@ -0,0 +1,597 @@
/**
* Isolated domain-command and commit boundary for SDK project changes.
*
* @module @deepseek-ai/dsh-helper/project/project-edit-session
*/
import { mkdir, readFile, unlink, writeFile } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import type {
Feature,
FeatureInstallation,
FeatureProjectView,
FeatureRequirement,
} from '../features/feature.ts'
import type { FeatureRegistry } from '../features/registry.ts'
import type { ProjectResource } from '../features/resources.ts'
import { CordisYamlFile, type CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
import { EnvFile } from '../documents/env-file.ts'
import { PackageJsonFile, type PackageManifest } from '../documents/package-json-file.ts'
import { ProjectFile } from '../documents/project-file.ts'
import { TsConfigFile } from '../documents/tsconfig-file.ts'
import { featureId, type FeatureId, type ResourceKey } from '../ids.ts'
import { LinkWorkspace } from '../package-managers/link-workspace.ts'
import type { LocalPluginBlueprint } from '../plugins/local-plugin-blueprint.ts'
import type { FeatureSelection, ProjectProfile } from './types.ts'
import { resolveNpmDependency } from './npm-dependency-policy.ts'
import type { ChangeSet, ProjectCommitResult } from './change-set.ts'
import type { SdkProject } from './sdk-project.ts'
interface MutableFeatureState {
selection?: FeatureSelection
state: FeatureInstallation['state']
}
function sameText(left: ProjectFile, right: ProjectFile | undefined): boolean {
return right !== undefined && left.serialize() === right.serialize()
}
function npmDependencyShape(manifest: Readonly<PackageManifest>): string {
return JSON.stringify({
/* v8 ignore next -- generated manifests always carry the managed dependency maps */
dependencies: manifest.dependencies ?? {},
/* v8 ignore next -- generated manifests always carry the managed dependency maps */
devDependencies: manifest.devDependencies ?? {},
})
}
function asError(error: unknown): Error {
/* v8 ignore else -- node:fs promise APIs reject Error objects */
if (error instanceof Error) return error
/* v8 ignore next -- node:fs promise APIs reject Error objects */
return new Error(String(error))
}
function canUpdateResource(previous: ProjectResource, next: ProjectResource): boolean {
if (previous.kind !== next.kind) return false
switch (previous.kind) {
case 'npm-dependency': return previous.name === (next as typeof previous).name
case 'package-script': return previous.name === (next as typeof previous).name
case 'cordis-config-entry': {
const candidate = next as typeof previous
return previous.entry.name === candidate.entry.name
}
case 'environment': return previous.name === (next as typeof previous).name
case 'owned-file': return previous.document.relativePath === (next as typeof previous).document.relativePath
}
}
/** Mutable working copy that applies feature and local-plugin domain commands. */
export class ProjectEditSession implements FeatureProjectView {
readonly profile: ProjectProfile
private readonly source: SdkProject
private readonly registry: FeatureRegistry
private readonly documents: Map<string, ProjectFile>
private readonly removed = new Map<string, ProjectFile>()
private readonly states = new Map<FeatureId, MutableFeatureState>()
private readonly added = new Set<FeatureId>()
private readonly enabled = new Set<FeatureId>()
private readonly disabled = new Set<FeatureId>()
private readonly configured = new Set<FeatureId>()
private readonly addedPlugins = new Set<string>()
private readonly enabledPlugins = new Set<string>()
private readonly disabledPlugins = new Set<string>()
private committed = false
/** Clone one project snapshot into an isolated working copy. */
constructor(source: SdkProject, registry: FeatureRegistry) {
this.source = source
this.registry = registry
this.profile = source.profile
this.documents = source.cloneDocuments()
for (const feature of registry.all()) {
if (!feature.isApplicable(this.profile)) continue
const installation = feature.inspect(this)
this.states.set(feature.id, {
state: installation.state,
...installation.selection ? { selection: installation.selection } : {},
})
}
}
/** Root manifest value for feature inspection. */
packageManifest(): Readonly<PackageManifest> {
return this.manifest().value()
}
/** Cordis config entries for feature and custom-plugin inspection. */
cordisConfigEntries(): readonly CordisConfigEntry[] {
return this.cordis().entries()
}
/** Whether one managed document exists in the working copy. */
/* jscpd:ignore-start -- FeatureProjectView deliberately has symmetric snapshot/edit implementations. */
hasDocument(path: string): boolean {
return this.documents.has(path)
}
/** Read one unique working-copy environment variable. */
readEnvironment(path: '.env' | '.env.example', name: string): string | undefined {
const document = this.documents.get(path)
if (!document) return undefined
if (!(document instanceof EnvFile)) throw new Error(`${path} is not an environment document`)
return document.get(name)
}
/* jscpd:ignore-end */
/** Inspect every applicable builtin against the current working copy. */
inspections(): readonly FeatureInstallation[] {
return this.registry.inspect(this)
}
/** Install a builtin and recursively satisfy its declared requirements. */
installFeature(feature: Feature, selection: FeatureSelection): void {
this.assertOpen()
this.installFeatureRecursive(feature, selection, new Set())
}
/** Replace one installed builtin's feature-option and captured-input selection. */
configureFeature(feature: Feature, selection: FeatureSelection): void {
this.assertOpen()
const current = this.state(feature)
if (current.state === 'inconsistent') throw new Error(`feature ${feature.id} is inconsistent`)
if (current.state === 'absent' || !current.selection) {
this.installFeature(feature, selection)
return
}
const normalized = feature.normalizeSelection(selection, this.profile)
this.ensureRequirements(feature, normalized, new Set([feature.id]))
this.replaceContribution(
feature.contribution(current.selection, this.profile),
feature.contribution(normalized, this.profile),
)
current.selection = normalized
current.state = current.state === 'disabled' ? 'disabled' : 'enabled'
if (current.state === 'disabled') this.setFeatureDisabled(feature, normalized, true)
this.assertFeatureConsistent(feature)
this.configured.add(feature.id)
}
/** Enable all entries owned by one installed feature. */
enableFeature(feature: Feature): void {
this.assertOpen()
const current = this.state(feature)
if (current.state === 'inconsistent') throw new Error(`feature ${feature.id} is inconsistent`)
if (current.state === 'absent' || !current.selection) {
throw new Error(`feature ${feature.id} is not installed`)
}
this.setFeatureDisabled(feature, current.selection, false)
current.state = 'enabled'
this.assertFeatureConsistent(feature)
this.disabled.delete(feature.id)
this.enabled.add(feature.id)
}
/** Disable an optional feature without removing its configuration. */
disableFeature(feature: Feature): void {
this.assertOpen()
if (feature.required) throw new Error(`required feature ${feature.id} cannot be disabled`)
const current = this.state(feature)
if (current.state === 'inconsistent') throw new Error(`feature ${feature.id} is inconsistent`)
if (current.state === 'absent' || !current.selection) {
throw new Error(`feature ${feature.id} is not installed`)
}
const dependent = this.registry.all().find((candidate) => {
const state = this.states.get(candidate.id)
return state?.state === 'enabled' && state.selection
&& candidate.requirements(state.selection).some(requirement => requirement.id === feature.id)
})
if (dependent) throw new Error(`feature ${feature.id} is required by ${dependent.id}`)
this.setFeatureDisabled(feature, current.selection, true)
current.state = 'disabled'
this.assertFeatureConsistent(feature)
this.enabled.delete(feature.id)
this.disabled.add(feature.id)
}
/** Add a generated local plugin and all four of its project registrations. */
addPlugin(blueprint: LocalPluginBlueprint): void {
this.assertOpen()
const manifest = this.manifest()
const cordis = this.cordis()
const tsconfig = this.documents.get('tsconfig.json')
if (!(tsconfig instanceof TsConfigFile)) {
throw new Error('adding a local plugin requires a valid tsconfig.json')
}
const packageName = blueprint.packageName(this.profile.name)
if (manifest.npmDependency(packageName)) throw new Error(`root NPM dependency already exists: ${packageName}`)
const entry = blueprint.cordisConfigEntry(this.profile.name)
if (cordis.entry(entry.id)) throw new Error(`Cordis config entry already exists: ${entry.id}`)
const documents = blueprint.documents(this.profile.name, this.profile.releaseVersion)
for (const document of documents) {
if (this.documents.has(document.relativePath)) {
throw new Error(`local plugin file already exists: ${document.relativePath}`)
}
}
for (const document of documents) this.documents.set(document.relativePath, document)
manifest.setNpmDependency('dependencies', packageName, this.profile.packageManager.localPluginSpec())
tsconfig.addReference(`./${blueprint.directory}`)
cordis.addEntry(entry)
this.addedPlugins.add(entry.id)
}
/** Enable or disable one custom/manual Cordis config entry by stable id. */
setCustomPluginDisabled(id: string, disabled: boolean): void {
this.assertOpen()
const entry = this.cordis().entry(id)
if (!entry) throw new Error(`Cordis config entry does not exist: ${id}`)
if (this.registry.ownerOfPackage(entry.name, this.profile)) {
throw new Error(`Cordis config entry ${id} belongs to a builtin feature`)
}
this.cordis().setDisabled(id, disabled)
if (disabled) {
this.enabledPlugins.delete(id)
this.disabledPlugins.add(id)
} else {
this.disabledPlugins.delete(id)
this.enabledPlugins.add(id)
}
}
/** Summarize all pending domain and file changes. */
changes(): ChangeSet {
const changedFiles = new Set<string>()
for (const [path, document] of this.documents) {
if (this.source.origin === 'create' || !sameText(document, this.source.document(path))) changedFiles.add(path)
}
for (const path of this.removed.keys()) changedFiles.add(path)
return {
addedFeatures: [...this.added].sort(),
enabledFeatures: [...this.enabled].sort(),
disabledFeatures: [...this.disabled].sort(),
configuredFeatures: [...this.configured].sort(),
addedPlugins: [...this.addedPlugins].sort(),
enabledPlugins: [...this.enabledPlugins].sort(),
disabledPlugins: [...this.disabledPlugins].sort(),
changedFiles: [...changedFiles].sort(),
npmDependenciesChanged: npmDependencyShape(this.manifest().value())
!== npmDependencyShape(this.source.packageManifest()),
}
}
/** Validate, detect external edits, write affected files, and return a fresh snapshot. */
async commit(): Promise<ProjectCommitResult<SdkProject>> {
this.assertOpen()
if (this.profile.linkWorkspaceRoot) {
const workspace = await LinkWorkspace.open(this.profile.linkWorkspaceRoot)
workspace.apply(
this.source.root,
this.manifest(),
this.profile.packageManager,
[...this.documents.values()],
)
}
this.validateFinalState()
const changes = this.changes()
await this.assertUnchanged(changes.changedFiles)
await mkdir(this.source.root, { recursive: true })
for (const path of changes.changedFiles) {
const document = this.documents.get(path)
const absolute = resolve(this.source.root, path)
if (!document) {
await unlink(absolute)
continue
}
await mkdir(dirname(absolute), { recursive: true })
await writeFile(absolute, document.serialize(), {
encoding: 'utf8',
...document.createMode === undefined ? {} : { mode: document.createMode },
})
}
this.committed = true
return { project: await this.source.reopen(), changes }
}
private installFeatureRecursive(
feature: Feature,
selection: FeatureSelection,
stack: Set<FeatureId>,
): void {
if (stack.has(feature.id)) throw new Error(`cyclic feature requirement involving ${feature.id}`)
const current = this.state(feature)
if (current.state === 'inconsistent') throw new Error(`feature ${feature.id} is inconsistent`)
if (current.state !== 'absent' && current.selection) {
this.configureFeature(feature, selection)
if (current.state === 'disabled') this.enableFeature(feature)
return
}
const normalized = feature.normalizeSelection(selection, this.profile)
const nextStack = new Set(stack).add(feature.id)
this.ensureRequirements(feature, normalized, nextStack)
this.replaceContribution(undefined, feature.contribution(normalized, this.profile))
current.selection = normalized
current.state = 'enabled'
this.assertFeatureConsistent(feature)
this.added.add(feature.id)
}
private ensureRequirements(feature: Feature, selection: FeatureSelection, stack: Set<FeatureId>): void {
for (const requirement of feature.requirements(selection)) {
const required = this.registry.get(requirement.id)
const state = this.state(required)
if (state.state === 'inconsistent') throw new Error(`required feature ${required.id} is inconsistent`)
if (state.state === 'absent' || !state.selection) {
this.installFeatureRecursive(required, {
id: required.id,
options: requirement.options ?? required.defaultOptions(this.profile),
}, stack)
} else {
const next = this.selectionWithRequiredOptions(required, state.selection, requirement)
if (next !== state.selection) this.configureFeature(required, next)
if (state.state === 'disabled') this.enableFeature(required)
}
}
}
private selectionWithRequiredOptions(
feature: Feature,
selection: FeatureSelection,
requirement: FeatureRequirement,
): FeatureSelection {
if (!requirement.options || requirement.options.every(option => selection.options.includes(option))) {
return selection
}
if (feature.mode !== 'multiple') {
throw new Error(`${feature.id} does not satisfy the option requirement from another feature`)
}
return { ...selection, options: [...new Set([...selection.options, ...requirement.options])] }
}
private replaceContribution(
previous: ReturnType<Feature['contribution']> | undefined,
next: ReturnType<Feature['contribution']>,
): void {
const previousByKey = previous?.byKey() ?? new Map<ResourceKey, ProjectResource>()
const nextByKey = next.byKey()
for (const [key, resource] of previousByKey) {
const replacement = nextByKey.get(key)
if (!replacement || !canUpdateResource(resource, replacement)) this.removeResource(resource)
}
for (const [key, resource] of nextByKey) {
const previousResource = previousByKey.get(key)
this.applyResource(
resource,
previousResource && canUpdateResource(previousResource, resource) ? previousResource : undefined,
)
}
}
private applyResource(resource: ProjectResource, previous: ProjectResource | undefined): void {
switch (resource.kind) {
case 'npm-dependency': {
const dependency = resolveNpmDependency(resource.name, resource.section, this.profile.releaseVersion)
this.manifest().setNpmDependency(dependency.section, resource.name, dependency.spec)
return
}
case 'package-script': {
const manifest = this.manifest()
const current = manifest.script(resource.name)
if (!previous || previous.kind !== 'package-script') {
if (current !== undefined) throw new Error(`feature-owned package script already exists: ${resource.name}`)
manifest.setScript(resource.name, resource.command)
return
}
if (current === resource.command) return
if (current !== previous.command) {
throw new Error(`feature-owned package script was modified: ${resource.name}`)
}
manifest.setScript(resource.name, resource.command)
return
}
case 'cordis-config-entry': {
const current = this.cordis().entry(resource.entry.id)
if (!current) this.cordis().addEntry(resource.entry, resource.commentedExample)
else {
if (current.name !== resource.entry.name) {
throw new Error(`Cordis config entry ${resource.entry.id} is owned by ${current.name}, not ${resource.entry.name}`)
}
this.cordis().updateOwnedConfig(
resource.entry.id,
resource.ownedConfigKeys,
resource.entry.config ?? {},
)
this.cordis().setDisabled(resource.entry.id, false)
}
return
}
case 'environment': {
this.environment('.env.example').set(resource.name, resource.exampleValue)
/* v8 ignore else -- an omitted secret intentionally materializes only its example placeholder */
if (resource.value !== undefined) {
const environment = this.environment('.env')
environment.append(
resource.name,
resource.value,
resource.value === '' ? resource.comment : undefined,
)
}
return
}
case 'owned-file': {
const existing = this.documents.get(resource.document.relativePath)
if (!existing) {
this.documents.set(resource.document.relativePath, resource.document.clone())
this.removed.delete(resource.document.relativePath)
return
}
if (!previous || previous.kind !== 'owned-file') {
throw new Error(`feature-owned file already exists: ${resource.document.relativePath}`)
}
if (previous.document.serialize() === resource.document.serialize()) return
if (existing.serialize() !== previous.document.serialize()) {
throw new Error(`feature-owned file was modified: ${resource.document.relativePath}`)
}
this.documents.set(resource.document.relativePath, resource.document.clone())
this.removed.delete(resource.document.relativePath)
return
}
}
}
private removeResource(resource: ProjectResource): void {
switch (resource.kind) {
case 'npm-dependency':
this.manifest().removeNpmDependency(resource.section, resource.name)
return
case 'package-script': {
const manifest = this.manifest()
const current = manifest.script(resource.name)
if (current === undefined) throw new Error(`owned package script is missing: ${resource.name}`)
if (resource.removeOnlyWhenUnchanged && current !== resource.command) {
throw new Error(`feature-owned package script was modified: ${resource.name}`)
}
manifest.removeScript(resource.name)
return
}
case 'cordis-config-entry': {
const entry = this.cordis().entry(resource.entry.id)
if (!entry || entry.name !== resource.entry.name) {
throw new Error(`cannot confirm old Cordis resource ${resource.entry.id}`)
}
this.cordis().removeEntry(resource.entry.id)
return
}
case 'environment':
this.environment('.env.example').remove(resource.name)
return
case 'owned-file': {
const document = this.documents.get(resource.document.relativePath)
if (!document) throw new Error(`owned file is missing: ${resource.document.relativePath}`)
if (resource.removeOnlyWhenUnchanged && document.serialize() !== resource.document.serialize()) {
throw new Error(`owned file was modified: ${resource.document.relativePath}`)
}
this.documents.delete(resource.document.relativePath)
if (this.source.document(resource.document.relativePath)) {
this.removed.set(resource.document.relativePath, document)
}
}
}
}
private setFeatureDisabled(feature: Feature, selection: FeatureSelection, disabled: boolean): void {
for (const resource of feature.contribution(selection, this.profile).resources) {
if (resource.kind === 'cordis-config-entry') this.cordis().setDisabled(resource.entry.id, disabled)
}
}
private validateFinalState(): void {
for (const document of this.documents.values()) document.validate()
const profile = this.finalProfile()
const view = this.projectView(profile)
for (const feature of this.registry.all()) {
const state = this.states.get(feature.id)
if (!feature.isApplicable(profile)) {
if (state?.state === 'enabled') {
throw new Error(`feature ${feature.id} is not available for ${profile.runInterface}`)
}
continue
}
const installation = feature.inspect(view)
/* v8 ignore next 3 -- public domain commands assert feature consistency before final validation */
if (installation.state === 'inconsistent') {
throw new Error(`feature ${feature.id} is inconsistent: ${installation.diagnostics.join('; ')}`)
}
/* v8 ignore next 3 -- required features are installed by creation and cannot be disabled by public commands */
if (feature.required && installation.state !== 'enabled') {
throw new Error(`required feature ${feature.id} must be installed and enabled`)
}
if (installation.state !== 'enabled' || !installation.selection) continue
for (const requirement of feature.requirements(installation.selection)) {
const required = this.registry.get(requirement.id).inspect(view)
/* v8 ignore next 3 -- ensureRequirements establishes enabled requirements before contributions change */
if (required.state !== 'enabled') {
throw new Error(`feature ${feature.id} requires enabled ${requirement.id}`)
}
for (const option of requirement.options ?? []) {
/* v8 ignore next 3 -- selectionWithRequiredOptions establishes required options before commit */
if (!required.options.includes(option)) {
throw new Error(`feature ${feature.id} requires ${requirement.id} option ${option}`)
}
}
}
}
}
private assertFeatureConsistent(feature: Feature): void {
const installation = feature.inspect(this)
/* v8 ignore next 3 -- resource application either succeeds completely or throws at the owning operation */
if (installation.state === 'inconsistent') {
throw new Error(`feature ${feature.id} is inconsistent: ${installation.diagnostics.join('; ')}`)
}
}
private finalProfile(): ProjectProfile {
const runInterface = this.states.get(featureId('app'))?.selection?.options[0]
if (runInterface !== 'acp' && runInterface !== 'stdio' && runInterface !== 'embed') return this.profile
return { ...this.profile, runInterface }
}
private projectView(profile: ProjectProfile): FeatureProjectView {
return {
profile,
cordisConfigEntries: () => this.cordisConfigEntries(),
packageManifest: () => this.packageManifest(),
hasDocument: path => this.hasDocument(path),
readEnvironment: (path, name) => this.readEnvironment(path, name),
}
}
private async assertUnchanged(paths: readonly string[]): Promise<void> {
for (const path of paths) {
const source = this.source.document(path)
const absolute = resolve(this.source.root, path)
try {
const current = await readFile(absolute, 'utf8')
if (source?.originalText === undefined || current !== source.originalText) {
throw new Error(`project file changed outside this edit session: ${path}`)
}
} catch (error) {
const code = (error as NodeJS.ErrnoException).code
if (code === 'ENOENT' && source?.originalText === undefined) continue
if (error instanceof Error && error.message.startsWith('project file changed outside')) throw error
throw new Error(`cannot verify project file ${path}: ${asError(error).message}`)
}
}
}
private state(feature: Feature): MutableFeatureState {
const state = this.states.get(feature.id)
if (!state) throw new Error(`feature ${feature.id} is not applicable to this project`)
return state
}
private manifest(): PackageJsonFile {
const document = this.documents.get('package.json')
if (!(document instanceof PackageJsonFile)) throw new Error('project package.json is missing')
return document
}
private cordis(): CordisYamlFile {
const document = this.documents.get('cordis.yml')
if (!(document instanceof CordisYamlFile)) throw new Error('project cordis.yml is missing')
return document
}
private environment(path: '.env' | '.env.example'): EnvFile {
const existing = this.documents.get(path)
if (existing instanceof EnvFile) return existing
if (existing) throw new Error(`${path} is not an environment document`)
const document = EnvFile.create(path)
this.documents.set(path, document)
return document
}
private assertOpen(): void {
if (this.committed) throw new Error('project edit session has already committed')
}
}

View File

@@ -0,0 +1,305 @@
/**
* Read-only aggregate for one generated or existing SDK project.
*
* @module @deepseek-ai/dsh-helper/project/sdk-project
*/
import { access, readFile } from 'node:fs/promises'
import { basename, resolve } from 'node:path'
import { CordisYamlFile, type CordisConfigEntry } from '../documents/cordis-yaml-file.ts'
import { EnvFile } from '../documents/env-file.ts'
import { PackageJsonFile, type PackageManifest } from '../documents/package-json-file.ts'
import { PnpmWorkspaceFile } from '../documents/pnpm-workspace-file.ts'
import { ProjectFile, TextProjectFile } from '../documents/project-file.ts'
import { TsConfigFile } from '../documents/tsconfig-file.ts'
import {
createPackageManager,
type PackageManager,
type PackageManagerName,
} from '../package-managers/package-manager.ts'
import {
createBaselineProjectArtifacts,
createPackageJsonDoc,
createProjectTemplateContext,
} from '../templates/project-template.ts'
import type { ProjectCreationRequest, ProjectProfile, RunInterface } from './types.ts'
import type { FeatureRegistry } from '../features/registry.ts'
import { ProjectEditSession } from './project-edit-session.ts'
/** Whether a project snapshot describes uncommitted creation or files on disk. */
export type ProjectOrigin = 'create' | 'disk'
const OPTIONAL_DOCUMENTS = [
'.env',
'.env.example',
'tsconfig.json',
'pnpm-workspace.yaml',
'hooks.json',
'codex-hooks.json',
'README.md',
'index.ts',
] as const
function runInterface(entries: readonly CordisConfigEntry[]): RunInterface {
if (entries.some(entry => entry.name === '@deepseek-ai/dsh-acp')) return 'acp'
if (entries.some(entry => entry.name === '@deepseek-ai/dsh-stdio')) return 'stdio'
return 'embed'
}
function runtimeModel(entries: readonly CordisConfigEntry[]): string {
const acp = entries.find(entry => entry.name === '@deepseek-ai/dsh-acp')
if (typeof acp?.config?.model === 'string' && acp.config.model.length > 0) return acp.config.model
const provider = entries.find(entry => entry.name === '@deepseek-ai/dsh-llm-deepseek'
|| entry.name === '@deepseek-ai/dsh-llm-pi-ai')
const models = provider?.config?.models
if (Array.isArray(models) && typeof models[0] === 'string') return models[0]
return 'deepseek-v4-flash'
}
function releaseVersion(manifest: Readonly<PackageManifest>): string {
const spec = manifest.dependencies?.['@deepseek-ai/dsh-scripts']
const match = spec && /(?:^|[^0-9])(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(spec)
return match?.[1] ?? '0.0.1'
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path)
return true
} catch (error) {
/* v8 ignore else -- the other arm requires a filesystem permission/IO fault from access */
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false
/* v8 ignore next -- paired with the ignored defensive access-error arm above */
throw error
}
}
async function detectPackageManager(root: string, manifest: Readonly<PackageManifest>): Promise<PackageManager> {
let name: PackageManagerName = 'npm'
let version = '10.0.0'
const field = manifest.packageManager
if (field) {
const match = /^(npm|pnpm|yarn)@(.+)$/.exec(field)
if (!match?.[1] || !match[2]) throw new Error(`invalid packageManager field: ${field}`)
name = match[1] as PackageManagerName
version = match[2]
} else if (await pathExists(resolve(root, 'pnpm-lock.yaml'))) {
name = 'pnpm'
version = '10.0.0'
} else if (await pathExists(resolve(root, 'yarn.lock'))) {
name = 'yarn'
version = '2.0.0'
}
return createPackageManager(name, version)
}
function linkedRepositoryRoot(root: string, manifest: Readonly<PackageManifest>): string | undefined {
const spec = manifest.dependencies?.['@deepseek-ai/dsh-scripts']
const match = /^(?:file|link|portal):(.+)\/packages\/sdk\/scripts\/?$/.exec(spec ?? '')
return match?.[1] ? resolve(root, match[1]) : undefined
}
function parseOptionalDocument(path: string, text: string): ProjectFile {
try {
switch (path) {
case '.env': return EnvFile.parse('.env', text)
case '.env.example': return EnvFile.parse('.env.example', text)
case 'tsconfig.json': return TsConfigFile.parse(text)
case 'pnpm-workspace.yaml': return PnpmWorkspaceFile.parse(text)
default: return new TextProjectFile(path, text, text)
}
} catch {
// Optional malformed resources do not invalidate the project aggregate;
// an operation that needs their structure checks the concrete document type.
return new TextProjectFile(path, text, text)
}
}
/** A project snapshot whose documents can only be changed through {@link ProjectEditSession}. */
export class SdkProject {
/** Absolute project directory. */
readonly root: string
/** Whether this snapshot is an uncommitted blueprint or disk state. */
readonly origin: ProjectOrigin
/** Project identity, runtime, interface, and package-manager context. */
readonly profile: ProjectProfile
private readonly documents: ReadonlyMap<string, ProjectFile>
private constructor(
root: string,
origin: ProjectOrigin,
profile: ProjectProfile,
documents: ReadonlyMap<string, ProjectFile>,
) {
this.root = resolve(root)
this.origin = origin
this.profile = profile
this.documents = documents
}
/**
* Build an in-memory project blueprint without touching the target directory.
* @param root - target project directory.
* @param request - complete creation request.
* @returns uncommitted project snapshot.
*/
static create(root: string, request: ProjectCreationRequest): SdkProject {
const app = request.features.find(selection => selection.id === 'app')
const selectedInterface = app?.options[0]
if (selectedInterface !== 'acp' && selectedInterface !== 'stdio' && selectedInterface !== 'embed') {
throw new Error('project creation requires one app feature option')
}
const profile: ProjectProfile = {
name: request.name,
description: request.description,
runtime: request.runtime,
runInterface: selectedInterface,
packageManager: request.packageManager,
releaseVersion: request.releaseVersion,
...request.linkWorkspaceRoot ? { linkWorkspaceRoot: resolve(request.linkWorkspaceRoot) } : {},
}
const templates = createProjectTemplateContext(profile)
const manifest = createPackageJsonDoc(templates)
const documents = new Map<string, ProjectFile>()
documents.set(manifest.relativePath, manifest)
documents.set('cordis.yml', CordisYamlFile.create())
documents.set('.env.example', EnvFile.create('.env.example'))
documents.set('tsconfig.json', TsConfigFile.create())
for (const document of request.packageManager.configureWorkspace(manifest)) {
documents.set(document.relativePath, document)
}
for (const document of createBaselineProjectArtifacts(templates)) {
documents.set(document.relativePath, document)
}
return new SdkProject(root, 'create', profile, documents)
}
/**
* Load an existing project from required and SDK-managed optional files.
* @param root - existing project directory.
* @returns disk-backed project snapshot.
*/
static async open(root: string): Promise<SdkProject> {
const absolute = resolve(root)
const [manifestText, cordisText] = await Promise.all([
readFile(resolve(absolute, 'package.json'), 'utf8'),
readFile(resolve(absolute, 'cordis.yml'), 'utf8'),
])
const manifest = PackageJsonFile.parse(manifestText)
const cordis = CordisYamlFile.parse(cordisText)
const value = manifest.value()
const manager = await detectPackageManager(absolute, value)
const entries = cordis.entries()
const linkWorkspaceRoot = linkedRepositoryRoot(absolute, value)
const profile: ProjectProfile = {
name: value.name ?? basename(absolute),
description: typeof value.description === 'string' ? value.description : '',
runtime: { model: runtimeModel(entries) },
runInterface: runInterface(entries),
packageManager: manager,
releaseVersion: releaseVersion(value),
...linkWorkspaceRoot ? { linkWorkspaceRoot } : {},
}
const documents = new Map<string, ProjectFile>([
['package.json', manifest],
['cordis.yml', cordis],
])
await Promise.all(OPTIONAL_DOCUMENTS.map(async (path) => {
try {
const text = await readFile(resolve(absolute, path), 'utf8')
documents.set(path, parseOptionalDocument(path, text))
} catch (error) {
/* v8 ignore next -- optional-file reads fail normally only with ENOENT; other IO faults surface */
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
}
}))
return new SdkProject(absolute, 'disk', profile, documents)
}
/**
* Read the root package manifest defensively.
* @returns cloned manifest value.
*/
packageManifest(): Readonly<PackageManifest> {
return this.packageJson.value()
}
/**
* Read Cordis config entries defensively in file order.
* @returns cloned Cordis config entries.
*/
cordisConfigEntries(): readonly CordisConfigEntry[] {
return this.cordis.entries()
}
/**
* Check whether this snapshot contains one managed document.
* @param path - project-relative document path.
* @returns whether the document is loaded.
*/
hasDocument(path: string): boolean {
return this.documents.has(path)
}
/**
* Read one environment variable from a loaded dotenv document.
* @param path - environment file to read.
* @param name - variable name.
* @returns variable value when present.
*/
readEnvironment(path: '.env' | '.env.example', name: string): string | undefined {
const document = this.documents.get(path)
if (!document) return undefined
if (!(document instanceof EnvFile)) throw new Error(`${path} is not an environment document`)
return document.get(name)
}
/** Read the root package document. */
get packageJson(): PackageJsonFile {
const document = this.documents.get('package.json')
if (!(document instanceof PackageJsonFile)) throw new Error('project package.json is missing or invalid')
return document
}
/** Read the root Cordis document. */
get cordis(): CordisYamlFile {
const document = this.documents.get('cordis.yml')
if (!(document instanceof CordisYamlFile)) throw new Error('project cordis.yml is missing or invalid')
return document
}
/**
* Return one managed document without exposing the aggregate map.
* @param path - project-relative document path.
* @returns loaded document when present.
*/
document(path: string): ProjectFile | undefined {
return this.documents.get(path)
}
/**
* Create the only mutable boundary for this snapshot.
* @param registry - feature catalog governing edits.
* @returns isolated edit session.
*/
edit(registry: FeatureRegistry): ProjectEditSession {
return new ProjectEditSession(this, registry)
}
/**
* Clone every managed document for an isolated edit session.
* @returns project-relative document map.
*/
cloneDocuments(): Map<string, ProjectFile> {
return new Map([...this.documents].map(([path, document]) => [path, document.clone()]))
}
/**
* Reload this aggregate from committed disk state.
* @returns fresh disk-backed snapshot.
*/
reopen(): Promise<SdkProject> {
return SdkProject.open(this.root)
}
}

View File

@@ -0,0 +1,48 @@
/**
* Shared creation and project-profile values for SDK project editing.
*
* @module @deepseek-ai/dsh-helper/project/types
*/
import type { PackageManager } from '../package-managers/package-manager.ts'
import type { LocalPluginBlueprint } from '../plugins/local-plugin-blueprint.ts'
import type { FeatureId } from '../ids.ts'
/** Runtime front door selected for a generated project. */
export type RunInterface = 'acp' | 'stdio' | 'embed'
/** Values shared by the required provider and app features. */
interface ProjectRuntimeOptions {
model: string
}
/** Selected options and captured secrets for one feature. */
export interface FeatureSelection {
id: FeatureId
options: readonly string[]
values?: Readonly<Record<string, unknown>>
secrets?: Readonly<Record<string, string>>
}
/** Stable context available to project and feature objects. */
export interface ProjectProfile {
name: string
description: string
runtime: ProjectRuntimeOptions
runInterface: RunInterface
packageManager: PackageManager
releaseVersion: string
linkWorkspaceRoot?: string
}
/** Fully collected create request; it contains intent, never rendered file text. */
export interface ProjectCreationRequest {
name: string
description: string
runtime: ProjectRuntimeOptions
packageManager: PackageManager
releaseVersion: string
linkWorkspaceRoot?: string
features: readonly FeatureSelection[]
localPlugins: readonly LocalPluginBlueprint[]
}

View File

@@ -0,0 +1,304 @@
/**
* Tree-shaped Clack picker for root checkboxes with finite child options.
*
* @module @deepseek-ai/dsh-helper/questions/clack-nested-multiselect
*/
import { styleText } from 'node:util'
import type { Readable, Writable } from 'node:stream'
import { Prompt, isCancel } from '@clack/core'
import {
S_BAR,
S_BAR_END,
S_CHECKBOX_ACTIVE,
S_CHECKBOX_INACTIVE,
S_CHECKBOX_SELECTED,
S_RADIO_ACTIVE,
S_RADIO_INACTIVE,
symbol,
symbolBar,
} from '@clack/prompts'
import type {
NestedMultiSelectOption,
NestedMultiSelectRequest,
NestedMultiSelectValue,
PromptOutcome,
} from './prompt-port.ts'
interface NestedPromptOptions<TValue, TChoice> extends NestedMultiSelectRequest<TValue, TChoice> {
input: Readable
output: Writable
}
class NestedPrompt<TValue, TChoice> extends Prompt<readonly NestedMultiSelectValue<TValue, TChoice>[]> {
readonly options: readonly NestedMultiSelectOption<TValue, TChoice>[]
private readonly selected = new Set<TValue>()
private readonly selectedChoices = new Map<TValue, Set<TChoice>>()
private readonly initialSelected: Set<TValue>
private readonly initialChoices: Map<TValue, Set<TChoice>>
private readonly showChanges: boolean
private layer: 'root' | 'choices' = 'root'
private rootCursor = 0
private choiceCursor = 0
constructor(options: NestedPromptOptions<TValue, TChoice>) {
super({
input: options.input,
output: options.output,
validate: value => NestedPrompt.validate(options.options, value),
render(this: Prompt<readonly NestedMultiSelectValue<TValue, TChoice>[]>) {
return (this as NestedPrompt<TValue, TChoice>).renderFrame(options.message)
},
}, false)
this.options = options.options
this.showChanges = options.showChanges ?? false
for (const option of options.options) {
if (option.required || option.default) this.selected.add(option.value)
this.selectedChoices.set(option.value, new Set(
option.choices?.filter(choice => choice.default).map(choice => choice.value) ?? [],
))
}
this.initialSelected = new Set(this.selected)
this.initialChoices = new Map([...this.selectedChoices].map(([value, choices]) => [
value, new Set(choices),
]))
this.updateValue()
this.on('cursor', (action) => { this.handleAction(action) })
}
private static validate<TValue, TChoice>(
options: readonly NestedMultiSelectOption<TValue, TChoice>[],
value: readonly NestedMultiSelectValue<TValue, TChoice>[] | undefined,
): string | undefined {
/* v8 ignore next -- NestedPrompt initializes its value before submission validation */
const selected = new Map(value?.map(item => [item.value, item.choices]) ?? [])
for (const option of options) {
if (option.disabled) continue
/* v8 ignore next -- required options initialize selected and cannot be toggled off */
if (option.required && !selected.has(option.value)) return `${option.label} is required`
if (!selected.has(option.value) || !option.choiceMode) continue
const choices = selected.get(option.value)
/* v8 ignore next -- selected.has above guarantees the map value exists */
if (!choices) continue
const count = choices.length
if (option.choiceMode === 'exclusive' && count !== 1) return `Choose one ${option.label} option`
if (option.choiceMode === 'multiple' && count === 0) return `Choose at least one ${option.label} option`
}
return undefined
}
protected override _shouldSubmit(): boolean {
if (this.layer === 'choices') {
this.leaveChoices()
return false
}
return true
}
private handleAction(action: string | undefined): void {
if (this.layer === 'root') this.handleRootAction(action)
else this.handleChoiceAction(action)
this.updateValue()
}
private handleRootAction(action: string | undefined): void {
if (action === 'up') this.rootCursor = this.move(this.rootCursor, -1, this.options.length)
if (action === 'down') this.rootCursor = this.move(this.rootCursor, 1, this.options.length)
const option = this.options[this.rootCursor]
/* v8 ignore next -- Clack cannot emit a cursor action when the option list is empty */
if (!option) return
if (action === 'space' && !option.required && !option.disabled) {
if (this.selected.has(option.value)) this.selected.delete(option.value)
else this.selected.add(option.value)
}
if (action === 'right' && !option.disabled && option.choices && option.choices.length > 0) {
this.selected.add(option.value)
this.layer = 'choices'
const selected = this.selectedChoices.get(option.value)
const selectedIndex = option.choices.findIndex(choice => selected?.has(choice.value))
this.choiceCursor = Math.max(selectedIndex, 0)
}
}
private handleChoiceAction(action: string | undefined): void {
const rootOption = this.options[this.rootCursor]
/* v8 ignore next -- the choices layer is entered only from a concrete root option */
if (!rootOption) return
/* v8 ignore next -- the choices layer is entered only for a non-empty choices array */
const choices = rootOption.choices ?? []
if (action === 'left') {
this.leaveChoices()
return
}
if (action === 'up') this.choiceCursor = this.move(this.choiceCursor, -1, choices.length)
if (action === 'down') this.choiceCursor = this.move(this.choiceCursor, 1, choices.length)
if ((action === 'up' || action === 'down') && rootOption.choiceMode === 'exclusive') {
const choice = choices[this.choiceCursor]
/* v8 ignore else -- a cursor in the non-empty choices layer always addresses a choice */
if (choice) this.selectedChoices.set(rootOption.value, new Set([choice.value]))
}
if (action !== 'space' && action !== 'right') return
const choice = choices[this.choiceCursor]
/* v8 ignore next -- the choices layer requires a non-empty choice list */
if (!choice) return
/* v8 ignore next -- every root option initializes its choice set in the constructor */
const selected = this.selectedChoices.get(rootOption.value) ?? new Set<TChoice>()
if (rootOption.choiceMode === 'exclusive') {
selected.clear()
selected.add(choice.value)
} else if (selected.has(choice.value)) selected.delete(choice.value)
else selected.add(choice.value)
this.selectedChoices.set(rootOption.value, selected)
}
private move(cursor: number, offset: number, length: number): number {
/* v8 ignore next -- cursor movement is emitted only for a non-empty displayed list */
if (length === 0) return 0
return (cursor + offset + length) % length
}
private updateValue(): void {
this._setValue(this.options.filter(option => this.selected.has(option.value)).map(option => ({
value: option.value,
/* v8 ignore next -- every root option initializes its choice set in the constructor */
choices: [...this.selectedChoices.get(option.value) ?? []],
})))
}
private renderFrame(message: string): string {
const header = `${symbolBar(this.state)} ${message}`
if (this.state === 'submit') {
/* v8 ignore next -- NestedPrompt initializes its value before it can submit */
const summary = (this.value ?? []).map(item => this.options.find(option => option.value === item.value)?.label)
.filter(Boolean).join(', ') || 'none'
return `${symbol(this.state)} ${message}\n${styleText('gray', S_BAR)} ${styleText('dim', summary)}`
}
if (this.state === 'cancel') return `${symbol(this.state)} ${message}`
const body = this.layer === 'root' ? this.renderRoot() : this.renderChoices()
const instructions = this.layer === 'root'
? `${styleText('dim', '↑/↓')} navigate ${styleText('dim', 'Space')} select ${styleText('dim', '→')} configure ${styleText('dim', 'Enter')} confirm`
: `${styleText('dim', '↑/↓')} navigate ${styleText('dim', 'Space/→')} select ${styleText('dim', '←/Enter')} back`
const error = this.state === 'error' ? `\n${styleText('yellow', `${S_BAR_END} ${this.error}`)}` : ''
return `${header}\n${styleText('cyan', S_BAR)} ${body.join(`\n${styleText('cyan', S_BAR)} `)}\n${styleText('cyan', S_BAR_END)} ${instructions}${error}`
}
private renderRoot(): string[] {
return this.options.map((option, index) => {
const active = index === this.rootCursor
const selected = this.selected.has(option.value)
const focus = active ? styleText('cyan', '') : ' '
const checkbox = selected
? styleText('green', S_CHECKBOX_SELECTED)
: styleText('dim', active ? S_CHECKBOX_ACTIVE : S_CHECKBOX_INACTIVE)
const choices = option.choices?.filter(choice => this.selectedChoices.get(option.value)?.has(choice.value))
.map(choice => choice.label).join(', ')
const suffix = option.choices?.length
? ` ${styleText('dim', `* →${choices ? ` ${choices}` : ''}`)}`
: ''
const required = option.required ? ` ${styleText('yellow', '(required)')}` : ''
const issue = this.choiceIssue(option)
const warningText = option.warning ?? issue
const warning = warningText ? ` ${styleText('yellow', `${warningText}`)}` : ''
const changed = this.optionChanged(option)
const change = changed ? ` ${styleText('yellow', '● changed')}` : ''
const label = active
? styleText('cyan', option.label)
: changed
? styleText('yellow', option.label)
: selected ? styleText('green', option.label) : styleText('dim', option.label)
const line = `${focus} ${checkbox} ${label}${required}${suffix}${warning}${change}`
return option.disabled ? styleText('gray', line) : line
})
}
private renderChoices(): string[] {
const rootOption = this.options[this.rootCursor]
/* v8 ignore next -- renderChoices runs only after entering from a concrete root option */
if (!rootOption) return []
/* v8 ignore next -- every root option initializes its choice set in the constructor */
const selected = this.selectedChoices.get(rootOption.value) ?? new Set<TChoice>()
const issue = this.choiceIssue(rootOption)
const changed = this.optionChanged(rootOption)
const header = styleText('dim', `${rootOption.label} options`)
+ (issue ? ` ${styleText('yellow', `${issue}`)}` : '')
+ (changed ? ` ${styleText('yellow', '● changed')}` : '')
const choices = rootOption.choices
/* v8 ignore next -- the choices layer is entered only for a non-empty choices array */
if (!choices) return [header]
return [
header,
...choices.map((choice, index) => {
const active = index === this.choiceCursor
const checked = selected.has(choice.value)
const choiceChanged = this.choiceChanged(rootOption.value, choice.value)
const focus = active ? styleText('cyan', '') : ' '
const marker = rootOption.choiceMode === 'exclusive'
? checked ? styleText('green', S_RADIO_ACTIVE) : styleText('dim', S_RADIO_INACTIVE)
: checked ? styleText('green', S_CHECKBOX_SELECTED) : styleText('dim', S_CHECKBOX_INACTIVE)
const label = active
? styleText('cyan', choice.label)
: choiceChanged
? styleText('yellow', choice.label)
: checked ? styleText('green', choice.label) : styleText('dim', choice.label)
const change = choiceChanged ? ` ${styleText('yellow', '●')}` : ''
return `${focus} ${marker} ${label}${change}`
}),
]
}
private optionChanged(option: NestedMultiSelectOption<TValue, TChoice>): boolean {
if (!this.showChanges) return false
const selected = this.selected.has(option.value)
const initiallySelected = this.initialSelected.has(option.value)
if (selected !== initiallySelected) return true
if (!selected) return false
/* v8 ignore next -- every root option initializes both current and baseline option sets */
const current = this.selectedChoices.get(option.value) ?? new Set<TChoice>()
/* v8 ignore next -- every root option initializes both current and baseline option sets */
const initial = this.initialChoices.get(option.value) ?? new Set<TChoice>()
return current.size !== initial.size || [...current].some(value => !initial.has(value))
}
private choiceChanged(value: TValue, choice: TChoice): boolean {
if (!this.showChanges) return false
return this.selectedChoices.get(value)?.has(choice) !== this.initialChoices.get(value)?.has(choice)
}
private choiceIssue(option: NestedMultiSelectOption<TValue, TChoice>): string | undefined {
if (option.disabled || !this.selected.has(option.value) || !option.choiceMode) return undefined
/* v8 ignore next -- every root option initializes its choice set in the constructor */
const count = this.selectedChoices.get(option.value)?.size ?? 0
if (option.choiceMode === 'exclusive' && count !== 1) return 'choose one'
if (option.choiceMode === 'multiple' && count === 0) return 'choose at least one'
return undefined
}
private leaveChoices(): boolean {
const option = this.options[this.rootCursor]
/* v8 ignore next -- leaveChoices runs only after entering from a concrete root option */
if (!option) return false
const issue = this.choiceIssue(option)
if (issue) {
this.error = `${option.label}: ${issue}`
this.state = 'error'
return false
}
this.error = ''
this.layer = 'root'
return true
}
}
/** Run the nested picker with Clack's standard cancellation symbol. */
export async function clackNestedMultiselect<TValue, TChoice>(
request: NestedPromptOptions<TValue, TChoice>,
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
const value = await new NestedPrompt(request).prompt()
return isCancel(value)
? { status: 'cancelled' }
: {
status: 'answered',
/* v8 ignore next -- NestedPrompt initializes its value before it can submit */
value: value ?? [],
}
}

View File

@@ -0,0 +1,127 @@
/**
* Thin @clack/prompts adapter for the shared prompt port.
*
* @module @deepseek-ai/dsh-helper/questions/clack-prompt-port
*/
import type { Readable, Writable } from 'node:stream'
import { styleText } from 'node:util'
import {
confirm,
isCancel,
multiselect,
password,
select,
text,
S_WARN,
} from '@clack/prompts'
import type { Option } from '@clack/prompts'
import type {
ConfirmPromptRequest,
MultiSelectPromptRequest,
NestedMultiSelectRequest,
NestedMultiSelectValue,
PromptOutcome,
PromptPort,
SecretPromptRequest,
SelectPromptRequest,
TextPromptRequest,
} from './prompt-port.ts'
import { clackNestedMultiselect } from './clack-nested-multiselect.ts'
function outcome<T>(value: T | symbol): PromptOutcome<T> {
return isCancel(value) ? { status: 'cancelled' } : { status: 'answered', value }
}
function clackOptions<T>(values: readonly import('./prompt-port.ts').PromptOption<T>[]): Option<T>[] {
return values.map(value => ({
value: value.value,
label: value.label,
...value.hint === undefined ? {} : { hint: value.hint },
...value.disabled === undefined ? {} : { disabled: value.disabled },
})) as Option<T>[]
}
/** Clack-backed prompt adapter with injectable streams for snapshots and tests. */
export class ClackPromptPort implements PromptPort {
private readonly input: Readable
private readonly output: Writable
/** Bind all prompts to one input/output pair. */
constructor(input: Readable = process.stdin, output: Writable = process.stdout) {
this.input = input
this.output = output
}
/** Ask for visible text through clack. */
async text(request: TextPromptRequest): Promise<PromptOutcome<string>> {
return outcome(await text({
message: request.message,
...request.placeholder === undefined ? {} : { placeholder: request.placeholder },
...request.initialValue === undefined ? {} : { initialValue: request.initialValue },
...request.defaultValue === undefined ? {} : { defaultValue: request.defaultValue },
...request.validate === undefined
? {}
: {
/* v8 ignore next -- value/default precedence is exercised through the adapter contract tests */
validate: value => request.validate?.(value || request.defaultValue || ''),
},
input: this.input,
output: this.output,
}))
}
/** Ask for a masked secret through clack. */
async secret(request: SecretPromptRequest): Promise<PromptOutcome<string>> {
return outcome(await password({
message: request.message,
...request.validate === undefined ? {} : {
/* v8 ignore next -- @clack/password always calls validation with a string; fallback is defensive */
validate: value => request.validate?.(value ?? ''),
},
input: this.input,
output: this.output,
}))
}
/** Ask for one option through clack. */
async select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>> {
return outcome(await select({
...request,
options: clackOptions(request.options),
input: this.input,
output: this.output,
}))
}
/** Ask for multiple options through clack. */
async multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>> {
return outcome(await multiselect({
message: request.message,
options: clackOptions(request.options),
...request.initialValues === undefined ? {} : { initialValues: [...request.initialValues] },
...request.required === undefined ? {} : { required: request.required },
input: this.input,
output: this.output,
}))
}
/** Ask for confirmation through clack. */
async confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>> {
return outcome(await confirm({
message: request.tone === 'warning'
? styleText('yellow', `${S_WARN} ${request.message}`)
: request.message,
...request.initialValue === undefined ? {} : { initialValue: request.initialValue },
input: this.input,
output: this.output,
}))
}
/** Select root values and finite child options in one tree prompt. */
nestedMultiselect<TValue, TChoice>(
request: NestedMultiSelectRequest<TValue, TChoice>,
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>> {
return clackNestedMultiselect({ ...request, input: this.input, output: this.output })
}
}

View File

@@ -0,0 +1,124 @@
/**
* Terminal-prompt port shared by create and config workflows.
*
* @module @deepseek-ai/dsh-helper/questions/prompt-port
*/
/** One selectable prompt option. */
export interface PromptOption<T> {
value: T
label: string
hint?: string
disabled?: boolean
}
/** Answer or explicit cancellation returned by every prompt. */
export type PromptOutcome<T> =
| { status: 'answered'; value: T }
| { status: 'cancelled' }
/** Input for one text prompt. */
export interface TextPromptRequest {
message: string
placeholder?: string
initialValue?: string
defaultValue?: string
validate?: (value: string) => string | undefined
}
/** Input for one masked secret prompt. */
export interface SecretPromptRequest {
message: string
validate?: (value: string) => string | undefined
}
/** Input for one single-choice prompt. */
export interface SelectPromptRequest<T> {
message: string
options: readonly PromptOption<T>[]
initialValue?: T
}
/** Input for one additive multi-choice prompt. */
export interface MultiSelectPromptRequest<T> {
message: string
options: readonly PromptOption<T>[]
initialValues?: readonly T[]
required?: boolean
}
/** Input for one yes/no prompt. */
export interface ConfirmPromptRequest {
message: string
initialValue?: boolean
tone?: 'default' | 'warning'
}
/** One nested choice under a multi-select option. */
interface NestedSelectChoice<T> {
value: T
label: string
default?: boolean
}
/** One root option with optional child option configuration. */
export interface NestedMultiSelectOption<TValue, TChoice> {
value: TValue
label: string
required?: boolean
default?: boolean
disabled?: boolean
warning?: string
choiceMode?: 'exclusive' | 'multiple'
choices?: readonly NestedSelectChoice<TChoice>[]
}
/** Input for a tree-shaped feature-style picker. */
export interface NestedMultiSelectRequest<TValue, TChoice> {
message: string
options: readonly NestedMultiSelectOption<TValue, TChoice>[]
showChanges?: boolean
}
/** One selected root option and its child options. */
export interface NestedMultiSelectValue<TValue, TChoice> {
value: TValue
choices: readonly TChoice[]
}
/** Interaction boundary consumed by typed question objects. */
export interface PromptPort {
/** Ask for one line of visible text. */
text(request: TextPromptRequest): Promise<PromptOutcome<string>>
/** Ask for one masked value. */
secret(request: SecretPromptRequest): Promise<PromptOutcome<string>>
/** Ask for exactly one option. */
select<T>(request: SelectPromptRequest<T>): Promise<PromptOutcome<T>>
/** Ask for zero or more options. */
multiselect<T>(request: MultiSelectPromptRequest<T>): Promise<PromptOutcome<readonly T[]>>
/** Ask for a boolean confirmation. */
confirm(request: ConfirmPromptRequest): Promise<PromptOutcome<boolean>>
/** Select root options and configure finite child options in one tree prompt. */
nestedMultiselect<TValue, TChoice>(
request: NestedMultiSelectRequest<TValue, TChoice>,
): Promise<PromptOutcome<readonly NestedMultiSelectValue<TValue, TChoice>[]>>
}
/** Error used when a workflow chooses to turn prompt cancellation into command cancellation. */
export class PromptCancelledError extends Error {
/** Create a stable cancellation error. */
constructor(message = 'operation cancelled') {
super(message)
this.name = 'PromptCancelledError'
}
}
/**
* Return an answered value or throw the shared cancellation error.
* @param outcome - prompt result to unwrap.
* @returns answered value.
*/
export function requireAnswer<T>(outcome: PromptOutcome<T>): T {
if (outcome.status === 'cancelled') throw new PromptCancelledError()
return outcome.value
}

Some files were not shown because too many files have changed in this diff Show More