Files
deepseek-harness/packages/subagent/subagent-fork/src/index.ts
T
Tianyi Cui a8986c2c8a Merge remote-tracking branch 'origin/master' into worktree-dynamic-workflows
Beyond the mechanical conflicts (provider capability lines vs master's new
inheritsParentContext field; generated catalogs regenerated rather than
hand-merged; knip/lockfile), three master-side reworks required semantic
adaptation of this branch:

- The persona rework removed AgentOptions.systemPrompt, which was the
  structured-output instruction's channel. The instruction now rides the
  SAME final-request enforcement listener that injects the schema'd tool:
  appended per request to final.system (per-request wire state, not agent
  prompt state). Tests assert the wire request (adapter.requests) instead
  of child.options; the bare-direct-dispatch test pins the no-system arm.
- Tool guidance moved out of deployment prompts into per-tool prompt
  sections; the examples' workflow paragraph became a tool:<toolName>
  section contributed by dsh-tool-workflow (explicit-ask-only policy),
  and both example personas resolve to master's minimal identity+behavior
  form. tool-workflow gains inject: systemPrompt (+ peer dep, tsconfig
  ref); the export-shape guard updated.
- The uniform-RFC-format gate: the dynamic-workflows RFC restructured to
  the implemented/ skeleton (bare Status line; Proposal -> Decision;
  What-was-rejected -> Alternatives considered; new Consequences), and
  the overall-run-timeout deferral is now recorded in the RFC's Deferred
  list. The doc-graphs atlas classification gains the workflows seam
  (workflow-vm implementation, tool-workflow consumer).

Master's harness-identity section made "empty assembled prompt" states
unreachable through the loop, so the instruction-append is a plain
undefined-ternary and the structured tests assert append-not-replace.
All snapshot goldens (including workflow-run) replay unchanged. Full
local CI-equivalent gate sequence green on the merged tree.
2026-07-06 03:14:07 +08:00

103 lines
4.5 KiB
TypeScript

/**
* The in-process FORK subagent backend: registers a {@link SubagentProvider} on
* `ctx.subagents` that runs each child as a child {@link Agent} SEEDED with a
* prefix of the parent's session log — so the child inherits the parent's
* conversation context instead of starting fresh. The run mechanics live in
* `@deepseek-ai/dsh-subagent-inprocess` ({@link startInProcessRun}); this
* backend just computes the seed. The spawn backend is an independent peer over
* the same driver.
*
* The seed boundary is the crux: at the moment a subagent tool's `execute`
* runs, the parent's CURRENT turn is open and unbalanced (it holds the
* `assistant/message` with this spawn's tool-call, plus the dangling `tool/call`
* with no `tool/result`). Seeding that raw prefix gives the child an open turn
* the session constructor and the dev-mode invariants replay REJECT. So the
* fork seeds only the **balanced completed-turn prefix**: the parent's log up
* to and including its last `turn/end`, excluding the in-flight turn entirely.
*
* Plugin export shape: named `name`/`inject`/`Config`/`apply`, NO default.
*
* @module @deepseek-ai/dsh-subagent-fork
*/
import type { Context } from 'cordis'
import z from 'schemastery'
import type { SessionEvent } from '@deepseek-ai/dsh-session'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type { SubagentCapabilities, SubagentProvider, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
import { acquireStructuredRuntime, startInProcessRun } from '@deepseek-ai/dsh-subagent-inprocess'
export const name = 'subagent-fork'
export const inject = ['subagents', 'agents', 'tools']
/** Config: the registry name to register the provider under, plus structured-run tuning. */
export interface Config {
/** Provider name on `ctx.subagents` (default `fork`). */
providerName: string
/**
* How many times a structured run re-prompts a child that finished cleanly
* without calling `structured_output` before giving up (default 1).
*/
structuredNudgeRetries: number
}
export const Config: z<Config> = z.object({
providerName: z.string().default('fork'),
structuredNudgeRetries: z.natural().default(1),
})
/**
* The balanced completed-turn prefix of `parent`'s log: every event up to and
* including the last `turn/end`. Empty if the parent has never completed a turn
* (the in-flight turn is excluded, so a parent on its very first turn forks an
* empty — i.e. fresh — child). The result is contiguous from seq 0 (the live
* log keeps `seq === index`), so it is a valid session seed; the in-flight,
* unbalanced turn is dropped so the invariants replay accepts it.
*/
export function completedTurnPrefix(parent: Agent): SessionEvent[] {
const events = parent.session.events
const lastEnd = events.findLast(e => e.type === 'turn/end')
if (lastEnd === undefined) return []
// seq === array index (the append contract), so slice up to and including it.
return events.slice(0, lastEnd.seq + 1)
}
/**
* The fork provider. Supports `depthLimit` and `outputSchema` (via the shared
* in-process structured runtime); NOT `toolFilter` this cut (the service
* rejects a request needing it before `start` runs).
*/
class ForkProvider implements SubagentProvider {
readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: false }
// Context contract: a forked child IS seeded with the parent's completed-turn prefix.
readonly inheritsParentContext = true
constructor(
readonly name: string,
private readonly ctx: Context,
private readonly structuredNudgeRetries: number,
) {}
start(request: SubagentStartRequest) {
const seed = completedTurnPrefix(request.parent)
return startInProcessRun(this.ctx, request, {
providerName: this.name,
structuredNudgeRetries: this.structuredNudgeRetries,
// Only pass a seed when there's a completed turn to inherit; an empty seed
// is equivalent to a fresh child, so omit it to keep the session unseeded.
...seed.length > 0 ? { seed } : {},
})
}
}
export function apply(ctx: Context, config: Config): void {
// Hold the structured runtime for the plugin's lifetime (see the spawn
// backend — same two-level lifetime: backends for availability, runs for
// mid-run survival across a backend unload).
ctx.effect(() => {
const acquisition = acquireStructuredRuntime(ctx)
return () => { acquisition.release() }
}, 'subagent-fork structured runtime')
ctx.subagents.registerProvider(new ForkProvider(config.providerName, ctx, config.structuredNudgeRetries))
}