@kirkchinese/harness-forge 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/docs/DETAIL.zh.md +47 -0
  6. package/lib/agents/presets.d.ts +98 -0
  7. package/lib/agents/presets.js +292 -0
  8. package/lib/agents/profiles.d.ts +58 -0
  9. package/lib/agents/profiles.js +279 -0
  10. package/lib/agents/row.d.ts +17 -0
  11. package/lib/agents/row.js +148 -0
  12. package/lib/client/paths.d.ts +12 -0
  13. package/lib/client/paths.js +68 -0
  14. package/lib/client/styles.d.ts +8 -0
  15. package/lib/client/styles.js +89 -0
  16. package/lib/client/typert.d.ts +25 -0
  17. package/lib/client/typert.js +158 -0
  18. package/lib/client.js +23823 -0
  19. package/lib/commands/definition.d.ts +40 -0
  20. package/lib/commands/definition.js +113 -0
  21. package/lib/commands/output-styles.d.ts +42 -0
  22. package/lib/commands/output-styles.js +152 -0
  23. package/lib/commands/row.d.ts +9 -0
  24. package/lib/commands/row.js +157 -0
  25. package/lib/context/instructions.d.ts +32 -0
  26. package/lib/context/instructions.js +88 -0
  27. package/lib/context/row.d.ts +16 -0
  28. package/lib/context/row.js +17 -0
  29. package/lib/dsh/commands.d.ts +30 -0
  30. package/lib/dsh/commands.js +61 -0
  31. package/lib/dsh/host.d.ts +110 -0
  32. package/lib/dsh/host.js +217 -0
  33. package/lib/dsh/model-route.d.ts +21 -0
  34. package/lib/dsh/model-route.js +37 -0
  35. package/lib/dsh/session-records.d.ts +78 -0
  36. package/lib/dsh/session-records.js +36 -0
  37. package/lib/dsh/subagents.d.ts +46 -0
  38. package/lib/dsh/subagents.js +14 -0
  39. package/lib/forge/contract.d.ts +271 -0
  40. package/lib/forge/contract.js +45 -0
  41. package/lib/forge/follow.d.ts +30 -0
  42. package/lib/forge/follow.js +73 -0
  43. package/lib/forge/ledger.d.ts +206 -0
  44. package/lib/forge/ledger.js +1005 -0
  45. package/lib/forge/live-mounts.d.ts +45 -0
  46. package/lib/forge/live-mounts.js +78 -0
  47. package/lib/forge/npm.d.ts +31 -0
  48. package/lib/forge/npm.js +60 -0
  49. package/lib/forge/projects.d.ts +97 -0
  50. package/lib/forge/projects.js +343 -0
  51. package/lib/forge/receipts.d.ts +5 -0
  52. package/lib/forge/receipts.js +31 -0
  53. package/lib/forge/remote/archive.d.ts +65 -0
  54. package/lib/forge/remote/archive.js +565 -0
  55. package/lib/forge/remote/code-parts.d.ts +18 -0
  56. package/lib/forge/remote/code-parts.js +76 -0
  57. package/lib/forge/remote/fetch.d.ts +265 -0
  58. package/lib/forge/remote/fetch.js +1133 -0
  59. package/lib/forge/remote/service.d.ts +256 -0
  60. package/lib/forge/remote/service.js +868 -0
  61. package/lib/forge/row.d.ts +32 -0
  62. package/lib/forge/row.js +59 -0
  63. package/lib/forge/service.d.ts +115 -0
  64. package/lib/forge/service.js +290 -0
  65. package/lib/forge/settings.d.ts +43 -0
  66. package/lib/forge/settings.js +122 -0
  67. package/lib/forge/state.d.ts +129 -0
  68. package/lib/forge/state.js +266 -0
  69. package/lib/forge/trust.d.ts +48 -0
  70. package/lib/forge/trust.js +107 -0
  71. package/lib/forge/turns.d.ts +13 -0
  72. package/lib/forge/turns.js +56 -0
  73. package/lib/hooks/broker/engine.d.ts +112 -0
  74. package/lib/hooks/broker/engine.js +722 -0
  75. package/lib/hooks/broker/helpers.d.ts +10 -0
  76. package/lib/hooks/broker/helpers.js +22 -0
  77. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  78. package/lib/hooks/broker/lifecycle.js +342 -0
  79. package/lib/hooks/broker/session-events.d.ts +27 -0
  80. package/lib/hooks/broker/session-events.js +205 -0
  81. package/lib/hooks/broker/tools.d.ts +52 -0
  82. package/lib/hooks/broker/tools.js +424 -0
  83. package/lib/hooks/broker/types.d.ts +264 -0
  84. package/lib/hooks/broker/types.js +1 -0
  85. package/lib/hooks/broker.d.ts +80 -0
  86. package/lib/hooks/broker.js +95 -0
  87. package/lib/hooks/codex-user.d.ts +5 -0
  88. package/lib/hooks/codex-user.js +109 -0
  89. package/lib/hooks/condition.d.ts +87 -0
  90. package/lib/hooks/condition.js +602 -0
  91. package/lib/hooks/config.d.ts +85 -0
  92. package/lib/hooks/config.js +154 -0
  93. package/lib/hooks/glob.d.ts +41 -0
  94. package/lib/hooks/glob.js +114 -0
  95. package/lib/hooks/matcher.d.ts +20 -0
  96. package/lib/hooks/matcher.js +39 -0
  97. package/lib/hooks/notice.d.ts +17 -0
  98. package/lib/hooks/notice.js +39 -0
  99. package/lib/hooks/output.d.ts +56 -0
  100. package/lib/hooks/output.js +214 -0
  101. package/lib/hooks/permissions.d.ts +19 -0
  102. package/lib/hooks/permissions.js +202 -0
  103. package/lib/hooks/powershell-aliases.d.ts +19 -0
  104. package/lib/hooks/powershell-aliases.js +58 -0
  105. package/lib/hooks/process.d.ts +64 -0
  106. package/lib/hooks/process.js +289 -0
  107. package/lib/hooks/row.d.ts +17 -0
  108. package/lib/hooks/row.js +96 -0
  109. package/lib/hooks/runner.d.ts +98 -0
  110. package/lib/hooks/runner.js +322 -0
  111. package/lib/hooks/shell-commands.d.ts +28 -0
  112. package/lib/hooks/shell-commands.js +241 -0
  113. package/lib/hooks/shell.d.ts +44 -0
  114. package/lib/hooks/shell.js +129 -0
  115. package/lib/hooks/transcript.d.ts +28 -0
  116. package/lib/hooks/transcript.js +141 -0
  117. package/lib/hooks/vocabulary.d.ts +57 -0
  118. package/lib/hooks/vocabulary.js +366 -0
  119. package/lib/index.d.ts +31 -0
  120. package/lib/index.js +287 -0
  121. package/lib/mcp/auth.d.ts +35 -0
  122. package/lib/mcp/auth.js +178 -0
  123. package/lib/mcp/catalog.d.ts +39 -0
  124. package/lib/mcp/catalog.js +69 -0
  125. package/lib/mcp/mount.d.ts +113 -0
  126. package/lib/mcp/mount.js +317 -0
  127. package/lib/mcp/policy.d.ts +42 -0
  128. package/lib/mcp/policy.js +43 -0
  129. package/lib/mcp/remote.d.ts +45 -0
  130. package/lib/mcp/remote.js +133 -0
  131. package/lib/mcp/row.d.ts +9 -0
  132. package/lib/mcp/row.js +225 -0
  133. package/lib/mods/bundler.d.ts +38 -0
  134. package/lib/mods/bundler.js +157 -0
  135. package/lib/mods/chain.d.ts +103 -0
  136. package/lib/mods/chain.js +436 -0
  137. package/lib/mods/claude.d.ts +27 -0
  138. package/lib/mods/claude.js +56 -0
  139. package/lib/mods/engine.d.ts +160 -0
  140. package/lib/mods/engine.js +701 -0
  141. package/lib/mods/expect.d.ts +8 -0
  142. package/lib/mods/expect.js +248 -0
  143. package/lib/mods/host.d.ts +105 -0
  144. package/lib/mods/host.js +462 -0
  145. package/lib/mods/loader.d.ts +53 -0
  146. package/lib/mods/loader.js +231 -0
  147. package/lib/mods/ops.d.ts +13 -0
  148. package/lib/mods/ops.js +117 -0
  149. package/lib/mods/row.d.ts +9 -0
  150. package/lib/mods/row.js +77 -0
  151. package/lib/mods/runtime.d.ts +60 -0
  152. package/lib/mods/runtime.js +133 -0
  153. package/lib/mods/service/commands.d.ts +17 -0
  154. package/lib/mods/service/commands.js +121 -0
  155. package/lib/mods/service/drawings.d.ts +36 -0
  156. package/lib/mods/service/drawings.js +64 -0
  157. package/lib/mods/service/sessions.d.ts +63 -0
  158. package/lib/mods/service/sessions.js +345 -0
  159. package/lib/mods/service/tools.d.ts +32 -0
  160. package/lib/mods/service/tools.js +253 -0
  161. package/lib/mods/service/turns.d.ts +33 -0
  162. package/lib/mods/service/turns.js +136 -0
  163. package/lib/mods/service/types.d.ts +151 -0
  164. package/lib/mods/service/types.js +1 -0
  165. package/lib/mods/service.d.ts +72 -0
  166. package/lib/mods/service.js +104 -0
  167. package/lib/mods/surfaces.d.ts +93 -0
  168. package/lib/mods/surfaces.js +309 -0
  169. package/lib/mods/values.d.ts +30 -0
  170. package/lib/mods/values.js +95 -0
  171. package/lib/opencode/bun.d.ts +40 -0
  172. package/lib/opencode/bun.js +168 -0
  173. package/lib/opencode/convert.d.ts +53 -0
  174. package/lib/opencode/convert.js +255 -0
  175. package/lib/opencode/row.d.ts +22 -0
  176. package/lib/opencode/row.js +104 -0
  177. package/lib/opencode/runtime/core.d.ts +74 -0
  178. package/lib/opencode/runtime/core.js +249 -0
  179. package/lib/opencode/runtime/events.d.ts +80 -0
  180. package/lib/opencode/runtime/events.js +281 -0
  181. package/lib/opencode/runtime/mount.d.ts +27 -0
  182. package/lib/opencode/runtime/mount.js +283 -0
  183. package/lib/opencode/runtime/server.d.ts +27 -0
  184. package/lib/opencode/runtime/server.js +354 -0
  185. package/lib/opencode/runtime/types.d.ts +109 -0
  186. package/lib/opencode/runtime/types.js +1 -0
  187. package/lib/opencode/runtime.d.ts +55 -0
  188. package/lib/opencode/runtime.js +79 -0
  189. package/lib/porting/adapter-paths.d.ts +13 -0
  190. package/lib/porting/adapter-paths.js +120 -0
  191. package/lib/porting/port-gap.d.ts +36 -0
  192. package/lib/porting/port-gap.js +158 -0
  193. package/lib/porting/port-sessions.d.ts +41 -0
  194. package/lib/porting/port-sessions.js +98 -0
  195. package/lib/porting/prompt.d.ts +23 -0
  196. package/lib/porting/prompt.js +51 -0
  197. package/lib/porting/row.d.ts +16 -0
  198. package/lib/porting/row.js +27 -0
  199. package/lib/porting/verify-port.d.ts +46 -0
  200. package/lib/porting/verify-port.js +82 -0
  201. package/lib/presets/fs-search.d.ts +25 -0
  202. package/lib/presets/fs-search.js +17 -0
  203. package/lib/presets/tool-filter.d.ts +35 -0
  204. package/lib/presets/tool-filter.js +91 -0
  205. package/lib/sessions/chat-import.d.ts +48 -0
  206. package/lib/sessions/chat-import.js +44 -0
  207. package/lib/sessions/claude.d.ts +35 -0
  208. package/lib/sessions/claude.js +104 -0
  209. package/lib/sessions/codex-discover.d.ts +34 -0
  210. package/lib/sessions/codex-discover.js +205 -0
  211. package/lib/sessions/codex-meta.d.ts +63 -0
  212. package/lib/sessions/codex-meta.js +148 -0
  213. package/lib/sessions/codex-text.d.ts +9 -0
  214. package/lib/sessions/codex-text.js +44 -0
  215. package/lib/sessions/codex.d.ts +42 -0
  216. package/lib/sessions/codex.js +270 -0
  217. package/lib/sessions/opencode.d.ts +38 -0
  218. package/lib/sessions/opencode.js +339 -0
  219. package/lib/sessions/persist.d.ts +162 -0
  220. package/lib/sessions/persist.js +377 -0
  221. package/lib/sessions/row.d.ts +15 -0
  222. package/lib/sessions/row.js +101 -0
  223. package/lib/sessions/turns.d.ts +31 -0
  224. package/lib/sessions/turns.js +63 -0
  225. package/lib/sessions/zstd.d.ts +15 -0
  226. package/lib/sessions/zstd.js +152 -0
  227. package/lib/shared/invocation.d.ts +169 -0
  228. package/lib/shared/invocation.js +325 -0
  229. package/lib/shared/render.d.ts +101 -0
  230. package/lib/shared/render.js +1353 -0
  231. package/lib/shared/util.d.ts +21 -0
  232. package/lib/shared/util.js +32 -0
  233. package/lib/skills/bundled.d.ts +3 -0
  234. package/lib/skills/bundled.js +42 -0
  235. package/lib/skills/provider.d.ts +74 -0
  236. package/lib/skills/provider.js +346 -0
  237. package/lib/skills/row.d.ts +22 -0
  238. package/lib/skills/row.js +204 -0
  239. package/lib/workbench/adapter-coverage.d.ts +65 -0
  240. package/lib/workbench/adapter-coverage.js +141 -0
  241. package/lib/workbench/model-tools.d.ts +10 -0
  242. package/lib/workbench/model-tools.js +122 -0
  243. package/lib/workbench/overview.d.ts +153 -0
  244. package/lib/workbench/overview.js +246 -0
  245. package/lib/workbench/remote.d.ts +161 -0
  246. package/lib/workbench/remote.js +561 -0
  247. package/lib/workbench/row.d.ts +15 -0
  248. package/lib/workbench/row.js +16 -0
  249. package/lib/workbench/settings.d.ts +19 -0
  250. package/lib/workbench/settings.js +60 -0
  251. package/lib/workbench/workbench.d.ts +130 -0
  252. package/lib/workbench/workbench.js +361 -0
  253. package/locale/agents/en.json +6 -0
  254. package/locale/agents/zh.json +6 -0
  255. package/locale/commands/en.json +6 -0
  256. package/locale/commands/zh.json +6 -0
  257. package/locale/context/en.json +6 -0
  258. package/locale/context/zh.json +6 -0
  259. package/locale/en.json +6 -0
  260. package/locale/hooks/en.json +6 -0
  261. package/locale/hooks/zh.json +6 -0
  262. package/locale/mcp/en.json +6 -0
  263. package/locale/mcp/zh.json +6 -0
  264. package/locale/mods/en.json +6 -0
  265. package/locale/mods/zh.json +6 -0
  266. package/locale/opencode/en.json +6 -0
  267. package/locale/opencode/zh.json +6 -0
  268. package/locale/porter/en.json +6 -0
  269. package/locale/porter/zh.json +6 -0
  270. package/locale/sessions/en.json +6 -0
  271. package/locale/sessions/zh.json +6 -0
  272. package/locale/skills/en.json +6 -0
  273. package/locale/skills/zh.json +6 -0
  274. package/locale/workbench/en.json +6 -0
  275. package/locale/workbench/zh.json +6 -0
  276. package/locale/zh.json +7 -0
  277. package/package.json +247 -3
  278. package/runtime/opencode-host.mjs +270 -0
  279. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,113 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { ForeignPlugin, McpComponent } from '@kirkchinese/harness-forge-core';
