Files
deepseek-harness/docs/cookbook/extension-cookbook.md
T
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00

13 KiB

Cookbook: extension plugin shapes

English | 中文

Reference patterns for harness extensions. The snippets omit imports and helper implementations and are not copy-paste-complete. For concrete authoring paths, see the package checklist, first-tool tutorial, tool reference, system-message cookbook, LLM adapter guide, and Session format version tutorial; the architecture owns the system and extension-point map.

A tool plugin

A tool registers on ctx.tools. The annotated defineTool example (typed execute arguments, result construction, the run_in_background pattern) lives in adding-a-tool.md — that guide is the source of truth for tool definitions. Raw JSON-Schema ToolDefinitions are also accepted by ctx.tools.register() directly (that is how MCP-sourced tools arrive); defineTool is the typed helper for first-party tools.

A hook plugin (permission-gate example)

This permission gate is one example of a hook plugin. It returns a typed decision from the tools/pre-execute gate to allow or deny a call; sandbox, permission, and plan-mode plugins can use this extension point. Hook plugins can intercept other extension points and are not inherently permission gates. A "native hook" is an ordinary Cordis plugin on an interception point; it needs no external protocol.

import type { Context } from '@deepseek-ai/cordis'
import type { PreToolDecision, ToolExecution } from '@deepseek-ai/dsh-tools'

declare function isAllowed(exec: ToolExecution): Promise<boolean>

export const name = 'permission-gate'

export function apply(ctx: Context) {
  ctx.on('tools/pre-execute', async (exec, next): Promise<PreToolDecision> => {
    if (!(await isAllowed(exec))) {
      return { kind: 'deny', reason: 'Denied by policy.' }
    }
    return next()
  })
}

This waterfall is the reorderable policy layer. Use ctx.tools.guard() when an invariant needs a monotonic final denial, tools/execute when a plugin must wrap the dispatch lifetime (timeouts/retries/metrics; only exec.signal is replaceable), tools/post-execute for explicit result transformation, and tools/result for contained observation of the immutable final outcome. The adding-a-tool guide gives the selection rule.

A UI plugin

A UI plugin combines durable session/event records (Assistant settlements, turn/step boundaries, and tool activity) with transient agent/assistant-stream frames for live token presentation, and drives input back in via agent.followup() / agent.steer(). A browser plugin contributing a business row to the built-in Web Client instead registers a ConversationNodeDefinition and keyed Chat renderer; follow the Conversation subsystem reference.

import type { Context } from '@deepseek-ai/cordis'
import { brandString } from '@deepseek-ai/dsh-brand'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
import type { SessionId } from '@deepseek-ai/dsh-session'

declare function render(text: string): void
declare function onUserInput(handler: (text: string) => void): void

export const name = 'my-ui'
export const inject = ['agents']

export function apply(ctx: Context) {
  ctx.on('agent/assistant-stream', ({ frame }) => {
    if (frame.type === 'chunk' && frame.chunk.type === 'text-delta') {
      render(frame.chunk.text)
    }
  })
  onUserInput(text => ctx.agents.get(brandString<SessionId>('client-session'))?.followup(createUserMessage({
    content: [{ type: 'text', text }],
    source: { kind: 'user' },
  })))
}

An external protocol driver

A protocol driver adapts a wire peer to ctx.agents; it may serve a UI or an automation client. A stdio driver owns stdout, creates or resumes agents through the factory, and maps protocol requests to followup() or cancel(). A low-level prompt request returns its durable enqueue receipt; it does not acquire a result by correlating MessageId with turn/end. Publish whole-agent status separately. An automation method may wait from its receipt through the next idle and summarize that explicitly owned interval, while a UI normally keeps observing the open-ended event stream. Tear agents down with AgentHandle.dispose() so disposal reaches quiescence.

packages/acp/acp is the automation-only worked example: it exposes fresh text sessions over Agent Client Protocol JSON-RPC stdio, emits committed assistant text, and registers a one-shot machine permission answerer for agents it owns. Its README defines the exact methods, event order, and lifecycle contract.

import type { Context } from '@deepseek-ai/cordis'
import { expandAssistantStream } from '@deepseek-ai/dsh-llm'

export const name = 'my-protocol-bridge'
export const inject = ['agents', 'sessions', 'sessionPersistence']

export function apply(ctx: Context) {
  // Publish every committed Assistant text delta to the client.
  ctx.on('session/event', (_session, event) => {
    if (event.type === 'assistant/message' || event.type === 'assistant/attempt') {
      for (const { chunk } of expandAssistantStream(event.data.stream)) {
        if (chunk.type === 'text-delta') {
          // sendToClient({ kind: 'message_chunk', text: chunk.text })
        }
      }
    }
  })
  // Inbound "prompt": create/resume an agent, feed it, and return its enqueue receipt.
  // Whole-agent status is a separate notification; no turn end belongs to this prompt.
  // Teardown reaches quiescence via AgentHandle.dispose() (stop + await exit).
}

A forge review extension

Change request review opens to plugins through the forge extension API. A Host plugin registers a filter lens, which keeps some of the files a changes view shows and names the lines it is about:

import type { Context } from '@deepseek-ai/cordis'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { ForgeLensId } from '@deepseek-ai/dsh-experimental-client-ui-forge'

export const name = 'exports-lens'
export const inject = ['forgePanel']

export function apply(ctx: Context) {
  // An effect of this plugin's fiber: unloading the plugin withdraws the lens and aborts its runs.
  ctx.forgePanel.registerLens({
    id: brandString<ForgeLensId>('example/exports'),
    version: '1',
    async classify(input, signal) {
      const files: Record<string, { ranges: { old: []; new: { start: number; end: number }[] } }> = {}
      for (const file of input.files) {
        const lines = (await input.text('new', file.path, signal))?.split('\n') ?? []
        const ranges = lines.flatMap((line, at) => line.startsWith('export') ? [{ start: at + 1, end: at + 1 }] : [])
        if (ranges.length > 0) files[file.path] = { ranges: { old: [], new: ranges } }
      }
      return { files }
    },
  })
}

