gen-tool-catalog.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. /**
  2. * Generate (and verify) the tool-schema catalog in docs/tool-catalog.md.
  3. *
  4. * The catalog is the MODEL-FACING TOOL reference: every tool a shipped plugin
  5. * contributes to `ctx.tools`, with the exact `name` / `description` / JSON-Schema
  6. * `parameters` the model receives via the system-prompt assembly. It complements
  7. * the cordis events/services catalog (the wiring a plugin author works against)
  8. * and the core-data-structures catalog (the vocabulary those signatures move):
  9. * this page is the TOOLS the agent is offered.
  10. *
  11. * `tsx scripts/gen-tool-catalog.ts` → write the catalog
  12. * `tsx scripts/gen-tool-catalog.ts --check` → exit 1 if the committed file
  13. * is stale (CI / pre-push gate)
  14. *
  15. * Why this generator BOOTS PLUGINS instead of parsing source (unlike its AST
  16. * sibling `gen-cordis-catalog.ts`): a tool's schema is not statically knowable.
  17. * `tool-todo` writes `enum: [...STATUSES]` (a runtime spread), descriptions are
  18. * built by string concatenation, `tool-subagent`'s tool name is `config.toolName`,
  19. * and an MCP plugin can register RAW JSON Schema without `defineTool` at all. The
  20. * faithful source of truth is therefore the SHIPPED schema: mount each tool
  21. * plugin on a real cordis Context and read `ctx.tools.schemas()` — exactly the
  22. * `ToolSchema[]` the model is sent. See
  23. * docs/rfc/implemented/process/2026-07-02-tool-schema-catalog.md.
  24. *
  25. * Booting sacrifices the AST pass's structural "nothing can be silently omitted"
  26. * property (there is no source declaration to enumerate), so a COMPLETENESS GUARD
  27. * restores it: the generator globs every `tool-*` package under `packages/` and
  28. * hard-errors if any such package is absent from the boot manifest below. A new
  29. * tool package fails the generator — and thus the freshness gate — until it is
  30. * registered here, mirroring how a new event appears in the cordis regenerate.
  31. *
  32. * Schema blocks use a plain ` ```json ` fence: doc-typecheck only extracts `ts*`
  33. * fences, so no BlockKind wiring is needed there.
  34. */
  35. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  36. import { basename, resolve } from 'node:path'
  37. import { Context } from 'cordis'
  38. import type { ToolSchema } from '@deepseek-ai/dsh-llm'
  39. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  40. import ToolRegistry, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools'
  41. import LocalBashExecutor from '@deepseek-ai/dsh-bash-local'
  42. import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
  43. import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
  44. import WebService from '@deepseek-ai/dsh-web'
  45. import * as WebSearchExa from '@deepseek-ai/dsh-web-search-exa'
  46. import * as WebFetchLocal from '@deepseek-ai/dsh-web-fetch-local'
  47. import SubagentService from '@deepseek-ai/dsh-subagent'
  48. import * as SubagentMock from '@deepseek-ai/dsh-subagent-mock'
  49. import * as ToolAskUser from '@deepseek-ai/dsh-tool-ask-user'
  50. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  51. import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
  52. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  53. import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
  54. import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
  55. import * as ToolWeb from '@deepseek-ai/dsh-tool-web'
  56. import VmWorkflowEngine from '@deepseek-ai/dsh-workflow-workerthread'
  57. import * as ToolWorkflow from '@deepseek-ai/dsh-tool-workflow'
  58. const root = resolve(import.meta.dirname, '..')
  59. const OUT = 'docs/tool-catalog.md'
  60. /**
  61. * One tool-plugin package to boot. `mount` is a per-entry recipe (async): it
  62. * plugs the injected seams the plugin's `apply` reads (an executor for
  63. * `ctx.bash`, a provider for `ctx.subagents`) BEFORE the tool plugin itself.
  64. * `SystemPrompt` + `ToolRegistry` are mounted for every entry by the caller
  65. * (`ToolRegistry` injects `systemPrompt`), so `mount` only handles the extras.
  66. *
  67. * The recipe is irreducible policy — WHICH seams a given tool needs and with
  68. * WHAT config is not derivable from the package layout — so it stays a hand-
  69. * maintained closure. The `dir` field is what the completeness guard matches
  70. * against the on-disk `tool-*` package glob, so a NEW tool package cannot be
  71. * silently omitted (see the module doc).
  72. */
  73. interface ToolPackage {
  74. /** The npm package name, used as the catalog section heading. */
  75. pkg: string
  76. /** The `packages/<group>/<dir>` leaf name — matched by the completeness guard. */
  77. dir: string
  78. /** Repo-relative source path linked from the catalog entry. */
  79. source: string
  80. /** Services or owning runtime surfaces the package requires at execution time. */
  81. requires: string[]
  82. /** Session events or other visible state the tools write or affect. */
  83. writes: string[]
  84. /** Additional model-visible names shipped by example/app config. */
  85. shippedNames?: string[]
  86. /** Plug the injected seams + the tool plugin onto a context that already
  87. * carries `systemPrompt` + `tools`. */
  88. mount: (ctx: Context) => Promise<void>
  89. /**
  90. * Config for the caller's `ToolRegistry` mount. The registry itself ships a
  91. * model-facing tool (`run_code`, registered under a non-native `mode`), so
  92. * ITS catalog entry boots the registry in the mode that surfaces it;
  93. * every other entry uses the default (native) registry.
  94. */
  95. toolsConfig?: ToolsConfig
  96. /**
  97. * A deployment note rendered after the package's tools, for a fact that
  98. * booting the package alone cannot show. The registered tool NAME can be a
  99. * load-time config (`tool-subagent`'s `toolName`), so one package may surface
  100. * under several names across deployments — the boot yields the package
  101. * DEFAULT, and this note records the shipped alternatives the model sees.
  102. */
  103. note?: string
  104. }
  105. /**
  106. * The boot manifest: every shipped tool package (a `tool-*` leaf under
  107. * `packages/`). Ordered by package name (the render order); the completeness
  108. * guard proves it is exhaustive against the on-disk glob.
  109. */
  110. const TOOL_PACKAGES: ToolPackage[] = [
  111. {
  112. pkg: '@deepseek-ai/dsh-tool-ask-user',
  113. dir: 'tool-ask-user',
  114. source: 'packages/ui/tool-ask-user/src/index.ts',
  115. requires: ['ctx.tools', 'ctx.userInteraction'],
  116. writes: ['tool/call', 'tool/result after a UI/provider answers the question'],
  117. async mount(ctx) {
  118. await ctx.plugin(UserInteractionService)
  119. await ctx.plugin(ToolAskUser)
  120. },
  121. note:
  122. 'ask_user_question pauses the tool call until the active UI provider returns a human answer.',
  123. },
  124. {
  125. pkg: '@deepseek-ai/dsh-tools',
  126. dir: 'tools',
  127. source: 'packages/core/tools/src/code-mode.ts',
  128. requires: ['ctx.tools', 'ctx.codeRuntime (execution time)', 'ctx.systemPrompt'],
  129. writes: ['tool/call', 'one tool/code-dispatch per bridged sub-call', 'tool/result'],
  130. // The registry's OWN tool: run_code exists only under a non-native mode
  131. // (the registry registers it in its constructor; the code runtime is read
  132. // at assembly/execution time, so the schema harvest needs none mounted).
  133. toolsConfig: { mode: 'code' },
  134. async mount() {},
  135. note:
  136. 'Registered by the tool registry itself under `mode: code` / `mode: both` (see the Code Mode RFC). Under `code` it is the ONLY wire tool; the other registered tools are declared to the model as a generated TypeScript SDK prompt section instead, and a program calls them through port-bridged bindings that dispatch through the ordinary tools/pre-execute → tools/post-execute pipeline, one at a time.',
  137. },
  138. {
  139. pkg: '@deepseek-ai/dsh-tool-bash',
  140. dir: 'tool-bash',
  141. source: 'packages/bash/tool-bash/src/index.ts',
  142. requires: ['ctx.tools', 'ctx.bash'],
  143. writes: ['tool/call', 'tool/result', 'context/message via agent.inject() for background completion notices'],
  144. async mount(ctx) {
  145. await ctx.plugin(LocalBashExecutor)
  146. await ctx.plugin(ToolBash)
  147. },
  148. note:
  149. 'The bash/bash_output/bash_kill tools are model-facing consumers of the bash executor seam.',
  150. },
  151. {
  152. pkg: '@deepseek-ai/dsh-tool-cordis',
  153. dir: 'tool-cordis',
  154. source: 'packages/cordis/tool-cordis/src/index.ts',
  155. requires: ['ctx.tools'],
  156. writes: ['tool/call', 'tool/result', 'live plugin-tree mutations (mount/unmount)'],
  157. async mount(ctx) {
  158. await ctx.plugin(ToolCordis)
  159. },
  160. note:
  161. 'Ships in examples/cordis-agent only (a deliberate opt-in — mounted code gets the real ctx, see docs/rfc/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). Plugins the model mounts may register ADDITIONAL model-visible tools at runtime; the request-header ToolsDelta logs those tool-set changes.',
  162. },
  163. {
  164. pkg: '@deepseek-ai/dsh-tool-fs',
  165. dir: 'tool-fs',
  166. source: 'packages/fs/tool-fs/src/index.ts',
  167. requires: ['ctx.tools', 'ctx.fs', 'ctx.systemPrompt'],
  168. writes: ['tool/call', 'fs/write-intent or fs/edit-intent for mutations', 'fs/observed after successful file operations', 'tool/result'],
  169. async mount(ctx) {
  170. // The tool injects `fs`; boot the local backend to satisfy it. The schemas
  171. // do not depend on the policy plugin (an event gate that changes behavior,
  172. // not tool shape), so the bare provider is enough to harvest them.
  173. await ctx.plugin(LocalFileSystem)
  174. await ctx.plugin(ToolFs)
  175. },
  176. note:
  177. 'The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-policy` (an `fs/*` event-gate plugin, no schema change); a deployment that loads these tools is expected to also load it. The tool schemas above are identical with or without the policy plugin.',
  178. },
  179. {
  180. pkg: '@deepseek-ai/dsh-tool-subagent',
  181. dir: 'tool-subagent',
  182. source: 'packages/subagent/tool-subagent/src/index.ts',
  183. requires: ['ctx.tools', 'ctx.subagents'],
  184. writes: ['tool/call', 'tool/result', 'child session events through the chosen provider'],
  185. shippedNames: ['subagent', 'subagent_fork'],
  186. async mount(ctx) {
  187. await ctx.plugin(SubagentService)
  188. // Register a scripted provider under the name the tool delegates to.
  189. await ctx.plugin(SubagentMock, { name: 'mock' })
  190. await ctx.plugin(ToolSubagent, { provider: 'mock' })
  191. },
  192. note:
  193. 'The registered tool name is the load-time `toolName` config (default `subagent`); the schema above is that default. The shipped example agents load this package once per subagent backend, so the model additionally sees `subagent_fork` (bound to the fork backend) with an identical schema — see `examples/coding-agent/cordis.yml` and `examples/acp-agent/cordis.yml`.',
  194. },
  195. {
  196. pkg: '@deepseek-ai/dsh-tool-todo',
  197. dir: 'tool-todo',
  198. source: 'packages/todo/tool-todo/src/index.ts',
  199. requires: ['ctx.tools', 'owning Agent session'],
  200. writes: ['tool/call', 'todo/write', 'tool/result'],
  201. async mount(ctx) {
  202. await ctx.plugin(ToolTodo)
  203. },
  204. note:
  205. 'todo_write is session-owned state; UIs render the latest todo/write event as a checklist or ACP plan.',
  206. },
  207. {
  208. pkg: '@deepseek-ai/dsh-tool-workflow',
  209. dir: 'tool-workflow',
  210. source: 'packages/workflow/tool-workflow/src/index.ts',
  211. requires: ['ctx.tools', 'ctx.workflows', 'ctx.systemPrompt', 'a calling Agent (exec.agent parents the script children)'],
  212. writes: ['tool/call', 'tool/result'],
  213. async mount(ctx) {
  214. // The tool injects `workflows`; boot the vm engine over a scripted
  215. // subagent provider to satisfy it. The schema does not depend on which
  216. // provider backs the engine.
  217. await ctx.plugin(SubagentService)
  218. await ctx.plugin(SubagentMock, { name: 'mock' })
  219. await ctx.plugin(VmWorkflowEngine, { provider: 'mock' })
  220. await ctx.plugin(ToolWorkflow)
  221. },
  222. },
  223. {
  224. pkg: '@deepseek-ai/dsh-tool-web',
  225. dir: 'tool-web',
  226. source: 'packages/web/tool-web/src/index.ts',
  227. requires: ['ctx.tools', 'ctx.web', 'ctx.systemPrompt'],
  228. writes: ['tool/call', 'tool/result'],
  229. async mount(ctx) {
  230. // The tools inject `web`; boot the seam plus one search and one fetch
  231. // provider so both `web_search` and `web_fetch` register. The schemas do
  232. // not depend on which provider backs the seam (or on it being available),
  233. // so any registered provider is enough to harvest them.
  234. await ctx.plugin(WebService)
  235. await ctx.plugin(WebSearchExa)
  236. await ctx.plugin(WebFetchLocal)
  237. await ctx.plugin(ToolWeb)
  238. },
  239. note:
  240. 'web_search and web_fetch keep provider selection behind ctx.web so model-visible schemas stay stable across backend swaps.',
  241. },
  242. ]
  243. /** One package's contribution to the catalog: its schemas plus attribution. */
  244. interface CatalogPackage {
  245. pkg: string
  246. source: string
  247. requires: string[]
  248. writes: string[]
  249. shippedNames?: string[]
  250. schemas: ToolSchema[]
  251. /** A deployment note (see {@link ToolPackage.note}), rendered after the tools. */
  252. note?: string
  253. }
  254. /** The whole catalog: one entry per booted tool package, in manifest order. */
  255. export type ToolCatalog = CatalogPackage[]
  256. /**
  257. * Assert the boot manifest covers every shipped tool package on disk (a
  258. * `tool-*` leaf under `packages/`).
  259. * Booting has no source declaration to enumerate, so this glob restores the
  260. * "a new tool cannot be silently undocumented" guarantee: an unlisted package
  261. * fails the generator (and the freshness gate) until it is added to
  262. * {@link TOOL_PACKAGES}. Exported for a direct negative test.
  263. *
  264. * `scanRoot` defaults to the repo root; a test may point it at a fixture tree.
  265. */
  266. export function assertManifestComplete(packages: ToolPackage[] = TOOL_PACKAGES, scanRoot: string = root): void {
  267. const onDisk = globSync('packages/*/tool-*', { cwd: scanRoot }).map(p => basename(p)).sort()
  268. const listed = new Set(packages.map(p => p.dir))
  269. const missing = onDisk.filter(dir => !listed.has(dir))
  270. if (missing.length > 0) {
  271. throw new Error(
  272. `gen-tool-catalog: ${missing.length} tool package(s) not in the boot manifest: ${missing.join(', ')}. `
  273. + 'Add each to TOOL_PACKAGES in scripts/gen-tool-catalog.ts so its schema is catalogued.',
  274. )
  275. }
  276. }
  277. /**
  278. * Boot each tool package on a fresh Context and harvest its model-facing
  279. * schemas. A fresh Context per package keeps attribution clean (each entry's
  280. * schemas come from exactly that package) and isolates a boot failure to its
  281. * own entry. Disposed after harvest so no executor/provider outlives the run.
  282. */
  283. export async function collectToolCatalog(packages: ToolPackage[] = TOOL_PACKAGES): Promise<ToolCatalog> {
  284. assertManifestComplete(packages)
  285. const catalog: ToolCatalog = []
  286. for (const entry of packages) {
  287. const ctx = new Context()
  288. // Dispose in `finally` so a throw from `mount`/`schemas()` after earlier
  289. // plugins mounted still tears the context down (no leaked executor/provider
  290. // fiber) — the repo's "dispose must reach quiescence" rule.
  291. try {
  292. await ctx.plugin(SystemPrompt)
  293. await ctx.plugin(ToolRegistry, entry.toolsConfig ?? {})
  294. await entry.mount(ctx)
  295. const schemas = ctx.tools.schemas().sort((a, b) => a.name.localeCompare(b.name))
  296. catalog.push({
  297. pkg: entry.pkg,
  298. source: entry.source,
  299. requires: entry.requires,
  300. writes: entry.writes,
  301. schemas,
  302. ...entry.shippedNames !== undefined ? { shippedNames: entry.shippedNames } : {},
  303. ...entry.note !== undefined ? { note: entry.note } : {},
  304. })
  305. } finally {
  306. await ctx.fiber.dispose()
  307. }
  308. }
  309. return catalog
  310. }
  311. /** Render one tool's entry: name, description, JSON-Schema parameters, source. */
  312. function renderTool(schema: ToolSchema, source: string): string[] {
  313. const out = [`### \`${schema.name}\``, '']
  314. if (schema.description) out.push(schema.description, '')
  315. out.push('```json', JSON.stringify(schema.parameters, null, 2), '```', '')
  316. out.push(`Source: [\`${source}\`](../${source})`, '')
  317. return out
  318. }
  319. function codeList(values: string[] | undefined): string {
  320. return values?.length ? values.map(value => `\`${value}\``).join(', ') : '-'
  321. }
  322. function tableCell(value: string | undefined): string {
  323. return value ? value.replace(/\|/g, '\\|').replace(/\n/g, '<br>') : '-'
  324. }
  325. /** Render the full catalog (pure, deterministic given the manifest-ordered input). */
  326. export function render(catalog: ToolCatalog): string {
  327. const lines: string[] = [
  328. '<!-- Generated by scripts/gen-tool-catalog.ts — do not edit by hand.',
  329. ' Run `pnpm run gen-tool-catalog` to regenerate. -->',
  330. '',
  331. '# Tool Schema Catalog',
  332. '',
  333. 'Every model-facing tool a shipped plugin contributes to `ctx.tools`: the `name`, `description`, and JSON-Schema `parameters` the model receives via the system-prompt assembly. It complements the cordis [events](cordis-catalog/events.md) & [services](cordis-catalog/services.md) catalogs (the wiring a plugin listens to and calls) and [core-data-structures/](core-data-structures/core.md) (the types those signatures move) — this page is the *tools* the agent is offered.',
  334. '',
  335. 'This file is GENERATED and verified fresh by `pnpm run verify-tool-catalog` (part of `doc-sync`) — do not edit it by hand. Unlike the cordis catalog (a pure source-AST pass), this generator BOOTS each tool plugin on a real context and reads `ctx.tools.schemas()`, because a tool schema is not statically knowable (runtime-spread enums, concatenated descriptions, config-driven names, raw-JSON-Schema MCP tools). A completeness guard globs `packages/*/tool-*` and fails if any package is missing from the generator\'s boot manifest, so a new tool cannot be silently undocumented. See [the tool-schema-catalog RFC](rfc/implemented/process/2026-07-02-tool-schema-catalog.md).',
  336. '',
  337. 'Scope: shipped product tools under `packages/*/tool-*`, each booted with its DEFAULT config. The registered tool NAME can be a load-time config (e.g. `tool-subagent`\'s `toolName`), so a deployment may surface a package under a different or additional name — a per-package note records those shipped aliases where they exist. The `examples/` demo tools (e.g. `echo`) are excluded, matching the cordis catalog\'s packages-only scope.',
  338. '',
  339. '## Tool Package Map',
  340. '',
  341. 'This table connects model-visible tool names to the plugin package and service seams behind them. Exact JSON Schemas follow in the package sections below.',
  342. '',
  343. '| Tool package | Model-visible names | Requires | Writes / affects | Shipped aliases | Deployment note |',
  344. '| --- | --- | --- | --- | --- | --- |',
  345. ...catalog.map(entry => `| \`${entry.pkg}\` | ${codeList(entry.schemas.map(schema => schema.name))} | ${codeList(entry.requires)} | ${codeList(entry.writes)} | ${codeList(entry.shippedNames)} | ${tableCell(entry.note)} |`),
  346. '',
  347. ]
  348. for (const entry of catalog) {
  349. lines.push(`## \`${entry.pkg}\``, '')
  350. for (const schema of entry.schemas) lines.push(...renderTool(schema, entry.source))
  351. if (entry.note) lines.push(entry.note, '')
  352. }
  353. return lines.join('\n')
  354. }
  355. /** CLI entry: default writes the catalog, `--check` fails if the committed copy
  356. * is stale. Guarded behind an entry-point check so importing this module for
  357. * tests neither regenerates the committed file nor calls process.exit. */
  358. async function main(): Promise<void> {
  359. const content = render(await collectToolCatalog())
  360. if (process.argv.includes('--check')) {
  361. let committed: string | null = null
  362. try {
  363. committed = readFileSync(resolve(root, OUT), 'utf8')
  364. } catch {
  365. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  366. // file is not a state this repo produces. Either way the remedy is the
  367. // same — regenerate — so treat a read failure as "stale".
  368. committed = null
  369. }
  370. if (committed === content) {
  371. console.log(`gen-tool-catalog: ${OUT} is up to date.`)
  372. process.exit(0)
  373. }
  374. console.error(`gen-tool-catalog: ${OUT} is stale. Run \`pnpm run gen-tool-catalog\` and commit ${OUT}.`)
  375. process.exit(1)
  376. }
  377. writeFileSync(resolve(root, OUT), content)
  378. console.log(`gen-tool-catalog: wrote ${OUT}.`)
  379. }
  380. // Run only when invoked as a script, not when imported by a test.
  381. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  382. await main()
  383. }