3
+ import type { McpAuthStore } from './auth.js';
4
+ import { RemoteMcp, type RemoteMcpState } from './remote.js';
5
+ /** One mounted MCP server. */
6
+ export interface McpMount {
7
+ readonly serverName: string;
8
+ /** Present for Streamable HTTP and SSE servers, which may need sign-in. */
9
+ readonly remote?: RemoteMcp;
10
+ /** True when the server is served through the capability catalog (`capability_call`, id `mcp:<server>/<tool>`). */
11
+ readonly catalog?: boolean;
12
+ readonly dispose: () => Promise<void>;
13
+ }
14
+ /** Resolve a program the way a spawned process would find it. */
15
+ export declare function findProgram(program: string, cwd: string, env?: NodeJS.ProcessEnv): string | undefined;
16
+ /** Raised when a foreign MCP transport has no implementation. */
17
+ export declare class UnsupportedMcpTransportError extends Error {
18
+ readonly transport: string;
19
+ readonly code = "unsupported-transport";
20
+ constructor(transport: string);
21
+ }
22
+ /** Variables a plugin's MCP configuration may reference. */
23
+ export interface McpVariables {
24
+ readonly pluginRoot: string;
25
+ readonly dataDir: string;
26
+ /** The `env` of imported harness settings: servers inherit it, `${VAR}` reads it. */
27
+ readonly env?: Readonly<Record<string, string>>;
28
+ /**
29
+ * Variables the foreign harness itself sets for its servers, read by
30
+ * `${VAR}` when neither the settings nor the environment set them; see
31
+ * {@link harnessVariables}.
32
+ */
33
+ readonly provided?: Readonly<Record<string, string>>;
34
+ }
35
+ /**
36
+ * The variables a harness provides to its plugins' MCP servers. Codex sets
37
+ * `CODEX_HOME` (its configuration directory) and, for plugin servers,
38
+ * `CODEX_MCP_NODE_PATH`, the Node.js it bundles (the openai-bundled plugins
39
+ * start their servers as `exec "$CODEX_MCP_NODE_PATH" ./server.mjs`). DSH
40
+ * provides the Node.js running it instead. They reach a server only through
41
+ * its configuration (`env_vars`, `env`, `${VAR}` in its command or arguments).
42
+ */
43
+ export declare function harnessVariables(plugin: Pick<ForeignPlugin, 'source'>): Readonly<Record<string, string>>;
44
+ /**
45
+ * The server name the foreign harness would use, before DSH length limits:
46
+ * Claude Code scopes a plugin's servers as `plugin_<plugin>_<server>` and
47
+ * keeps user, project and local servers under their own names.
48
+ */
49
+ export declare function foreignServerName(plugin: Pick<ForeignPlugin, 'source' | 'name'> & {
50
+ readonly manifest?: Readonly<Record<string, unknown>>;
51
+ }, server: string): string;
52
+ /** A user's or project's own assets rather than a plugin. */
53
+ export declare function isOwnAssets(plugin: {
54
+ readonly manifest?: Readonly<Record<string, unknown>>;
55
+ }): boolean;
56
+ /** Whose templates a plugin's commands and skills are: the person's own, a project's, or an installed plugin's. */
57
+ export declare function templateScope(plugin: {
58
+ readonly manifest?: Readonly<Record<string, unknown>>;
59
+ }): 'user' | 'project' | 'plugin';
60
+ /** The project directory of a project's assets, else undefined. */
61
+ export declare function projectRootOf(plugin: {
62
+ readonly manifest?: Readonly<Record<string, unknown>>;
63
+ }): string | undefined;
64
+ /**
65
+ * Expand `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, `${PLUGIN_ROOT}`,
66
+ * `${PLUGIN_DATA}`, `${VAR}` and `${VAR:-default}` the way Claude Code expands
67
+ * `.mcp.json`; then what the harness provides ({@link McpVariables.provided}).
68
+ * Unknown variables without a default expand to empty text; a stdio server
69
+ * whose command or arguments need one does not start (`missingVariables`).
70
+ * The value goes in as plain text, as in Claude Code: expanded into an
71
+ * explicit `sh -c '… ${VAR} …'` argument it becomes part of that script. The
72
+ * values are the plugin author's and the user's own environment, so this
73
+ * keeps the original harness's meaning instead of quoting them.
74
+ */
75
+ export declare function expandVariables(value: string, vars: McpVariables, env?: NodeJS.ProcessEnv): string;
76
+ /** Build the official mcp-client config for one component. */
77
+ export declare function mcpClientConfig(component: McpComponent, serverName: string, vars: McpVariables): Record<string, unknown>;
78
+ /** What a remote mount needs beyond the component. */
79
+ export interface RemoteMcpHost {
80
+ readonly auth: McpAuthStore;
81
+ onState(server: RemoteMcp, state: RemoteMcpState): void;
82
+ }
83
+ /**
84
+ * Whether `mountMcp` serves a server through the capability catalog: with the
85
+ * catalog composed, a stdio server is listed in its compact index and started
86
+ * on demand instead of putting every tool schema in every request. Remote
87
+ * servers keep the direct path, which adds OAuth; `options.catalog: false`
88
+ * (a session's own server) keeps it direct too.
89
+ */
90
+ export declare function servedByCatalog(ctx: object, component: McpComponent, options?: {
91
+ readonly catalog?: boolean;
92
+ }): boolean;
93
+ /**
94
+ * Mount one MCP server and wait until it is connected and its tools are
95
+ * registered, so the first model request already sees them. A stdio server
96
+ * whose program is missing, or a server that cannot connect, fails the mount
97
+ * with that reason. A remote server that requires sign-in stays mounted in
98
+ * that state.
99
+ */
100
+ export declare function mountMcp(ctx: Context, component: McpComponent, serverName: string, vars: McpVariables, remoteHost: RemoteMcpHost, options?: {
101
+ readonly catalog?: boolean;
102
+ }): Promise<McpMount>;
103
+ /**
104
+ * A DSH-safe server name (`[A-Za-z0-9_-]{1,32}`), stable for the same input.
105
+ * It never holds `__` nor starts or ends with `_`: a model-facing tool name
106
+ * `mcp__<server>__<tool>` then names one server only (with servers `app` and
107
+ * `app__reports`, `mcp__app__reports__x` would name either). A name that had
108
+ * `__` is collapsed to single `_` and keeps a hash of the original, so it
109
+ * stays apart from a server that was named that way to begin with.
110
+ */
111
+ export declare function mcpServerName(name: string): string;
112
+ /** The per-plugin data directory under a profile-local root. */
113
+ export declare function pluginDataDir(dataRoot: string, pluginId: string): string;
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Dynamic MCP bridge. A stdio server mounts one official `mcp-client`
3
+ * instance; Streamable HTTP and SSE servers connect through `remote.ts`,
4
+ * which adds OAuth sign-in. Server names follow the foreign harness so the model-facing
5
+ * tool names are the ones the plugin's hooks, agents and prompts already use:
6
+ * Claude Code plugin servers are `plugin_<plugin>_<server>`
7
+ * (`mcp__plugin_<plugin>_<server>__<tool>`), Codex and portable servers keep
8
+ * their own name.
9
+ * @module @kirkchinese/harness-forge
10
+ */
11
+ import { existsSync, statSync } from 'node:fs';
12
+ import { delimiter, join, resolve } from 'node:path';
13
+ import { codexHome, contentPath, LEADS_TO_SHARE, shortHash, stripAround } from '@kirkchinese/harness-forge-core';
14
+ import { RemoteMcp } from './remote.js';
15
+ import { composedCatalog, mountInCatalog } from './catalog.js';
16
+ import { DEFAULT_TOOL_CALL_TIMEOUT_MS } from './policy.js';
17
+ /** Resolve a program the way a spawned process would find it. */
18
+ export function findProgram(program, cwd, env = process.env) {
19
+ const extensions = process.platform === 'win32'
20
+ ? ['', ...(env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(extension => extension.length > 0)]
21
+ : [''];
22
+ // A program path the configuration names is checked against the folder it runs in (see `contentPath`).
23
+ const named = /[\\/]/u.test(program) ? contentPath(program, cwd) : undefined;
24
+ if (/[\\/]/u.test(program) && named === undefined)
25
+ return undefined;
26
+ const candidates = named !== undefined
27
+ ? [named]
28
+ : (env['PATH'] ?? env['Path'] ?? '').split(delimiter).filter(entry => entry.length > 0).map(entry => join(entry, program));
29
+ for (const candidate of candidates) {
30
+ for (const extension of extensions) {
31
+ const path = `${candidate}${extension}`;
32
+ if (existsSync(path) && statSync(path).isFile())
33
+ return path;
34
+ }
35
+ }
36
+ return undefined;
37
+ }
38
+ /** Raised when a foreign MCP transport has no implementation. */
39
+ export class UnsupportedMcpTransportError extends Error {
40
+ transport;
41
+ code = 'unsupported-transport';
42
+ constructor(transport) {
43
+ super(`MCP transport "${transport}" is not supported`);
44
+ this.transport = transport;
45
+ this.name = 'UnsupportedMcpTransportError';
46
+ }
47
+ }
48
+ /** How long a server may take to connect and list its tools when its configuration does not say. */
49
+ const READY_TIMEOUT_MS = 120_000;
50
+ /**
51
+ * The variables a harness provides to its plugins' MCP servers. Codex sets
52
+ * `CODEX_HOME` (its configuration directory) and, for plugin servers,
53
+ * `CODEX_MCP_NODE_PATH`, the Node.js it bundles (the openai-bundled plugins
54
+ * start their servers as `exec "$CODEX_MCP_NODE_PATH" ./server.mjs`). DSH
55
+ * provides the Node.js running it instead. They reach a server only through
56
+ * its configuration (`env_vars`, `env`, `${VAR}` in its command or arguments).
57
+ */
58
+ export function harnessVariables(plugin) {
59
+ return plugin.source === 'codex' ? { CODEX_HOME: codexHome(), CODEX_MCP_NODE_PATH: process.execPath } : {};
60
+ }
61
+ /**
62
+ * The server name the foreign harness would use, before DSH length limits:
63
+ * Claude Code scopes a plugin's servers as `plugin_<plugin>_<server>` and
64
+ * keeps user, project and local servers under their own names.
65
+ */
66
+ export function foreignServerName(plugin, server) {
67
+ if (plugin.source !== 'claude-code' || isOwnAssets(plugin))
68
+ return server;
69
+ return `plugin_${plugin.name}_${server}`;
70
+ }
71
+ /** A user's or project's own assets rather than a plugin. */
72
+ export function isOwnAssets(plugin) {
73
+ const scope = plugin.manifest?.['scope'];
74
+ return scope === 'user' || scope === 'project';
75
+ }
76
+ /** Whose templates a plugin's commands and skills are: the person's own, a project's, or an installed plugin's. */
77
+ export function templateScope(plugin) {
78
+ const scope = plugin.manifest?.['scope'];
79
+ return scope === 'user' || scope === 'project' ? scope : 'plugin';
80
+ }
81
+ /** The project directory of a project's assets, else undefined. */
82
+ export function projectRootOf(plugin) {
83
+ const root = plugin.manifest?.['projectRoot'];
84
+ return plugin.manifest?.['scope'] === 'project' && typeof root === 'string' ? root : undefined;
85
+ }
86
+ /**
87
+ * Expand `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, `${PLUGIN_ROOT}`,
88
+ * `${PLUGIN_DATA}`, `${VAR}` and `${VAR:-default}` the way Claude Code expands
89
+ * `.mcp.json`; then what the harness provides ({@link McpVariables.provided}).
90
+ * Unknown variables without a default expand to empty text; a stdio server
91
+ * whose command or arguments need one does not start (`missingVariables`).
92
+ * The value goes in as plain text, as in Claude Code: expanded into an
93
+ * explicit `sh -c '… ${VAR} …'` argument it becomes part of that script. The
94
+ * values are the plugin author's and the user's own environment, so this
95
+ * keeps the original harness's meaning instead of quoting them.
96
+ */
97
+ export function expandVariables(value, vars, env = process.env) {
98
+ const expand = (name, fallback) => {
99
+ if (name === 'CLAUDE_PLUGIN_ROOT' || name === 'PLUGIN_ROOT')
100
+ return vars.pluginRoot;
101
+ if (name === 'CLAUDE_PLUGIN_DATA' || name === 'PLUGIN_DATA')
102
+ return vars.dataDir;
103
+ const resolved = [vars.env?.[name], env[name], vars.provided?.[name]].find(value => value !== undefined && value.length > 0);
104
+ return resolved ?? fallback ?? '';
105
+ };
106
+ // A scan: `/\$\{(NAME)(?::-([^}]*))?\}/g` reads to the end from every unclosed `${NAME:-`, quadratic.
107
+ let out = '';
108
+ let index = 0;
109
+ let close = -1;
110
+ for (;;) {
111
+ const start = value.indexOf('${', index);
112
+ if (close < start + 2)
113
+ close = value.indexOf('}', start + 2);
114
+ if (start === -1 || close === -1)
115
+ return out + value.slice(index);
116
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)(?::-(.*))?$/su.exec(value.slice(start + 2, close));
117
+ if (match === null) {
118
+ out += value.slice(index, start + 2);
119
+ index = start + 2;
120
+ continue;
121
+ }
122
+ out += value.slice(index, start) + expand(match[1] ?? '', match[2]);
123
+ index = close + 1;
124
+ }
125
+ }
126
+ /** Build the official mcp-client config for one component. */
127
+ export function mcpClientConfig(component, serverName, vars) {
128
+ const expand = (value) => expandVariables(value, vars);
129
+ const expandRecord = (record) => Object.fromEntries(Object.entries(record ?? {}).map(([key, value]) => [key, expand(value)]));
130
+ if (component.transport === 'stdio') {
131
+ if (component.command === undefined)
132
+ throw new Error(`MCP server "${component.name}" has no command`);
133
+ const env = expandRecord(component.env);
134
+ const missing = missingVariables(component, env, vars);
135
+ if (missing.length > 0) {
136
+ throw new Error(`MCP server "${component.name}" needs ${missing.join(', ')}, which DSH does not provide; set ${missing.length > 1 ? 'them' : 'it'} in the environment DSH starts in`);
137
+ }
138
+ const command = resolveCommand(expand(component.command), vars.pluginRoot);
139
+ return {
140
+ serverName,
141
+ transport: 'stdio',
142
+ command,
143
+ args: (component.args ?? []).map(expand),
144
+ env: {
145
+ ...vars.env,
146
+ ...env,
147
+ CLAUDE_PLUGIN_ROOT: vars.pluginRoot,
148
+ CLAUDE_PLUGIN_DATA: vars.dataDir,
149
+ PLUGIN_ROOT: vars.pluginRoot,
150
+ PLUGIN_DATA: vars.dataDir,
151
+ },
152
+ cwd: component.cwd === undefined ? vars.pluginRoot : workingDirectory(component, expand(component.cwd), vars.pluginRoot),
153
+ failOnStartupError: true,
154
+ toolCallTimeoutMs: component.toolTimeoutMs ?? DEFAULT_TOOL_CALL_TIMEOUT_MS,
155
+ ...(component.startupTimeoutMs !== undefined ? { startupTimeoutMs: component.startupTimeoutMs } : {}),
156
+ };
157
+ }
158
+ if (component.transport === 'streamable-http') {
159
+ if (component.url === undefined)
160
+ throw new Error(`MCP server "${component.name}" has no url`);
161
+ return {
162
+ serverName,
163
+ transport: 'streamable-http',
164
+ url: expand(component.url),
165
+ headers: expandRecord(component.headers),
166
+ failOnStartupError: true,
167
+ toolCallTimeoutMs: component.toolTimeoutMs ?? DEFAULT_TOOL_CALL_TIMEOUT_MS,
168
+ ...(component.startupTimeoutMs !== undefined ? { startupTimeoutMs: component.startupTimeoutMs } : {}),
169
+ };
170
+ }
171
+ throw new UnsupportedMcpTransportError(component.transport);
172
+ }
173
+ /**
174
+ * The variables a stdio server's command or arguments reference that would
175
+ * be empty: a `${VAR}` without a default that nothing sets, and a shell
176
+ * `$VAR` the server's `env` passes through (`env_vars`) but nothing sets.
177
+ * Started anyway, such a server runs an empty program
178
+ * (`exec "$CODEX_MCP_NODE_PATH"` fails with `exec: : Permission denied`).
179
+ * A shell variable the server does not declare may be the script's own, so
180
+ * it is left alone.
181
+ */
182
+ function missingVariables(component, env, vars) {
183
+ const missing = new Set();
184
+ const declared = component.env ?? {};
185
+ for (const text of [component.command ?? '', ...(component.args ?? [])]) {
186
+ for (const match of text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu)) {
187
+ const name = match[1] ?? '';
188
+ if (expandVariables(match[0], vars) === '')
189
+ missing.add(name);
190
+ }
191
+ for (const match of text.matchAll(/\$([A-Za-z_][A-Za-z0-9_]*)/gu)) {
192
+ const name = match[1] ?? '';
193
+ const passed = declared[name];
194
+ if (passed !== undefined && /^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/u.test(passed) && env[name] === '')
195
+ missing.add(name);
196
+ }
197
+ }
198
+ return [...missing];
199
+ }
200
+ /**
201
+ * Whether `mountMcp` serves a server through the capability catalog: with the
202
+ * catalog composed, a stdio server is listed in its compact index and started
203
+ * on demand instead of putting every tool schema in every request. Remote
204
+ * servers keep the direct path, which adds OAuth; `options.catalog: false`
205
+ * (a session's own server) keeps it direct too.
206
+ */
207
+ export function servedByCatalog(ctx, component, options = {}) {
208
+ return options.catalog !== false && component.transport === 'stdio' && composedCatalog(ctx) !== undefined;
209
+ }
210
+ /**
211
+ * Mount one MCP server and wait until it is connected and its tools are
212
+ * registered, so the first model request already sees them. A stdio server
213
+ * whose program is missing, or a server that cannot connect, fails the mount
214
+ * with that reason. A remote server that requires sign-in stays mounted in
215
+ * that state.
216
+ */
217
+ export async function mountMcp(ctx, component, serverName, vars, remoteHost, options = {}) {
218
+ const catalog = servedByCatalog(ctx, component, options) ? composedCatalog(ctx) : undefined;
219
+ if (catalog !== undefined) {
220
+ const config = mcpClientConfig(component, serverName, vars);
221
+ const program = String(config['command']);
222
+ const resolved = findProgram(program, String(config['cwd']));
223
+ if (resolved === undefined) {
224
+ throw new Error(`MCP server "${component.name}" needs the program "${program}", which is not installed or not on PATH`);
225
+ }
226
+ return { serverName, catalog: true, dispose: await mountInCatalog(ctx, catalog, component, serverName, config, program, resolved, component.startupTimeoutMs ?? READY_TIMEOUT_MS) };
227
+ }
228
+ if (component.transport === 'streamable-http' || component.transport === 'sse') {
229
+ if (component.url === undefined)
230
+ throw new Error(`MCP server "${component.name}" has no url`);
231
+ const expand = (value) => expandVariables(value, vars);
232
+ const server = new RemoteMcp(ctx, {
233
+ ...component,
234
+ url: expand(component.url),
235
+ headers: Object.fromEntries(Object.entries(component.headers ?? {}).map(([key, value]) => [key, expand(value)])),
236
+ }, serverName, remoteHost.auth, state => remoteHost.onState(server, state));
237
+ const state = await server.start();
238
+ if (state.kind === 'failed') {
239
+ await server.dispose();
240
+ throw new Error(`MCP server "${component.name}" failed to connect: ${state.error}`);
241
+ }
242
+ return { serverName, remote: server, dispose: () => server.dispose() };
243
+ }
244
+ const config = mcpClientConfig(component, serverName, vars);
245
+ const program = String(config['command']);
246
+ if (findProgram(program, String(config['cwd'])) === undefined) {
247
+ throw new Error(`MCP server "${component.name}" needs the program "${program}", which is not installed or not on PATH`);
248
+ }
249
+ const module = await import('@deepseek-ai/dsh-mcp-client');
250
+ const fiber = ctx.plugin(module, config);
251
+ try {
252
+ const readyMs = component.startupTimeoutMs ?? READY_TIMEOUT_MS;
253
+ await withTimeout(fiber, readyMs, `MCP server "${component.name}" did not become ready within ${readyMs / 1000}s`);
254
+ }
255
+ catch (error) {
256
+ await fiber.dispose();
257
+ throw new Error(`MCP server "${component.name}" failed to start: ${rootCause(error)}`);
258
+ }
259
+ return { serverName, dispose: async () => { await fiber.dispose(); } };
260
+ }
261
+ /** The longest server name DSH's MCP client accepts. */
262
+ const MAX_SERVER_NAME_LENGTH = 32;
263
+ /** Hex characters of the hash that keeps a shortened or collapsed server name apart from the others. */
264
+ const SERVER_NAME_HASH_LENGTH = 8;
265
+ /** Characters kept before that hash: the name, `_` and the hash fit {@link MAX_SERVER_NAME_LENGTH}. */
266
+ const SERVER_NAME_KEPT_LENGTH = MAX_SERVER_NAME_LENGTH - SERVER_NAME_HASH_LENGTH - 1;
267
+ /**
268
+ * A DSH-safe server name (`[A-Za-z0-9_-]{1,32}`), stable for the same input.
269
+ * It never holds `__` nor starts or ends with `_`: a model-facing tool name
270
+ * `mcp__<server>__<tool>` then names one server only (with servers `app` and
271
+ * `app__reports`, `mcp__app__reports__x` would name either). A name that had
272
+ * `__` is collapsed to single `_` and keeps a hash of the original, so it
273
+ * stays apart from a server that was named that way to begin with.
274
+ */
275
+ export function mcpServerName(name) {
276
+ const base = stripAround(name.replace(/[^A-Za-z0-9_-]+/gu, '_'), '_');
277
+ const collapsed = base.replace(/_{2,}/gu, '_');
278
+ if (collapsed === base && base.length > 0 && base.length <= MAX_SERVER_NAME_LENGTH)
279
+ return base;
280
+ const kept = collapsed.slice(0, SERVER_NAME_KEPT_LENGTH).replace(/[_-]+$/u, '');
281
+ return `${kept.length > 0 ? kept : 'mcp'}_${shortHash(base.length > 0 ? base : name, SERVER_NAME_HASH_LENGTH)}`;
282
+ }
283
+ /** The per-plugin data directory under a profile-local root. */
284
+ export function pluginDataDir(dataRoot, pluginId) {
285
+ return join(dataRoot, pluginId.replace(/[^A-Za-z0-9._-]+/gu, '-'));
286
+ }
287
+ function resolveCommand(command, root) {
288
+ if (command.startsWith('./') || command.startsWith('.\\'))
289
+ return resolve(root, command);
290
+ return command;
291
+ }
292
+ /** A server's configured working directory, resolved against its plugin; one on a network share the plugin is not on is refused. */
293
+ function workingDirectory(component, path, root) {
294
+ const resolved = contentPath(path, root);
295
+ if (resolved === undefined)
296
+ throw new Error(`MCP server "${component.name}" would run in ${path}, which ${LEADS_TO_SHARE}; Harness Forge does not start servers there`);
297
+ return resolved;
298
+ }
299
+ function rootCause(error) {
300
+ let current = error;
301
+ let message = error instanceof Error ? error.message : String(error);
302
+ while (current instanceof Error && current.cause !== undefined) {
303
+ current = current.cause;
304
+ if (current instanceof Error)
305
+ message = current.message;
306
+ }
307
+ return message;
308
+ }
309
+ function withTimeout(promise, ms, message) {
310
+ return Promise.race([
311
+ promise,
312
+ new Promise((_resolve, reject) => {
313
+ const timer = setTimeout(() => reject(new Error(message)), ms);
314
+ timer.unref?.();
315
+ }),
316
+ ]);
317
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A server's own tool policy, from its configuration (Codex's
3
+ * `enabled_tools`, `disabled_tools`, `default_tools_approval_mode` and
4
+ * `tools.<tool>.approval_mode`): which of its tools may run and which ask the
5
+ * user first. `@deepseek-ai/dsh-mcp-client` registers every tool a server
6
+ * lists, so the MCP row enforces this when a call is made; the capability
7
+ * catalog and remote servers also leave filtered tools out of the list.
8
+ * @module @kirkchinese/harness-forge
9
+ */
10
+ import type { McpComponent } from '@kirkchinese/harness-forge-core';
11
+ /**
12
+ * How long one MCP tool call may run when the server's configuration does not
13
+ * say (Codex `tool_timeout_sec`): long-running tools (builds, test runs) are
14
+ * common, and the call can be cancelled like any other. Direct, catalog and
15
+ * remote mounts all use it.
16
+ */
17
+ export declare const DEFAULT_TOOL_CALL_TIMEOUT_MS = 600000;
18
+ /** Same public naming contract as dsh-mcp-client: `mcp__<server>__<tool>`, normalized with a hash when needed. */
19
+ export declare function publicToolName(serverName: string, rawName: string): string;
20
+ /** A mounted server's tool policy. */
21
+ export interface McpToolPolicy {
22
+ /** Whether the raw tool may run at all. */
23
+ runs(rawName: string): boolean;
24
+ /**
25
+ * The raw name of a configured tool of this server, from the public name
26
+ * `dsh-mcp-client` registers it under ({@link publicToolName}); undefined
27
+ * for a tool the configuration does not name.
28
+ */
29
+ rawName(publicName: string): string | undefined;
30
+ /**
31
+ * The decision for a call to one of this server's tools by its raw name
32
+ * (undefined for a tool the configuration does not name): `deny` for a
33
+ * filtered tool, `ask` for one that asks first, else undefined.
34
+ * @param shownName - the tool as the reason names it.
35
+ */
36
+ decide(rawName: string | undefined, shownName: string): {
37
+ readonly kind: 'deny' | 'ask';
38
+ readonly reason: string;
39
+ } | undefined;
40
+ }
41
+ /** The policy of one server, or undefined when its configuration sets none. */
42
+ export declare function mcpToolPolicy(component: McpComponent, serverName: string): McpToolPolicy | undefined;
@@ -0,0 +1,43 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** The longest public tool name, as `dsh-mcp-client` names tools. */
3
+ const MAX_PUBLIC_NAME_LENGTH = 64;
4
+ /** Hex characters of the hash a normalized public tool name ends with, as `dsh-mcp-client` names tools. */
5
+ const HASH_LENGTH = 12;
6
+ /**
7
+ * How long one MCP tool call may run when the server's configuration does not
8
+ * say (Codex `tool_timeout_sec`): long-running tools (builds, test runs) are
9
+ * common, and the call can be cancelled like any other. Direct, catalog and
10
+ * remote mounts all use it.
11
+ */
12
+ export const DEFAULT_TOOL_CALL_TIMEOUT_MS = 600_000;
13
+ /** Same public naming contract as dsh-mcp-client: `mcp__<server>__<tool>`, normalized with a hash when needed. */
14
+ export function publicToolName(serverName, rawName) {
15
+ const joined = `mcp__${serverName}__${rawName}`;
16
+ const normalized = joined.replace(/[^A-Za-z0-9_-]/gu, '_');
17
+ if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH)
18
+ return normalized;
19
+ const hash = createHash('sha256').update(`${serverName}\0${rawName}`).digest('hex').slice(0, HASH_LENGTH);
20
+ return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
21
+ }
22
+ /** The policy of one server, or undefined when its configuration sets none. */
23
+ export function mcpToolPolicy(component, serverName) {
24
+ const { enabledTools, disabledTools = [], toolApproval } = component;
25
+ if (enabledTools === undefined && disabledTools.length === 0 && toolApproval === undefined)
26
+ return undefined;
27
+ const runs = (rawName) => (enabledTools === undefined || enabledTools.includes(rawName)) && !disabledTools.includes(rawName);
28
+ const configured = new Set([...enabledTools ?? [], ...disabledTools, ...Object.keys(toolApproval?.tools ?? {})]);
29
+ const byPublicName = new Map([...configured].map(tool => [publicToolName(serverName, tool), tool]));
30
+ return {
31
+ runs,
32
+ rawName: publicName => byPublicName.get(publicName),
33
+ decide(raw, toolName) {
34
+ // A tool the configuration does not name is some other tool of the server: an allowlist refuses it.
35
+ if (raw === undefined ? enabledTools !== undefined : !runs(raw)) {
36
+ return { kind: 'deny', reason: `${toolName} is switched off by the configuration of MCP server "${component.name}" (enabled_tools / disabled_tools).` };
37
+ }
38
+ const own = raw !== undefined && toolApproval !== undefined && Object.hasOwn(toolApproval.tools, raw) ? toolApproval.tools[raw] : undefined;
39
+ const asks = own ?? toolApproval?.askByDefault === true;
40
+ return asks ? { kind: 'ask', reason: `MCP server "${component.name}" asks before running ${toolName} (approval_mode = "prompt").` } : undefined;
41
+ },
42
+ };
43
+ }
@@ -0,0 +1,45 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { McpComponent } from '@kirkchinese/harness-forge-core';
3
+ import type { McpAuthStore } from './auth.js';
4
+ /** Connection state reported to the service. */
5
+ export type RemoteMcpState = {
6
+ readonly kind: 'connected';
7
+ readonly tools: readonly string[];
8
+ } | {
9
+ readonly kind: 'sign-in-required';
10
+ readonly url: string;
11
+ } | {
12
+ readonly kind: 'failed';
13
+ readonly error: string;
14
+ };
15
+ /** One live remote server. */
16
+ export declare class RemoteMcp {
17
+ private readonly ctx;
18
+ private readonly component;
19
+ readonly serverName: string;
20
+ private readonly auth;
21
+ private readonly onState;
22
+ private client;
23
+ private transport;
24
+ private toolCtx;
25
+ private fiber;
26
+ private registrations;
27
+ private authorizationUrl;
28
+ private state;
29
+ private closed;
30
+ constructor(ctx: Context, component: McpComponent & {
31
+ readonly url: string;
32
+ }, serverName: string, auth: McpAuthStore, onState: (state: RemoteMcpState) => void);
33
+ /** Connect and register tools; resolves with the resulting state. */
34
+ start(): Promise<RemoteMcpState>;
35
+ /** Open the sign-in page, finish the OAuth exchange, then connect. */
36
+ signIn(): Promise<RemoteMcpState>;
37
+ get current(): RemoteMcpState;
38
+ /** Whether the server was disposed: it waits for nothing any more. */
39
+ get disposed(): boolean;
40
+ dispose(): Promise<void>;
41
+ private connect;
42
+ private register;
43
+ private unregister;
44
+ private settle;
45
+ }