1
0

gen-tool-catalog.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. /**
  2. * Generate `docs/tool-catalog.md` from schemas collected by booting each tool
  3. * plugin. Runtime registration is the source of truth for computed schemas;
  4. * the manifest is checked against every on-disk `tool-*` package. `--check`
  5. * verifies the committed artifact. Rationale and ownership live in
  6. * `.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.md`.
  7. */
  8. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  9. import { basename, resolve } from 'node:path'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import type { ToolSchema } from '@deepseek-ai/dsh-llm'
  12. import AgentRegistry from '@deepseek-ai/dsh-agent'
  13. import type { Agent } from '@deepseek-ai/dsh-agent'
  14. import { createScope } from '@deepseek-ai/dsh-scope'
  15. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  16. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  17. import SqliteSessionQueryEngine from '@deepseek-ai/dsh-session-query-sqlite'
  18. import GoalService from '@deepseek-ai/dsh-goal'
  19. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  20. import ToolRuntime, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools'
  21. import LocalBashExecutor from '@deepseek-ai/dsh-bash-local'
  22. import * as BashEnvPlugin from '@deepseek-ai/dsh-shell-env'
  23. import { PwshLocalExecutor } from '@deepseek-ai/dsh-pwsh-local'
  24. import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
  25. import LocalFileSystem from '@deepseek-ai/dsh-fs-local'
  26. import { AttachmentStore } from '@deepseek-ai/dsh-attachment'
  27. import type { ImageAttachmentLimits, ImageAttachmentRef, SaveImageAttachment, StoredImageAttachment } from '@deepseek-ai/dsh-attachment'
  28. import UserQuestionService from '@deepseek-ai/dsh-user-questions'
  29. import PlanModeController from '@deepseek-ai/dsh-plan-mode'
  30. import WebRuntime from '@deepseek-ai/dsh-web'
  31. import * as WebSearchExa from '@deepseek-ai/dsh-web-search-exa'
  32. import * as WebFetchLocal from '@deepseek-ai/dsh-web-fetch-http'
  33. import SubagentRuntime from '@deepseek-ai/dsh-subagent'
  34. import type { SubagentProvider, SubagentReportDelivery } from '@deepseek-ai/dsh-subagent'
  35. import * as ToolSubagentControl from '@deepseek-ai/dsh-tool-subagent-control'
  36. import * as ToolSubagentListAgents from '@deepseek-ai/dsh-tool-subagent-control/list-agents'
  37. import * as ToolSubagentReport from '@deepseek-ai/dsh-tool-subagent-report'
  38. import SkillRegistry from '@deepseek-ai/dsh-skill'
  39. import * as SkillFileSystem from '@deepseek-ai/dsh-skill-filesystem'
  40. import LocalJobRegistry from '@deepseek-ai/dsh-jobs-local'
  41. import * as ToolAskUser from '@deepseek-ai/dsh-tool-ask-user'
  42. import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
  43. import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh'
  44. import * as ToolBashPersistent from '@deepseek-ai/dsh-tool-bash-persistent'
  45. import CordisHostRunner from '@deepseek-ai/dsh-cordis-host-runner'
  46. import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
  47. import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
  48. import * as ToolFsSearch from '@deepseek-ai/dsh-tool-fs-search'
  49. import * as ToolStrReplaceEditor from '@deepseek-ai/dsh-tool-str-replace-editor'
  50. import TerminalSessionService from '@deepseek-ai/dsh-terminal'
  51. import * as ToolPty from '@deepseek-ai/dsh-tool-terminal'
  52. import * as ToolGoal from '@deepseek-ai/dsh-tool-goal'
  53. import * as ToolSchedule from '@deepseek-ai/dsh-schedule'
  54. import Lsp from '@deepseek-ai/dsh-lsp'
  55. import * as ToolLsp from '@deepseek-ai/dsh-tool-lsp'
  56. import * as ToolSkill from '@deepseek-ai/dsh-tool-skill'
  57. import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query'
  58. import * as ToolTasks from '@deepseek-ai/dsh-tool-jobs'
  59. import type TeamService from '@deepseek-ai/dsh-team'
  60. import * as ToolTeam from '@deepseek-ai/dsh-tool-team'
  61. import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
  62. import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
  63. import * as ToolWeb from '@deepseek-ai/dsh-tool-web'
  64. import VmWorkflowEngine from '@deepseek-ai/dsh-workflow-worker-thread'
  65. import * as ToolRalph from '@deepseek-ai/dsh-tool-ralph'
  66. import * as ToolWorkflow from '@deepseek-ai/dsh-tool-workflow'
  67. import { githubSlug } from './verify-md-links.ts'
  68. /** Attachment seam marker that makes the attachments-conditional `read_image` schema harvestable. */
  69. class CatalogAttachmentStore extends AttachmentStore {
  70. readonly imageLimits: ImageAttachmentLimits = Object.freeze({
  71. maxImageBytes: 1,
  72. maxImagesPerMessage: 1,
  73. maxMessageImageBytes: 1,
  74. maxImagePixels: 1,
  75. maxImageDimension: 1,
  76. mediaTypes: Object.freeze(['image/png'] as const),
  77. })
  78. override validateImage(_input: SaveImageAttachment): Promise<void> {
  79. return Promise.reject(new Error('gen-tool-catalog: attachment validation is unreachable during schema harvest'))
  80. }
  81. override saveImage(_input: SaveImageAttachment): Promise<ImageAttachmentRef> {
  82. return Promise.reject(new Error('gen-tool-catalog: attachment writes are unreachable during schema harvest'))
  83. }
  84. override readImage(_ref: ImageAttachmentRef): Promise<StoredImageAttachment> {
  85. return Promise.reject(new Error('gen-tool-catalog: attachment reads are unreachable during schema harvest'))
  86. }
  87. }
  88. const root = resolve(import.meta.dirname, '..')
  89. const OUT = 'docs/tool-catalog.md'
  90. /**
  91. * Register the descriptor needed to mount schema-producing consumers. Declares
  92. * the full capability set of the shipped in-process providers so consumers
  93. * mount under their shipped defaults (tool-subagent's default numeric maxDepth
  94. * requires `depthLimit`).
  95. */
  96. function registerCatalogSubagentProvider(ctx: Context, name: string): void {
  97. const provider: SubagentProvider = {
  98. name,
  99. capabilities: { outputSchema: true, depthLimit: true, toolFilter: true, persona: true },
  100. inheritsParentContext: false,
  101. start: () => Promise.reject(new Error('tool-catalog provider cannot start a child')),
  102. // Declared so consumers configured for continuable background mode mount.
  103. prepareContinuable: () => Promise.reject(new Error('tool-catalog provider cannot prepare a child')),
  104. }
  105. ctx.subagents.registerProvider(provider)
  106. }
  107. /** Minted child-scope keys for packages whose tools are never global. */
  108. const catalogChildScopes = new WeakMap<Context, Agent>()
  109. /**
  110. * Install one scope-local tool package into an agent-like child scope for
  111. * schema harvest, without starting a model, Agent loop, or persistence backend.
  112. * @param ctx - catalog context owning the scope.
  113. * @param mountScoped - package installer for the scoped context.
  114. * @param key - agent-like scope key exposed to the package's scope selector.
  115. * @param inject - services the package installer must await before mounting.
  116. */
  117. async function mountCatalogChildScope(
  118. ctx: Context,
  119. mountScoped: (childCtx: Context) => void,
  120. key: Agent = { id: SessionId('tool-catalog-child') } as Agent,
  121. inject: string[] = ['tools', 'systemPrompt', 'subagents'],
  122. ): Promise<void> {
  123. await ctx.plugin(Object.assign((inner: Context) => {
  124. mountScoped(createScope(inner, key).ctx)
  125. }, { inject }))
  126. catalogChildScopes.set(ctx, key)
  127. }
  128. /**
  129. * Tool package plus its hand-maintained boot recipe. The caller mounts the
  130. * prompt and registry; each recipe supplies only package-specific seams and
  131. * config, while `dir` participates in the completeness check.
  132. */
  133. export interface ToolPackage {
  134. /** The npm package name, used as the catalog section heading. */
  135. pkg: string
  136. /** The `packages/<group>/<dir>` leaf name — matched by the completeness guard. */
  137. dir: string
  138. /**
  139. * Repo-relative implementation source linked per harvested tool. Packages
  140. * whose tools share one plugin may use a string; split plugins map each tool
  141. * name to its own source.
  142. */
  143. source: string | Readonly<Record<string, string>>
  144. /** Services or owning runtimes the package requires at execution time. */
  145. requires: string[]
  146. /** Session events or other visible state the tools write or affect. */
  147. writes: string[]
  148. /** Additional model-visible names shipped by example/app config. */
  149. shippedNames?: string[]
  150. /** Plug the injected seams + the tool plugin onto a context that already
  151. * carries `systemPrompt` + `tools`. */
  152. mount: (ctx: Context) => Promise<void>
  153. /** Agent-like scope key whose tool view is catalogued instead of the global view. */
  154. scope?: (ctx: Context) => Agent
  155. /**
  156. * Config for the caller's `ToolRuntime` mount. The registry itself ships a
  157. * model-facing tool (`run_code`, registered under a non-native `mode`), so
  158. * ITS catalog entry boots the registry in the mode that exposes it;
  159. * every other entry uses the default (native) registry.
  160. */
  161. toolsConfig?: ToolsConfig
  162. /**
  163. * A deployment note rendered after the package's tools, for a fact that
  164. * booting the package alone cannot show. The registered tool NAME can be a
  165. * load-time config (`tool-subagent`'s `toolName`), so one package may appear
  166. * under several names across deployments — the boot yields the package
  167. * DEFAULT, and this note records the shipped alternatives the model sees.
  168. */
  169. note?: string
  170. }
  171. /**
  172. * The boot manifest: every shipped tool package (a `tool-*` leaf under
  173. * `packages/`). Ordered by package name (the render order); the completeness
  174. * guard proves it is exhaustive against the on-disk glob.
  175. */
  176. const TOOL_PACKAGES: ToolPackage[] = [
  177. {
  178. pkg: '@deepseek-ai/dsh-tool-ask-user',
  179. dir: 'tool-ask-user',
  180. source: 'packages/interaction/tool-ask-user/src/index.ts',
  181. requires: ['ctx.tools', 'ctx.userQuestions'],
  182. writes: ['tool/call', 'tool/result after a UI/provider answers the question'],
  183. async mount(ctx) {
  184. await ctx.plugin(UserQuestionService)
  185. await ctx.plugin(ToolAskUser)
  186. },
  187. note:
  188. 'ask_user_question pauses the tool call until the active UI provider returns a human answer.',
  189. },
  190. {
  191. pkg: '@deepseek-ai/dsh-tools',
  192. dir: 'tools',
  193. source: 'packages/core/tools/src/code-mode.ts',
  194. requires: ['ctx.tools', 'ctx.codeRuntime (execution time)', 'ctx.systemPrompt'],
  195. writes: ['tool/call', 'one tool/code-dispatch-start + tool/code-dispatch pair per bridged sub-call', 'tool/result'],
  196. // The registry's OWN tool: run_code exists only under a non-native mode
  197. // (the registry registers it in its constructor; the code runtime is read
  198. // at assembly/execution time, so the schema harvest needs none mounted).
  199. toolsConfig: { mode: 'code' },
  200. async mount() {},
  201. note:
  202. 'Owned by the tool registry as a reserved transport outside filterable capability layers under `mode: code` / `mode: both` (see the Code Mode Agent Note). Under `code` it is the registry\'s only wire contribution; the other visible capabilities are declared in a generated SDK section in the loaded runtime\'s language, and a program calls them through bindings scheduled under the native concurrency contract (submission-ordered starts and policy; concurrency-safe bodies overlap up to `maxParallelSubCalls`) that re-enter the complete guarded tool pipeline and link each nested execution to this outer result.',
  203. },
  204. {
  205. pkg: '@deepseek-ai/dsh-plan-mode',
  206. dir: 'plan-mode',
  207. source: 'packages/plan/plan-mode/src/index.ts',
  208. requires: ['ctx.tools', 'ctx.systemPrompt', 'ctx.userQuestions (execution time, opportunistic)'],
  209. writes: ['tool/call', 'plan/mode inactive on an approved review', 'tool/result'],
  210. async mount(ctx) {
  211. await ctx.plugin(PlanModeController, { section: 'Tool catalog schema harvest.' })
  212. },
  213. note:
  214. 'exit_plan_mode stays in the model-facing schema while planning is inactive so transitions add no tool-catalog churn on top of the plan-policy change. Its execute path rejects calls outside plan mode; in plan mode it presents the plan over the user-questions seam (approve / keep planning with feedback), and approval logs plan mode inactive at the step boundary.',
  215. },
  216. {
  217. pkg: '@deepseek-ai/dsh-tool-bash',
  218. dir: 'tool-bash',
  219. source: 'packages/shell/tool-bash/src/index.ts',
  220. requires: ['ctx.tools', 'ctx.shell', 'ctx.systemPrompt', 'ctx.shellEnv', 'ctx.jobs at call time for run_in_background'],
  221. writes: ['tool/call', 'tool/result'],
  222. async mount(ctx) {
  223. await ctx.plugin(LocalSubprocessRuntime)
  224. await ctx.plugin(BashEnvPlugin)
  225. await ctx.plugin(LocalBashExecutor)
  226. await ctx.plugin(ToolBash)
  227. },
  228. note:
  229. 'The bash tool is the model-facing consumer of the bash executor seam. A `run_in_background` run registers with the generic `ctx.jobs` runtime and is collected/stopped through the `job_*` tools from `@deepseek-ai/dsh-tool-jobs`; the `enableRunInBackground` config (default true) removes the parameter entirely when disabled.',
  230. },
  231. {
  232. pkg: '@deepseek-ai/dsh-tool-pwsh',
  233. dir: 'tool-pwsh',
  234. source: 'packages/shell/tool-pwsh/src/index.ts',
  235. requires: ['ctx.tools', 'ctx.shell', 'ctx.systemPrompt', 'ctx.shellEnv', 'ctx.jobs at call time for run_in_background'],
  236. writes: ['tool/call', 'tool/result'],
  237. async mount(ctx) {
  238. // The pwsh tool consumes the bash executor seam; the schema harvest
  239. // mounts the pwsh-local implementation so the inject resolves without
  240. // executing anything (registration never spawns a process).
  241. await ctx.plugin(LocalSubprocessRuntime)
  242. await ctx.plugin(BashEnvPlugin)
  243. await ctx.plugin(PwshLocalExecutor)
  244. await ctx.plugin(ToolPwsh)
  245. },
  246. note:
  247. 'The pwsh tool is the PowerShell-dialect consumer of the bash executor seam for Windows compositions (a PowerShell executor such as `@deepseek-ai/dsh-pwsh-local` backs `ctx.shell`); it mirrors the bash tool call-for-call minus sandbox controls — `run_in_background` runs register with the generic `ctx.jobs` runtime and are collected/stopped through the `job_*` tools, and the managed `DSH_*` environment comes from `@deepseek-ai/dsh-shell-env`. Each call runs in a fresh process (no persistent PTY session), with native `C:\\...` paths and `$env:NAME` variables.',
  248. },
  249. {
  250. pkg: '@deepseek-ai/dsh-tool-cordis',
  251. dir: 'tool-cordis',
  252. source: 'packages/extensions/tool-cordis/src/index.ts',
  253. requires: ['ctx.tools', 'ctx.dynamicCordisRunner'],
  254. writes: ['tool/call', 'tool/result', 'process-local dynamic package lifecycle'],
  255. async mount(ctx) {
  256. await ctx.plugin(CordisHostRunner)
  257. await ctx.plugin(ToolCordis)
  258. },
  259. note:
  260. 'Not in any shipped tree (a deliberate opt-in — dynamic package code reaches the real runtime, see .agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). The toolset injects `ctx.dynamicCordisRunner` from `@deepseek-ai/dsh-cordis-host-runner`, which owns the definition registry and the vm sandbox; a composition missing it never activates the tools. A running package may register ADDITIONAL model-visible tools until it is stopped, undefined, or DSH restarts; a full changed request header logs those tool-set changes.',
  261. },
  262. {
  263. pkg: '@deepseek-ai/dsh-tool-bash-persistent',
  264. dir: 'tool-bash-persistent',
  265. source: 'packages/shell/tool-bash-persistent/src/index.ts',
  266. requires: ['ctx.tools', 'ctx.terminals', 'an owning Agent at execution time'],
  267. writes: ['tool/call', 'PTY shell state', 'tool/result'],
  268. async mount(ctx) {
  269. await ctx.plugin(TerminalSessionService)
  270. await ctx.plugin(ToolBashPersistent)
  271. },
  272. note:
  273. 'One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description.',
  274. },
  275. {
  276. pkg: '@deepseek-ai/dsh-tool-str-replace-editor',
  277. dir: 'tool-str-replace-editor',
  278. source: 'packages/fs/tool-str-replace-editor/src/index.ts',
  279. requires: ['ctx.tools', 'ctx.fs'],
  280. writes: ['tool/call', 'fs/observed after view presence/absence, edit absence, or successful mutation', 'tool/result'],
  281. async mount(ctx) {
  282. await ctx.plugin(LocalFileSystem)
  283. await ctx.plugin(ToolStrReplaceEditor)
  284. },
  285. note:
  286. 'Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal API.',
  287. },
  288. {
  289. pkg: '@deepseek-ai/dsh-tool-fs',
  290. dir: 'tool-fs',
  291. source: 'packages/fs/tool-fs/src/index.ts',
  292. requires: ['ctx.tools', 'ctx.fs', 'ctx.systemPrompt', 'ctx.attachments (read_image registration)', 'ctx.llm + an image-capable route (read_image execution)'],
  293. writes: ['tool/call', 'fs/write-intent or fs/edit-intent for mutations', 'fs/observed after read presence/absence or successful file operation', 'durable attachment (read_image)', 'tool/result'],
  294. async mount(ctx) {
  295. // The tool needs `fs`; the bare provider is sufficient because policy
  296. // changes behavior, not schema shape. The catalog seam marker opts into
  297. // the attachments-conditional read_image schema without attachment I/O.
  298. await ctx.plugin(LocalFileSystem)
  299. await ctx.plugin(CatalogAttachmentStore)
  300. await ctx.plugin(ToolFs)
  301. },
  302. note:
  303. 'The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-observation-policy` (an `fs/*` event-gate plugin, no schema change); a deployment that loads these tools is expected to also load it. `read_image` is not registered without `ctx.attachments`; its schema is route-independent, and execution refuses unless the exact routed model declares image input.',
  304. },
  305. {
  306. pkg: '@deepseek-ai/dsh-tool-fs-search',
  307. dir: 'tool-fs-search',
  308. source: 'packages/fs/tool-fs-search/src/index.ts',
  309. requires: ['ctx.tools', 'ctx.subprocess', 'ctx.systemPrompt'],
  310. writes: ['tool/call', 'tool/result'],
  311. async mount(ctx) {
  312. // The tools inject `subprocess` (search spawns the packaged ripgrep
  313. // binary through the seam, not ctx.fs); registration itself never
  314. // spawns, so the real local service is inert here. `ctx.spillStore` is
  315. // optional (read via ctx.get) and does not affect the schemas, so no
  316. // spill backend is mounted.
  317. await ctx.plugin(LocalSubprocessRuntime)
  318. await ctx.plugin(ToolFsSearch, { sampleOverCapGlobResults: true })
  319. },
  320. note:
  321. 'glob and grep are unconditional discovery tools that spawn the packaged ripgrep binary (`@vscode/ripgrep`) through ctx.subprocess as ordinary foreground calls (never background jobs) — no host `rg` install and no shell layer. The catalog uses `sampleOverCapGlobResults: true`; deployments must choose that behavior explicitly. Capped results save the complete formatted list through the optional ctx.spillStore backend; returned locators are follow-up-readable/searchable when the backend exposes local paths in co-located deployments.',
  322. },
  323. {
  324. pkg: '@deepseek-ai/dsh-tool-terminal',
  325. dir: 'tool-terminal',
  326. source: 'packages/terminal/tool-terminal/src/index.ts',
  327. requires: ['ctx.tools', 'ctx.terminals', 'ctx.systemPrompt', 'ctx.jobs at call time for run_in_background'],
  328. writes: ['tool/call', 'tool/result'],
  329. async mount(ctx) {
  330. await ctx.plugin(TerminalSessionService)
  331. await ctx.plugin(ToolPty)
  332. },
  333. note:
  334. 'The six terminal tools are opt-in and complement one-shot shell/filesystem tools. `terminal_send(run_in_background: true)` registers with `ctx.jobs`; TUI, named key sequences, BEL, resize, auto-start, and cross-agent sharing are absent from the schema.',
  335. },
  336. {
  337. pkg: '@deepseek-ai/dsh-tool-goal',
  338. dir: 'tool-goal',
  339. source: 'packages/goal/tool-goal/src/index.ts',
  340. requires: ['ctx.tools', 'ctx.agents', 'ctx.goals', 'ctx.systemPrompt', 'a calling Agent in an authorized open turn'],
  341. writes: ['tool/call', 'goal/change for mutations', 'tool/result'],
  342. async mount(ctx) {
  343. await ctx.plugin(AgentRegistry)
  344. await ctx.plugin(GoalService)
  345. await ctx.plugin(ToolGoal)
  346. },
  347. note:
  348. 'create, edit, pause, and resume require direct-human root authority; complete and blocked also accept the exact current goal round. The default blocked lower bound is three admitted rounds.',
  349. },
  350. {
  351. pkg: '@deepseek-ai/dsh-schedule',
  352. dir: 'schedule',
  353. source: 'packages/schedule/schedule/src/tools.ts',
  354. requires: ['ctx.tools', 'ctx.sessions', 'Session persistence', 'a future live root Agent'],
  355. writes: ['tool/call', 'schedule/change create or delete', 'tool/result'],
  356. async mount(ctx) {
  357. await ctx.plugin(SessionStore)
  358. const session = ctx.sessions.create(SessionId('tool-catalog-schedule'))
  359. const agent = { id: session.id, session } as Agent
  360. await mountCatalogChildScope(ctx, (childCtx) => {
  361. ToolSchedule.registerScheduleTools(ctx, childCtx, agent, () => {})
  362. }, agent, ['tools', 'systemPrompt'])
  363. },
  364. scope: ctx => catalogChildScopes.get(ctx) as Agent,
  365. note:
  366. 'Registered only inside live root Agent scopes created after the opt-in Schedule plugin loads. '
  367. + 'Version 1 accepts after_seconds, explicit absolute at, and bounded fixed-rate every_seconds, '
  368. + 'and discloses session-local delivery; '
  369. + 'management reads and mutations require the shared Session persistence barrier.',
  370. },
  371. {
  372. pkg: '@deepseek-ai/dsh-tool-lsp',
  373. dir: 'tool-lsp',
  374. source: 'packages/lsp/tool-lsp/src/index.ts',
  375. requires: ['ctx.tools', 'ctx.lsp', 'ctx.systemPrompt'],
  376. writes: ['tool/call', 'tool/result'],
  377. async mount(ctx) {
  378. // The tool registers from the seam alone; the schema does not depend on any provider.
  379. await ctx.plugin(Lsp)
  380. await ctx.plugin(ToolLsp)
  381. },
  382. note:
  383. 'The lsp tool keeps provider selection and language-server subprocesses behind ctx.lsp, so its model-visible schema stays stable across providers. Requires a registered provider (e.g. `@deepseek-ai/dsh-lsp-stdio`) at runtime; without one, a query returns the structured `LSP_UNAVAILABLE` error rather than changing the schema.',
  384. },
  385. {
  386. pkg: '@deepseek-ai/dsh-tool-ralph',
  387. dir: 'tool-ralph',
  388. source: 'packages/workflow/tool-ralph/src/index.ts',
  389. requires: ['ctx.tools', 'ctx.workflowEngine', 'ctx.subagents', 'ctx.systemPrompt', 'a calling Agent (exec.agent parents every fresh round)'],
  390. writes: ['tool/call', 'tool/result', 'workflow and child session events during execution'],
  391. async mount(ctx) {
  392. await ctx.plugin(SubagentRuntime)
  393. registerCatalogSubagentProvider(ctx, 'mock')
  394. await ctx.plugin(VmWorkflowEngine, { provider: 'mock' })
  395. await ctx.plugin(ToolRalph, { subagentProvider: 'mock' })
  396. },
  397. note:
  398. 'A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap.',
  399. },
  400. {
  401. pkg: '@deepseek-ai/dsh-tool-skill',
  402. dir: 'tool-skill',
  403. source: 'packages/skill/tool-skill/src/index.ts',
  404. requires: ['ctx.tools', 'ctx.agents', 'ctx.skills'],
  405. writes: ['tool/call', 'tool/result', 'user/message replacement catalogs via agent.inject()'],
  406. async mount(ctx) {
  407. await ctx.plugin(AgentRegistry)
  408. await ctx.plugin(SkillRegistry)
  409. await ctx.plugin(SkillFileSystem, {
  410. dshHome: resolve(root, '.tmp/tool-catalog/.dsh'),
  411. agentsHome: resolve(root, '.tmp/tool-catalog/.agents'),
  412. })
  413. await ctx.plugin(ToolSkill)
  414. },
  415. },
  416. {
  417. pkg: '@deepseek-ai/dsh-tool-session-query',
  418. dir: 'tool-session-query',
  419. source: 'packages/session-query/tool-session-query/src/index.ts',
  420. requires: ['ctx.tools', 'ctx.systemPrompt', 'ctx.sessionQuery', 'a calling Agent for workspace authority'],
  421. writes: ['tool/call', 'tool/result'],
  422. async mount(ctx) {
  423. await ctx.plugin(SessionStore)
  424. await ctx.plugin(SqliteSessionQueryEngine, { path: ':memory:' })
  425. await ctx.plugin(ToolSessionQuery)
  426. },
  427. note:
  428. 'The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. The package is opt-in; compositions that need enforced deadlines or bounded inline output also mount the generic timeout or spill policies.',
  429. },
  430. {
  431. pkg: '@deepseek-ai/dsh-tool-subagent',
  432. dir: 'tool-subagent',
  433. source: 'packages/subagent/tool-subagent/src/index.ts',
  434. requires: ['ctx.tools', 'ctx.subagents', 'ctx.systemPrompt'],
  435. writes: ['tool/call', 'tool/result', 'child session events through the chosen provider'],
  436. shippedNames: ['subagent', 'subagent_fork'],
  437. async mount(ctx) {
  438. await ctx.plugin(SubagentRuntime)
  439. registerCatalogSubagentProvider(ctx, 'mock')
  440. await ctx.plugin(ToolSubagent, { provider: 'mock' })
  441. },
  442. note:
  443. 'The registered tool name is the load-time `toolName` config (default `subagent`); the schema above is that default. The shipped compositions load this package once per subagent backend, so the model additionally sees `subagent_fork` bound to the fork backend. Each instance\'s description, `run_in_background` parameter, and system-prompt policy follow its own `backgroundMode` and `enableRunInBackground`, so the two shipped schemas are not identical: `subagent` is `continuable` and defaults omitted calls to background with automatic settlement delivery, while `subagent_fork` stays `one-shot` and defaults them to foreground — see `packages/bundle/base/cordis.patch.yml` and `examples/acp-agent/cordis.yml`.',
  444. },
  445. {
  446. pkg: '@deepseek-ai/dsh-tool-subagent-control',
  447. dir: 'tool-subagent-control',
  448. source: {
  449. interrupt_agent: 'packages/subagent/tool-subagent-control/src/index.ts',
  450. list_agents: 'packages/subagent/tool-subagent-control/src/list-agents.ts',
  451. send_message: 'packages/subagent/tool-subagent-control/src/index.ts',
  452. },
  453. requires: ['ctx.tools', 'ctx.subagents', 'ctx.agents and ctx.sessionProjections (list_agents only)'],
  454. writes: ['tool/call', 'tool/result', 'child session events through ctx.subagents'],
  455. async mount(ctx) {
  456. await ctx.plugin(SubagentRuntime)
  457. await ctx.plugin(LocalJobRegistry)
  458. await ctx.plugin(AgentRegistry)
  459. await ctx.plugin(SessionStore)
  460. await ctx.plugin(SessionProjectionRegistry)
  461. await ctx.plugin(ToolSubagentControl)
  462. await ctx.plugin(ToolSubagentListAgents)
  463. },
  464. note:
  465. 'The globally named control tools over continuable background subagents: provider-bound `tool-subagent` instances register distinct delegation tools, while this package registers `send_message` and `interrupt_agent` once, plus `list_agents` from its separately loaded `/list-agents` plugin (whose catalog rows use the sessionProjections and live Agent registries).',
  466. },
  467. {
  468. pkg: '@deepseek-ai/dsh-tool-subagent-report',
  469. dir: 'tool-subagent-report',
  470. source: 'packages/subagent/tool-subagent-report/src/index.ts',
  471. requires: ['ctx.subagents', 'ctx.systemPrompt', 'a live continuable in-process child Agent'],
  472. writes: ['tool/call', 'tool/result', 'a user-role message in the direct parent session'],
  473. async mount(ctx) {
  474. await ctx.plugin(AgentRegistry)
  475. await ctx.plugin(SubagentRuntime)
  476. const { reportDelivery } = ToolSubagentReport.Config({}) as { reportDelivery: SubagentReportDelivery }
  477. await mountCatalogChildScope(ctx, (childCtx) => {
  478. ToolSubagentReport.installReportTool(childCtx, ctx, reportDelivery)
  479. })
  480. },
  481. scope: ctx => catalogChildScopes.get(ctx) as Agent,
  482. note:
  483. 'Registered per continuable in-process child rather than globally, so this schema is visible only '
  484. + 'inside such a child and survives its global `toolFilter`. The same contribution installs the '
  485. + 'child-scoped `tool:report` prompt section, which this catalog does not render. The parent-facing '
  486. + '`send_message` tool is installed independently.',
  487. },
  488. {
  489. pkg: '@deepseek-ai/dsh-tool-jobs',
  490. dir: 'tool-jobs',
  491. source: 'packages/jobs/tool-jobs/src/index.ts',
  492. requires: ['ctx.tools', 'ctx.jobs', 'ctx.systemPrompt'],
  493. writes: ['tool/call', 'tool/result', 'user/message via agent.inject() for background completion notices'],
  494. async mount(ctx) {
  495. await ctx.plugin(LocalJobRegistry)
  496. await ctx.plugin(ToolTasks)
  497. },
  498. note:
  499. 'The kind-agnostic background-job controller: background bash commands, PTY sends, and subagents are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers\' `ctx.jobs.start()`.',
  500. },
  501. {
  502. pkg: '@deepseek-ai/dsh-tool-team',
  503. dir: 'tool-team',
  504. source: 'packages/experimental/tool-team/src/index.ts',
  505. requires: ['ctx.tools', 'ctx.systemPrompt', 'ctx.teams', 'an exact live Team member Agent'],
  506. writes: ['tool/call', 'team/member', 'team/message/queued', 'team/message/delivered', 'team/task', 'tool/result'],
  507. async mount(ctx) {
  508. await ctx.plugin(AgentRegistry)
  509. await ctx.plugin(SessionStore)
  510. const session = ctx.sessions.create(SessionId('tool-catalog-team-lead'))
  511. let agent!: Agent
  512. const membership = {
  513. get root() { return agent },
  514. id: session.id,
  515. role: 'lead' as const,
  516. name: 'lead',
  517. }
  518. ctx.provide('teams', {
  519. tryMembership: (candidate: Agent) => candidate === agent ? membership : undefined,
  520. membership: () => membership,
  521. } as unknown as TeamService)
  522. await ctx.plugin(Object.assign((inner: Context) => {
  523. agent = {
  524. id: session.id,
  525. session,
  526. options: {},
  527. status: 'idle',
  528. } as unknown as Agent
  529. Object.assign(agent, { ctx: createScope(inner, agent).ctx })
  530. inner.agents.register(agent)
  531. }, { inject: ['tools', 'systemPrompt', 'agents', 'teams'] }))
  532. await ctx.plugin(ToolTeam)
  533. catalogChildScopes.set(ctx, agent)
  534. },
  535. scope: ctx => catalogChildScopes.get(ctx) as Agent,
  536. note:
  537. 'All ten tools are scoped to implicit Team Leads and durable teammates. The shipped dsh-base bundle keeps the package disabled; the documented Agent Teams profile patch enables it while disabling the legacy continuable-child control names.',
  538. },
  539. {
  540. pkg: '@deepseek-ai/dsh-tool-todo',
  541. dir: 'tool-todo',
  542. source: 'packages/todo/tool-todo/src/index.ts',
  543. requires: ['ctx.tools', 'owning Agent session'],
  544. writes: ['tool/call', 'todo/write', 'tool/result'],
  545. async mount(ctx) {
  546. await ctx.plugin(ToolTodo, { allowParallelInProgress: true })
  547. },
  548. note:
  549. 'todo_write is session-owned state; UIs render the latest todo/write event as a checklist. `allowParallelInProgress` is required with no default, so the catalog states its choice: `true`, whose description invites several `in_progress` items. A deployment choosing `false` receives the same tool with a description asking for exactly one active task.',
  550. },
  551. {
  552. pkg: '@deepseek-ai/dsh-tool-workflow',
  553. dir: 'tool-workflow',
  554. source: 'packages/workflow/tool-workflow/src/index.ts',
  555. requires: ['ctx.tools', 'ctx.workflowEngine', 'ctx.systemPrompt', 'a calling Agent (exec.agent parents the script children)'],
  556. writes: ['tool/call', 'tool/result'],
  557. async mount(ctx) {
  558. // The tool injects `workflows`; boot the vm engine over a scripted
  559. // subagent provider to satisfy it. The schema does not depend on which
  560. // provider backs the engine.
  561. await ctx.plugin(SubagentRuntime)
  562. registerCatalogSubagentProvider(ctx, 'mock')
  563. await ctx.plugin(VmWorkflowEngine, { provider: 'mock' })
  564. await ctx.plugin(ToolWorkflow)
  565. },
  566. },
  567. {
  568. pkg: '@deepseek-ai/dsh-tool-web',
  569. dir: 'tool-web',
  570. source: 'packages/web/tool-web/src/index.ts',
  571. requires: ['ctx.tools', 'ctx.web', 'ctx.systemPrompt'],
  572. writes: ['tool/call', 'tool/result'],
  573. async mount(ctx) {
  574. // Mount search and fetch providers so both tools register. Their schemas
  575. // do not depend on provider identity or availability.
  576. await ctx.plugin(WebRuntime)
  577. await ctx.plugin(WebSearchExa)
  578. await ctx.plugin(WebFetchLocal)
  579. await ctx.plugin(ToolWeb)
  580. },
  581. note:
  582. 'web_search and web_fetch keep provider selection behind ctx.web so model-visible schemas stay stable across backend swaps.',
  583. },
  584. ]
  585. /** One package's contribution to the catalog: its schemas plus attribution. */
  586. interface CatalogPackage {
  587. pkg: string
  588. sources: Readonly<Record<string, string>>
  589. requires: string[]
  590. writes: string[]
  591. shippedNames?: string[]
  592. schemas: ToolSchema[]
  593. /** A deployment note (see {@link ToolPackage.note}), rendered after the tools. */
  594. note?: string
  595. }
  596. /** The whole catalog: one entry per booted tool package, in manifest order. */
  597. export type ToolCatalog = CatalogPackage[]
  598. /**
  599. * Assert the boot manifest covers every shipped tool package on disk (a
  600. * `tool-*` leaf under `packages/`).
  601. * Booting has no source declaration to enumerate, so this glob restores the
  602. * "a new tool cannot be silently undocumented" guarantee: an unlisted package
  603. * fails the generator (and the freshness gate) until it is added to
  604. * {@link TOOL_PACKAGES}. Exported for a direct negative test.
  605. *
  606. * `scanRoot` defaults to the repo root; a test may point it at a fixture tree.
  607. */
  608. export function assertManifestComplete(packages: ToolPackage[] = TOOL_PACKAGES, scanRoot: string = root): void {
  609. const onDisk = globSync('packages/*/tool-*', { cwd: scanRoot }).map(p => basename(p)).sort()
  610. const listed = new Set(packages.map(p => p.dir))
  611. const missing = onDisk.filter(dir => !listed.has(dir))
  612. if (missing.length > 0) {
  613. throw new Error(
  614. `gen-tool-catalog: ${missing.length} tool package(s) not in the boot manifest: ${missing.join(', ')}. `
  615. + 'Add each to TOOL_PACKAGES in scripts/gen-tool-catalog.ts so its schema is catalogued.',
  616. )
  617. }
  618. }
  619. /**
  620. * Assert one manifest entry actually registered a tool.
  621. *
  622. * A tool package that boots without registering anything is a broken boot, not
  623. * an empty catalog section. The usual cause is an `inject` the entry's `mount`
  624. * does not satisfy: cordis leaves the plugin PENDING, every step here still
  625. * succeeds, and the generator writes a catalog missing that package's tools —
  626. * with the freshness gate green on it, because the omission is now what the
  627. * generator produces. {@link assertManifestComplete} cannot see this: the
  628. * package IS listed, it just contributed nothing.
  629. * @param entry - the manifest entry that was booted.
  630. * @param harvested - how many schemas its boot registered.
  631. * @throws when the boot registered no tool at all.
  632. */
  633. export function assertToolsHarvested(entry: ToolPackage, harvested: number): void {
  634. if (harvested > 0) return
  635. throw new Error(
  636. `gen-tool-catalog: ${entry.pkg} booted without registering a single tool. `
  637. + 'Its plugin is most likely PENDING on a service this manifest entry does not mount — '
  638. + `compare the plugin's inject with mount() and requires: ${entry.requires.join(', ')}.`,
  639. )
  640. }
  641. /**
  642. * Boot each tool package on a fresh Context and harvest its model-facing
  643. * schemas. A fresh Context per package keeps attribution clean (each entry's
  644. * schemas come from exactly that package) and isolates a boot failure to its
  645. * own entry. Disposed after harvest so no executor/provider outlives the run.
  646. */
  647. export async function collectToolCatalog(packages: ToolPackage[] = TOOL_PACKAGES): Promise<ToolCatalog> {
  648. assertManifestComplete(packages)
  649. const catalog: ToolCatalog = []
  650. for (const entry of packages) {
  651. const ctx = new Context()
  652. // Dispose in `finally` so a throw from `mount`/`schemas()` after earlier
  653. // plugins mounted still tears the context down (no leaked executor/provider
  654. // fiber) — the repo's "dispose must reach quiescence" rule.
  655. try {
  656. await ctx.plugin(SystemPrompt)
  657. await ctx.plugin(ToolRuntime, entry.toolsConfig ?? {})
  658. await entry.mount(ctx)
  659. const schemas = ctx.tools.schemas(entry.scope?.(ctx)).sort((a, b) => a.name.localeCompare(b.name))
  660. assertToolsHarvested(entry, schemas.length)
  661. catalog.push({
  662. pkg: entry.pkg,
  663. sources: Object.fromEntries(schemas.map(schema => [
  664. schema.name,
  665. toolSource(entry, schema.name),
  666. ])),
  667. requires: entry.requires,
  668. writes: entry.writes,
  669. schemas,
  670. ...entry.shippedNames !== undefined ? { shippedNames: entry.shippedNames } : {},
  671. ...entry.note !== undefined ? { note: entry.note } : {},
  672. })
  673. } finally {
  674. await ctx.fiber.dispose()
  675. }
  676. }
  677. return catalog
  678. }
  679. /** Resolve one harvested tool to the plugin source that registered it. */
  680. function toolSource(entry: ToolPackage, toolName: string): string {
  681. if (typeof entry.source === 'string') return entry.source
  682. const source = entry.source[toolName]
  683. if (source === undefined) {
  684. throw new Error(
  685. `gen-tool-catalog: ${entry.pkg} has no source mapping for harvested tool ${toolName}`,
  686. )
  687. }
  688. return source
  689. }
  690. /** Render one tool's entry: name, description, JSON-Schema parameters, source. */
  691. function renderTool(schema: ToolSchema, source: string): string[] {
  692. const out = [`### \`${schema.name}\``, '']
  693. if (schema.description) out.push(schema.description, '')
  694. out.push('```json', JSON.stringify(schema.parameters, null, 2), '```', '')
  695. out.push(`Source: [\`${source}\`](../${source})`, '')
  696. return out
  697. }
  698. function codeList(values: string[] | undefined): string {
  699. return values?.length ? values.map(value => `\`${value}\``).join(', ') : '-'
  700. }
  701. function tableCell(value: string | undefined): string {
  702. return value ? value.replace(/\|/g, '\\|').replace(/\n/g, '<br>') : '-'
  703. }
  704. /** Render the full catalog (pure, deterministic given the manifest-ordered input). */
  705. export function render(catalog: ToolCatalog): string {
  706. const lines: string[] = [
  707. '<!-- Generated by scripts/gen-tool-catalog.ts — do not edit by hand.',
  708. ' Run `pnpm run gen-tool-catalog` to regenerate. -->',
  709. '',
  710. '# Tool Schema Catalog',
  711. '',
  712. '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 [subsystem pages](subsystems/core.md) (the types plus each page\'s generated Cordis API region) — this page is the *tools* the agent is offered.',
  713. '',
  714. '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 Agent Note](../.agents/notes/implemented/process/2026-07-02-tool-schema-catalog.md).',
  715. '',
  716. 'Scope: shipped product tools under `packages/*/tool-*`, each booted with its DEFAULT config, except where a Config field is REQUIRED with no default — there the generator must choose, and the per-package note records which branch this page shows. The registered tool NAME can be a load-time config (e.g. `tool-subagent`\'s `toolName`), so a deployment may expose 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.',
  717. '',
  718. '## Tool Package Map',
  719. '',
  720. '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.',
  721. '',
  722. '| Tool package | Model-visible names | Requires | Writes / affects | Shipped aliases | Deployment note |',
  723. '| --- | --- | --- | --- | --- | --- |',
  724. ...catalog.map(entry => `| \`${entry.pkg}\` | ${codeList(entry.schemas.map(schema => schema.name))} | ${codeList(entry.requires)} | ${codeList(entry.writes)} | ${codeList(entry.shippedNames)} | ${tableCell(entry.note)} |`),
  725. '',
  726. ]
  727. for (const entry of catalog) {
  728. lines.push(`<a id="${githubSlug(entry.pkg)}"></a>`, '', `## \`${entry.pkg}\``, '')
  729. for (const schema of entry.schemas) {
  730. // Collection validated that every harvested schema has a source.
  731. const source = entry.sources[schema.name] as string
  732. lines.push(...renderTool(schema, source))
  733. }
  734. if (entry.note) lines.push(entry.note, '')
  735. }
  736. return lines.join('\n')
  737. }
  738. /** CLI entry: default writes the catalog, `--check` fails if the committed copy
  739. * is stale. Guarded behind an entry-point check so importing this module for
  740. * tests neither regenerates the committed file nor calls process.exit. */
  741. async function main(): Promise<void> {
  742. const content = render(await collectToolCatalog())
  743. if (process.argv.includes('--check')) {
  744. let committed: string | null = null
  745. try {
  746. committed = readFileSync(resolve(root, OUT), 'utf8')
  747. } catch {
  748. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  749. // file is not a state this repo produces. Either way the remedy is the
  750. // same — regenerate — so treat a read failure as "stale".
  751. committed = null
  752. }
  753. if (committed === content) {
  754. console.log(`gen-tool-catalog: ${OUT} is up to date.`)
  755. process.exit(0)
  756. }
  757. console.error(`gen-tool-catalog: ${OUT} is stale. Run \`pnpm run gen-tool-catalog\` and commit ${OUT}.`)
  758. const committedLines = committed?.split('\n') ?? []
  759. const generatedLines = content.split('\n')
  760. const lineCount = Math.max(committedLines.length, generatedLines.length)
  761. for (let index = 0; index < lineCount; index += 1) {
  762. if (committedLines[index] === generatedLines[index]) continue
  763. console.error(`gen-tool-catalog: first difference at line ${index + 1}`)
  764. console.error(` committed: ${JSON.stringify(committedLines[index])}`)
  765. console.error(` generated: ${JSON.stringify(generatedLines[index])}`)
  766. break
  767. }
  768. process.exit(1)
  769. }
  770. writeFileSync(resolve(root, OUT), content)
  771. console.log(`gen-tool-catalog: wrote ${OUT}.`)
  772. }
  773. // Run only when invoked as a script, not when imported by a test.
  774. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  775. await main()
  776. }