A Client plugin names that lens and adds line annotations; notesOf returns one stable observable per view, and NoteBody is a module-scope component that draws one annotation inside the frame the view draws. The forge tests' fixture plugin also uses the toolbar, file menu, comment form, and card slots.

export const inject = ['forgeChanges', 'slots']

export function apply(ctx: Context) {
  ctx.effect(() => ctx.forgeChanges.describeLens({ id: brandString<ForgeLensId>('example/exports'), title: () => 'Exports' }))
  ctx.effect(() => ctx.forgeChanges.registerAnnotations({ id: 'example-notes', observe: target => notesOf(target) }))
  ctx.slots.inject('forge.diff.line.annotation', () => ctx.slots.register(
    { name: 'forge.diff.line.annotation', key: 'example-notes' }, NoteBody))
}

Runnable wirings

Shipped applications contribute profile layers through packages/bundle/*/cordis.patch.yml, and the product dsh launcher owns Web, ACP, SDK, and one-shot headless execution through named profiles. Optional user-facing overlays live under apps/cli/config/examples/; profile integration tests live under apps/cli/tests/profiles/, while package-specific Loader compositions stay with their package tests.

The feature → mechanism map

Every product feature maps to a listener on a documented extension point — the microkernel claim made checkable (microkernel reference). No row modifies the loop.

system-prompt/assemble is an expert cooperative whole-assembly transform: its returned assembly is authoritative, so listener authors own preserving active PTC mode and structured-output protocol contributions. Prefer ctx.tools.restrict() for tool filtering that must stay aligned across presentation, lookup, and execution.

Product feature Plugin mechanism
Hook system (user + project level) listeners on agent/created, agent/pre-step, tools/pre-execute, tools/post-execute, and agent/turn-stopping; the waterfalls return typed decisions, while agent/turn-stopping may steer another step; the dsh-hooks-claude-code / dsh-hooks-codex bridges map hook config files onto these extension points
/goal ctx.goals owns durable state, dsh-goal-round-driver schedules same-session rounds through the public Agent, and separate command/tool producers expose human/model control
/loop on the turn/end session event, followup() the next iteration; or force-continue
Dynamic workflow ctx.workflowEngine + the PTC workflow engine + the workflow tool; structured in-process children enforce output with scoped prompt/tool registrations, a monotonic tool guard, final tools/result commit (including enclosing run_code), and the structured-output execution's monotonic concludeTurn() marker
Queued + steering messages core Agent.followup() / Agent.steer()
Context compaction (auto + manual) the ctx.compaction seam + dsh-compaction-basic; automatic pressure runs on serial agent/pre-step, canonical overflow recovery runs on agent/request-error, and manual callers use the same compact service (compaction reference)
System prompt configurability ctx.systemPrompt.section() with ordering and scope-local shadowing
AGENTS.md (root) a section provider reading the file
AGENTS.md (subdir, on-touch) + file-change notices agent.inject() from a watcher / tool-result listener
Built-in tools ctx.tools.register(); schemas flow into the assembly automatically — the dsh-tool-* families (bash, fs, web, subagent, todo) are the shipped examples
ToolSearch / progressive disclosure replace a scoped ctx.tools.restrict() registration as the visible set changes; the registry keeps presentation, lookup, and execution aligned
Tool deadline / retry / metrics wrap core dispatch with tools/execute; a wrapper may replace exec.signal, delegate, and inspect the normalized result in one lexical lifetime
Final tool-result metrics / audit / capture observe immutable authoritative outcomes with tools/result; use tools/post-execute instead only when the plugin must transform the result or attach context
Monotonic terminal turn policy call ToolExecution.concludeTurn() from the successful terminal tool; later tool calls in the same response remain guardable, and the loop stops after the step
Subprocess sandbox (landlock / sandbox-exec) use a ctx.sandbox backend through dsh-bash-sandbox; use tools/pre-execute for capability-level denial
Permission system / AskUserQuestion return ask from tools/pre-execute and answer through ctx.approval; register a separate model-facing ask tool for ordinary user questions
Plan mode @deepseek-ai/dsh-plan-mode — logged plan/mode state, the plan:policy guidance section, /plan [message] entry, /plan off direct exit, and the user-reviewed exit_plan_mode exit; enforcement stays on the independent sandbox/approval axes
Sub-agent delegation the ctx.subagents provider registry (dsh-subagent-spawn-in-process/dsh-subagent-fork-in-process/dsh-subagent-acp/dsh-subagent-codex/dsh-subagent-claude-code/dsh-subagent-dsh-sdk) + dsh-tool-subagent exposing one configured provider to the model
MCP one plugin per server: discover tools → ctx.tools.register()
Skills section + tool registration; inject() skill content on invocation
Memory section provider + tool
Scheduled tasks (cron) a plugin registers model-callable scheduling tools; a due timer delivers through followup(…, {source: {kind: 'schedule'}})
UI (GUI; CLI emits JSONL) listen to agent/assistant-stream for live chunks and session/event for durable settlements, boundaries, and tool activity; input → followup()
Web Client Chat business node register a ConversationNodeDefinition and conversation.chat.node keyed renderer
SessionTelemetryBackend / replayable trace session/event → JSONL; replay = sessions.create(id, { seed })
Model adapters LlmAdapter subclass via registerAdapter (dsh-llm-deepseek, dsh-llm-pi-ai)
Plugin hot-reload every registration is a ctx.effect → vendored HMR just works