feat(bundle): ship dsh-base, dsh-web-app, and dsh-headless profile bundles

Profile bundles are npm packages declaring dsh.patch in their manifest:
dsh-base carries the former base.cordis.yml rows as one insert over the empty
profile root; dsh-web-app carries the web overlay plus a runtime glue plugin
owning what used to be launcher code (frontend dist resolution via
frontend-static, the web-surface prompt section, bash runtime variables, the
readiness-gated URL line); dsh-headless carries the one-shot runner driving a
task turn through the in-process API carrier under the launcher-provided
ctx.headlessIo seam.
This commit is contained in:
Turtle
2026-08-06 04:40:11 +08:00
parent 2ee2ee2f96
commit 2365b2c54f
39 changed files with 2282 additions and 327 deletions

View File

@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/bundle/headless/README.md
README.md: d08fb08e2aca3c4e5ccd733b37fc415d492974ca
README.zh.md: 99a64ef04c4fd8fb0c6a979d3f09f1bd98b434a0

View File

@@ -0,0 +1,18 @@
# `@deepseek-ai/dsh-headless`
English | [中文](README.zh.md)
The dsh one-shot bundle. [`cordis.patch.yml`](cordis.patch.yml) rides over [`dsh-base`](../base/README.md) + [`dsh-web-app`](../web-app/README.md): it moves the webserver to an OS-assigned port (parallel runs never collide), silences the URL line, and inserts this package's `headless-runner` plugin (config `{task}`). The runner drives one task turn through the in-process API carrier (`InProcessApiClient` over `toFetchHandler(ctx.apiProxy)`, so the full wire chain — serialization, zod, SSE framing — really runs), aggregates the turn's final assistant text, writes it to stdout, and requests exit (completed → 0, else 1) through the launcher-provided `ctx.headlessIo` seam. The Web composition stays mounted, so the running session is observable in a browser at the stderr-announced URL. The launcher patches the task text in (`dsh --profile headless "task"`), and fails loud when a task is given to a profile without this row.
## Model Experience
None, as the runner submits the task as an ordinary user message over the shared composition; prompts and tools belong to the base/web bundles.
#### KV Cache effect
None; the runner adds nothing to the request prefix.
## Known Limitations and Deferred Work
- **One turn only** — the runner anchors on the first message-triggered turn and exits at its end; queued follow-ups and multi-turn tasks are out of scope.
- **`ctx.headlessIo` is launcher-owned** — booting the headless profile outside the `dsh` launcher fails loud at activation until the host provides the seam.

View File

