@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.
Files changed (246) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/lib/agents/presets.d.ts +91 -0
  6. package/lib/agents/presets.js +282 -0
  7. package/lib/agents/profiles.d.ts +58 -0
  8. package/lib/agents/profiles.js +278 -0
  9. package/lib/agents/row.d.ts +17 -0
  10. package/lib/agents/row.js +146 -0
  11. package/lib/client/styles.d.ts +8 -0
  12. package/lib/client/styles.js +89 -0
  13. package/lib/client/typert.d.ts +14 -0
  14. package/lib/client/typert.js +110 -0
  15. package/lib/client.js +22500 -0
  16. package/lib/commands/definition.d.ts +40 -0
  17. package/lib/commands/definition.js +113 -0
  18. package/lib/commands/output-styles.d.ts +42 -0
  19. package/lib/commands/output-styles.js +152 -0
  20. package/lib/commands/row.d.ts +9 -0
  21. package/lib/commands/row.js +157 -0
  22. package/lib/context/instructions.d.ts +32 -0
  23. package/lib/context/instructions.js +88 -0
  24. package/lib/context/row.d.ts +16 -0
  25. package/lib/context/row.js +17 -0
  26. package/lib/dsh/commands.d.ts +30 -0
  27. package/lib/dsh/commands.js +61 -0
  28. package/lib/dsh/host.d.ts +107 -0
  29. package/lib/dsh/host.js +214 -0
  30. package/lib/dsh/model-route.d.ts +21 -0
  31. package/lib/dsh/model-route.js +37 -0
  32. package/lib/dsh/session-records.d.ts +78 -0
  33. package/lib/dsh/session-records.js +36 -0
  34. package/lib/dsh/subagents.d.ts +46 -0
  35. package/lib/dsh/subagents.js +14 -0
  36. package/lib/forge/contract.d.ts +231 -0
  37. package/lib/forge/contract.js +43 -0
  38. package/lib/forge/ledger.d.ts +143 -0
  39. package/lib/forge/ledger.js +733 -0
  40. package/lib/forge/live-mounts.d.ts +45 -0
  41. package/lib/forge/live-mounts.js +78 -0
  42. package/lib/forge/marketplace-install.d.ts +3 -0
  43. package/lib/forge/marketplace-install.js +64 -0
  44. package/lib/forge/npm.d.ts +31 -0
  45. package/lib/forge/npm.js +60 -0
  46. package/lib/forge/projects.d.ts +94 -0
  47. package/lib/forge/projects.js +336 -0
  48. package/lib/forge/receipts.d.ts +5 -0
  49. package/lib/forge/receipts.js +31 -0
  50. package/lib/forge/row.d.ts +32 -0
  51. package/lib/forge/row.js +59 -0
  52. package/lib/forge/service.d.ts +105 -0
  53. package/lib/forge/service.js +274 -0
  54. package/lib/forge/settings.d.ts +41 -0
  55. package/lib/forge/settings.js +115 -0
  56. package/lib/forge/state.d.ts +69 -0
  57. package/lib/forge/state.js +150 -0
  58. package/lib/forge/trust.d.ts +48 -0
  59. package/lib/forge/trust.js +107 -0
  60. package/lib/forge/turns.d.ts +13 -0
  61. package/lib/forge/turns.js +56 -0
  62. package/lib/hooks/broker/engine.d.ts +112 -0
  63. package/lib/hooks/broker/engine.js +728 -0
  64. package/lib/hooks/broker/helpers.d.ts +10 -0
  65. package/lib/hooks/broker/helpers.js +22 -0
  66. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  67. package/lib/hooks/broker/lifecycle.js +342 -0
  68. package/lib/hooks/broker/session-events.d.ts +22 -0
  69. package/lib/hooks/broker/session-events.js +196 -0
  70. package/lib/hooks/broker/tools.d.ts +52 -0
  71. package/lib/hooks/broker/tools.js +424 -0
  72. package/lib/hooks/broker/types.d.ts +262 -0
  73. package/lib/hooks/broker/types.js +1 -0
  74. package/lib/hooks/broker.d.ts +80 -0
  75. package/lib/hooks/broker.js +95 -0
  76. package/lib/hooks/codex-user.d.ts +5 -0
  77. package/lib/hooks/codex-user.js +109 -0
  78. package/lib/hooks/condition.d.ts +11 -0
  79. package/lib/hooks/condition.js +181 -0
  80. package/lib/hooks/config.d.ts +85 -0
  81. package/lib/hooks/config.js +150 -0
  82. package/lib/hooks/matcher.d.ts +20 -0
  83. package/lib/hooks/matcher.js +39 -0
  84. package/lib/hooks/notice.d.ts +17 -0
  85. package/lib/hooks/notice.js +39 -0
  86. package/lib/hooks/output.d.ts +56 -0
  87. package/lib/hooks/output.js +214 -0
  88. package/lib/hooks/permissions.d.ts +14 -0
  89. package/lib/hooks/permissions.js +109 -0
  90. package/lib/hooks/process.d.ts +47 -0
  91. package/lib/hooks/process.js +134 -0
  92. package/lib/hooks/row.d.ts +17 -0
  93. package/lib/hooks/row.js +94 -0
  94. package/lib/hooks/runner.d.ts +85 -0
  95. package/lib/hooks/runner.js +293 -0
  96. package/lib/hooks/shell-commands.d.ts +19 -0
  97. package/lib/hooks/shell-commands.js +177 -0
  98. package/lib/hooks/shell.d.ts +43 -0
  99. package/lib/hooks/shell.js +126 -0
  100. package/lib/hooks/transcript.d.ts +28 -0
  101. package/lib/hooks/transcript.js +141 -0
  102. package/lib/hooks/vocabulary.d.ts +57 -0
  103. package/lib/hooks/vocabulary.js +364 -0
  104. package/lib/index.d.ts +31 -0
  105. package/lib/index.js +287 -0
  106. package/lib/mcp/auth.d.ts +35 -0
  107. package/lib/mcp/auth.js +178 -0
  108. package/lib/mcp/catalog.d.ts +36 -0
  109. package/lib/mcp/catalog.js +61 -0
  110. package/lib/mcp/mount.d.ts +75 -0
  111. package/lib/mcp/mount.js +217 -0
  112. package/lib/mcp/remote.d.ts +45 -0
  113. package/lib/mcp/remote.js +143 -0
  114. package/lib/mcp/row.d.ts +9 -0
  115. package/lib/mcp/row.js +131 -0
  116. package/lib/mods/bundler.d.ts +38 -0
  117. package/lib/mods/bundler.js +157 -0
  118. package/lib/mods/chain.d.ts +103 -0
  119. package/lib/mods/chain.js +436 -0
  120. package/lib/mods/claude.d.ts +27 -0
  121. package/lib/mods/claude.js +56 -0
  122. package/lib/mods/engine.d.ts +160 -0
  123. package/lib/mods/engine.js +701 -0
  124. package/lib/mods/expect.d.ts +8 -0
  125. package/lib/mods/expect.js +248 -0
  126. package/lib/mods/host.d.ts +105 -0
  127. package/lib/mods/host.js +462 -0
  128. package/lib/mods/loader.d.ts +53 -0
  129. package/lib/mods/loader.js +227 -0
  130. package/lib/mods/ops.d.ts +13 -0
  131. package/lib/mods/ops.js +117 -0
  132. package/lib/mods/row.d.ts +9 -0
  133. package/lib/mods/row.js +77 -0
  134. package/lib/mods/runtime.d.ts +60 -0
  135. package/lib/mods/runtime.js +133 -0
  136. package/lib/mods/service/commands.d.ts +17 -0
  137. package/lib/mods/service/commands.js +121 -0
  138. package/lib/mods/service/drawings.d.ts +36 -0
  139. package/lib/mods/service/drawings.js +64 -0
  140. package/lib/mods/service/sessions.d.ts +63 -0
  141. package/lib/mods/service/sessions.js +345 -0
  142. package/lib/mods/service/tools.d.ts +32 -0
  143. package/lib/mods/service/tools.js +253 -0
  144. package/lib/mods/service/turns.d.ts +32 -0
  145. package/lib/mods/service/turns.js +161 -0
  146. package/lib/mods/service/types.d.ts +151 -0
  147. package/lib/mods/service/types.js +1 -0
  148. package/lib/mods/service.d.ts +72 -0
  149. package/lib/mods/service.js +104 -0
  150. package/lib/mods/surfaces.d.ts +93 -0
  151. package/lib/mods/surfaces.js +309 -0
  152. package/lib/mods/values.d.ts +30 -0
  153. package/lib/mods/values.js +95 -0
  154. package/lib/opencode/bun.d.ts +40 -0
  155. package/lib/opencode/bun.js +156 -0
  156. package/lib/opencode/convert.d.ts +53 -0
  157. package/lib/opencode/convert.js +255 -0
  158. package/lib/opencode/row.d.ts +9 -0
  159. package/lib/opencode/row.js +86 -0
  160. package/lib/opencode/runtime/core.d.ts +74 -0
  161. package/lib/opencode/runtime/core.js +249 -0
  162. package/lib/opencode/runtime/events.d.ts +80 -0
  163. package/lib/opencode/runtime/events.js +281 -0
  164. package/lib/opencode/runtime/mount.d.ts +27 -0
  165. package/lib/opencode/runtime/mount.js +283 -0
  166. package/lib/opencode/runtime/server.d.ts +27 -0
  167. package/lib/opencode/runtime/server.js +353 -0
  168. package/lib/opencode/runtime/types.d.ts +109 -0
  169. package/lib/opencode/runtime/types.js +1 -0
  170. package/lib/opencode/runtime.d.ts +55 -0
  171. package/lib/opencode/runtime.js +79 -0
  172. package/lib/porting/port-gap.d.ts +30 -0
  173. package/lib/porting/port-gap.js +122 -0
  174. package/lib/porting/port-sessions.d.ts +41 -0
  175. package/lib/porting/port-sessions.js +98 -0
  176. package/lib/porting/prompt.d.ts +23 -0
  177. package/lib/porting/prompt.js +49 -0
  178. package/lib/porting/row.d.ts +16 -0
  179. package/lib/porting/row.js +25 -0
  180. package/lib/porting/verify-port.d.ts +53 -0
  181. package/lib/porting/verify-port.js +104 -0
  182. package/lib/presets/fs-search.d.ts +25 -0
  183. package/lib/presets/fs-search.js +17 -0
  184. package/lib/presets/tool-filter.d.ts +35 -0
  185. package/lib/presets/tool-filter.js +91 -0
  186. package/lib/sessions/claude.d.ts +29 -0
  187. package/lib/sessions/claude.js +83 -0
  188. package/lib/sessions/codex.d.ts +30 -0
  189. package/lib/sessions/codex.js +303 -0
  190. package/lib/sessions/opencode.d.ts +32 -0
  191. package/lib/sessions/opencode.js +320 -0
  192. package/lib/sessions/row.d.ts +14 -0
  193. package/lib/sessions/row.js +35 -0
  194. package/lib/shared/invocation.d.ts +169 -0
  195. package/lib/shared/invocation.js +325 -0
  196. package/lib/shared/render.d.ts +72 -0
  197. package/lib/shared/render.js +588 -0
  198. package/lib/shared/util.d.ts +21 -0
  199. package/lib/shared/util.js +32 -0
  200. package/lib/skills/bundled.d.ts +3 -0
  201. package/lib/skills/bundled.js +42 -0
  202. package/lib/skills/provider.d.ts +72 -0
  203. package/lib/skills/provider.js +340 -0
  204. package/lib/skills/row.d.ts +22 -0
  205. package/lib/skills/row.js +204 -0
  206. package/lib/workbench/adapter-coverage.d.ts +47 -0
  207. package/lib/workbench/adapter-coverage.js +102 -0
  208. package/lib/workbench/model-tools.d.ts +10 -0
  209. package/lib/workbench/model-tools.js +122 -0
  210. package/lib/workbench/overview.d.ts +103 -0
  211. package/lib/workbench/overview.js +159 -0
  212. package/lib/workbench/remote.d.ts +118 -0
  213. package/lib/workbench/remote.js +422 -0
  214. package/lib/workbench/row.d.ts +15 -0
  215. package/lib/workbench/row.js +16 -0
  216. package/lib/workbench/settings.d.ts +15 -0
  217. package/lib/workbench/settings.js +56 -0
  218. package/lib/workbench/workbench.d.ts +100 -0
  219. package/lib/workbench/workbench.js +260 -0
  220. package/locale/agents/en.json +6 -0
  221. package/locale/agents/zh.json +6 -0
  222. package/locale/commands/en.json +6 -0
  223. package/locale/commands/zh.json +6 -0
  224. package/locale/context/en.json +6 -0
  225. package/locale/context/zh.json +6 -0
  226. package/locale/en.json +6 -0
  227. package/locale/hooks/en.json +6 -0
  228. package/locale/hooks/zh.json +6 -0
  229. package/locale/mcp/en.json +6 -0
  230. package/locale/mcp/zh.json +6 -0
  231. package/locale/mods/en.json +6 -0
  232. package/locale/mods/zh.json +6 -0
  233. package/locale/opencode/en.json +6 -0
  234. package/locale/opencode/zh.json +6 -0
  235. package/locale/porter/en.json +6 -0
  236. package/locale/porter/zh.json +6 -0
  237. package/locale/sessions/en.json +6 -0
  238. package/locale/sessions/zh.json +6 -0
  239. package/locale/skills/en.json +6 -0
  240. package/locale/skills/zh.json +6 -0
  241. package/locale/workbench/en.json +6 -0
  242. package/locale/workbench/zh.json +6 -0
  243. package/locale/zh.json +6 -0
  244. package/package.json +246 -3
  245. package/runtime/opencode-host.mjs +270 -0
  246. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,336 @@
