@kirkchinese/harness-forge 0.0.0-stage → 0.4.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.
- package/LICENSE +21 -0
- package/README.md +42 -2
- package/assets/icon.svg +12 -0
- package/cordis.patch.yml +28 -0
- package/lib/agents/presets.d.ts +91 -0
- package/lib/agents/presets.js +282 -0
- package/lib/agents/profiles.d.ts +58 -0
- package/lib/agents/profiles.js +278 -0
- package/lib/agents/row.d.ts +17 -0
- package/lib/agents/row.js +146 -0
- package/lib/client/styles.d.ts +8 -0
- package/lib/client/styles.js +89 -0
- package/lib/client/typert.d.ts +14 -0
- package/lib/client/typert.js +110 -0
- package/lib/client.js +22500 -0
- package/lib/commands/definition.d.ts +40 -0
- package/lib/commands/definition.js +113 -0
- package/lib/commands/output-styles.d.ts +42 -0
- package/lib/commands/output-styles.js +152 -0
- package/lib/commands/row.d.ts +9 -0
- package/lib/commands/row.js +157 -0
- package/lib/context/instructions.d.ts +32 -0
- package/lib/context/instructions.js +88 -0
- package/lib/context/row.d.ts +16 -0
- package/lib/context/row.js +17 -0
- package/lib/dsh/commands.d.ts +30 -0
- package/lib/dsh/commands.js +61 -0
- package/lib/dsh/host.d.ts +107 -0
- package/lib/dsh/host.js +214 -0
- package/lib/dsh/model-route.d.ts +21 -0
- package/lib/dsh/model-route.js +37 -0
- package/lib/dsh/session-records.d.ts +78 -0
- package/lib/dsh/session-records.js +36 -0
- package/lib/dsh/subagents.d.ts +46 -0
- package/lib/dsh/subagents.js +14 -0
- package/lib/forge/contract.d.ts +231 -0
- package/lib/forge/contract.js +43 -0
- package/lib/forge/ledger.d.ts +143 -0
- package/lib/forge/ledger.js +733 -0
- package/lib/forge/live-mounts.d.ts +45 -0
- package/lib/forge/live-mounts.js +78 -0
- package/lib/forge/marketplace-install.d.ts +3 -0
- package/lib/forge/marketplace-install.js +64 -0
- package/lib/forge/npm.d.ts +31 -0
- package/lib/forge/npm.js +60 -0
- package/lib/forge/projects.d.ts +94 -0
- package/lib/forge/projects.js +336 -0
- package/lib/forge/receipts.d.ts +5 -0
- package/lib/forge/receipts.js +31 -0
- package/lib/forge/row.d.ts +32 -0
- package/lib/forge/row.js +59 -0
- package/lib/forge/service.d.ts +105 -0
- package/lib/forge/service.js +274 -0
- package/lib/forge/settings.d.ts +41 -0
- package/lib/forge/settings.js +115 -0
- package/lib/forge/state.d.ts +69 -0
- package/lib/forge/state.js +150 -0
- package/lib/forge/trust.d.ts +48 -0
- package/lib/forge/trust.js +107 -0
- package/lib/forge/turns.d.ts +13 -0
- package/lib/forge/turns.js +56 -0
- package/lib/hooks/broker/engine.d.ts +112 -0
- package/lib/hooks/broker/engine.js +728 -0
- package/lib/hooks/broker/helpers.d.ts +10 -0
- package/lib/hooks/broker/helpers.js +22 -0
- package/lib/hooks/broker/lifecycle.d.ts +65 -0
- package/lib/hooks/broker/lifecycle.js +342 -0
- package/lib/hooks/broker/session-events.d.ts +22 -0
- package/lib/hooks/broker/session-events.js +196 -0
- package/lib/hooks/broker/tools.d.ts +52 -0
- package/lib/hooks/broker/tools.js +424 -0
- package/lib/hooks/broker/types.d.ts +262 -0
- package/lib/hooks/broker/types.js +1 -0
- package/lib/hooks/broker.d.ts +80 -0
- package/lib/hooks/broker.js +95 -0
- package/lib/hooks/codex-user.d.ts +5 -0
- package/lib/hooks/codex-user.js +109 -0
- package/lib/hooks/condition.d.ts +11 -0
- package/lib/hooks/condition.js +181 -0
- package/lib/hooks/config.d.ts +85 -0
- package/lib/hooks/config.js +150 -0
- package/lib/hooks/matcher.d.ts +20 -0
- package/lib/hooks/matcher.js +39 -0
- package/lib/hooks/notice.d.ts +17 -0
- package/lib/hooks/notice.js +39 -0
- package/lib/hooks/output.d.ts +56 -0
- package/lib/hooks/output.js +214 -0
- package/lib/hooks/permissions.d.ts +14 -0
- package/lib/hooks/permissions.js +109 -0
- package/lib/hooks/process.d.ts +47 -0
- package/lib/hooks/process.js +134 -0
- package/lib/hooks/row.d.ts +17 -0
- package/lib/hooks/row.js +94 -0
- package/lib/hooks/runner.d.ts +85 -0
- package/lib/hooks/runner.js +293 -0
- package/lib/hooks/shell-commands.d.ts +19 -0
- package/lib/hooks/shell-commands.js +177 -0
- package/lib/hooks/shell.d.ts +43 -0
- package/lib/hooks/shell.js +126 -0
- package/lib/hooks/transcript.d.ts +28 -0
- package/lib/hooks/transcript.js +141 -0
- package/lib/hooks/vocabulary.d.ts +57 -0
- package/lib/hooks/vocabulary.js +364 -0
- package/lib/index.d.ts +31 -0
- package/lib/index.js +287 -0
- package/lib/mcp/auth.d.ts +35 -0
- package/lib/mcp/auth.js +178 -0
- package/lib/mcp/catalog.d.ts +36 -0
- package/lib/mcp/catalog.js +61 -0
- package/lib/mcp/mount.d.ts +75 -0
- package/lib/mcp/mount.js +217 -0
- package/lib/mcp/remote.d.ts +45 -0
- package/lib/mcp/remote.js +143 -0
- package/lib/mcp/row.d.ts +9 -0
- package/lib/mcp/row.js +131 -0
- package/lib/mods/bundler.d.ts +38 -0
- package/lib/mods/bundler.js +157 -0
- package/lib/mods/chain.d.ts +103 -0
- package/lib/mods/chain.js +436 -0
- package/lib/mods/claude.d.ts +27 -0
- package/lib/mods/claude.js +56 -0
- package/lib/mods/engine.d.ts +160 -0
- package/lib/mods/engine.js +701 -0
- package/lib/mods/expect.d.ts +8 -0
- package/lib/mods/expect.js +248 -0
- package/lib/mods/host.d.ts +105 -0
- package/lib/mods/host.js +462 -0
- package/lib/mods/loader.d.ts +53 -0
- package/lib/mods/loader.js +227 -0
- package/lib/mods/ops.d.ts +13 -0
- package/lib/mods/ops.js +117 -0
- package/lib/mods/row.d.ts +9 -0
- package/lib/mods/row.js +77 -0
- package/lib/mods/runtime.d.ts +60 -0
- package/lib/mods/runtime.js +133 -0
- package/lib/mods/service/commands.d.ts +17 -0
- package/lib/mods/service/commands.js +121 -0
- package/lib/mods/service/drawings.d.ts +36 -0
- package/lib/mods/service/drawings.js +64 -0
- package/lib/mods/service/sessions.d.ts +63 -0
- package/lib/mods/service/sessions.js +345 -0
- package/lib/mods/service/tools.d.ts +32 -0
- package/lib/mods/service/tools.js +253 -0
- package/lib/mods/service/turns.d.ts +32 -0
- package/lib/mods/service/turns.js +161 -0
- package/lib/mods/service/types.d.ts +151 -0
- package/lib/mods/service/types.js +1 -0
- package/lib/mods/service.d.ts +72 -0
- package/lib/mods/service.js +104 -0
- package/lib/mods/surfaces.d.ts +93 -0
- package/lib/mods/surfaces.js +309 -0
- package/lib/mods/values.d.ts +30 -0
- package/lib/mods/values.js +95 -0
- package/lib/opencode/bun.d.ts +40 -0
- package/lib/opencode/bun.js +156 -0
- package/lib/opencode/convert.d.ts +53 -0
- package/lib/opencode/convert.js +255 -0
- package/lib/opencode/row.d.ts +9 -0
- package/lib/opencode/row.js +86 -0
- package/lib/opencode/runtime/core.d.ts +74 -0
- package/lib/opencode/runtime/core.js +249 -0
- package/lib/opencode/runtime/events.d.ts +80 -0
- package/lib/opencode/runtime/events.js +281 -0
- package/lib/opencode/runtime/mount.d.ts +27 -0
- package/lib/opencode/runtime/mount.js +283 -0
- package/lib/opencode/runtime/server.d.ts +27 -0
- package/lib/opencode/runtime/server.js +353 -0
- package/lib/opencode/runtime/types.d.ts +109 -0
- package/lib/opencode/runtime/types.js +1 -0
- package/lib/opencode/runtime.d.ts +55 -0
- package/lib/opencode/runtime.js +79 -0
- package/lib/porting/port-gap.d.ts +30 -0
- package/lib/porting/port-gap.js +122 -0
- package/lib/porting/port-sessions.d.ts +41 -0
- package/lib/porting/port-sessions.js +98 -0
- package/lib/porting/prompt.d.ts +23 -0
- package/lib/porting/prompt.js +49 -0
- package/lib/porting/row.d.ts +16 -0
- package/lib/porting/row.js +25 -0
- package/lib/porting/verify-port.d.ts +53 -0
- package/lib/porting/verify-port.js +104 -0
- package/lib/presets/fs-search.d.ts +25 -0
- package/lib/presets/fs-search.js +17 -0
- package/lib/presets/tool-filter.d.ts +35 -0
- package/lib/presets/tool-filter.js +91 -0
- package/lib/sessions/claude.d.ts +29 -0
- package/lib/sessions/claude.js +83 -0
- package/lib/sessions/codex.d.ts +30 -0
- package/lib/sessions/codex.js +303 -0
- package/lib/sessions/opencode.d.ts +32 -0
- package/lib/sessions/opencode.js +320 -0
- package/lib/sessions/row.d.ts +14 -0
- package/lib/sessions/row.js +35 -0
- package/lib/shared/invocation.d.ts +169 -0
- package/lib/shared/invocation.js +325 -0
- package/lib/shared/render.d.ts +72 -0
- package/lib/shared/render.js +588 -0
- package/lib/shared/util.d.ts +21 -0
- package/lib/shared/util.js +32 -0
- package/lib/skills/bundled.d.ts +3 -0
- package/lib/skills/bundled.js +42 -0
- package/lib/skills/provider.d.ts +72 -0
- package/lib/skills/provider.js +340 -0
- package/lib/skills/row.d.ts +22 -0
- package/lib/skills/row.js +204 -0
- package/lib/workbench/adapter-coverage.d.ts +47 -0
- package/lib/workbench/adapter-coverage.js +102 -0
- package/lib/workbench/model-tools.d.ts +10 -0
- package/lib/workbench/model-tools.js +122 -0
- package/lib/workbench/overview.d.ts +103 -0
- package/lib/workbench/overview.js +159 -0
- package/lib/workbench/remote.d.ts +118 -0
- package/lib/workbench/remote.js +422 -0
- package/lib/workbench/row.d.ts +15 -0
- package/lib/workbench/row.js +16 -0
- package/lib/workbench/settings.d.ts +15 -0
- package/lib/workbench/settings.js +56 -0
- package/lib/workbench/workbench.d.ts +100 -0
- package/lib/workbench/workbench.js +260 -0
- package/locale/agents/en.json +6 -0
- package/locale/agents/zh.json +6 -0
- package/locale/commands/en.json +6 -0
- package/locale/commands/zh.json +6 -0
- package/locale/context/en.json +6 -0
- package/locale/context/zh.json +6 -0
- package/locale/en.json +6 -0
- package/locale/hooks/en.json +6 -0
- package/locale/hooks/zh.json +6 -0
- package/locale/mcp/en.json +6 -0
- package/locale/mcp/zh.json +6 -0
- package/locale/mods/en.json +6 -0
- package/locale/mods/zh.json +6 -0
- package/locale/opencode/en.json +6 -0
- package/locale/opencode/zh.json +6 -0
- package/locale/porter/en.json +6 -0
- package/locale/porter/zh.json +6 -0
- package/locale/sessions/en.json +6 -0
- package/locale/sessions/zh.json +6 -0
- package/locale/skills/en.json +6 -0
- package/locale/skills/zh.json +6 -0
- package/locale/workbench/en.json +6 -0
- package/locale/workbench/zh.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +246 -3
- package/runtime/opencode-host.mjs +270 -0
- package/skills/harness-forge/SKILL.md +47 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `harness-forge` row: the ledger (discover, plan, apply, undo, remove),
|
|
3
|
+
* the shared service every other row reaches as `harnessForge`, imported
|
|
4
|
+
* settings, project assets, the turn lifecycle of invoked skills and
|
|
5
|
+
* commands, `/harness` and the `harness_*` model tools. The capability rows
|
|
6
|
+
* (skills, commands, agents, hooks, MCP, mods, OpenCode, sessions, porter,
|
|
7
|
+
* workbench) are rows of their own; each can be off without affecting the rest.
|
|
8
|
+
* @module @kirkchinese/harness-forge
|
|
9
|
+
*/
|
|
10
|
+
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
11
|
+
import { dirname, join } from 'node:path';
|
|
12
|
+
import z from '@deepseek-ai/schemastery';
|
|
13
|
+
import { dialectIds } from '@kirkchinese/harness-forge-core';
|
|
14
|
+
import { FORGE_SERVICE, HarnessForge } from './forge/service.js';
|
|
15
|
+
import { registerModelTools } from './workbench/model-tools.js';
|
|
16
|
+
import { setModelAliases } from './shared/invocation.js';
|
|
17
|
+
import { registerBundledSkills } from './skills/bundled.js';
|
|
18
|
+
import { defaultStatePath, resolveDshHome } from './forge/state.js';
|
|
19
|
+
import { dshService, onDsh, reportFaults } from './dsh/host.js';
|
|
20
|
+
import { turnListeners } from './forge/turns.js';
|
|
21
|
+
import { Workbench } from './workbench/workbench.js';
|
|
22
|
+
import { loggerOf, messageOf } from './shared/util.js';
|
|
23
|
+
import { Parts } from './forge/row.js';
|
|
24
|
+
/** Schemastery validation for the plugin configuration. */
|
|
25
|
+
// Schemastery's inferred array-output type includes its Volatile wrapper even
|
|
26
|
+
// for a required array; the runtime schema is a plain string array.
|
|
27
|
+
export const Config = z.object({
|
|
28
|
+
preload: z.array(z.string()),
|
|
29
|
+
debug: z.boolean(),
|
|
30
|
+
modelAliases: z.object({ haiku: z.string(), sonnet: z.string(), opus: z.string() }),
|
|
31
|
+
});
|
|
32
|
+
/** Cordis plugin name. */
|
|
33
|
+
export const name = 'harness-compat';
|
|
34
|
+
/** Every DSH service the row uses is optional: a headless profile runs the ledger alone. */
|
|
35
|
+
export const inject = [];
|
|
36
|
+
/** How long a new session's first request waits for imported plugins to mount at most. */
|
|
37
|
+
const READY_WAIT_MS = 30_000;
|
|
38
|
+
const COMMAND_HINT = '<status|list|scan|plan|import|undo|remove|roots|login> [args]';
|
|
39
|
+
/** Create the `/harness` command over the installation service. */
|
|
40
|
+
function harnessCommand(service, workbench) {
|
|
41
|
+
return {
|
|
42
|
+
name: 'harness',
|
|
43
|
+
description: 'Scan, install and inspect foreign Claude Code / Codex / OpenCode plugins',
|
|
44
|
+
input: { hint: COMMAND_HINT },
|
|
45
|
+
handler: async (invocation) => {
|
|
46
|
+
const input = invocation.rawInput.trim();
|
|
47
|
+
const space = input.indexOf(' ');
|
|
48
|
+
const verb = (space === -1 ? input : input.slice(0, space)).toLowerCase();
|
|
49
|
+
const rest = space === -1 ? '' : input.slice(space + 1).trim();
|
|
50
|
+
switch (verb) {
|
|
51
|
+
case '':
|
|
52
|
+
case 'status':
|
|
53
|
+
return { kind: 'success', text: statusText(service, workbench) };
|
|
54
|
+
case 'roots':
|
|
55
|
+
return { kind: 'success', text: rootsText(workbench) };
|
|
56
|
+
case 'list':
|
|
57
|
+
return { kind: 'success', text: listText(service) };
|
|
58
|
+
case 'scan': {
|
|
59
|
+
const [path, source] = splitPathAndSource(rest);
|
|
60
|
+
if (path.length === 0)
|
|
61
|
+
return { kind: 'error', text: 'usage: /harness scan <path> [source]' };
|
|
62
|
+
try {
|
|
63
|
+
const plugin = service.scan(path, source);
|
|
64
|
+
return { kind: 'success', text: scanText(plugin) };
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
return { kind: 'error', text: `scan failed: ${messageOf(error)}` };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
case 'import': {
|
|
71
|
+
const [path, source] = splitPathAndSource(rest);
|
|
72
|
+
if (path.length === 0)
|
|
73
|
+
return { kind: 'error', text: 'usage: /harness import <path> [source]' };
|
|
74
|
+
try {
|
|
75
|
+
const report = await service.install(path, source);
|
|
76
|
+
return {
|
|
77
|
+
kind: 'success',
|
|
78
|
+
text: [
|
|
79
|
+
`Imported ${report.plugin.name} (${report.plugin.source})`,
|
|
80
|
+
`skills: ${report.plugin.components.filter(component => component.kind === 'skill').length}`,
|
|
81
|
+
`commands: ${report.commands.length}${report.commands.length > 0 ? ` (${report.commands.join(', ')})` : ''}`,
|
|
82
|
+
`mcp: ${report.mcp.filter(item => item.status === 'mounted').length}/${report.mcp.length} mounted`,
|
|
83
|
+
`hooks: ${report.hooks.filter(item => item.status === 'mounted').length}/${report.hooks.length} mounted`,
|
|
84
|
+
`agents: ${report.agents.filter(item => item.status === 'mounted').length}/${report.agents.length} presets`,
|
|
85
|
+
...(report.mcp.some(item => item.status === 'failed') ? [`mcp failures: ${report.mcp.filter(item => item.status === 'failed').map(item => item.name).join(', ')}`] : []),
|
|
86
|
+
...(report.hooks.some(item => item.status === 'failed') ? [`hooks failures: ${report.hooks.filter(item => item.status === 'failed').map(item => item.name).join(', ')}`] : []),
|
|
87
|
+
...(report.agents.some(item => item.status === 'failed') ? [`agent failures: ${report.agents.filter(item => item.status === 'failed').map(item => item.name).join(', ')}`] : []),
|
|
88
|
+
...(report.alreadyInstalled ? ['already installed; no changes'] : []),
|
|
89
|
+
// Every warning, by code: what was left out (an escaping path, a clash of names) and why.
|
|
90
|
+
...report.plugin.warnings.slice(0, 12).map(warning => `warning ${warning.code}: ${warning.message}`),
|
|
91
|
+
...(report.plugin.warnings.length > 12 ? [`… ${report.plugin.warnings.length - 12} more warning(s)`] : []),
|
|
92
|
+
].join('\n'),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
return { kind: 'error', text: `import failed: ${messageOf(error)}` };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
case 'undo': {
|
|
100
|
+
if (rest.length === 0)
|
|
101
|
+
return { kind: 'error', text: 'usage: /harness undo <receipt-id>' };
|
|
102
|
+
return await service.undo(rest)
|
|
103
|
+
? { kind: 'success', text: `Undid receipt ${rest}.` }
|
|
104
|
+
: { kind: 'error', text: `No receipt with id ${rest}.` };
|
|
105
|
+
}
|
|
106
|
+
case 'plan': {
|
|
107
|
+
const [path, source] = splitPathAndSource(rest);
|
|
108
|
+
if (path.length === 0)
|
|
109
|
+
return { kind: 'error', text: 'usage: /harness plan <path> [source]' };
|
|
110
|
+
try {
|
|
111
|
+
const plan = service.plan(path, source);
|
|
112
|
+
return {
|
|
113
|
+
kind: 'success',
|
|
114
|
+
text: [
|
|
115
|
+
`Plan ${plan.id.slice(0, 12)} for ${plan.pluginId}`,
|
|
116
|
+
`actions: ${plan.actions.length}`,
|
|
117
|
+
`target: assets=${plan.target.assets} runtime=${plan.target.declarativeRuntime} code=${plan.target.codeRuntime} ui=${plan.target.interaction}`,
|
|
118
|
+
`resident tokens: ~${plan.summary.residentTokens}`,
|
|
119
|
+
...plan.actions.map(action => `- ${action.kind}: ${action.name}`),
|
|
120
|
+
].join('\n'),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
return { kind: 'error', text: `plan failed: ${messageOf(error)}` };
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
case 'remove': {
|
|
128
|
+
if (rest.length === 0)
|
|
129
|
+
return { kind: 'error', text: 'usage: /harness remove <plugin-id>' };
|
|
130
|
+
return await service.uninstall(rest)
|
|
131
|
+
? { kind: 'success', text: `Removed ${rest}.` }
|
|
132
|
+
: { kind: 'error', text: `No installed plugin with id ${rest}.` };
|
|
133
|
+
}
|
|
134
|
+
case 'login': {
|
|
135
|
+
const mcp = service.lookup('mcp');
|
|
136
|
+
if (mcp === undefined)
|
|
137
|
+
return { kind: 'error', text: 'The Harness Forge mcp row is off; turn it on in Plugin Manager.' };
|
|
138
|
+
const sessionId = invocation.agent.session.header.id;
|
|
139
|
+
const pending = mcp.pendingSignIns(sessionId);
|
|
140
|
+
const server = rest.length > 0 ? rest : pending.length === 1 ? pending[0] : '';
|
|
141
|
+
if (server.length === 0) {
|
|
142
|
+
return pending.length === 0
|
|
143
|
+
? { kind: 'success', text: 'No MCP server is waiting for sign-in.' }
|
|
144
|
+
: { kind: 'success', text: `MCP servers waiting for sign-in:\n${pending.map(name => `- ${name}`).join('\n')}\nRun /harness login <server>.` };
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
const url = mcp.startSignIn(server, sessionId);
|
|
148
|
+
return { kind: 'success', text: `Opened the sign-in page for ${server} in your browser. If it did not open, visit:\n${url}\nThe server connects as soon as you finish.` };
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
return { kind: 'error', text: messageOf(error) };
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
default:
|
|
155
|
+
return {
|
|
156
|
+
kind: 'error',
|
|
157
|
+
text: `usage: /harness ${COMMAND_HINT}`,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Activate the ledger and the shared service. The ledger and `preload`
|
|
165
|
+
* plugins mount in the background; a new session's first request waits for
|
|
166
|
+
* them (at most a while), so it already has their skills, commands, hooks,
|
|
167
|
+
* MCP tools and agents, as Claude Code loads plugins before a session starts.
|
|
168
|
+
*/
|
|
169
|
+
export async function apply(ctx, config) {
|
|
170
|
+
setModelAliases(config.modelAliases);
|
|
171
|
+
const log = loggerOf(ctx);
|
|
172
|
+
const profile = dshService(ctx, 'profileContext');
|
|
173
|
+
const statePath = defaultStatePath(process.env, profile);
|
|
174
|
+
const dataRoot = profile?.dir !== undefined && profile.dir.length > 0
|
|
175
|
+
? join(profile.dir, '.harness-forge', 'data')
|
|
176
|
+
: join(resolveDshHome(), 'harness-forge', 'data');
|
|
177
|
+
const forge = new HarnessForge(ctx, statePath, dataRoot);
|
|
178
|
+
const workbench = new Workbench(forge);
|
|
179
|
+
// Started before anything else can reach the service, so the restore holds its queue ahead of any install or
|
|
180
|
+
// removal (which would otherwise write a ledger without the restored records).
|
|
181
|
+
const startup = forge.start(config.preload ?? []);
|
|
182
|
+
startup.catch((error) => { log?.warn?.(`harness-forge: startup failed: ${messageOf(error)}`); });
|
|
183
|
+
const parts = new Parts(ctx, forge, 'harness-forge');
|
|
184
|
+
ctx.effect(() => () => parts.dispose(), 'harness-forge.parts');
|
|
185
|
+
ctx.effect(() => () => forge.dispose(), 'harness-forge.ledger');
|
|
186
|
+
parts.add('faults', () => reportFaults(ctx, (error) => { forge.fault('harness-forge', error); }));
|
|
187
|
+
if (typeof ctx.provide === 'function')
|
|
188
|
+
parts.add('shared service', () => ctx.provide(FORGE_SERVICE, forge));
|
|
189
|
+
if (config.debug === true)
|
|
190
|
+
parts.add('debug log', () => debugLog(ctx, join(dirname(statePath), 'debug.log')));
|
|
191
|
+
ctx.inject(['skills'], (skillCtx) => { registerBundledSkills(skillCtx); });
|
|
192
|
+
for (const [label, start] of turnListeners(ctx, forge))
|
|
193
|
+
parts.add(label, start);
|
|
194
|
+
// Project assets load for every new top-level session; the hooks row, when it runs, loads them first
|
|
195
|
+
// (before SessionStart) and withdraws them after SessionEnd, otherwise this row does.
|
|
196
|
+
parts.add('project assets', () => {
|
|
197
|
+
const stops = [
|
|
198
|
+
onDsh(ctx, 'agent/created', ((payload) => {
|
|
199
|
+
const agent = payload.agent;
|
|
200
|
+
return forge.directory(agent, payload.signal ?? new AbortController().signal).then(cwd => forge.projects.prepare(agent, cwd));
|
|
201
|
+
}), { owner: 'harness-forge' }),
|
|
202
|
+
onDsh(ctx, 'agent/disposed', ((payload) => {
|
|
203
|
+
if (forge.lookup('hooks') === undefined)
|
|
204
|
+
void forge.projects.release(payload.agent.session.header.id);
|
|
205
|
+
}), { owner: 'harness-forge' }),
|
|
206
|
+
];
|
|
207
|
+
return () => { for (const stop of stops)
|
|
208
|
+
stop(); };
|
|
209
|
+
});
|
|
210
|
+
// DSH awaits `agent/created` listeners before an agent takes its first input: waiting there holds a new session's
|
|
211
|
+
// first request until what is installed has mounted (DSH 0.2.2 collects a request's tools before assembling it).
|
|
212
|
+
parts.add('readiness', () => onDsh(ctx, 'agent/created', (async () => {
|
|
213
|
+
await Promise.race([forge.ready(), new Promise((resolve) => { setTimeout(resolve, READY_WAIT_MS).unref?.(); })]);
|
|
214
|
+
}), { prepend: true, owner: 'harness-forge' }));
|
|
215
|
+
ctx.inject(['commands'], (commandCtx) => {
|
|
216
|
+
commandCtx.effect(() => commandCtx.commands.register(harnessCommand(forge, workbench)), 'harness-forge.command');
|
|
217
|
+
});
|
|
218
|
+
ctx.inject(['tools'], (toolCtx) => {
|
|
219
|
+
toolCtx.effect(() => registerModelTools(toolCtx, forge), 'harness-forge.model-tools');
|
|
220
|
+
});
|
|
221
|
+
// The capability parts, each isolated from the others.
|
|
222
|
+
}
|
|
223
|
+
/** Write agent lifecycle diagnostics to a file. Returns the disposer. */
|
|
224
|
+
function debugLog(ctx, path) {
|
|
225
|
+
const write = (line) => {
|
|
226
|
+
try {
|
|
227
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
228
|
+
appendFileSync(path, `${new Date().toISOString()} ${line}\n`);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
// Diagnostics must never affect the host.
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
return onDsh(ctx, 'agent/created', ((payload) => {
|
|
235
|
+
write(`agent/created ${payload.agent?.id ?? '?'} source=${JSON.stringify(payload.source)}`);
|
|
236
|
+
}));
|
|
237
|
+
}
|
|
238
|
+
function statusText(service, workbench) {
|
|
239
|
+
const records = service.list();
|
|
240
|
+
const pending = service.lookup('mcp')?.pendingSignIns() ?? [];
|
|
241
|
+
return [
|
|
242
|
+
'Harness Forge',
|
|
243
|
+
`installed plugins: ${records.length}`,
|
|
244
|
+
`skill roots: ${workbench.listSkillRoots().length}`,
|
|
245
|
+
...(pending.length > 0 ? [`waiting for sign-in: ${pending.join(', ')} (run /harness login <server>)`] : []),
|
|
246
|
+
'subcommands: status, list, scan <path>, plan <path>, import <path>, undo <receipt>, remove <id>, roots, login [server]',
|
|
247
|
+
].join('\n');
|
|
248
|
+
}
|
|
249
|
+
function rootsText(workbench) {
|
|
250
|
+
const roots = workbench.listSkillRoots();
|
|
251
|
+
return roots.length === 0 ? 'No skill roots installed.' : `Skill roots:\n${roots.map(root => `- ${root}`).join('\n')}`;
|
|
252
|
+
}
|
|
253
|
+
function listText(service) {
|
|
254
|
+
const records = service.list();
|
|
255
|
+
if (records.length === 0)
|
|
256
|
+
return 'No foreign plugins installed.';
|
|
257
|
+
return records.map(record => [
|
|
258
|
+
`${record.id}`,
|
|
259
|
+
` root: ${record.root}`,
|
|
260
|
+
` components: ${record.components.map(component => component.kind).join(', ') || 'none'}`,
|
|
261
|
+
].join('\n')).join('\n');
|
|
262
|
+
}
|
|
263
|
+
function scanText(plugin) {
|
|
264
|
+
const counts = new Map();
|
|
265
|
+
for (const component of plugin.components)
|
|
266
|
+
counts.set(component.kind, (counts.get(component.kind) ?? 0) + 1);
|
|
267
|
+
return [
|
|
268
|
+
`${plugin.name} (${plugin.source}, ${plugin.ref.manifestKind})`,
|
|
269
|
+
`root: ${plugin.root}`,
|
|
270
|
+
...(plugin.version !== undefined ? [`version: ${plugin.version}`] : []),
|
|
271
|
+
...(plugin.license !== undefined ? [`license: ${plugin.license}`] : []),
|
|
272
|
+
`components: ${[...counts].map(([kind, count]) => `${kind}=${count}`).join(', ') || 'none'}`,
|
|
273
|
+
...(plugin.warnings.length > 0 ? [`warnings: ${plugin.warnings.map(warning => warning.code).join(', ')}`] : []),
|
|
274
|
+
].join('\n');
|
|
275
|
+
}
|
|
276
|
+
function splitPathAndSource(input) {
|
|
277
|
+
if (input.length === 0)
|
|
278
|
+
return ['', undefined];
|
|
279
|
+
const lastSpace = input.lastIndexOf(' ');
|
|
280
|
+
if (lastSpace === -1)
|
|
281
|
+
return [input, undefined];
|
|
282
|
+
const maybeSource = input.slice(lastSpace + 1);
|
|
283
|
+
if ([...dialectIds(), 'foreign'].includes(maybeSource)) {
|
|
284
|
+
return [input.slice(0, lastSpace).trim(), maybeSource];
|
|
285
|
+
}
|
|
286
|
+
return [input, undefined];
|
|
287
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { OAuthClientProvider } from '@modelcontextprotocol/client';
|
|
2
|
+
/** Persistent OAuth state for remote MCP servers in one profile. */
|
|
3
|
+
export declare class McpAuthStore {
|
|
4
|
+
private readonly root;
|
|
5
|
+
private readonly open;
|
|
6
|
+
private listener;
|
|
7
|
+
private readonly waiting;
|
|
8
|
+
/**
|
|
9
|
+
* @param root - directory for per-server records.
|
|
10
|
+
* @param open - shows the sign-in page to the user; defaults to the system browser.
|
|
11
|
+
*/
|
|
12
|
+
constructor(root: string, open?: (url: string) => void | Promise<void>);
|
|
13
|
+
/** The SDK provider for one server URL. `onAuthorizationUrl` receives the sign-in URL. */
|
|
14
|
+
provider(serverUrl: string, onAuthorizationUrl: (url: URL) => void): OAuthClientProvider;
|
|
15
|
+
/**
|
|
16
|
+
* Make sure the loopback listener runs and the server's redirect URI names
|
|
17
|
+
* it. A changed port drops the old client registration, whose redirect URI
|
|
18
|
+
* no longer matches.
|
|
19
|
+
*/
|
|
20
|
+
prepare(serverUrl: string): Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* Show the sign-in page and wait for the redirect back.
|
|
23
|
+
* @returns the callback parameters (`code`, `iss`, …) for `finishAuth`.
|
|
24
|
+
*/
|
|
25
|
+
signIn(serverUrl: string, authorizationUrl: URL): Promise<URLSearchParams>;
|
|
26
|
+
/** Stop the loopback listener. */
|
|
27
|
+
close(): void;
|
|
28
|
+
private listen;
|
|
29
|
+
private file;
|
|
30
|
+
private read;
|
|
31
|
+
private update;
|
|
32
|
+
private write;
|
|
33
|
+
}
|
|
34
|
+
/** Open a URL in the user's browser. */
|
|
35
|
+
export declare function openBrowser(url: string): void;
|
package/lib/mcp/auth.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth for remote MCP servers, as Claude Code's `/mcp` sign-in does it: the
|
|
3
|
+
* MCP SDK discovers the authorization server, registers this client
|
|
4
|
+
* dynamically and runs PKCE; this module supplies the persistent store, the
|
|
5
|
+
* loopback redirect listener and the browser hand-off.
|
|
6
|
+
* @module @kirkchinese/harness-forge
|
|
7
|
+
*/
|
|
8
|
+
import { spawn } from 'node:child_process';
|
|
9
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
10
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { createServer } from 'node:http';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
const CALLBACK_PATH = '/callback';
|
|
14
|
+
const SIGN_IN_TIMEOUT_MS = 5 * 60_000;
|
|
15
|
+
/** Persistent OAuth state for remote MCP servers in one profile. */
|
|
16
|
+
export class McpAuthStore {
|
|
17
|
+
root;
|
|
18
|
+
open;
|
|
19
|
+
listener;
|
|
20
|
+
waiting = new Map();
|
|
21
|
+
/**
|
|
22
|
+
* @param root - directory for per-server records.
|
|
23
|
+
* @param open - shows the sign-in page to the user; defaults to the system browser.
|
|
24
|
+
*/
|
|
25
|
+
constructor(root, open = openBrowser) {
|
|
26
|
+
this.root = root;
|
|
27
|
+
this.open = open;
|
|
28
|
+
}
|
|
29
|
+
/** The SDK provider for one server URL. `onAuthorizationUrl` receives the sign-in URL. */
|
|
30
|
+
provider(serverUrl, onAuthorizationUrl) {
|
|
31
|
+
const key = shortKey(serverUrl);
|
|
32
|
+
const redirect = () => {
|
|
33
|
+
const port = this.read(key).redirectPort;
|
|
34
|
+
return port === undefined ? undefined : `http://127.0.0.1:${port}${CALLBACK_PATH}`;
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
get redirectUrl() { return redirect(); },
|
|
38
|
+
get clientMetadata() {
|
|
39
|
+
const uri = redirect();
|
|
40
|
+
return {
|
|
41
|
+
client_name: 'DeepSeek Harness (Harness Forge)',
|
|
42
|
+
redirect_uris: uri === undefined ? [] : [uri],
|
|
43
|
+
grant_types: ['authorization_code', 'refresh_token'],
|
|
44
|
+
response_types: ['code'],
|
|
45
|
+
token_endpoint_auth_method: 'none',
|
|
46
|
+
};
|
|
47
|
+
},
|
|
48
|
+
state: () => {
|
|
49
|
+
const state = randomBytes(16).toString('hex');
|
|
50
|
+
this.update(key, { state });
|
|
51
|
+
return state;
|
|
52
|
+
},
|
|
53
|
+
clientInformation: () => this.read(key).client,
|
|
54
|
+
saveClientInformation: (client) => { this.update(key, { client }); },
|
|
55
|
+
tokens: () => this.read(key).tokens,
|
|
56
|
+
saveTokens: (tokens) => { this.update(key, { tokens }); },
|
|
57
|
+
saveCodeVerifier: (verifier) => { this.update(key, { verifier }); },
|
|
58
|
+
codeVerifier: () => this.read(key).verifier ?? '',
|
|
59
|
+
saveDiscoveryState: (discovery) => { this.update(key, { discovery }); },
|
|
60
|
+
discoveryState: () => this.read(key).discovery,
|
|
61
|
+
invalidateCredentials: (scope) => {
|
|
62
|
+
const record = this.read(key);
|
|
63
|
+
if (scope === 'all' || scope === 'client')
|
|
64
|
+
delete record.client;
|
|
65
|
+
if (scope === 'all' || scope === 'tokens')
|
|
66
|
+
delete record.tokens;
|
|
67
|
+
if (scope === 'all' || scope === 'verifier')
|
|
68
|
+
delete record.verifier;
|
|
69
|
+
if (scope === 'all' || scope === 'discovery')
|
|
70
|
+
delete record.discovery;
|
|
71
|
+
this.write(key, record);
|
|
72
|
+
},
|
|
73
|
+
redirectToAuthorization: (url) => { onAuthorizationUrl(url); },
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Make sure the loopback listener runs and the server's redirect URI names
|
|
78
|
+
* it. A changed port drops the old client registration, whose redirect URI
|
|
79
|
+
* no longer matches.
|
|
80
|
+
*/
|
|
81
|
+
async prepare(serverUrl) {
|
|
82
|
+
const key = shortKey(serverUrl);
|
|
83
|
+
const record = this.read(key);
|
|
84
|
+
const port = await this.listen(record.redirectPort);
|
|
85
|
+
if (port !== record.redirectPort) {
|
|
86
|
+
delete record.client;
|
|
87
|
+
this.write(key, { ...record, redirectPort: port });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Show the sign-in page and wait for the redirect back.
|
|
92
|
+
* @returns the callback parameters (`code`, `iss`, …) for `finishAuth`.
|
|
93
|
+
*/
|
|
94
|
+
async signIn(serverUrl, authorizationUrl) {
|
|
95
|
+
const expected = this.read(shortKey(serverUrl)).state ?? authorizationUrl.searchParams.get('state') ?? '';
|
|
96
|
+
const params = new Promise((resolve, reject) => {
|
|
97
|
+
const timer = setTimeout(() => {
|
|
98
|
+
this.waiting.delete(expected);
|
|
99
|
+
reject(new Error('sign-in was not completed within 5 minutes'));
|
|
100
|
+
}, SIGN_IN_TIMEOUT_MS);
|
|
101
|
+
timer.unref?.();
|
|
102
|
+
this.waiting.set(expected, (value) => {
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
resolve(value);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
await this.open(authorizationUrl.href);
|
|
108
|
+
return params;
|
|
109
|
+
}
|
|
110
|
+
/** Stop the loopback listener. */
|
|
111
|
+
close() {
|
|
112
|
+
this.listener?.server.close();
|
|
113
|
+
this.listener = undefined;
|
|
114
|
+
}
|
|
115
|
+
async listen(preferred) {
|
|
116
|
+
if (this.listener !== undefined)
|
|
117
|
+
return this.listener.port;
|
|
118
|
+
const server = createServer((request, response) => {
|
|
119
|
+
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
|
120
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
121
|
+
response.writeHead(404).end();
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const resolve = this.waiting.get(url.searchParams.get('state') ?? '');
|
|
125
|
+
if (resolve === undefined || !url.searchParams.has('code')) {
|
|
126
|
+
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('This sign-in link is not the one DSH is waiting for. Start the sign-in again from DSH.');
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
this.waiting.delete(url.searchParams.get('state') ?? '');
|
|
130
|
+
resolve(url.searchParams);
|
|
131
|
+
response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }).end('<p>Signed in. You can close this tab and return to DSH.</p>');
|
|
132
|
+
});
|
|
133
|
+
const port = await new Promise((resolve, reject) => {
|
|
134
|
+
const bind = (candidate) => {
|
|
135
|
+
server.once('error', (error) => {
|
|
136
|
+
if (candidate !== 0 && error.code === 'EADDRINUSE')
|
|
137
|
+
bind(0);
|
|
138
|
+
else
|
|
139
|
+
reject(error);
|
|
140
|
+
});
|
|
141
|
+
server.listen(candidate, '127.0.0.1', () => resolve(server.address().port));
|
|
142
|
+
};
|
|
143
|
+
bind(preferred ?? 0);
|
|
144
|
+
});
|
|
145
|
+
server.unref();
|
|
146
|
+
this.listener = { server, port };
|
|
147
|
+
return port;
|
|
148
|
+
}
|
|
149
|
+
file(key) {
|
|
150
|
+
return join(this.root, `${key}.json`);
|
|
151
|
+
}
|
|
152
|
+
read(key) {
|
|
153
|
+
try {
|
|
154
|
+
return JSON.parse(readFileSync(this.file(key), 'utf8'));
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return {};
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
update(key, patch) {
|
|
161
|
+
this.write(key, { ...this.read(key), ...patch });
|
|
162
|
+
}
|
|
163
|
+
write(key, record) {
|
|
164
|
+
mkdirSync(this.root, { recursive: true });
|
|
165
|
+
writeFileSync(this.file(key), JSON.stringify(record, null, 2));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
function shortKey(serverUrl) {
|
|
169
|
+
const url = new URL(serverUrl);
|
|
170
|
+
return `${url.host.replace(/[^A-Za-z0-9.-]/gu, '_')}-${createHash('sha256').update(serverUrl).digest('hex').slice(0, 12)}`;
|
|
171
|
+
}
|
|
172
|
+
/** Open a URL in the user's browser. */
|
|
173
|
+
export function openBrowser(url) {
|
|
174
|
+
const [command, args] = process.platform === 'win32'
|
|
175
|
+
? ['rundll32', ['url.dll,FileProtocolHandler', url]]
|
|
176
|
+
: process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
|
|
177
|
+
spawn(command, [...args], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
|
|
178
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The capability catalog (`@kirkchinese/dsh-capability-catalog`, an optional
|
|
3
|
+
* plugin of its own), in one place. When a profile composes it, stdio MCP
|
|
4
|
+
* servers are listed in its compact index and started on demand instead of
|
|
5
|
+
* putting every tool schema in every request; the model calls such a tool as
|
|
6
|
+
* `capability_call` with the entry id `mcp:<server>/<tool>`. Nothing here
|
|
7
|
+
* waits for the catalog: the MCP row mounts directly while it is absent and
|
|
8
|
+
* moves its servers into it when it appears.
|
|
9
|
+
* @module @kirkchinese/harness-forge
|
|
10
|
+
*/
|
|
11
|
+
import type { McpComponent } from '@kirkchinese/harness-forge-core';
|
|
12
|
+
/** The catalog meta-tool that runs a catalog entry. */
|
|
13
|
+
export declare const CATALOG_CALL_TOOL = "capability_call";
|
|
14
|
+
/** Every catalog meta-tool; an agent that may use an MCP tool may use these. */
|
|
15
|
+
export declare const CATALOG_TOOLS: readonly ["capability_search", "capability_describe", "capability_call"];
|
|
16
|
+
/** The services the catalog provides. */
|
|
17
|
+
export declare const CATALOG_SERVICES: readonly ["capabilityCatalogServers", "capabilityCatalog"];
|
|
18
|
+
/** The `mcp__<server>__<tool>` name of a catalog entry id `mcp:<server>/<tool>`. */
|
|
19
|
+
export declare function catalogToolName(id: unknown): string | undefined;
|
|
20
|
+
/** The tool a call runs: a catalog call runs the MCP tool its id names. */
|
|
21
|
+
export declare function calledTool(name: string, args: unknown): string;
|
|
22
|
+
/** The capability catalog's server registry. */
|
|
23
|
+
export interface CatalogServers {
|
|
24
|
+
addMcpServer(server: Record<string, unknown>): Promise<() => Promise<void>>;
|
|
25
|
+
}
|
|
26
|
+
/** The catalog's server registry when the profile composes the catalog and it runs. */
|
|
27
|
+
export declare function composedCatalog(ctx: object): CatalogServers | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* Hand one stdio server to the capability catalog. The catalog records a
|
|
30
|
+
* failed discovery instead of throwing; its overview tells, so a server that
|
|
31
|
+
* never started fails the mount with the catalog's reason.
|
|
32
|
+
* @param config - the server's `mcp-client` configuration.
|
|
33
|
+
* @param program - the program as the configuration names it; `resolved`, where it was found.
|
|
34
|
+
* @returns the removal.
|
|
35
|
+
*/
|
|
36
|
+
export declare function mountInCatalog(ctx: object, catalog: CatalogServers, component: McpComponent, serverName: string, config: Record<string, unknown>, program: string, resolved: string, discoveryTimeoutMs: number): Promise<() => Promise<void>>;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { dshService } from '../dsh/host.js';
|
|
2
|
+
/** The catalog meta-tool that runs a catalog entry. */
|
|
3
|
+
export const CATALOG_CALL_TOOL = 'capability_call';
|
|
4
|
+
/** Every catalog meta-tool; an agent that may use an MCP tool may use these. */
|
|
5
|
+
export const CATALOG_TOOLS = ['capability_search', 'capability_describe', CATALOG_CALL_TOOL];
|
|
6
|
+
/** The services the catalog provides. */
|
|
7
|
+
export const CATALOG_SERVICES = ['capabilityCatalogServers', 'capabilityCatalog'];
|
|
8
|
+
/** The `mcp__<server>__<tool>` name of a catalog entry id `mcp:<server>/<tool>`. */
|
|
9
|
+
export function catalogToolName(id) {
|
|
10
|
+
if (typeof id !== 'string')
|
|
11
|
+
return undefined;
|
|
12
|
+
const match = /^mcp:([^/]+)\/(.+)$/u.exec(id);
|
|
13
|
+
return match === null ? undefined : `mcp__${match[1] ?? ''}__${match[2] ?? ''}`;
|
|
14
|
+
}
|
|
15
|
+
/** The tool a call runs: a catalog call runs the MCP tool its id names. */
|
|
16
|
+
export function calledTool(name, args) {
|
|
17
|
+
return name === CATALOG_CALL_TOOL ? catalogToolName(args?.id) ?? name : name;
|
|
18
|
+
}
|
|
19
|
+
/** The catalog's server registry when the profile composes the catalog and it runs. */
|
|
20
|
+
export function composedCatalog(ctx) {
|
|
21
|
+
return dshService(ctx, 'capabilityCatalogServers');
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Hand one stdio server to the capability catalog. The catalog records a
|
|
25
|
+
* failed discovery instead of throwing; its overview tells, so a server that
|
|
26
|
+
* never started fails the mount with the catalog's reason.
|
|
27
|
+
* @param config - the server's `mcp-client` configuration.
|
|
28
|
+
* @param program - the program as the configuration names it; `resolved`, where it was found.
|
|
29
|
+
* @returns the removal.
|
|
30
|
+
*/
|
|
31
|
+
export async function mountInCatalog(ctx, catalog, component, serverName, config, program, resolved, discoveryTimeoutMs) {
|
|
32
|
+
const dispose = await catalog.addMcpServer({
|
|
33
|
+
name: serverName,
|
|
34
|
+
enabled: true,
|
|
35
|
+
...(component.description !== undefined && !/^\w+ MCP server$|^[\w-]+ \w+ MCP server$/u.test(component.description) ? { description: component.description } : {}),
|
|
36
|
+
transport: 'stdio',
|
|
37
|
+
// The catalog spawns without a shell; a Windows `.cmd` shim runs through cmd.exe,
|
|
38
|
+
// named as the config names it so a path with spaces never reaches cmd's parser.
|
|
39
|
+
...(/\.(cmd|bat)$/iu.test(resolved)
|
|
40
|
+
? { command: process.env['ComSpec'] ?? 'cmd.exe', args: ['/d', '/s', '/c', /[\\/]/u.test(program) ? resolved : program, ...config['args']] }
|
|
41
|
+
: { command: resolved, args: config['args'] }),
|
|
42
|
+
env: config['env'],
|
|
43
|
+
cwd: config['cwd'],
|
|
44
|
+
headers: {},
|
|
45
|
+
allowTools: [],
|
|
46
|
+
denyTools: [],
|
|
47
|
+
families: [],
|
|
48
|
+
idleDisconnectMs: 300_000,
|
|
49
|
+
callTimeoutMs: 600_000,
|
|
50
|
+
discoveryTimeoutMs,
|
|
51
|
+
catalogTtlMs: 86_400_000,
|
|
52
|
+
});
|
|
53
|
+
const remote = dshService(ctx, 'capabilityCatalog');
|
|
54
|
+
const overview = await remote?.request({ action: 'overview' }, AbortSignal.timeout(30_000)).catch(() => undefined);
|
|
55
|
+
const problem = overview?.servers?.find(server => server.name === serverName)?.problem;
|
|
56
|
+
if (typeof problem === 'string' && problem.length > 0) {
|
|
57
|
+
await dispose();
|
|
58
|
+
throw new Error(`MCP server "${component.name}" failed in the capability catalog: ${problem}`);
|
|
59
|
+
}
|
|
60
|
+
return dispose;
|
|
61
|
+
}
|