@@ -0,0 +1,18 @@
# `@deepseek-ai/dsh-headless`
[English](README.md) | 中文
dsh 一次性任务组合包。[`cordis.patch.yml`](cordis.patch.yml) 叠加在 [`dsh-base`](../base/README.md) + [`dsh-web-app`](../web-app/README.md) 之上:把 webserver 移到 OS 分配的端口(并行运行绝不冲突),关闭 URL 行输出,并插入本包的 `headless-runner` 插件(配置为 `{task}`。runner 通过进程内 API 载体(架在 `toFetchHandler(ctx.apiProxy)` 之上的 `InProcessApiClient`因此序列化、zod、SSEServer-Sent Events帧封装这整条 wire 链路都会真实运行)驱动一个任务轮次,聚合该轮次最终的 assistant 文本,写到 stdout再经启动器提供的 `ctx.headlessIo` seam 请求退出(完成 → 0否则 1。Web 组合保持挂载,因此运行中的会话可在浏览器中通过 stderr 公告的 URL 观察。启动器把任务文本 patch 进来(`dsh --profile headless "task"`);如果向没有这一行的 profile 传入任务,则大声失败。
## 模型体验
无。runner 把任务作为普通用户消息经共享组合提交;提示词与工具归 baseweb 组合包所有。
#### KV Cache 影响
runner 不向请求前缀添加任何内容。
## 已知限制与延期工作
- **只运行一个轮次**runner 锚定第一个由消息触发的轮次,并在其结束时退出;排队的后续消息与多轮任务不在范围内。
- **`ctx.headlessIo` 由启动器持有**:在 `dsh` 启动器之外启动 headless profile 会在激活时大声失败,直到宿主提供该 seam。

View File

@@ -0,0 +1,19 @@
# The dsh-headless bundle patch: one-shot task mode over dsh-base +
# dsh-web-app. The web composition stays mounted (the session is observable
# in a browser while it runs); this layer silences the URL line, moves the
# webserver to an OS-assigned port so parallel headless runs never collide,
# and mounts the one-shot runner. The launcher patches the runner's `task`.
- id: webserver
config:
host: 127.0.0.1
port: 0
- id: web-runtime
config:
mode: production
printUrl: false
- insert:
- id: headless-runner
name: '@deepseek-ai/dsh-headless'

View File

@@ -0,0 +1,49 @@
{
"name": "@deepseek-ai/dsh-headless",
"description": "The dsh one-shot bundle: a patch layer over dsh-base + dsh-web-app plus the runner plugin driving one task turn through the in-process API carrier",
"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"
},
"./invariant": {
"types": "./lib/types/invariant.d.ts",
"default": "./lib/invariant.js"
},
"./cordis.patch.yml": "./cordis.patch.yml",
"./src/*": "./src/*",
"./package.json": "./package.json"
},
"files": [
"lib/index.js",
"lib/invariant.js",
"cordis.patch.yml",
"lib/types/**/*.d.ts"
],
"license": "BSD-3-Clause",
"dsh": {
"patch": "./cordis.patch.yml"
},
"dependencies": {
"schemastery": "^3.18.0"
},
"peerDependencies": {
"@deepseek-ai/dsh-host-apiproxy": "^0.0.1",
"@deepseek-ai/dsh-host-webserver": "^0.0.1",
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-session": "^0.0.1",
"cordis": "^4.0.0-rc.7"
},
"devDependencies": {
"@deepseek-ai/dsh-host-apiproxy": "workspace:^",
"@deepseek-ai/dsh-host-webserver": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"cordis": "^4.0.0-rc.7"
}
}

View File