1
+ import { appendRecord } from '../dsh/session-records.js';
2
+ import { homedir } from 'node:os';
3
+ import { claudeMcpApproval, dialects, isInside, planPlugin, restrictiveSettings, trustRequirement, } from '@kirkchinese/harness-forge-core';
4
+ import { appendNotice } from '../hooks/notice.js';
5
+ import { pluginDataDir } from '../mcp/mount.js';
6
+ import { messageOf } from '../shared/util.js';
7
+ import { mountKindOf } from './contract.js';
8
+ import { failedToSwitchOff, inactive } from './ledger.js';
9
+ import { LiveMounts } from './live-mounts.js';
10
+ import { WAITING_FOR_APPROVAL, WAITING_FOR_TRUST } from './trust.js';
11
+ /** Whether a project part may run now: undefined when it may, else the outcome it gets instead. */
12
+ function gate(component, plugin, cwd, trust) {
13
+ if (trustRequirement(component) === undefined)
14
+ return undefined;
15
+ const waiting = (message) => ({ componentId: component.id, status: 'inactive', level: 'L0', evidence: 'source', message });
16
+ if (!trust.trusted)
17
+ return waiting(WAITING_FOR_TRUST);
18
+ // A `.mcp.json` server: Claude Code's rejection always holds; its approval is needed unless the person trusted the workspace here.
19
+ if (component.kind === 'mcp' && plugin.source === 'claude-code' && component.metadata?.['scope'] === 'project') {
20
+ const approval = claudeMcpApproval(component.name, trust.workspace, cwd, true, homedir());
21
+ if (approval === 'disabled')
22
+ return { componentId: component.id, status: 'skipped', level: 'L0', evidence: 'source', message: 'disabled in Claude Code (disabledMcpjsonServers)' };
23
+ if (approval === 'pending' && !trust.sources.includes('forge'))
24
+ return waiting(WAITING_FOR_APPROVAL);
25
+ }
26
+ return undefined;
27
+ }
28
+ /** The project assets of a directory, one plugin per dialect that has any. */
29
+ function projectPlugins(cwd) {
30
+ return dialects().map(dialect => dialect.projectAssets?.(cwd, homedir())).filter((plugin) => plugin !== undefined);
31
+ }
32
+ /** The parts of a directory's project assets that wait for trust (or approval) now. */
33
+ export function waitingParts(cwd, trust) {
34
+ return projectPlugins(cwd).flatMap(plugin => plugin.components.flatMap((component) => {
35
+ const outcome = gate(component, plugin, cwd, trust);
36
+ if (outcome?.status !== 'inactive')
37
+ return [];
38
+ return [{ pluginId: plugin.id, componentId: component.id, kind: component.kind, name: component.name, does: trustRequirement(component) ?? '', message: outcome.message ?? '' }];
39
+ }));
40
+ }
41
+ /**
42
+ * Per-session project assets, mounted through the same mounters as installed
43
+ * plugins, in the session's scope. Parts that run code or reach the network
44
+ * wait until the workspace is trusted; trusting it here mounts them in the
45
+ * sessions already open in it.
46
+ */
47
+ export class ProjectAssets {
48
+ ledger;
49
+ dataRoot;
50
+ trust;
51
+ fault;
52
+ mounts = new Map();
53
+ /** Each session's mounts, once its first mount finished. */
54
+ settled = new Map();
55
+ /** Mounts of ended sessions whose withdrawal failed: kept, and withdrawn again on the next release or at dispose. */
56
+ retained = new Map();
57
+ /** Mounting, reconciling and releasing run one at a time, in the order they were asked for. */
58
+ chain = Promise.resolve();
59
+ /** Bumped on every trust change: a mount that was running across one is stale. */
60
+ generation = 0;
61
+ stopTrust;
62
+ constructor(ledger, dataRoot, trust, fault) {
63
+ this.ledger = ledger;
64
+ this.dataRoot = dataRoot;
65
+ this.trust = trust;
66
+ this.fault = fault;
67
+ this.stopTrust = trust.onChange((workspace) => {
68
+ this.generation += 1;
69
+ void this.serial(() => this.reconcile(workspace)).catch((error) => this.fault?.(error));
70
+ });
71
+ }
72
+ /** A directory's trust now, with the generation it belongs to: read together, with no await between. */
73
+ snapshot(cwd) {
74
+ return { trust: this.trust.state(cwd), generation: this.generation };
75
+ }
76
+ /** Run `task` after everything asked for before it. */
77
+ serial(task) {
78
+ const run = this.chain.then(task);
79
+ this.chain = run.catch(() => undefined);
80
+ return run;
81
+ }
82
+ /**
83
+ * Trust (or stop trusting) a workspace in Harness Forge, and return once its
84
+ * open sessions have mounted or withdrawn what changed, with the parts in it
85
+ * whose withdrawal failed: they are still live, and setting trust again retries.
86
+ */
87
+ async setTrust(cwd, trusted) {
88
+ const { workspace } = this.trust.set(cwd, trusted);
89
+ await this.chain;
90
+ const mounts = [...this.settled.values(), ...this.retained.values()].flat().filter(mount => isInside(workspace, mount.workspace));
91
+ return { decision: this.trust.state(cwd), stillLive: mounts.flatMap(mount => mount.live.stuck()) };
92
+ }
93
+ /**
94
+ * Mount the project assets of a new top-level session, once: every caller
95
+ * (the `harness-forge` row, the hooks row before SessionStart) waits for
96
+ * the same mount.
97
+ */
98
+ prepare(agent, cwd) {
99
+ const sessionId = agent.session.header.id;
100
+ if ((agent.session.header.delegationDepth ?? 0) > 0)
101
+ return Promise.resolve();
102
+ let pending = this.mounts.get(sessionId);
103
+ if (pending === undefined) {
104
+ pending = this.serial(() => this.mountAll(agent, cwd));
105
+ this.mounts.set(sessionId, pending);
106
+ }
107
+ return pending.then(() => undefined, () => undefined);
108
+ }
109
+ /** The workspaces of the open sessions, with their trust and what waits for it. */
110
+ async workspaces() {
111
+ const byWorkspace = new Map();
112
+ for (const pending of this.mounts.values()) {
113
+ for (const mount of await pending.catch(() => []))
114
+ if (!byWorkspace.has(mount.workspace))
115
+ byWorkspace.set(mount.workspace, mount.cwd);
116
+ }
117
+ return [...byWorkspace.values()].map((cwd) => {
118
+ const state = this.trust.state(cwd);
119
+ return { ...state, cwd, waiting: waitingParts(cwd, state) };
120
+ });
121
+ }
122
+ async mountAll(agent, cwd) {
123
+ const plugins = projectPlugins(cwd);
124
+ const scoped = agent.ctx;
125
+ if (plugins.length === 0 || scoped === undefined)
126
+ return [];
127
+ const scope = { ctx: scoped, sessionId: agent.session.header.id };
128
+ const { workspace } = this.trust.state(cwd);
129
+ const mounts = [];
130
+ for (const plugin of plugins) {
131
+ const mount = {
132
+ sessionId: agent.session.header.id,
133
+ root: plugin.root,
134
+ plugin,
135
+ agent,
136
+ scope,
137
+ cwd,
138
+ workspace,
139
+ outcomes: [],
140
+ live: new LiveMounts((error) => this.fault?.(error)),
141
+ commandNames: new Map(),
142
+ waiting: new Set(),
143
+ unsettled: new Set(),
144
+ };
145
+ await this.mountParts(mount, this.snapshot(cwd), plugin.components.map(component => component.id));
146
+ mounts.push(mount);
147
+ }
148
+ this.settled.set(agent.session.header.id, mounts);
149
+ return mounts;
150
+ }
151
+ /**
152
+ * Trust changed for a workspace: mount what now may run in its open
153
+ * sessions, and withdraw what no longer may (trust revoked).
154
+ */
155
+ async reconcile(workspace) {
156
+ // Runs in the chain: every session mounted before it has settled, and those after read the new trust themselves.
157
+ for (const mount of [...this.settled.values()].flat()) {
158
+ if (!isInside(workspace, mount.workspace) && mount.unsettled.size === 0)
159
+ continue;
160
+ const trust = this.trust.state(mount.cwd);
161
+ const changed = mount.plugin.components.filter((component) => {
162
+ if (mount.unsettled.has(component.id))
163
+ return true;
164
+ if (trustRequirement(component) === undefined)
165
+ return false;
166
+ const held = gate(component, mount.plugin, mount.cwd, trust)?.status === 'inactive';
167
+ return held !== mount.waiting.has(component.id);
168
+ }).map(component => component.id);
169
+ if (changed.length === 0)
170
+ continue;
171
+ // A part now held back is withdrawn first (a settings part stays, restricted); one now allowed replaces its restricted form.
172
+ await mount.live.release(live => changed.includes(live.componentId));
173
+ // Trust may have changed during the withdrawal: mount by what holds after it.
174
+ await this.mountParts(mount, this.snapshot(mount.cwd), changed);
175
+ }
176
+ }
177
+ /** Mount the given parts of a session's project assets that may run; the others wait. */
178
+ async mountParts(mount, initial, componentIds) {
179
+ let { trust, generation } = initial;
180
+ const { plugin, scope, agent } = mount;
181
+ const plan = planPlugin(plugin);
182
+ const components = new Map(plugin.components.map(component => [component.id, component]));
183
+ const wanted = new Set(componentIds);
184
+ const outcomes = new Map(mount.outcomes.map(outcome => [outcome.componentId, outcome]));
185
+ const used = new Map();
186
+ const mountedNow = [];
187
+ for (const action of plan.actions) {
188
+ const component = action.componentId === undefined ? undefined : components.get(action.componentId);
189
+ if (component === undefined || !wanted.has(component.id))
190
+ continue;
191
+ const kind = mountKindOf(action, component);
192
+ if (typeof kind !== 'string') {
193
+ outcomes.set(component.id, { componentId: component.id, status: 'skipped', level: 'L0', evidence: 'source', message: kind.skipped });
194
+ continue;
195
+ }
196
+ // Its withdrawal failed: it stays live as it was, and the next reconcile retries.
197
+ const stuck = mount.live.has(action.id) ? mount.live.failure(action.id) : undefined;
198
+ if (stuck !== undefined) {
199
+ outcomes.set(component.id, failedToSwitchOff(component.id, stuck));
200
+ mount.unsettled.add(component.id);
201
+ continue;
202
+ }
203
+ // Trust changed since this began: decide the rest by what holds now.
204
+ if (generation !== this.generation) {
205
+ trust = this.trust.state(mount.cwd);
206
+ generation = this.generation;
207
+ }
208
+ const held = gate(component, plugin, mount.cwd, trust);
209
+ // Only what reduces privilege is applied while the rest waits.
210
+ const restricted = held?.status === 'inactive' && component.kind === 'settings' ? restrictiveSettings(component) : undefined;
211
+ if (held !== undefined && restricted === undefined) {
212
+ outcomes.set(component.id, held);
213
+ if (held.status === 'inactive')
214
+ mount.waiting.add(component.id);
215
+ mount.unsettled.delete(component.id);
216
+ continue;
217
+ }
218
+ if (held !== undefined)
219
+ mount.waiting.add(component.id);
220
+ else
221
+ mount.waiting.delete(component.id);
222
+ const mounter = this.ledger.mounters.get(kind);
223
+ if (mounter === undefined) {
224
+ outcomes.set(component.id, inactive(component.id, kind));
225
+ continue;
226
+ }
227
+ used.set(mounter, kind);
228
+ try {
229
+ const applied = await mounter.mount({
230
+ action,
231
+ component: restricted ?? component,
232
+ plugin,
233
+ dataDir: pluginDataDir(this.dataRoot, plugin.id),
234
+ scope,
235
+ commandNames: mount.commandNames,
236
+ takenNames: () => this.ledger.allCommandNames(),
237
+ });
238
+ if (generation !== this.generation) {
239
+ // Trust changed while it mounted. A part that needed trust is rolled back; the reconcile queued behind decides it again.
240
+ mount.unsettled.add(component.id);
241
+ if (held === undefined && trustRequirement(component) !== undefined) {
242
+ // Withdrawn through the live set, so a withdrawal that fails stays tracked and is retried.
243
+ if (applied.disposer !== undefined)
244
+ mount.live.add(action.id, { componentId: component.id, kind, dispose: applied.disposer });
245
+ const { failed } = await mount.live.release((_live, actionId) => actionId === action.id);
246
+ mount.waiting.add(component.id);
247
+ outcomes.set(component.id, failed[0] !== undefined ? failedToSwitchOff(component.id, failed[0].reason) : { componentId: component.id, status: 'inactive', level: 'L0', evidence: 'source', message: WAITING_FOR_TRUST });
248
+ continue;
249
+ }
250
+ }
251
+ else
252
+ mount.unsettled.delete(component.id);
253
+ outcomes.set(component.id, held !== undefined ? { ...held, message: `${held.message ?? ''}; its deny and ask rules already apply` } : applied.outcome);
254
+ mountedNow.push(component.id);
255
+ if (applied.disposer !== undefined)
256
+ mount.live.add(action.id, { componentId: component.id, kind, dispose: applied.disposer });
257
+ }
258
+ catch (error) {
259
+ outcomes.set(component.id, { componentId: component.id, status: 'failed', level: 'L0', evidence: 'runtime', message: messageOf(error) });
260
+ }
261
+ }
262
+ // The first model request must offer every project agent.
263
+ for (const [mounter, kind] of used) {
264
+ await mounter.settle?.(scope).catch((error) => {
265
+ for (const id of mountedNow) {
266
+ const outcome = outcomes.get(id);
267
+ const component = components.get(id);
268
+ const action = plan.actions.find((candidate) => candidate.componentId === id);
269
+ if (outcome?.status !== 'mounted' || component === undefined || action === undefined || mountKindOf(action, component) !== kind)
270
+ continue;
271
+ outcomes.set(id, { ...outcome, status: 'failed', level: 'L0', evidence: 'runtime', message: `the ${kind} mount did not settle: ${messageOf(error)}` });
272
+ }
273
+ });
274
+ }
275
+ mount.outcomes.splice(0, mount.outcomes.length, ...plugin.components.flatMap(component => outcomes.get(component.id) ?? []));
276
+ try {
277
+ appendRecord(agent.session, 'plugin:harness-forge/project', {
278
+ root: plugin.root,
279
+ pluginId: plugin.id,
280
+ components: plugin.components.map(component => ({ id: component.id, kind: component.kind, name: component.name })),
281
+ outcomes: mount.outcomes,
282
+ });
283
+ }
284
+ catch {
285
+ // The record is informational.
286
+ }
287
+ const failed = mount.outcomes.filter(outcome => outcome.status === 'failed' && wanted.has(outcome.componentId));
288
+ const names = new Map(plugin.components.map(component => [component.id, `${component.kind} ${component.name}`]));
289
+ const harness = plugin.source === 'codex' ? 'Codex' : 'Claude Code';
290
+ if (failed.length > 0) {
291
+ appendNotice(agent.session, {
292
+ kind: 'hook-error',
293
+ event: 'ProjectAssets',
294
+ plugin: plugin.id,
295
+ text: `${harness} project assets of ${plugin.root}: ${failed.map(outcome => `${names.get(outcome.componentId) ?? outcome.componentId}: ${outcome.message ?? 'failed'}`).join('; ')}`,
296
+ });
297
+ }
298
+ const waiting = [...mount.waiting].filter(id => wanted.has(id));
299
+ if (waiting.length > 0) {
300
+ appendNotice(agent.session, {
301
+ kind: 'system-message',
302
+ event: 'ProjectAssets',
303
+ plugin: plugin.id,
304
+ text: `${harness} project assets of ${plugin.root} that run code wait until you trust ${trust.workspace} (Harness Forge → Migrated): ${waiting.map(id => names.get(id) ?? id).join(', ')}`,
305
+ });
306
+ }
307
+ }
308
+ /** Withdraw a session's project assets. */
309
+ async release(sessionId) {
310
+ if (!this.mounts.has(sessionId) && !this.retained.has(sessionId))
311
+ return;
312
+ this.mounts.delete(sessionId);
313
+ await this.serial(async () => {
314
+ const mounts = this.settled.get(sessionId) ?? this.retained.get(sessionId) ?? [];
315
+ this.settled.delete(sessionId);
316
+ const left = [];
317
+ for (const mount of mounts)
318
+ if ((await mount.live.release()).failed.length > 0)
319
+ left.push(mount);
320
+ if (left.length > 0) {
321
+ this.retained.set(sessionId, left);
322
+ return;
323
+ }
324
+ this.retained.delete(sessionId);
325
+ if (mounts.length === 0)
326
+ return;
327
+ for (const mounter of this.ledger.mounters.values())
328
+ await mounter.release?.({ sessionId }).catch((error) => this.fault?.(error));
329
+ });
330
+ }
331
+ async dispose() {
332
+ this.stopTrust();
333
+ for (const id of new Set([...this.mounts.keys(), ...this.retained.keys()]))
334
+ await this.release(id);
335
+ }
336
+ }
@@ -0,0 +1,5 @@
1
+ import type { Receipt } from '@kirkchinese/harness-forge-core';
2
+ /** Write one receipt atomically under `dir/<id>.json`. */
3
+ export declare function writeReceipt(receipt: Receipt, dir: string): string;
4
+ /** Read one receipt, or undefined when absent/malformed. */
5
+ export declare function readReceipt(id: string, dir: string): Receipt | undefined;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Receipt persistence. A receipt is the durable record of what apply actually
3
+ * did; it is small, JSON-serializable and safe to expose in diagnostics.
4
+ * @module @kirkchinese/harness-forge
5
+ */
6
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ /** Write one receipt atomically under `dir/<id>.json`. */
9
+ export function writeReceipt(receipt, dir) {
10
+ mkdirSync(dir, { recursive: true });
11
+ const path = join(dir, `${receipt.id}.json`);
12
+ const temporary = `${path}.tmp`;
13
+ writeFileSync(temporary, `${JSON.stringify(receipt, null, 2)}\n`, 'utf8');
14
+ renameSync(temporary, path);
15
+ return path;
16
+ }
17
+ /** Read one receipt, or undefined when absent/malformed. */
18
+ export function readReceipt(id, dir) {
19
+ try {
20
+ const value = JSON.parse(readFileSync(join(dir, `${id}.json`), 'utf8'));
21
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
22
+ return undefined;
23
+ const receipt = value;
24
+ if (typeof receipt['id'] !== 'string' || typeof receipt['pluginId'] !== 'string')
25
+ return undefined;
26
+ return value;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * What every capability row does the same way: find the shared service,
3
+ * start isolated (a row that throws while starting is logged and recorded,
4
+ * and the other rows go on), and report its listeners' failures.
5
+ * @module @kirkchinese/harness-forge
6
+ */
7
+ import type { Context } from '@deepseek-ai/cordis';
8
+ import type { ComponentOutcome, ForeignComponent } from '@kirkchinese/harness-forge-core';
9
+ import type { Disposer } from './contract.js';
10
+ import { type HarnessForge } from './service.js';
11
+ /** A component's outcome once mounted: `mounted` at most; only a runtime observation upgrades it. */
12
+ export declare function mounted(component: ForeignComponent, level: ComponentOutcome['level'], message?: string): ComponentOutcome;
13
+ /**
14
+ * Run one row on the shared service for as long as the row's context lives.
15
+ * A start that throws is logged and recorded as the row's fault; its
16
+ * listeners' failures are recorded too.
17
+ */
18
+ export declare function rowEffect(ctx: Context, row: string, start: (forge: HarnessForge) => Disposer): void;
19
+ /**
20
+ * The parts one row starts, each isolated: a part that throws is logged and
21
+ * recorded and the row's other parts start; teardown runs every part's
22
+ * disposer, last started first, each isolated too.
23
+ */
24
+ export declare class Parts {
25
+ private readonly ctx;
26
+ private readonly forge;
27
+ private readonly row;
28
+ private readonly disposers;
29
+ constructor(ctx: Context, forge: HarnessForge, row: string);
30
+ add(label: string, start: () => Disposer | void): void;
31
+ dispose(): Promise<void>;
32
+ }
@@ -0,0 +1,59 @@
1
+ import { reportFaults } from '../dsh/host.js';
2
+ import { FORGE_SERVICE } from './service.js';
3
+ import { disposeAll, loggerOf, messageOf } from '../shared/util.js';
4
+ /** A component's outcome once mounted: `mounted` at most; only a runtime observation upgrades it. */
5
+ export function mounted(component, level, message) {
6
+ return { componentId: component.id, status: 'mounted', level, evidence: 'source', ...(message !== undefined ? { message } : {}) };
7
+ }
8
+ /**
9
+ * Run one row on the shared service for as long as the row's context lives.
10
+ * A start that throws is logged and recorded as the row's fault; its
11
+ * listeners' failures are recorded too.
12
+ */
13
+ export function rowEffect(ctx, row, start) {
14
+ ctx.effect(() => {
15
+ const forge = ctx.get(FORGE_SERVICE);
16
+ if (forge === undefined)
17
+ return () => { };
18
+ const stopReporting = reportFaults(ctx, (error) => { forge.fault(row, error); });
19
+ let stop = () => { };
20
+ try {
21
+ stop = start(forge);
22
+ }
23
+ catch (error) {
24
+ loggerOf(ctx)?.warn?.(`harness-forge: the ${row} row did not start: ${messageOf(error)}`);
25
+ forge.fault(row, error);
26
+ }
27
+ return () => disposeAll(loggerOf(ctx), row, [stop, stopReporting]);
28
+ }, `harness-forge.${row}`);
29
+ }
30
+ /**
31
+ * The parts one row starts, each isolated: a part that throws is logged and
32
+ * recorded and the row's other parts start; teardown runs every part's
33
+ * disposer, last started first, each isolated too.
34
+ */
35
+ export class Parts {
36
+ ctx;
37
+ forge;
38
+ row;
39
+ disposers = [];
40
+ constructor(ctx, forge, row) {
41
+ this.ctx = ctx;
42
+ this.forge = forge;
43
+ this.row = row;
44
+ }
45
+ add(label, start) {
46
+ try {
47
+ const dispose = start();
48
+ if (dispose !== undefined)
49
+ this.disposers.push(dispose);
50
+ }
51
+ catch (error) {
52
+ loggerOf(this.ctx)?.warn?.(`harness-forge: ${this.row}: ${label} did not start: ${messageOf(error)}`);
53
+ this.forge.fault(this.row, error);
54
+ }
55
+ }
56
+ dispose() {
57
+ return disposeAll(loggerOf(this.ctx), this.row, this.disposers.splice(0).reverse());
58
+ }
59
+ }
@@ -0,0 +1,105 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { type ForeignPlugin, type MarketplaceIndex, type Plan } from '@kirkchinese/harness-forge-core';
3
+ import { type ForeignShell } from '../hooks/shell.js';
4
+ import { Invocations } from '../shared/invocation.js';
5
+ import type { InstalledPluginRecord } from './state.js';
6
+ import type { Disposer, MountKind, Mounter, RowApis } from './contract.js';
7
+ import { Ledger, type ApplyResult, type InstallReport } from './ledger.js';
8
+ import { ProjectAssets } from './projects.js';
9
+ import { ImportedSettings } from './settings.js';
10
+ export type { AgentReport, ApplyResult, HookReport, InstallReport, McpReport } from './ledger.js';
11
+ /** The service name the `harness-forge` row provides. */
12
+ export declare const FORGE_SERVICE = "harnessForge";
13
+ declare module '@deepseek-ai/cordis' {
14
+ interface Context {
15
+ harnessForge: HarnessForge;
16
+ }
17
+ }
18
+ /** A failure of one row's listener or part, kept for the workbench. */
19
+ export interface RowFault {
20
+ readonly row: string;
21
+ readonly at: string;
22
+ readonly message: string;
23
+ }
24
+ /** The shared service. */
25
+ export declare class HarnessForge {
26
+ readonly ctx: Context;
27
+ readonly statePath: string;
28
+ readonly dataRoot: string;
29
+ /** The shell imported hooks, commands and mods run in. */
30
+ readonly shell: ForeignShell;
31
+ readonly settings: ImportedSettings;
32
+ /** Turn-scoped effects of invoked skills and commands (`allowed-tools`, `model`, `context: fork`, ...). */
33
+ readonly invocations: Invocations;
34
+ /** Claude Code and Codex project assets per session. */
35
+ readonly projects: ProjectAssets;
36
+ readonly ledger: Ledger;
37
+ private readonly apis;
38
+ private readonly watchers;
39
+ private readonly recentFaults;
40
+ /**
41
+ * @param ctx - the `harness-forge` row's context.
42
+ * @param statePath - the ledger file.
43
+ * @param dataRoot - profile-local writable directory (shims, OAuth state, mod store).
44
+ */
45
+ constructor(ctx: Context, statePath: string, dataRoot: string);
46
+ /** A session's working directory, as hooks and commands see it. */
47
+ directory(agent: unknown, signal: AbortSignal): Promise<string>;
48
+ /** Register the mounter of one kind of component; see {@link Ledger.registerMounter}. */
49
+ registerMounter(kind: MountKind, mounter: Mounter): Disposer;
50
+ /** Offer a row's API to the other rows while the row runs. */
51
+ provide<K extends keyof RowApis>(name: K, api: RowApis[K]): Disposer;
52
+ /** A row's API, or undefined while that row is off. */
53
+ lookup<K extends keyof RowApis>(name: K): RowApis[K] | undefined;
54
+ /**
55
+ * Use a row's API whenever it is there: `use` runs now if the row runs, and
56
+ * again each time it starts; what `use` returns is released when the row
57
+ * stops or the returned disposer runs.
58
+ */
59
+ watch<K extends keyof RowApis>(name: K, use: (api: RowApis[K]) => Disposer | void): Disposer;
60
+ private use;
61
+ private release;
62
+ /** Record a row's failure (a listener that threw, a part that did not start) for the workbench. */
63
+ fault(row: string, error: unknown): void;
64
+ /** The latest row failures, oldest first. */
65
+ faults(): readonly RowFault[];
66
+ /** Runtime evidence for one component. */
67
+ observe(componentId: string, signal: string, ok: boolean, detail: string): void;
68
+ /** Withdraw a condition that no longer holds, such as a sign-in that completed. */
69
+ clearObservation(componentId: string, signal: string): void;
70
+ /**
71
+ * Restore the durable ledger, then install `preload` roots. An entry may
72
+ * name the dialect to read a multi-harness root as: `codex:<path>`. It
73
+ * takes the ledger's queue at once, so no install or removal can run
74
+ * before the ledger is restored (and write a ledger without its records).
75
+ */
76
+ start(preload?: readonly string[]): Promise<void>;
77
+ /** Settles once every queued install, restore and re-apply (a row that just started mounting) is done. */
78
+ ready(): Promise<void>;
79
+ /** Build a pure plan for one plugin. */
80
+ plan(root: string, source?: string): Plan;
81
+ /** Apply a plan previously returned by {@link plan}. */
82
+ applyById(planId: string): Promise<ApplyResult>;
83
+ /** Apply one reviewed plan. Re-scans the root and refuses a changed source. */
84
+ apply(plan: Plan): Promise<ApplyResult>;
85
+ /** Plan and apply one plugin root. */
86
+ install(root: string, source?: string): Promise<InstallReport>;
87
+ /** Read a marketplace index without installing anything. */
88
+ scanMarketplace(path: string): MarketplaceIndex;
89
+ /** Install one marketplace entry from a local path or git source. */
90
+ installMarketplace(path: string, name: string): Promise<InstallReport>;
91
+ /** Undo the actions of one receipt and remove its live registrations. */
92
+ undo(receiptId: string): Promise<boolean>;
93
+ /** Switch one part of an installed plugin off or on again; it stays so across restarts. */
94
+ setPartEnabled(pluginId: string, componentId: string, enabled: boolean): Promise<boolean>;
95
+ /** Remove one installation and every registration it owns. */
96
+ uninstall(id: string): Promise<boolean>;
97
+ /** Scan one plugin without writing anything. */
98
+ scan(root: string, source?: string): ForeignPlugin;
99
+ /** List current installations in stable name order. */
100
+ list(): readonly InstalledPluginRecord[];
101
+ /** Drop every runtime registration without rewriting the durable ledger. */
102
+ dispose(): Promise<void>;
103
+ }
104
+ /** Infer the dialect of a marketplace index from its manifest location. */
105
+ export declare function marketplaceDialect(index: MarketplaceIndex): string;