@kirkchinese/harness-forge 0.4.0 → 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 (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
package/lib/mcp/row.js CHANGED
@@ -9,8 +9,9 @@ import { HarnessError } from '@kirkchinese/harness-forge-core';
9
9
  import { onDsh } from '../dsh/host.js';
10
10
  import { FORGE_SERVICE } from '../forge/service.js';
11
11
  import { McpAuthStore } from './auth.js';
12
- import { CATALOG_SERVICES, calledTool } from './catalog.js';
13
- import { foreignServerName, mcpServerName, mountMcp } from './mount.js';
12
+ import { CATALOG_CALL_TOOL, CATALOG_SERVICES, catalogEntry } from './catalog.js';
13
+ import { foreignServerName, harnessVariables, mcpServerName, mountMcp, servedByCatalog } from './mount.js';
14
+ import { mcpToolPolicy } from './policy.js';
14
15
  import { messageOf } from '../shared/util.js';
15
16
  import { mounted, Parts, rowEffect } from '../forge/row.js';
16
17
  export const name = 'harness-forge-mcp';
@@ -19,6 +20,8 @@ export const inject = [FORGE_SERVICE];
19
20
  export function apply(ctx) {
20
21
  rowEffect(ctx, 'mcp', forge => startMcp(ctx, forge));
21
22
  }
23
+ /** Claude Code's scoped hook server name `plugin:<plugin>:<server>`. */
24
+ const SCOPED_HOOK_SERVER = /^plugin:([^:]+):(.+)$/u;
22
25
  /** Start the MCP row on the shared service. Returns its teardown. */
23
26
  export function startMcp(ctx, forge) {
24
27
  const auth = new McpAuthStore(join(forge.dataRoot, 'mcp-auth'));
@@ -28,8 +31,12 @@ export function startMcp(ctx, forge) {
28
31
  * with its own sign-in state and component.
29
32
  */
30
33
  const remotes = new Map();
31
- /** Each mounted server's tool-name prefix, with its component and session. */
32
- const prefixes = new Set();
34
+ /**
35
+ * Each server's registration, with its component and session: published
36
+ * before its tools are, and kept until their withdrawal succeeds, so its
37
+ * policy covers every moment they can be called.
38
+ */
39
+ const servers = new Set();
33
40
  const remoteHost = (componentId, scope = {}) => ({
34
41
  auth,
35
42
  onState: (server, state) => {
@@ -68,6 +75,15 @@ export function startMcp(ctx, forge) {
68
75
  return state.url;
69
76
  },
70
77
  remoteHost,
78
+ toolPolicy: call => toolPolicy(call),
79
+ hookServer: (pluginId, server, sessionId) => {
80
+ const scoped = SCOPED_HOOK_SERVER.exec(server);
81
+ const declared = scoped?.[2] ?? server;
82
+ const named = [...servers].filter(entry => entry.declaredName === declared);
83
+ const pick = (matching) => matching.find(entry => sessionId !== undefined && entry.sessionId === sessionId) ?? matching.find(entry => entry.sessionId === undefined);
84
+ const own = pick(named.filter(entry => scoped === null ? entry.pluginId === pluginId : entry.pluginName === scoped[1]));
85
+ return (own ?? (scoped === null ? pick(named.filter(entry => entry.userLevel)) : undefined))?.serverName;
86
+ },
71
87
  };
72
88
  const mounter = {
73
89
  mount: async ({ component, plugin, dataDir, scope }) => {
@@ -75,30 +91,108 @@ export function startMcp(ctx, forge) {
75
91
  throw new HarnessError('component-failed', `action expects MCP: ${component.id}`);
76
92
  const serverName = mcpServerName(foreignServerName(plugin, component.name));
77
93
  // A session's project servers stay in its own context; the catalog is process-wide.
78
- const mount = await mountMcp(scope.ctx ?? ctx, component, serverName, { pluginRoot: plugin.root, dataDir, env: forge.settings.env() }, remoteHost(component.id, scope), { catalog: scope.sessionId === undefined });
79
- const prefix = { prefix: `mcp__${serverName}__`, componentId: component.id, ...(scope.sessionId !== undefined ? { sessionId: scope.sessionId } : {}) };
80
- prefixes.add(prefix);
94
+ const vars = { pluginRoot: plugin.root, dataDir, env: forge.settings.env(), provided: harnessVariables(plugin) };
95
+ const policy = mcpToolPolicy(component, serverName);
96
+ const options = { catalog: scope.sessionId === undefined };
97
+ const entry = (route) => ({
98
+ serverName,
99
+ componentId: component.id,
100
+ route,
101
+ pluginId: plugin.id,
102
+ pluginName: plugin.name,
103
+ declaredName: component.declaredName ?? component.name,
104
+ userLevel: plugin.manifest?.['scope'] === 'user',
105
+ ...(scope.sessionId !== undefined ? { sessionId: scope.sessionId } : {}),
106
+ ...(policy !== undefined ? { policy } : {}),
107
+ });
108
+ // Published before the server's tools can be called; a mount that fails has withdrawn them itself.
109
+ let server = entry(servedByCatalog(scope.ctx ?? ctx, component, options) ? 'catalog' : 'direct');
110
+ servers.add(server);
111
+ let mount;
112
+ try {
113
+ mount = await mountMcp(scope.ctx ?? ctx, component, serverName, vars, remoteHost(component.id, scope), options);
114
+ }
115
+ catch (error) {
116
+ servers.delete(server);
117
+ throw error;
118
+ }
119
+ // The catalog came or went while the server mounted: the policy follows the route it took.
120
+ const route = mount.catalog === true ? 'catalog' : 'direct';
121
+ if (route !== server.route) {
122
+ const moved = entry(route);
123
+ servers.add(moved);
124
+ servers.delete(server);
125
+ server = moved;
126
+ }
81
127
  return {
82
128
  outcome: mounted(component, 'L1b', mount.catalog === true ? `${serverName} (capability catalog)` : serverName),
129
+ // A withdrawal that fails leaves the tools registered, so their policy stays until one succeeds.
83
130
  disposer: async () => {
84
- prefixes.delete(prefix);
131
+ await mount.dispose();
132
+ servers.delete(server);
85
133
  if (mount.remote !== undefined)
86
134
  remotes.delete(mount.remote);
87
- await mount.dispose();
88
135
  },
89
136
  };
90
137
  },
91
138
  };
139
+ /**
140
+ * The server a call goes to: a catalog call (`capability_call`) only among
141
+ * servers registered in the catalog, a direct call only among direct ones,
142
+ * so two servers of one name, one in each, never lend each other a policy.
143
+ * Among those, the calling session's own first, then the process-wide one of
144
+ * that name. A catalog call names the server and the raw
145
+ * tool exactly. A direct call names the tool `dsh-mcp-client` registered in
146
+ * the server's namespace `mcp__<server>__`; server names never hold `__`
147
+ * ({@link mcpServerName}), so one namespace holds it, and the policy knows
148
+ * the raw name of every tool it configures by that same public name.
149
+ */
150
+ const targetOf = (exec) => {
151
+ const sessionId = exec.agent?.session?.header?.id;
152
+ const pick = (route, matches) => {
153
+ const matching = [...servers].filter(server => server.route === route && matches(server));
154
+ return matching.find(candidate => sessionId !== undefined && candidate.sessionId === sessionId)
155
+ ?? matching.find(candidate => candidate.sessionId === undefined);
156
+ };
157
+ if (exec.name === CATALOG_CALL_TOOL) {
158
+ const entry = catalogEntry(exec.arguments?.id);
159
+ const server = entry === undefined ? undefined : pick('catalog', candidate => candidate.serverName === entry.server);
160
+ return entry === undefined || server === undefined ? undefined : { server, rawName: entry.tool, toolName: `mcp__${entry.server}__${entry.tool}` };
161
+ }
162
+ const server = pick('direct', candidate => exec.name.startsWith(`mcp__${candidate.serverName}__`));
163
+ const rawName = server?.policy?.rawName(exec.name);
164
+ return server === undefined ? undefined : { server, ...(rawName !== undefined ? { rawName } : {}), toolName: exec.name };
165
+ };
166
+ /**
167
+ * Calls refused before they ran. DSH still runs `tools/post-execute` for the refusal's error result, but the
168
+ * server never saw the call: a refusal is the policy's doing, not evidence about the part, and recording it
169
+ * would mark the part failed (and list it in Diagnostics as one that failed to start).
170
+ */
171
+ const refused = new WeakSet();
172
+ /** A server's own filters and approval modes for one call (see `McpApi.toolPolicy`). */
173
+ function toolPolicy(exec) {
174
+ const target = targetOf(exec);
175
+ return target?.server.policy?.decide(target.rawName, target.toolName);
176
+ }
92
177
  const parts = new Parts(ctx, forge, 'mcp');
178
+ // A server's own tool filters and approval modes: a switched-off tool is refused, an asking one asks whatever
179
+ // the rest of the chain allowed. First in the chain, so nothing before it can allow the call outright.
180
+ parts.add('tool policy', () => onDsh(ctx, 'tools/pre-execute', (async (exec, next) => {
181
+ const target = targetOf(exec);
182
+ const verdict = toolPolicy(exec);
183
+ if (verdict?.kind === 'deny') {
184
+ refused.add(exec);
185
+ return { kind: 'deny', reason: verdict.reason };
186
+ }
187
+ const decided = await next();
188
+ if (decided.kind === 'deny' && target !== undefined)
189
+ refused.add(exec);
190
+ return verdict?.kind === 'ask' && decided.kind === 'allow' ? { kind: 'ask', reason: verdict.reason } : decided;
191
+ }), { owner: 'mcp', prepend: true }));
93
192
  parts.add('tool evidence', () => onDsh(ctx, 'tools/post-execute', ((exec, result, next) => {
94
- const toolName = calledTool(exec.name, exec.arguments);
95
- const sessionId = exec.agent?.session?.header?.id;
96
- const matching = [...prefixes].filter(entry => toolName.startsWith(entry.prefix));
97
- // The calling session's own server first, then the process-wide one of that name.
98
- const entry = matching.find(candidate => sessionId !== undefined && candidate.sessionId === sessionId)
99
- ?? matching.find(candidate => candidate.sessionId === undefined);
100
- if (entry !== undefined) {
101
- forge.observe(entry.componentId, `tool:${toolName}`, !result.isError, result.isError ? result.error?.message ?? 'tool call failed' : `tool call returned${toolName !== exec.name ? ' through the capability catalog' : ''}`);
193
+ const target = targetOf(exec);
194
+ if (target !== undefined && !refused.has(exec)) {
195
+ forge.observe(target.server.componentId, `tool:${target.toolName}`, !result.isError, result.isError ? result.error?.message ?? 'tool call failed' : `tool call returned${target.toolName !== exec.name ? ' through the capability catalog' : ''}`);
102
196
  }
103
197
  return next();
104
198
  }), { owner: 'mcp' }));
@@ -10,6 +10,7 @@ import { createHash, getRandomValues, randomUUID, subtle } from 'node:crypto';
10
10
  import { readFileSync } from 'node:fs';
11
11
  import { dirname, extname, isAbsolute } from 'node:path';
12
12
  import vm from 'node:vm';
13
+ import { leadsToShare } from '@kirkchinese/harness-forge-core';
13
14
  import { CLAUDE_CODE_MODULE, Fragment, h } from './runtime.js';
14
15
  /** Modules a hooks module imports from the engine rather than from its folder. */
15
16
  const VIRTUAL = ['claude-code', 'claude-code/testing'];
@@ -197,6 +198,9 @@ export function scanBundleRefusal(bundle, parseAst) {
197
198
  const ext = extname(file).toLowerCase();
198
199
  const lang = ext === '.tsx' ? 'tsx' : ext === '.ts' || ext === '.mts' || ext === '.cts' ? 'ts' : ext === '.jsx' ? 'jsx' : 'js';
199
200
  let text;
201
+ // A file on a link to a network share it is not on is unreadable (see `leadsToShare`).
202
+ if (leadsToShare(file))
203
+ continue;
200
204
  try {
201
205
  text = readFileSync(file, 'utf8');
202
206
  }
@@ -7,9 +7,9 @@ export declare class ModTurns {
7
7
  preStep(payload: PreStep, next: () => Promise<PreStepDecision>): Promise<PreStepDecision>;
8
8
  /**
9
9
  * `prompt.context` for the conversation's first prompt: the instruction
10
- * files Claude Code itself would load (CLAUDE.md from the root down, the
11
- * user's, the local ones) and the blocks they frame. Files a hook adds that
12
- * DSH's own instructions did not load enter the conversation as context.
10
+ * files Claude Code itself would load (found as core's `loadInstructions`
11
+ * finds them) and the blocks they frame. Files a hook adds that DSH's own
12
+ * instructions did not load enter the conversation as context.
13
13
  */
14
14
  private promptContext;
15
15
  sessionEvent(session: {
@@ -20,10 +20,11 @@ export declare class ModTurns {
20
20
  }): void;
21
21
  }
22
22
  /**
23
- * The instruction files Claude Code loads for a working directory: the
24
- * user's (~/.claude/CLAUDE.md), then from the filesystem root down to the
25
- * directory each CLAUDE.md and .claude/CLAUDE.md (project) and
26
- * CLAUDE.local.md (local).
23
+ * The instruction files Claude Code loads for a working directory, found by
24
+ * core's discovery: the user's (~/.claude/CLAUDE.md), then from the repository
25
+ * root (the working directory outside a repository) down to the directory each
26
+ * CLAUDE.md, .claude/CLAUDE.md and CLAUDE.local.md, with their `@path` imports.
27
+ * Every file is returned, including those DSH injects itself.
27
28
  */
28
29
  export declare function claudeInstructionFiles(cwd: string, home?: string): Array<{
29
30
  path: string;
@@ -3,10 +3,9 @@
3
3
  * `turn.complete`.
4
4
  * @module @kirkchinese/harness-forge/mods
5
5
  */
6
- import { existsSync, readFileSync } from 'node:fs';
7
6
  import { homedir } from 'node:os';
8
- import { dirname, join } from 'node:path';
9
7
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
8
+ import { loadInstructions } from '@kirkchinese/harness-forge-core';
10
9
  import { appendNotice } from '../../hooks/notice.js';
11
10
  import { claudeMdText } from '../engine.js';
12
11
  import { isRecord } from '../values.js';
@@ -68,9 +67,9 @@ export class ModTurns {
68
67
  }
69
68
  /**
70
69
  * `prompt.context` for the conversation's first prompt: the instruction
71
- * files Claude Code itself would load (CLAUDE.md from the root down, the
72
- * user's, the local ones) and the blocks they frame. Files a hook adds that
73
- * DSH's own instructions did not load enter the conversation as context.
70
+ * files Claude Code itself would load (found as core's `loadInstructions`
71
+ * finds them) and the blocks they frame. Files a hook adds that DSH's own
72
+ * instructions did not load enter the conversation as context.
74
73
  */
75
74
  async promptContext(session, signal) {
76
75
  session.isContextRaised = true;
@@ -126,36 +125,12 @@ export class ModTurns {
126
125
  }
127
126
  }
128
127
  /**
129
- * The instruction files Claude Code loads for a working directory: the
130
- * user's (~/.claude/CLAUDE.md), then from the filesystem root down to the
131
- * directory each CLAUDE.md and .claude/CLAUDE.md (project) and
132
- * CLAUDE.local.md (local).
128
+ * The instruction files Claude Code loads for a working directory, found by
129
+ * core's discovery: the user's (~/.claude/CLAUDE.md), then from the repository
130
+ * root (the working directory outside a repository) down to the directory each
131
+ * CLAUDE.md, .claude/CLAUDE.md and CLAUDE.local.md, with their `@path` imports.
132
+ * Every file is returned, including those DSH injects itself.
133
133
  */
134
134
  export function claudeInstructionFiles(cwd, home = homedir()) {
135
- const files = [];
136
- const read = (path, kind) => {
137
- if (!existsSync(path))
138
- return;
139
- try {
140
- files.push({ path, kind, content: readFileSync(path, 'utf8') });
141
- }
142
- catch {
143
- // An unreadable file is not loaded.
144
- }
145
- };
146
- read(join(home, '.claude', 'CLAUDE.md'), 'user');
147
- const dirs = [];
148
- for (let current = cwd;; current = dirname(current)) {
149
- dirs.unshift(current);
150
- if (dirname(current) === current)
151
- break;
152
- }
153
- for (const dir of dirs) {
154
- if (dir === home)
155
- continue;
156
- read(join(dir, 'CLAUDE.md'), 'project');
157
- read(join(dir, '.claude', 'CLAUDE.md'), 'project');
158
- read(join(dir, 'CLAUDE.local.md'), 'local');
159
- }
160
- return files;
135
+ return loadInstructions({ cwd, home, skipCodex: true }).files.map(({ path, kind, content }) => ({ path, kind, content }));
161
136
  }
@@ -13,7 +13,7 @@
13
13
  import { spawnSync } from 'node:child_process';
14
14
  import { existsSync, readFileSync } from 'node:fs';
15
15
  import { homedir } from 'node:os';
16
- import { join } from 'node:path';
16
+ import { dirname, join, resolve } from 'node:path';
17
17
  import { npmInstall, runProcess } from '../forge/npm.js';
18
18
  export { npmLaunch } from '../forge/npm.js';
19
19
  const EXE = process.platform === 'win32' ? 'bun.exe' : 'bun';
@@ -132,6 +132,15 @@ export async function ensureBun(dataRoot, host = defaultHost) {
132
132
  }
133
133
  throw new Error(`Bun is needed to run OpenCode plugins and could not be installed automatically (${problems.join('; ')}). Install Bun (https://bun.sh), or set BUN_PATH to a working bun executable, then restart DSH.`);
134
134
  }
135
+ /** Whether `name` resolves from `root` the way Node and Bun look it up: `node_modules` of `root` and each parent. */
136
+ function resolvableFrom(root, name) {
137
+ for (let dir = resolve(root);; dir = dirname(dir)) {
138
+ if (existsSync(join(dir, 'node_modules', ...name.split('/'))))
139
+ return true;
140
+ if (dirname(dir) === dir)
141
+ return false;
142
+ }
143
+ }
135
144
  /**
136
145
  * Install a plugin's dependencies the way OpenCode installs a plugin package:
137
146
  * production dependencies, no lifecycle scripts of the plugin's own repository.
@@ -149,7 +158,10 @@ export async function ensureDependencies(bun, root) {
149
158
  catch {
150
159
  return;
151
160
  }
152
- const missing = Object.keys(declared).filter(name => !existsSync(join(root, 'node_modules', ...name.split('/'))));
161
+ // A package OpenCode installed has its dependencies hoisted beside it (`~/.cache/opencode/node_modules`), where
162
+ // Bun resolves them from: a dependency found in any parent `node_modules` is there, and nothing is installed
163
+ // into OpenCode's own folders.
164
+ const missing = Object.keys(declared).filter(name => !resolvableFrom(root, name));
153
165
  if (missing.length === 0)
154
166
  return;
155
167
  await runProcess(bun, ['install', '--production', '--ignore-scripts'], root, 600_000);
@@ -1,5 +1,6 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
- import type { Disposer } from '../forge/contract.js';
2
+ import type { Disposer, MountScope } from '../forge/contract.js';
3
+ import type { OpenCodeCommand } from './runtime/types.js';
3
4
  import { type HarnessForge } from '../forge/service.js';
4
5
  export declare const name = "harness-forge-opencode";
5
6
  export declare const inject: string[];
@@ -7,3 +8,15 @@ export declare const inject: string[];
7
8
  export declare function apply(ctx: Context): void;
8
9
  /** Start the OpenCode row on the shared service. Returns its teardown. */
9
10
  export declare function startOpenCode(ctx: Context, forge: HarnessForge): Disposer;
11
+ /**
12
+ * Register a mounted plugin's added commands for as long as both the plugin and the commands row run: again each
13
+ * time the commands row starts, withdrawn when it stops or `dispose` runs. `record` gets, at each registration, the
14
+ * DSH name of each command in order (empty where none was given).
15
+ */
16
+ export declare function bindAddedCommands(forge: Pick<HarnessForge, 'watch'>, commands: readonly OpenCodeCommand[], owner: {
17
+ readonly pluginId: string;
18
+ readonly pluginRoot: string;
19
+ readonly dataDir: string;
20
+ readonly scope: MountScope;
21
+ takenNames(): Set<string>;
22
+ }, record: (names: readonly string[]) => void): Disposer;
@@ -2,7 +2,8 @@
2
2
  * The OpenCode row: OpenCode code plugins, each in its own Bun host, their
3
3
  * hooks raised where DSH does the same work. It adds `shell.env` to the hooks
4
4
  * row and `command.execute.before` to the commands row while those run, and
5
- * its plugins' added commands through the commands row.
5
+ * its plugins' added commands through the commands row while both the plugin
6
+ * and that row run.
6
7
  * @module @kirkchinese/harness-forge/opencode
7
8
  */
8
9
  import { join } from 'node:path';
@@ -45,27 +46,17 @@ export function startOpenCode(ctx, forge) {
45
46
  const mount = await opencode.mount(component, plugin);
46
47
  for (const tool of mount.tools)
47
48
  tools.set(tool, component.id);
48
- // Commands the plugin's `config` hook added run like the project's own OpenCode commands.
49
- const withdraw = [];
50
- const commandNames = [];
51
- const commands = forge.lookup('commands');
52
- if (commands !== undefined) {
53
- const taken = takenNames();
54
- for (const command of mount.commands) {
55
- const added = commands.registerAdded({ component: command.component, name: command.name, foreignName: command.name, pluginId: plugin.id, pluginRoot: plugin.root, dataDir }, scope, taken);
56
- if (added === undefined)
57
- continue;
58
- taken.add(added.name);
59
- withdraw.push(added.dispose);
60
- commandNames.push(added.name);
61
- }
62
- opencode.recordAddedCommands(component.id, mount.commands.map((command, index) => ({ name: commandNames[index] ?? command.name, foreignName: command.name, template: command.component.body })));
63
- }
49
+ // Commands the plugin's `config` hook added run like the project's own OpenCode commands, while the commands row runs.
50
+ let commandNames = [];
51
+ const unbind = bindAddedCommands(forge, mount.commands, { pluginId: plugin.id, pluginRoot: plugin.root, dataDir, scope, takenNames }, (names) => {
52
+ commandNames = names;
53
+ opencode.recordAddedCommands(component.id, mount.commands.map((command, index) => ({ name: names[index] || command.name, foreignName: command.name, template: command.component.body })));
54
+ });
64
55
  const summary = [
65
56
  `opencode-plugin hooks [${mount.hooks.join(', ')}]`,
66
57
  `tools [${mount.tools.join(', ')}]`,
67
58
  // The names they are typed under in DSH.
68
- ...(commandNames.length > 0 ? [`commands [${commandNames.join(', ')}]`] : []),
59
+ ...(commandNames.some(name => name.length > 0) ? [`commands [${commandNames.filter(name => name.length > 0).join(', ')}]`] : []),
69
60
  // What its config hook changed: only `command` is applied in DSH.
70
61
  ...(mount.configChanged.length > 0 ? [`config [${mount.configChanged.join(', ')}]`] : []),
71
62
  ].join('; ');
@@ -75,8 +66,7 @@ export function startOpenCode(ctx, forge) {
75
66
  for (const tool of mount.tools)
76
67
  if (tools.get(tool) === component.id)
77
68
  tools.delete(tool);
78
- for (const dispose of withdraw)
79
- dispose();
69
+ unbind();
80
70
  await mount.dispose();
81
71
  },
82
72
  };
@@ -84,3 +74,31 @@ export function startOpenCode(ctx, forge) {
84
74
  }));
85
75
  return () => parts.dispose();
86
76
  }
77
+ /**
78
+ * Register a mounted plugin's added commands for as long as both the plugin and the commands row run: again each
79
+ * time the commands row starts, withdrawn when it stops or `dispose` runs. `record` gets, at each registration, the
80
+ * DSH name of each command in order (empty where none was given).
81
+ */
82
+ export function bindAddedCommands(forge, commands, owner, record) {
83
+ if (commands.length === 0)
84
+ return () => undefined;
85
+ const unwatch = forge.watch('commands', (api) => {
86
+ const taken = owner.takenNames();
87
+ const names = [];
88
+ const withdraw = [];
89
+ for (const command of commands) {
90
+ const added = api.registerAdded({ component: command.component, name: command.name, foreignName: command.name, pluginId: owner.pluginId, pluginRoot: owner.pluginRoot, dataDir: owner.dataDir }, owner.scope, taken);
91
+ names.push(added?.name ?? '');
92
+ if (added === undefined)
93
+ continue;
94
+ taken.add(added.name);
95
+ withdraw.push(added.dispose);
96
+ }
97
+ record(names);
98
+ return () => {
99
+ for (const dispose of withdraw)
100
+ dispose();
101
+ };
102
+ });
103
+ return unwatch;
104
+ }
@@ -9,6 +9,7 @@ import { createServer } from 'node:http';
9
9
  import { homedir } from 'node:os';
10
10
  import { join, resolve } from 'node:path';
11
11
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
12
+ import { stripTrailing } from '@kirkchinese/harness-forge-core';
12
13
  import { appendNotice } from '../../hooks/notice.js';
13
14
  import { isRecord, messagesOf, sessionInfo, userInfo, userParts } from '../convert.js';
14
15
  import { dshService } from '../../dsh/host.js';
@@ -114,7 +115,7 @@ export class OpenCodeServer {
114
115
  }
115
116
  /** OpenCode's server routes, as DSH serves them; undefined when not served. */
116
117
  async route(method, url, body) {
117
- const path = url.pathname.replace(/\/+$/u, '') || '/';
118
+ const path = stripTrailing(url.pathname, '/') || '/';
118
119
  const agents = this.core.agents();
119
120
  const sessionMatch = /^\/session\/([^/]+)(?:\/(.+))?$/u.exec(path);
120
121
  const sessionId = sessionMatch === null ? undefined : decodeURIComponent(sessionMatch[1] ?? '');
@@ -0,0 +1,13 @@
1
+ /** One place the source breaks a rule. */
2
+ export interface PathFinding {
3
+ /** File relative to the adapter directory, with `/`. */
4
+ readonly file: string;
5
+ readonly line: number;
6
+ readonly what: string;
7
+ }
8
+ /** The source with comments blanked out (newlines kept), so findings name real code lines. */
9
+ export declare function withoutComments(source: string): string;
10
+ /** Where an adapter's source hard-codes the DSH home or lists the profiles. */
11
+ export declare function hardCodedPaths(dir: string): PathFinding[];
12
+ /** The check's detail for its findings. */
13
+ export declare function pathsDetail(findings: readonly PathFinding[]): string;
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The `paths` check of `harness_verify_port`: the commonest way a generated
3
+ * adapter breaks the brief's data access rules, read from its source. It
4
+ * finds a DSH home written into the code (`~/.dsh`, `/home/<user>/.dsh`) and
5
+ * a listing of a `profiles` directory. Comments are skipped, so a source that
6
+ * documents the default `~/.dsh` beside `$DSH_HOME` passes; resolving the
7
+ * running profile as `join(home, 'profiles', name)` passes too, since only a
8
+ * listing reads other profiles.
9
+ * @module @kirkchinese/harness-forge/porting
10
+ */
11
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
12
+ import { extname, join, relative, sep } from 'node:path';
13
+ /** Source files an adapter runs: JavaScript and TypeScript, as written and as built. */
14
+ const SOURCE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx']);
15
+ /** Directories that hold others' code or history, not the adapter's. */
16
+ const SKIPPED_DIRS = new Set(['node_modules', '.git']);
17
+ /** Most source files read: an adapter is a small package, and a link to a large tree must not stall the tool. */
18
+ const FILE_LIMIT = 500;
19
+ /** Largest source file read, in bytes: bigger ones are bundles whose findings would be a dependency's. */
20
+ const SIZE_LIMIT = 1_000_000;
21
+ /** Most findings named in the check's detail; the rest are counted. */
22
+ const SHOWN_LIMIT = 8;
23
+ /** A DSH home written into the code: `~/.dsh`, or an absolute user home's `.dsh` on Linux, macOS or Windows. */
24
+ const HARD_CODED_HOME = /~[/\\]\.dsh\b|(?:\/home|\/Users|[A-Za-z]:[/\\]{1,2}Users)[/\\]{1,2}[^/\\'"`\s]+[/\\]{1,2}\.dsh\b/u;
25
+ /** A directory listing whose argument names `profiles`: a path literal or a variable named for them. */
26
+ const PROFILES_LISTING = /\b(?:readdir|readdirSync|opendir|opendirSync|glob|globSync)\s*\([^;\n]*(?:['"`/\\]profiles\b|\w*profiles\w*)/iu;
27
+ /** The source with comments blanked out (newlines kept), so findings name real code lines. */
28
+ export function withoutComments(source) {
29
+ let out = '';
30
+ let quote;
31
+ for (let index = 0; index < source.length; index++) {
32
+ const char = source[index];
33
+ const next = source[index + 1];
34
+ if (quote !== undefined) {
35
+ out += char;
36
+ if (char === '\\') {
37
+ out += next ?? '';
38
+ index++;
39
+ }
40
+ else if (char === quote)
41
+ quote = undefined;
42
+ continue;
43
+ }
44
+ if (char === '"' || char === "'" || char === '`') {
45
+ quote = char;
46
+ out += char;
47
+ continue;
48
+ }
49
+ if (char === '/' && next === '/') {
50
+ while (index < source.length && source[index] !== '\n')
51
+ index++;
52
+ out += '\n';
53
+ continue;
54
+ }
55
+ if (char === '/' && next === '*') {
56
+ const end = source.indexOf('*/', index + 2);
57
+ const stop = end === -1 ? source.length : end + 2;
58
+ out += source.slice(index, stop).replace(/[^\n]/gu, ' ');
59
+ index = stop - 1;
60
+ continue;
61
+ }
62
+ out += char;
63
+ }
64
+ return out;
65
+ }
66
+ function sourcesUnder(dir, out) {
67
+ let entries;
68
+ try {
69
+ entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
70
+ }
71
+ catch {
72
+ return;
73
+ }
74
+ for (const entry of entries) {
75
+ if (out.length >= FILE_LIMIT)
76
+ return;
77
+ const path = join(dir, entry.name);
78
+ if (entry.isDirectory()) {
79
+ if (!SKIPPED_DIRS.has(entry.name))
80
+ sourcesUnder(path, out);
81
+ }
82
+ else if (entry.isFile() && SOURCE_EXTENSIONS.has(extname(entry.name))) {
83
+ out.push(path);
84
+ }
85
+ }
86
+ }
87
+ /** Where an adapter's source hard-codes the DSH home or lists the profiles. */
88
+ export function hardCodedPaths(dir) {
89
+ const files = [];
90
+ sourcesUnder(dir, files);
91
+ const findings = [];
92
+ for (const path of files) {
93
+ let text;
94
+ try {
95
+ if (statSync(path).size > SIZE_LIMIT)
96
+ continue;
97
+ text = withoutComments(readFileSync(path, 'utf8'));
98
+ }
99
+ catch {
100
+ continue;
101
+ }
102
+ const file = relative(dir, path).split(sep).join('/');
103
+ text.split('\n').forEach((line, index) => {
104
+ const home = HARD_CODED_HOME.exec(line);
105
+ if (home !== null)
106
+ findings.push({ file, line: index + 1, what: `hard-codes the DSH home (${home[0]})` });
107
+ if (PROFILES_LISTING.test(line))
108
+ findings.push({ file, line: index + 1, what: 'lists the profiles directory' });
109
+ });
110
+ }
111
+ return findings;
112
+ }
113
+ /** The check's detail for its findings. */
114
+ export function pathsDetail(findings) {
115
+ if (findings.length === 0)
116
+ return 'the source resolves DSH paths at run time: no hard-coded DSH home and no listing of profiles';
117
+ const shown = findings.slice(0, SHOWN_LIMIT).map(item => `${item.file}:${item.line} ${item.what}`);
118
+ const more = findings.length > SHOWN_LIMIT ? `; and ${findings.length - SHOWN_LIMIT} more` : '';
119
+ return `${shown.join('; ')}${more}. Resolve the DSH home at run time from $DSH_HOME (default ~/.dsh under os.homedir()) and the profile from profileContext or $DSH_PROFILE_DIR; never read or list other profiles (the brief's data access rules)`;
120
+ }
@@ -1,8 +1,8 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
- import { type ForeignComponent, type ForeignPlugin, type Gap } from '@kirkchinese/harness-forge-core';
2
+ import { type ForeignComponent, type ForeignPlugin, type Gap, type PortRuntime } from '@kirkchinese/harness-forge-core';
3
3
  /** The preset of DSH's creation mode ("Let the agent create a plugin" in the Plugin Manager). */
4
4
  export declare const CREATOR_PRESET = "cordis";
5
- /** Where a creation session runs: a DSH Workspace, or a directory; DSH's default directory when neither. */
5
+ /** Where a creation session runs: a DSH Workspace or an explicit directory, otherwise the adapters directory. */
6
6
  export interface PortLocation {
7
7
  readonly workspaceId?: string;
8
8
  readonly cwd?: string;
@@ -15,10 +15,16 @@ export declare function briefTitle(brief: string): string;
15
15
  * plugin's manifest itself lists the manifest.
16
16
  */
17
17
  export declare function partFiles(plugin: ForeignPlugin, component: ForeignComponent): string[];
18
+ /**
19
+ * The DSH home and profile this Harness Forge runs in, resolved as DSH does:
20
+ * `$DSH_HOME` (a blank value is unset), else `~/.dsh`; the profile from the
21
+ * `profileContext` service, which only a profile-launched DSH composes.
22
+ */
23
+ export declare function portRuntime(ctx: Context, env?: NodeJS.ProcessEnv): PortRuntime;
18
24
  /** The brief for one part of a plugin, or a failure naming what is missing. */
19
- export declare function briefFor(plugin: ForeignPlugin, gaps: readonly Gap[], componentId: string): string;
25
+ export declare function briefFor(plugin: ForeignPlugin, gaps: readonly Gap[], componentId: string, runtime?: PortRuntime): string;
20
26
  /** The first message of a part's port session: the protocol, then the brief (see `prompt.ts`). */
21
- export declare function taskFor(plugin: ForeignPlugin, gaps: readonly Gap[], componentId: string, language?: string): string;
27
+ export declare function taskFor(plugin: ForeignPlugin, gaps: readonly Gap[], componentId: string, language?: string, runtime?: PortRuntime): string;
22
28
  /**
23
29
  * Start a creation-mode session and send it the task, as the Plugin
24
30
  * Manager's creation entry and a typed message would.