@@ -0,0 +1,147 @@
/**
* @deepseek-ai/dsh-headless — the one-shot headless bundle: the bundle patch
* (`cordis.patch.yml`) rides over dsh-base + dsh-web-app (the headless
* session is web-observable while it runs — same composition), and this
* runner plugin drives one task turn through the in-process API carrier
* (InProcessApiClient over toFetchHandler(ctx.apiProxy), so the full wire
* chain — serialization, zod, SSE framing — really runs), prints the final
* assistant text, and exits (completed → 0, else 1). The task text arrives as
* launcher-patched config (`dsh --profile headless "task"`).
* @module @deepseek-ai/dsh-headless
*/
import type { Context } from 'cordis'
import z from 'schemastery'
import { InProcessApiClient, toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
// Empty type import carries the httpServer Context merge for the port read below.
import type {} from '@deepseek-ai/dsh-host-webserver'
import type { MuxFrame } from '@deepseek-ai/dsh-host-apiproxy/api'
import type { RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
import type { SessionId } from '@deepseek-ai/dsh-session'
/** Stable Cordis plugin name. */
export const name = 'headless-runner'
/** Services required before the one-shot turn can start. */
export const inject = ['apiProxy', 'httpServer']
/** Plugin config: the task, patched in by the launcher. */
export interface Config {
/** The prompt text for the single turn. */
task: string
}
export const Config: z<Config> = z.object({
task: z.string().required(),
})
/** Outcome of one headless turn: aggregated final text plus the turn-end reason kind. */
interface TurnOutcome {
text: string
reason: string
}
/**
* The process-facing effects of one run, injectable for tests: output
* streams and the exit request (the launcher wires it to its bounded
* shutdown controller).
*/
export interface HeadlessIo {
stdout: { write(chunk: string): unknown }
stderr: { write(chunk: string): unknown }
/** Request process exit with `code` after the tree disposes. */
exit(code: number): void
}
/** Host seam: the launcher provides the exit wiring before the tree mounts. */
declare module 'cordis' {
interface Context {
/** Process-facing effects for the one-shot headless runner. */
headlessIo?: HeadlessIo
}
}
/** Unwrap an RpcResponse or fail loud: business errors print and exit 1. */
async function unwrap<T>(response: RpcResponse<T>, io: HeadlessIo): Promise<T> {
if (response.result.ok) return response.result.value
const { code, message } = response.result.error
io.stderr.write(`dsh: ${code}: ${message}\n`)
io.exit(1)
// Exit is asynchronous (bounded tree disposal); park this turn forever so
// no further request rides a session that is already being torn down.
return new Promise<never>(() => {})
}
/**
* Consume mux frames until the task turn ends: anchor on the first turn/start
* whose trigger kind is 'message' (startup-injected turns are skipped),
* aggregate text from that turn's assistant/message events (last one wins),
* finish on its turn/end.
*/
async function consumeUntilTurnEnd(
frames: AsyncIterable<RpcRequest<MuxFrame>>, sessionId: SessionId, io: HeadlessIo,
): Promise<TurnOutcome> {
let targetTurn: number | undefined
let text = ''
try {
for await (const frame of frames) {
const payload = frame.payload
if (payload.type === 'stream/error') {
io.stderr.write(`dsh: stream error: ${payload.error.message}\n`)
return { text, reason: 'error' }
}
if (payload.type !== 'session/event' || payload.sessionId !== sessionId) continue
const event = payload.event
if (targetTurn === undefined) {
if (event.type === 'turn/start' && event.data.trigger.kind === 'message') targetTurn = event.data.turn
continue
}
if (event.type === 'assistant/message' && event.data.turn === targetTurn) {
const joined = event.data.message.content.filter(block => block.type === 'text').map(block => block.text).join('')
if (joined !== '') text = joined
}
if (event.type === 'turn/end' && event.data.turn === targetTurn) {
return { text, reason: event.data.reason.kind }
}
}
} catch (error: unknown) {
io.stderr.write(`dsh: event stream failed: ${String(error)}\n`)
}
return { text, reason: 'error' }
}
/**
* Run one headless turn for the configured task and request exit
* (completed → 0, else 1).
* @param ctx - plugin context carrying apiProxy, httpServer, and the launcher's headlessIo.
* @param config - validated {@link Config}.
*/
export function apply(ctx: Context, config: Config): void {
const io = ctx.headlessIo
if (io === undefined) {
throw new Error('headless-runner: the launcher must provide ctx.headlessIo before the tree mounts')
}
// Fire-and-forget by design: the turn outlives plugin activation, and every
// failure path inside ends in io.exit, not a rejection.
void (async () => {
// The headless session is web-observable while it runs (same composition).
io.stderr.write(`dsh: observing at http://127.0.0.1:${String(ctx.httpServer.port)}\n`)
const api = new InProcessApiClient(toFetchHandler(ctx.apiProxy))
const created = await unwrap(await api.sessions.create({}), io)
// Open the stream before prompting so no frame is lost — kept in this
// order even though in-process delivery has no race, so the code survives
// a move to a remote HTTP carrier unchanged.
const abort = new AbortController()
const frames = api.events.mux({}, abort.signal)
const done = consumeUntilTurnEnd(frames, created.sessionId, io)
await unwrap(await api.sessions.prompt({
sessionId: created.sessionId,
mode: 'queue',
content: [{ type: 'text', text: config.task }],
}), io)
const outcome = await done
io.stdout.write(outcome.text + '\n')
abort.abort()
io.exit(outcome.reason === 'completed' ? 0 : 1)
})()
}

View File

@@ -0,0 +1,30 @@
/**
* Package-owned invariant companion for `@deepseek-ai/dsh-headless`.
* @module @deepseek-ai/dsh-headless/invariant
*/
import type { Context } from 'cordis'
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
const PACKAGE_NAME = '@deepseek-ai/dsh-headless'
/** Cordis companion plugin name. */
export const name = 'headless-invariant'
/** Service required before the companion can register. */
export const inject = ['invariants']
/**
* No runtime invariant: the runner is a one-shot driver over the API carrier
* whose observable contract (final text on stdout, exit code by turn-end
* reason) is process-level and owned by the launcher e2e; it registers
* nothing and holds no mutable relation to audit inside the tree.
*/
const install: InvariantInstaller = () => {}
/**
* Register this package's invariant companion.
* @param ctx - Cordis context carrying the invariant service.
* @returns the installed registration's disposer after setup succeeds.
*/
export const apply = (ctx: Context): Promise<() => void> =>
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))

