index.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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
  4. * prefix of the parent's session log — so the child inherits the parent's
  5. * conversation context instead of starting fresh. The run mechanics live in
  6. * `@deepseek-ai/dsh-subagent-inprocess` ({@link startInProcessRun}); this
  7. * backend just computes the seed. The spawn backend is an independent peer over
  8. * the same driver.
  9. *
  10. * The seed boundary is the crux: at the moment a subagent tool's `execute`
  11. * runs, the parent's CURRENT turn is open and unbalanced (it holds the
  12. * `assistant/message` with this spawn's tool-call, plus the dangling `tool/call`
  13. * with no `tool/result`). Seeding that raw prefix gives the child an open turn
  14. * the session constructor and the dev-mode invariants replay REJECT. So the
  15. * fork seeds only the **balanced completed-turn prefix**: the parent's log up
  16. * to and including its last `turn/end`, excluding the in-flight turn entirely.
  17. *
  18. * Plugin export shape: named `name`/`inject`/`Config`/`apply`, NO default.
  19. *
  20. * @module @deepseek-ai/dsh-subagent-fork
  21. */
  22. import type { Context } from 'cordis'
  23. import z from 'schemastery'
  24. import type { SessionEvent } from '@deepseek-ai/dsh-session'
  25. import type { Agent } from '@deepseek-ai/dsh-agent'
  26. import type { SubagentCapabilities, SubagentProvider, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  27. import { startInProcessRun } from '@deepseek-ai/dsh-subagent-inprocess'
  28. export const name = 'subagent-fork'
  29. // `tools` is deliberately NOT injected — same rationale as subagent-spawn: the
  30. // per-run structured runtime gates its capture-tool registration on `tools`
  31. // itself, so this backend's apply timing (and the delegation tool's position
  32. // in the model-visible tool list) is unchanged by structured output.
  33. export const inject = ['subagents', 'agents']
  34. /** Config: the registry name to register the provider under. */
  35. export interface Config {
  36. /** Provider name on `ctx.subagents` (default `fork`). */
  37. providerName: string
  38. }
  39. export const Config: z<Config> = z.object({
  40. providerName: z.string().default('fork'),
  41. })
  42. /**
  43. * The balanced completed-turn prefix of `parent`'s log: every event up to and
  44. * including the last `turn/end`. Empty if the parent has never completed a turn
  45. * (the in-flight turn is excluded, so a parent on its very first turn forks an
  46. * empty — i.e. fresh — child). The result is contiguous from seq 0 (the live
  47. * log keeps `seq === index`), so it is a valid session seed; the in-flight,
  48. * unbalanced turn is dropped so the invariants replay accepts it.
  49. * @param parent - the agent whose session log to slice.
  50. * @returns the seed events, contiguous from seq 0; empty when no turn has completed.
  51. */
  52. export function completedTurnPrefix(parent: Agent): SessionEvent[] {
  53. const events = parent.session.events
  54. const lastEnd = events.findLast(e => e.type === 'turn/end')
  55. if (lastEnd === undefined) return []
  56. // seq === array index (the append contract), so slice up to and including it.
  57. return events.slice(0, lastEnd.seq + 1)
  58. }
  59. /**
  60. * The fork provider. Supports `depthLimit` and `outputSchema` (via the shared
  61. * in-process structured runtime), plus `toolFilter`/`persona` (scoped
  62. * restrict() and a scoped shadowing persona section).
  63. */
  64. class ForkProvider implements SubagentProvider {
  65. readonly capabilities: SubagentCapabilities = { outputSchema: true, depthLimit: true, toolFilter: true, persona: true }
  66. // Context contract: a forked child IS seeded with the parent's completed-turn prefix.
  67. readonly inheritsParentContext = true
  68. constructor(readonly name: string, private readonly ctx: Context) {}
  69. start(request: SubagentStartRequest) {
  70. const seed = completedTurnPrefix(request.parent)
  71. return startInProcessRun(this.ctx, request, {
  72. providerName: this.name,
  73. // Only pass a seed when there's a completed turn to inherit; an empty seed
  74. // is equivalent to a fresh child, so omit it to keep the session unseeded.
  75. ...seed.length > 0 ? { seed } : {},
  76. })
  77. }
  78. }
  79. export function apply(ctx: Context, config: Config): void {
  80. ctx.subagents.registerProvider(new ForkProvider(config.providerName, ctx))
  81. }