返回源码地图

packages/subagent/subagent-fork-in-process/src/index.ts

main snapshot · da00f7f5358f · 正文引用章节 05 / 13;完整原文可核对,不声称全文件人工逐行审计

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * The in-process FORK subagent backend: registers a {@link SubagentProvider} on
3 * `ctx.subagents` that runs each child as a child {@link Agent} SEEDED with a prefix of the
4 * parent's session log — so the child inherits the parent's conversation context instead of
5 * starting fresh. The seed ends at the last `turn/end`: the current tool-call turn is
6 * unbalanced and cannot be replayed as a valid child session.
7 * @module @deepseek-ai/dsh-subagent-fork-in-process
8 */
9
10import type { Context } from '@deepseek-ai/cordis'
11import z from '@deepseek-ai/schemastery'
12import type { SessionEvent } from '@deepseek-ai/dsh-session'
13import type { Agent } from '@deepseek-ai/dsh-agent'
14import type {
15 ContinuableCreateRequest,
16 ContinuableCreateSpec,
17 ResolvedSubagentStartRequest,
18 SubagentCapabilities,
19 SubagentProvider,
20} from '@deepseek-ai/dsh-subagent'
21import { startInProcessRun } from '@deepseek-ai/dsh-subagent-in-process-driver'
22
23export const name = 'subagent-fork-in-process'
24// `tools` is deliberately NOT injected — same rationale as subagent-spawn-in-process: the
25// per-run structured runtime gates its capture-tool registration on `tools`
26// itself, so this backend's apply timing (and the delegation tool's position
27// in the model-visible tool list) is unchanged by structured output.
28export const inject = ['subagents']
29
30/** Config: the registry name to register the provider under. */
31export interface Config {
32 /** Provider name on `ctx.subagents` (default `fork`). */
33 providerName: string
34}
35
36export const Config: z<Config> = z.object({
37 providerName: z.string().default('fork'),
38})
39
40/**
41 * The balanced completed-turn prefix of `parent`'s log: every event up to and including the
42 * last `turn/end`. The in-flight turn is excluded; before any completed turn the child starts
43 * fresh. Because live sequence numbers equal array indexes, the result remains a valid seed
44 * beginning at sequence zero.
45 * @param parent - the agent whose session log to slice.
46 * @returns the seed events, contiguous from seq 0; empty when no turn has completed.
47 */
48function completedTurnPrefix(parent: Agent): SessionEvent[] {
49 // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
50 const events = parent.session.snapshotEvents()
51 const lastEnd = events.findLast(e => e.type === 'turn/end')
52 if (lastEnd === undefined) return []
53 // seq === array index (the append contract), so slice up to and including it.
54 return events.slice(0, lastEnd.seq + 1)
55}
56
57/**
58 * The fork provider. Supports `depthLimit` and `outputSchema` (via the shared
59 * in-process structured runtime), `agentOptions` (merged over the parent
60 * route), and `toolFilter`/`persona` (scoped restrict() and a scoped shadowing
61 * persona section).
62 */
63class ForkInProcessProvider implements SubagentProvider {
64 readonly capabilities: SubagentCapabilities = {
65 agentOptions: true,
66 outputSchema: true,
67 depthLimit: true,
68 toolFilter: true,
69 persona: true,
70 }
71 // Context contract: a forked child IS seeded with the parent's completed-turn prefix.
72 readonly inheritsParentContext = true
73
74 constructor(readonly name: string) {}
75
76 start(request: ResolvedSubagentStartRequest) {
77 const seed = completedTurnPrefix(request.parent)
78 return startInProcessRun(request, {
79 // Only pass a seed when there's a completed turn to inherit; an empty seed
80 // is equivalent to a fresh child, so omit it to keep the session unseeded.
81 ...seed.length > 0 ? { seed } : {},
82 })
83 }
84
85 prepareContinuable(request: ContinuableCreateRequest): Promise<ContinuableCreateSpec> {
86 // The fork prefix is captured ONCE, at creation: it becomes part of the
87 // child's own durable transcript, so a later cold resume replays that
88 // prefix instead of re-forking the parent's newer history.
89 const seed = completedTurnPrefix(request.parent)
90 return Promise.resolve(seed.length > 0 ? { seed } : {})
91 }
92}
93
94export function apply(ctx: Context, config: Config): void {
95 ctx.subagents.registerProvider(new ForkInProcessProvider(config.providerName))
96}