index.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /**
  2. * The model-facing `subagent` tool: delegate a task to a child agent and return
  3. * its final output. Pure schema + lifecycle shaping — every transport concern
  4. * lives behind the `ctx.subagents` provider registry
  5. * (`@deepseek-ai/dsh-subagent`), so an in-process, ACP, or future A2A backend
  6. * swaps in without touching what the model sees.
  7. *
  8. * Provider selection is config, not model-facing: this plugin is bound to
  9. * EXACTLY ONE provider name (`Config.provider`). To expose more than one
  10. * transport, load the plugin more than once, each bound to a different provider
  11. * — there is no provider/type parameter in the model-facing schema. The model
  12. * sees only `{ description, prompt }`.
  13. *
  14. * The tool DESCRIPTION is derived from the bound provider's context contract
  15. * ({@link providerWording}): a fresh-context provider (spawn, ACP) gets the
  16. * standalone-prompt wording, an inheriting provider (fork) tells the model the
  17. * child already sees the conversation's completed turns. The tool MIRRORS the
  18. * provider's lifecycle via `subagent/provider-added`/`-removed` — it registers
  19. * when the provider is (or becomes) available and unregisters when the
  20. * provider goes away — so no load-order requirement exists and an HMR reload
  21. * of the backend re-derives the wording from the fresh provider.
  22. *
  23. * Collection is SYNCHRONOUS this cut: `execute` starts a run and awaits
  24. * `run.result` inside a `try/finally` that always disposes the run, so the
  25. * owned child agent/session is torn down on every path (success, error, abort)
  26. * and never leaks as a live idle child. A non-`completed` stop reason maps to an
  27. * `isError` tool result (by throwing) rather than returning partial output as
  28. * success.
  29. *
  30. * @module @deepseek-ai/dsh-tool-subagent
  31. */
  32. import type { Context } from 'cordis'
  33. import z from 'schemastery'
  34. import { defineTool } from '@deepseek-ai/dsh-tools'
  35. import type { AgentOptions } from '@deepseek-ai/dsh-agent'
  36. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  37. import type { SubagentProvider, SubagentResult, SubagentRun, SubagentStartRequest } from '@deepseek-ai/dsh-subagent'
  38. export const name = 'tool-subagent'
  39. export const inject = ['tools', 'subagents']
  40. /** Config: which registered provider this tool delegates to, plus child defaults. */
  41. export interface Config {
  42. /** The `ctx.subagents` provider name to start runs on (e.g. `spawn`, `acp`). */
  43. provider: string
  44. /**
  45. * The model-facing tool name to register (default `subagent`). To expose more
  46. * than one transport, load this plugin once per provider — each load MUST set
  47. * a distinct `toolName` (the tool registry rejects a duplicate name), e.g.
  48. * `{ provider: 'spawn', toolName: 'subagent' }` and
  49. * `{ provider: 'acp', toolName: 'subagent_acp' }`.
  50. */
  51. toolName?: string
  52. /**
  53. * Default per-child agent options (model) applied to every spawned child.
  54. * Omitted fields fall back to the child loop's own defaults.
  55. */
  56. agentOptions?: AgentOptions
  57. /**
  58. * Per-child persona applied to every child this tool spawns: a scoped
  59. * `deployment:persona` section shadowing the deployment's persona for the
  60. * child alone. Requires the bound provider's `persona` capability
  61. * (in-process backends support it; a request against one that doesn't is
  62. * rejected at start). Omitted ⇒ the child renders the deployment persona.
  63. */
  64. persona?: string
  65. /**
  66. * Tool scoping applied to every child this tool spawns (see
  67. * `SubagentStartRequest.toolFilter`): the named global tools vanish from
  68. * the child's prompt AND refuse to execute. Requires the provider's
  69. * `toolFilter` capability. Unknown names fail the spawn loudly. Note the
  70. * child otherwise sees every global tool — including this delegation tool
  71. * itself; `deny`-listing it (or setting `maxDepth`) is how a deployment
  72. * bounds recursion.
  73. */
  74. toolFilter?: {
  75. /** Global tool names the child keeps; everything else is removed. */
  76. allow?: string[]
  77. /** Global tool names removed from the child. */
  78. deny?: string[]
  79. }
  80. /**
  81. * Recursion cap applied to every child this tool spawns (see
  82. * `SubagentStartRequest.maxDepth`): a spawn whose child would sit deeper
  83. * than this in the delegation tree is rejected. Requires the provider's
  84. * `depthLimit` capability. Omitted ⇒ unbounded (bound it in deployments
  85. * that expose this tool to children).
  86. */
  87. maxDepth?: number
  88. }
  89. export const Config: z<Config> = z.object({
  90. provider: z.string().required(),
  91. toolName: z.string().default('subagent'),
  92. // Omitted-object discipline (see the toolFilter note below): without the
  93. // forced default an omitted `agentOptions` materializes `{}`, which reads as
  94. // present — the request would carry `agentOptions: {}` and the presence
  95. // check in execute() could never be false through config.
  96. agentOptions: z.object({
  97. model: z.string(),
  98. }).default(undefined as unknown as { model: string }),
  99. persona: z.string(),
  100. // A schemastery object materializes {} (with [] for nested arrays) when the
  101. // key is omitted — for toolFilter that would mean an EMPTY ALLOW-LIST, i.e.
  102. // deny-everything, silently. Force the omitted key to stay absent (the same
  103. // shape discipline as SystemPrompt's toolOrder); the cast is needed because
  104. // .default() expects the object type.
  105. // The NESTED arrays get the same treatment as the object itself: a partial
  106. // filter ({deny: […]}) must not materialize allow: [] beside it — an empty
  107. // allow-list means deny-EVERYTHING, so the materialized default would turn
  108. // a deny-one config into deny-all. An EXPLICIT allow: [] (grant-only
  109. // children) survives, since only the omitted key defaults to undefined.
  110. toolFilter: z.object({
  111. allow: z.array(z.string()).default(undefined as unknown as string[]),
  112. deny: z.array(z.string()).default(undefined as unknown as string[]),
  113. }).default(undefined as unknown as { allow: string[]; deny: string[] }),
  114. maxDepth: z.number(),
  115. })
  116. /**
  117. * Flatten a child's final output blocks to text for the tool result. The child
  118. * may return non-text blocks; this cut surfaces the text content (the common
  119. * case) and drops the rest, which is acceptable for a synchronous summary —
  120. * the structured path (`outputSchema`) is the channel for non-text results.
  121. */
  122. function outputText(blocks: ContentBlock[]): string {
  123. return blocks
  124. .filter((b): b is Extract<ContentBlock, { type: 'text' }> => b.type === 'text')
  125. .map(b => b.text)
  126. .join('')
  127. }
  128. /** A non-`completed` stop reason means the child did not finish cleanly. */
  129. function stopReasonError(result: SubagentResult): string | undefined {
  130. switch (result.stopReason) {
  131. case 'completed':
  132. return undefined
  133. case 'aborted':
  134. return 'subagent run was cancelled'
  135. case 'error':
  136. return 'subagent run failed'
  137. case 'max-tokens':
  138. return 'subagent run hit its token limit before finishing'
  139. case 'refusal':
  140. return 'subagent declined the task'
  141. // Merge-extensible union: a backend may add stop reasons. Treat an unknown
  142. // terminal reason as a failure rather than reporting partial output as success.
  143. default:
  144. return `subagent run ended abnormally (${String(result.stopReason)})`
  145. }
  146. }
  147. /**
  148. * Model-facing wording per context contract ({@link SubagentProvider.inheritsParentContext}).
  149. * A fresh child needs a standalone prompt; a forked child already sees the
  150. * conversation's completed turns — telling the model to restate everything
  151. * (or, worse, that the child "does not see this conversation") would be false
  152. * for a fork. Exported for tests.
  153. * @param inherits - the bound provider's context contract.
  154. * @returns the tool `description` and the `prompt` parameter description.
  155. */
  156. export function providerWording(inherits: boolean): { description: string; promptDescription: string } {
  157. if (inherits) {
  158. return {
  159. description:
  160. 'Delegate a task to a subagent that INHERITS this conversation: a child agent seeded with all '
  161. + 'completed turns so far (it does not see the current in-flight turn), returning only its final '
  162. + 'result. Use this when the subtask builds on this conversation\'s context — a follow-up analysis, '
  163. + 'a review, a continuation — without consuming this conversation\'s context for the work itself. '
  164. + 'You receive only its final answer, not its intermediate steps.',
  165. promptDescription:
  166. 'The task for the subagent. It already sees this conversation\'s completed turns, so build on them '
  167. + 'freely and state only what is new.',
  168. }
  169. }
  170. return {
  171. description:
  172. 'Delegate a self-contained task to a subagent (a separate agent that works in its own context) '
  173. + 'and return its final result. Use this to offload focused, independent work — research, a scoped '
  174. + 'implementation, an analysis — so it does not consume this conversation\'s context. The subagent '
  175. + 'runs to completion and you receive only its final answer, not its intermediate steps. Give it a '
  176. + 'complete, standalone prompt: it does not see this conversation.',
  177. promptDescription:
  178. 'The complete, self-contained task for the subagent. It does not share this '
  179. + 'conversation\'s context, so include everything it needs.',
  180. }
  181. }
  182. export function apply(ctx: Context, config: Config): void {
  183. // Misconfiguration fails loud AT LOAD (the check is self-contained): an
  184. // explicit `toolFilter: {}` would otherwise pass the capability gate and
  185. // kill every delegation later, in the child-setup `restrict({})` throw.
  186. if (config.toolFilter !== undefined && config.toolFilter.allow === undefined && config.toolFilter.deny === undefined) {
  187. throw new Error('tool-subagent: `toolFilter` is configured but names neither `allow` nor `deny` — remove the key or fill the filter')
  188. }
  189. // The tool MIRRORS its provider's lifecycle instead of assuming load order:
  190. // the cordis Loader starts sibling entries concurrently, so "backend listed
  191. // first in cordis.yml" does not guarantee "provider registered first", and
  192. // an HMR reload of the backend replaces the provider while this fiber stays
  193. // loaded. Register the tool when the bound provider is (or becomes)
  194. // available — deriving the wording from THAT provider — and unregister it
  195. // when the provider goes away, so the description can never outlive or
  196. // predate the provider it describes.
  197. let disposeTool: (() => Promise<void> | void) | undefined
  198. const mount = (provider: SubagentProvider): void => {
  199. const wording = providerWording(provider.inheritsParentContext)
  200. disposeTool = ctx.tools.register(defineTool({
  201. name: config.toolName ?? 'subagent',
  202. description: wording.description,
  203. parameters: {
  204. description: {
  205. type: 'string',
  206. required: true,
  207. description: 'A short (3-5 word) description of the delegated task, for display.',
  208. },
  209. prompt: {
  210. type: 'string',
  211. required: true,
  212. description: wording.promptDescription,
  213. },
  214. },
  215. async execute(args, exec): Promise<ContentBlock[]> {
  216. const parent = exec.agent
  217. if (!parent) {
  218. // The loop sets `exec.agent` for every model-driven call; its absence
  219. // means a non-agent caller invoked the tool directly, which has no
  220. // parent to attribute the child to. Fail loud rather than guess.
  221. throw new Error('subagent tool requires a calling agent (exec.agent was undefined)')
  222. }
  223. const request: SubagentStartRequest = {
  224. prompt: [{ type: 'text', text: args.prompt }],
  225. parent,
  226. ...exec.signal ? { signal: exec.signal } : {},
  227. ...config.agentOptions !== undefined ? { agentOptions: config.agentOptions } : {},
  228. ...config.persona !== undefined ? { persona: config.persona } : {},
  229. ...config.toolFilter !== undefined ? { toolFilter: config.toolFilter } : {},
  230. ...config.maxDepth !== undefined ? { maxDepth: config.maxDepth } : {},
  231. }
  232. const run: SubagentRun = ctx.subagents.start(config.provider, request)
  233. // Bridge the tool's abort signal to the run: if the parent step is
  234. // aborted while the child is in flight, cancel the child too.
  235. const onAbort = (): void => { run.cancel('parent step aborted') }
  236. exec.signal?.addEventListener('abort', onAbort, { once: true })
  237. // `addEventListener` does NOT fire for a signal already aborted before this
  238. // line, so a step cancelled before the tool ran would never reach the
  239. // child. Cancel explicitly in that case — the bridge must honor an
  240. // already-aborted signal, not lean on each provider re-checking it.
  241. if (exec.signal?.aborted) run.cancel('parent step aborted')
  242. try {
  243. const result = await run.result
  244. const error = stopReasonError(result)
  245. if (error !== undefined) {
  246. // Map a non-clean finish to an isError result (the registry turns a
  247. // throw into an isError). Report the reason, not partial output.
  248. throw new Error(error)
  249. }
  250. return [{ type: 'text', text: outputText(result.output) }]
  251. } finally {
  252. exec.signal?.removeEventListener('abort', onAbort)
  253. // Always reach child quiescence — never leak a live idle child/session.
  254. await run.dispose()
  255. }
  256. },
  257. }))
  258. }
  259. // Listeners first, then the presence check: both run synchronously, so no
  260. // registration can slip between them; the `disposeTool === undefined` guard
  261. // makes a same-tick added-event after a successful mount a no-op.
  262. // TODO(subagent-dup-toolname): two WAITING fibers configured with the same
  263. // toolName collide only when their provider finally arrives — the duplicate
  264. // tool-name throw then propagates through `subagent/provider-added` and
  265. // rolls back the PROVIDER registration, so an invalid config blasts the
  266. // backend's fiber instead of the misconfigured tool's. Config-time detection
  267. // would need a cross-fiber registry of intended tool names; revisit if a
  268. // real deployment ever hits it.
  269. ctx.on('subagent/provider-added', (provider) => {
  270. if (provider.name === config.provider && disposeTool === undefined) mount(provider)
  271. })
  272. ctx.on('subagent/provider-removed', (name) => {
  273. if (name !== config.provider || disposeTool === undefined) return
  274. void disposeTool()
  275. disposeTool = undefined
  276. })
  277. const present = ctx.subagents.getProvider(config.provider)
  278. if (present !== undefined) {
  279. mount(present)
  280. } else {
  281. // Not an error: the backend's fiber may simply activate after this one.
  282. // The tool appears the moment the provider registers; a typo'd provider
  283. // name shows up as this note plus a tool that never materializes.
  284. ctx.logger.info(`subagent provider "${config.provider}" not registered yet; the "${config.toolName ?? 'subagent'}" tool will register when it appears`)
  285. }
  286. }