View File

@@ -0,0 +1,186 @@
/**
* One-shot runner behavior over a scripted in-process API: turn anchoring on
* the first message-triggered turn, last-text-wins aggregation, exit-code
* mapping by turn-end reason, stream/error and RPC-error paths, and the
* launcher-owned `ctx.headlessIo` requirement.
*/
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import { apply, Config, type HeadlessIo } from '../src/index.ts'
interface ScriptedEvent { type: string; seq?: number; time?: number; sessionId?: string; data: Record<string, unknown> }
let nextSeq = 0
/** Stamp the envelope fields the wire schema requires. */
function stamped(event: ScriptedEvent): ScriptedEvent {
nextSeq += 1
return { seq: nextSeq, time: nextSeq, ...event }
}
interface RpcShapedRequest { rpcId: string }
/** Build a fake apiProxy (echoing rpcIds like the real gateway) whose mux stream replays `events` for the created session. */
function scriptedApi(events: ScriptedEvent[], options: { promptFails?: boolean } = {}): unknown {
return {
sessions: {
create: (request: RpcShapedRequest) =>
Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value: { sessionId: 'S1' } } }),
prompt: (request: RpcShapedRequest) => Promise.resolve(options.promptFails === true
// A code from the closed wire union: the carrier schema rejects invented codes.
? { rpcId: request.rpcId, result: { ok: false, error: { code: 'agent-busy', message: 'agent is busy', details: { reason: 'test' } } } }
: { rpcId: request.rpcId, result: { ok: true, value: { accepted: true } } }),
},
events: {
mux: async function* () {
for (const event of events) {
if (event.type === 'stream/error') {
yield { rpcId: 'e', payload: { type: 'stream/error', error: { code: 'cancelled', message: 'stream broke', details: {} } } }
continue
}
const { sessionId = 'S1', ...rest } = event
yield { rpcId: 'e', payload: { type: 'session/event', sessionId, event: stamped(rest) } }
}
},
},
}
}
/** Mount the runner against a scripted API and wait for its exit request. */
async function run(events: ScriptedEvent[], options: { promptFails?: boolean } = {}): Promise<{ code: number; out: string; err: string }> {
const ctx = new Context()
let out = ''
let err = ''
const exited = new Promise<number>((resolve) => {
const io: HeadlessIo = {
stdout: { write: (chunk: string) => { out += chunk; return true } },
stderr: { write: (chunk: string) => { err += chunk; return true } },
exit: resolve,
}
ctx.provide('headlessIo', io)
})
ctx.provide('apiProxy', scriptedApi(events, options) as never)
ctx.provide('httpServer', { port: 12345 } as never)
apply(ctx, { task: 'do the thing' })
const code = await exited
await ctx.fiber.dispose()
return { code, out, err }
}
const startupTurn: ScriptedEvent = { type: 'turn/start', data: { turn: 0, trigger: { kind: 'startup' } } }
const messageTurn: ScriptedEvent = { type: 'turn/start', data: { turn: 1, trigger: { kind: 'message' } } }
const text = (turn: number, value: string): ScriptedEvent => ({
type: 'assistant/message',
data: { turn, message: { content: [{ type: 'text', text: value }] } },
})
const end = (turn: number, reason: string): ScriptedEvent => ({ type: 'turn/end', data: { turn, reason: { kind: reason } } })
describe('headless runner', () => {
it('anchors past startup turns, keeps the last text, prints, and exits 0 on completion', async () => {
const { code, out, err } = await run([
startupTurn,
end(0, 'completed'),
messageTurn,
// Off-session, non-text, and text-empty frames are skipped without affecting the aggregate.
{ type: 'assistant/message', sessionId: 'OTHER', data: { turn: 1, message: { content: [{ type: 'text', text: 'other session' }] } } },
{ type: 'assistant/message', data: { turn: 1, message: { content: [{ type: 'tool_call', text: 'ignored' }] } } },
text(1, 'draft'),
text(1, 'final answer'),
end(1, 'completed'),
])
expect(code).toBe(0)
expect(out).toBe('final answer\n')
expect(err).toContain('observing at http://127.0.0.1:12345')
})
it('exits 1 when the turn ends for any other reason', async () => {
const { code } = await run([messageTurn, end(1, 'aborted')])
expect(code).toBe(1)
})
it('reports a stream error and exits 1', async () => {
const { code, err } = await run([messageTurn, { type: 'stream/error', data: {} }])
expect(code).toBe(1)
expect(err).toContain('stream error')
})
it('prints an RPC business error and exits 1 without prompting further', async () => {
const { code, err } = await run([messageTurn, end(1, 'completed')], { promptFails: true })
expect(code).toBe(1)
expect(err).toContain('agent-busy')
})
it('exits 1 through the stream-error path when the underlying carrier dies', async () => {
const ctx = new Context()
let err = ''
const exited = new Promise<number>((resolve) => {
ctx.provide('headlessIo', {
stdout: { write: () => true },
stderr: { write: (chunk: string) => { err += chunk; return true } },
exit: resolve,
} satisfies HeadlessIo)
})
ctx.provide('apiProxy', {
sessions: {
create: (request: RpcShapedRequest) =>
Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value: { sessionId: 'S1' } } }),
prompt: (request: RpcShapedRequest) =>
Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value: { accepted: true } } }),
},
events: {
mux: async function* (): AsyncGenerator<never> {
throw new Error('carrier died')
},
},
} as never)
ctx.provide('httpServer', { port: 1 } as never)
apply(ctx, { task: 't' })
expect(await exited).toBe(1)
// The carrier converts its own failure into a stream/error frame.
expect(err).toContain('stream error')
expect(err).toContain('carrier died')
await ctx.fiber.dispose()
})
it('fails loud without the launcher-owned headlessIo seam', () => {
const ctx = new Context()
ctx.provide('apiProxy', scriptedApi([]) as never)
ctx.provide('httpServer', { port: 1 } as never)
expect(() => { apply(ctx, { task: 't' }) }).toThrow('must provide ctx.headlessIo')
})
it('exits 1 with the stream-failed diagnostic when the event channel cannot open at all', async () => {
const ctx = new Context()
let err = ''
const exited = new Promise<number>((resolve) => {
ctx.provide('headlessIo', {
stdout: { write: () => true },
stderr: { write: (chunk: string) => { err += chunk; return true } },
exit: resolve,
} satisfies HeadlessIo)
})
ctx.provide('apiProxy', {
sessions: {
create: (request: RpcShapedRequest) =>
Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value: { sessionId: 'S1' } } }),
prompt: (request: RpcShapedRequest) =>
Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value: { accepted: true } } }),
},
events: {
// Synchronous throw: the SSE response never forms, so the client-side
// iterable rejects — the runner's own catch path, not a carrier frame.
mux: () => { throw new Error('channel exploded') },
},
} as never)
ctx.provide('httpServer', { port: 1 } as never)
apply(ctx, { task: 't' })
expect(await exited).toBe(1)
expect(err).toContain('event stream failed')
await ctx.fiber.dispose()
})
it('validates config: the task is required', () => {
expect(() => new Config({ } as never)).toThrow()
expect(new Config({ task: 'x' })).toEqual({ task: 'x' })
})
})

View File

@@ -0,0 +1,30 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib/types"
},
"include": [
"src"
],
"references": [
{
"path": "../../../vendor/cordis"
},
{
"path": "../../../vendor/schemastery"
},
{
"path": "../../host/apiproxy"
},
{
"path": "../../host/webserver"
},
{
"path": "../../core/session"
},
{
"path": "../../support/invariants"
}
]
}