@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,281 @@
1
+ /**
2
+ * The OpenCode runtime's DSH-event mapping.
3
+ * @module @kirkchinese/harness-forge/opencode
4
+ */
5
+ import { randomUUID } from 'node:crypto';
6
+ import { appendNotice } from '../../hooks/notice.js';
7
+ import { dshArgs, isRecord, messagesOf, openCodeArgs, openCodeToolName, permissionType, sessionInfo, toolPart, userInfo, userParts, } from '../convert.js';
8
+ /**
9
+ * DSH's events raised as OpenCode hooks and events: session events,
10
+ * `chat.message`, `chat.params`, `tool.execute.before` / `.after`,
11
+ * `permission.ask`, the prompt and tool transforms, `shell.env` and
12
+ * `command.execute.before`.
13
+ */
14
+ export class EventBridge {
15
+ core;
16
+ /** Calls whose arguments the `tool.execute.before` hooks saw, by call id. */
17
+ calls = new Map();
18
+ constructor(core) {
19
+ this.core = core;
20
+ }
21
+ sessionCreated(agent) {
22
+ if (this.core.hosts.size === 0)
23
+ return;
24
+ const info = sessionInfo(this.core.facts(agent));
25
+ this.core.emit({ type: 'session.created', properties: { info } });
26
+ this.core.emit({ type: 'session.updated', properties: { info } });
27
+ }
28
+ /** The session log, as OpenCode's events. */
29
+ sessionEvent(sessionId, event) {
30
+ if (this.core.hosts.size === 0)
31
+ return;
32
+ const agent = this.core.agents()?.get(sessionId);
33
+ if (agent === undefined)
34
+ return;
35
+ const facts = this.core.facts(agent);
36
+ const data = isRecord(event.data) ? event.data : {};
37
+ switch (event.type) {
38
+ case 'user/message': {
39
+ const info = userInfo(facts, data, event.time);
40
+ this.core.emit({ type: 'message.updated', properties: { info } });
41
+ for (const part of userParts(sessionId, data))
42
+ this.core.emit({ type: 'message.part.updated', properties: { part } });
43
+ return;
44
+ }
45
+ case 'assistant/message': {
46
+ const [message] = messagesOf(facts, [event]);
47
+ if (message === undefined)
48
+ return;
49
+ this.core.emit({ type: 'message.updated', properties: { info: message.info } });
50
+ for (const part of message.parts)
51
+ this.core.emit({ type: 'message.part.updated', properties: { part } });
52
+ return;
53
+ }
54
+ case 'tool/call': {
55
+ const part = toolPart({ id: `prt_${String(data['callId'])}`, sessionID: sessionId, messageID: `msg_${String(data['turn'])}_${String(data['step'])}` }, { id: data['callId'], name: data['name'], arguments: data['arguments'] }, undefined, facts.cwd, event.time);
56
+ this.core.emit({ type: 'message.part.updated', properties: { part } });
57
+ return;
58
+ }
59
+ case 'turn/start':
60
+ this.core.emit({ type: 'session.status', properties: { sessionID: sessionId, status: { type: 'busy' } } });
61
+ return;
62
+ case 'turn/end':
63
+ // DSH's turn/end reason is { kind: 'error', error: { message, … } } for a failed turn.
64
+ if (isFailure(data['reason']))
65
+ this.core.emit({ type: 'session.error', properties: { sessionID: sessionId, error: { name: 'UnknownError', data: { message: failureMessage(data['reason']) } } } });
66
+ this.core.emit({ type: 'session.status', properties: { sessionID: sessionId, status: { type: 'idle' } } });
67
+ this.core.emit({ type: 'session.idle', properties: { sessionID: sessionId } });
68
+ this.core.emit({ type: 'session.updated', properties: { info: sessionInfo(facts) } });
69
+ return;
70
+ case 'command/done':
71
+ this.core.emit({ type: 'command.executed', properties: { name: String(data['name'] ?? ''), sessionID: sessionId, arguments: String(data['args'] ?? ''), messageID: '' } });
72
+ return;
73
+ case 'compaction/end':
74
+ if (data['error'] === undefined)
75
+ this.core.emit({ type: 'session.compacted', properties: { sessionID: sessionId } });
76
+ return;
77
+ default:
78
+ }
79
+ }
80
+ /**
81
+ * `chat.message` for each prompt about to enter: the plugin sees the
82
+ * message and its parts before the session holds it, may change or add
83
+ * parts, and the prompts it sends meanwhile (`noReply`) enter before it.
84
+ */
85
+ async preStep(payload, next) {
86
+ const prompts = payload.messages.filter(message => message.source?.kind === 'user');
87
+ if (prompts.length === 0 || !this.core.has('chat.message'))
88
+ return next();
89
+ const sessionId = payload.agent.session.header.id;
90
+ const facts = this.core.facts(payload.agent);
91
+ const replaced = new Map();
92
+ for (const message of prompts) {
93
+ this.core.admitting.set(sessionId, []);
94
+ const info = userInfo(facts, message, Date.now());
95
+ const parts = userParts(sessionId, message);
96
+ const { output, error, faults } = await this.core.trigger('chat.message', {
97
+ sessionID: sessionId,
98
+ agent: facts.agent,
99
+ model: { providerID: facts.provider, modelID: facts.model },
100
+ messageID: info['id'],
101
+ }, { message: info, parts });
102
+ for (const text of [...(error === undefined ? [] : [error]), ...faults])
103
+ appendNotice(payload.agent.session, { kind: 'hook-error', event: 'chat.message', plugin: 'opencode', text });
104
+ const before = this.core.admitting.get(sessionId) ?? [];
105
+ this.core.admitting.delete(sessionId);
106
+ const after = Array.isArray(output['parts']) ? output['parts'].filter(isRecord) : parts;
107
+ const changed = JSON.stringify(after) !== JSON.stringify(parts);
108
+ replaced.set(message, { before, message: changed ? withParts(message, after) : message });
109
+ }
110
+ const decision = await next();
111
+ if (decision.kind !== 'enter' || decision.messages === undefined) {
112
+ // A prompt that does not enter leaves what the plugin added waiting for the next one.
113
+ for (const { before } of replaced.values())
114
+ for (const message of before)
115
+ payload.agent.inject(message);
116
+ return decision;
117
+ }
118
+ const messages = [];
119
+ for (const message of decision.messages) {
120
+ const entry = replaced.get(message);
121
+ if (entry === undefined) {
122
+ messages.push(message);
123
+ continue;
124
+ }
125
+ messages.push(...entry.before, entry.message);
126
+ }
127
+ return { ...decision, messages };
128
+ }
129
+ /** `chat.params`: the temperature and output tokens a plugin sets reach the request. */
130
+ async request(payload, next) {
131
+ const config = await next();
132
+ if (!this.core.has('chat.params'))
133
+ return config;
134
+ const facts = this.core.facts(payload.agent);
135
+ const before = {
136
+ temperature: typeof config['temperature'] === 'number' ? config['temperature'] : 0,
137
+ topP: 1,
138
+ topK: 0,
139
+ maxOutputTokens: typeof config['maxTokens'] === 'number' ? config['maxTokens'] : undefined,
140
+ options: {},
141
+ };
142
+ const { output } = await this.core.trigger('chat.params', {
143
+ sessionID: facts.id,
144
+ agent: facts.agent,
145
+ model: { id: facts.model, providerID: facts.provider, name: facts.model },
146
+ provider: { source: 'config', info: { id: facts.provider, name: facts.provider, env: [], models: {} }, options: {} },
147
+ message: userInfo(facts, { id: `msg_${facts.id}` }, Date.now()),
148
+ }, { ...before });
149
+ return {
150
+ ...config,
151
+ ...(output['temperature'] !== before.temperature && typeof output['temperature'] === 'number' ? { temperature: output['temperature'] } : {}),
152
+ ...(output['maxOutputTokens'] !== before.maxOutputTokens && typeof output['maxOutputTokens'] === 'number' ? { maxTokens: output['maxOutputTokens'] } : {}),
153
+ };
154
+ }
155
+ /** `tool.execute.before`: OpenCode's view of the call; a throw refuses it, changed arguments run. */
156
+ async preExecute(exec, next) {
157
+ if (exec.callId === undefined || exec.agent === undefined || this.core.hosts.size === 0)
158
+ return next();
159
+ const cwd = await this.core.host.directory(exec.agent, exec.signal).catch(() => exec.agent?.session.header.cwd ?? process.cwd());
160
+ const args = openCodeArgs(exec.name, exec.arguments, cwd);
161
+ const sessionId = exec.agent.session.header.id;
162
+ this.calls.set(exec.callId, { name: exec.name, args, sessionId });
163
+ if (!this.core.has('tool.execute.before'))
164
+ return next();
165
+ const { output, error } = await this.core.trigger('tool.execute.before', { tool: openCodeToolName(exec.name), sessionID: sessionId, callID: exec.callId }, { args: structuredClone(args) });
166
+ if (error !== undefined)
167
+ return { kind: 'deny', reason: error };
168
+ const updated = isRecord(output['args']) ? output['args'] : args;
169
+ if (JSON.stringify(updated) !== JSON.stringify(args)) {
170
+ this.calls.set(exec.callId, { name: exec.name, args: updated, sessionId });
171
+ this.core.host.rewrite(exec.callId, dshArgs(exec.name, exec.arguments, updated));
172
+ }
173
+ return next();
174
+ }
175
+ /** `tool.execute.after`: the plugin may rewrite the output the model reads. */
176
+ async postExecute(exec, result, next) {
177
+ const decision = await next();
178
+ const call = exec.callId === undefined ? undefined : this.calls.get(exec.callId);
179
+ if (call === undefined || !this.core.has('tool.execute.after') || decision.kind !== 'accept')
180
+ return decision;
181
+ const content = (decision.content ?? result.content ?? []);
182
+ const text = content.filter(block => block.type === 'text').map(block => block.text ?? '').join('');
183
+ const before = { title: openCodeToolName(exec.name), output: text, metadata: {} };
184
+ const { output } = await this.core.trigger('tool.execute.after', { tool: openCodeToolName(exec.name), sessionID: call.sessionId, callID: exec.callId, args: call.args }, { ...before });
185
+ if (typeof output['output'] === 'string' && output['output'] !== text)
186
+ return { ...decision, content: [{ type: 'text', text: output['output'] }] };
187
+ return decision;
188
+ }
189
+ toolResult(exec, result) {
190
+ const call = exec.callId === undefined ? undefined : this.calls.get(exec.callId);
191
+ if (exec.callId !== undefined)
192
+ this.calls.delete(exec.callId);
193
+ if (call === undefined || result.isError)
194
+ return;
195
+ const tool = openCodeToolName(exec.name);
196
+ if ((tool === 'write' || tool === 'edit') && typeof call.args['filePath'] === 'string') {
197
+ this.core.emit({ type: 'file.edited', properties: { file: call.args['filePath'] } });
198
+ }
199
+ }
200
+ /** `permission.ask` before DSH asks the person: `allow` and `deny` answer for them. */
201
+ async approval(request, next) {
202
+ if (this.core.hosts.size === 0)
203
+ return next();
204
+ const sessionId = request.agent.session.header.id;
205
+ const call = request.callId === undefined ? undefined : this.calls.get(request.callId);
206
+ const pattern = call === undefined ? undefined : call.args['command'] ?? call.args['filePath'] ?? call.args['url'];
207
+ const permission = {
208
+ id: `per_${request.callId ?? randomUUID()}`,
209
+ type: permissionType(request.toolName),
210
+ ...(typeof pattern === 'string' ? { pattern } : {}),
211
+ sessionID: sessionId,
212
+ messageID: '',
213
+ ...(request.callId !== undefined ? { callID: request.callId } : {}),
214
+ title: request.reason ?? request.toolName,
215
+ metadata: call?.args ?? {},
216
+ time: { created: Date.now() },
217
+ };
218
+ this.core.emit({ type: 'permission.updated', properties: permission });
219
+ const { output } = this.core.has('permission.ask') ? await this.core.trigger('permission.ask', permission, { status: 'ask' }) : { output: { status: 'ask' } };
220
+ const outcome = output['status'] === 'allow' ? 'allowed-once' : output['status'] === 'deny' ? 'rejected' : await next();
221
+ this.core.emit({ type: 'permission.replied', properties: { sessionID: sessionId, permissionID: permission.id, response: outcome === 'allowed-once' ? 'once' : 'reject' } });
222
+ return outcome;
223
+ }
224
+ /**
225
+ * `experimental.chat.system.transform` on the assembled prompt. (`tool.definition` has no seam: DSH collects the
226
+ * offered tools outside the assembly a listener sees.)
227
+ */
228
+ async assemble(next) {
229
+ const assembly = await next();
230
+ if (this.core.has('experimental.chat.system.transform')) {
231
+ const system = assembly.sections.map(section => section.text);
232
+ const { output } = await this.core.trigger('experimental.chat.system.transform', { model: {} }, { system: [...system] });
233
+ const after = Array.isArray(output['system']) ? output['system'].map(String) : system;
234
+ const sections = assembly.sections.map((section, index) => (after[index] !== undefined && after[index] !== section.text ? { ...section, text: after[index] } : section));
235
+ for (const [index, text] of after.slice(system.length).entries())
236
+ sections.push({ name: `opencode-system-${String(index)}`, text });
237
+ assembly.sections = sections;
238
+ }
239
+ return assembly;
240
+ }
241
+ /** `shell.env`: the variables plugins add to a shell call's environment. */
242
+ async shellEnv(exec) {
243
+ if (!this.core.has('shell.env') || exec.agent === undefined)
244
+ return {};
245
+ const cwd = await this.core.host.directory(exec.agent, exec.signal).catch(() => process.cwd());
246
+ const { output } = await this.core.trigger('shell.env', { cwd, sessionID: exec.agent.session.header.id, ...(exec.callId !== undefined ? { callID: exec.callId } : {}) }, { env: {} });
247
+ const env = isRecord(output['env']) ? output['env'] : {};
248
+ return Object.fromEntries(Object.entries(env).filter((entry) => typeof entry[1] === 'string'));
249
+ }
250
+ /**
251
+ * `command.execute.before` for an OpenCode command about to be submitted:
252
+ * the plugin sees the command and the parts of its prompt, and may change them.
253
+ */
254
+ async beforeCommand(agent, command, prompt) {
255
+ if (!this.core.has('command.execute.before'))
256
+ return [prompt];
257
+ const sessionId = agent.session.header.id;
258
+ const parts = [{ id: `prt_${randomUUID()}`, sessionID: sessionId, messageID: '', type: 'text', text: prompt }];
259
+ const { output, error } = await this.core.trigger('command.execute.before', { command: command.name, sessionID: sessionId, arguments: command.args }, { parts });
260
+ // A plugin that throws has handled the command itself; its prompt is not sent.
261
+ if (error !== undefined)
262
+ return { stopped: error };
263
+ const after = Array.isArray(output['parts']) ? output['parts'].filter(isRecord) : parts;
264
+ return after.filter(part => part['type'] === 'text').map(part => String(part['text'] ?? ''));
265
+ }
266
+ }
267
+ /** A DSH message with its text replaced by OpenCode parts (non-text blocks kept). */
268
+ /** Whether a `turn/end` reason is a failed turn. */
269
+ function isFailure(reason) {
270
+ return typeof reason === 'object' && reason !== null && reason.kind === 'error';
271
+ }
272
+ /** The message of a failed turn's reason. */
273
+ function failureMessage(reason) {
274
+ const message = reason.error?.message;
275
+ return typeof message === 'string' && message.length > 0 ? message : 'the turn ended with an error';
276
+ }
277
+ function withParts(message, parts) {
278
+ const texts = parts.filter(part => part['type'] === 'text').map(part => ({ type: 'text', text: String(part['text'] ?? '') }));
279
+ const others = message.content.filter(block => block['type'] !== 'text');
280
+ return { ...message, content: [...texts, ...others] };
281
+ }
@@ -0,0 +1,27 @@
1
+ import { type CodeComponent, type ForeignPlugin } from '@kirkchinese/harness-forge-core';
2
+ import type { OpenCodeCore } from './core.js';
3
+ import type { OpenCodeServer } from './server.js';
4
+ import type { OpenCodeMount } from './types.js';
5
+ /** Starts plugins' Bun hosts and registers their tools and commands. */
6
+ export declare class PluginMounter {
7
+ private readonly core;
8
+ private readonly http;
9
+ private readonly loadTimeoutMs;
10
+ constructor(core: OpenCodeCore, http: OpenCodeServer, loadTimeoutMs?: number);
11
+ /** Start a plugin's Bun host and register its tools and commands. */
12
+ mount(component: CodeComponent, plugin: ForeignPlugin, options?: Record<string, unknown>): Promise<OpenCodeMount>;
13
+ /**
14
+ * How a plugin's unload went (its `dispose` hooks, the process ending), appended to
15
+ * `<dataRoot>/disposed.jsonl`: the record of an uninstalled plugin is gone from the ledger.
16
+ */
17
+ private recordDisposal;
18
+ /** Evidence: the commands a plugin's `config` hook added, under their DSH names, with the templates the hook gave them. */
19
+ recordAddedCommands(componentId: string, commands: ReadonlyArray<{
20
+ readonly name: string;
21
+ readonly foreignName: string;
22
+ readonly template: string;
23
+ }>): void;
24
+ /** Commands a plugin's `config` hook added, as command components. */
25
+ private addedCommands;
26
+ private toolDefinition;
27
+ }
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Mounting an OpenCode plugin: its Bun host, its tools as DSH tools, the
3
+ * commands its `config` hook adds, and its unload.
4
+ * @module @kirkchinese/harness-forge/opencode
5
+ */
6
+ import { spawn } from 'node:child_process';
7
+ import { randomUUID } from 'node:crypto';
8
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { kebabCase, uniqueName } from '@kirkchinese/harness-forge-core';
12
+ import { ensureBun, ensureDependencies } from '../bun.js';
13
+ import { isRecord } from '../convert.js';
14
+ import { dshService } from '../../dsh/host.js';
15
+ import { messageOf } from '../../shared/util.js';
16
+ /** `@opencode-ai/sdk/client` (an ESM-only export), found from this module up. */
17
+ function sdkClient() {
18
+ for (let dir = dirname(fileURLToPath(import.meta.url));; dir = dirname(dir)) {
19
+ const candidate = join(dir, 'node_modules', '@opencode-ai', 'sdk', 'dist', 'client.js');
20
+ if (existsSync(candidate))
21
+ return candidate;
22
+ if (dirname(dir) === dir)
23
+ throw new Error('@opencode-ai/sdk is not installed beside Harness Forge');
24
+ }
25
+ }
26
+ const HOST_SCRIPT = fileURLToPath(new URL('../../../runtime/opencode-host.mjs', import.meta.url));
27
+ /** Starts plugins' Bun hosts and registers their tools and commands. */
28
+ export class PluginMounter {
29
+ core;
30
+ http;
31
+ loadTimeoutMs;
32
+ constructor(core, http, loadTimeoutMs = 180_000) {
33
+ this.core = core;
34
+ this.http = http;
35
+ this.loadTimeoutMs = loadTimeoutMs;
36
+ }
37
+ // ---------------------------------------------------------------------------
38
+ // Mounting
39
+ // ---------------------------------------------------------------------------
40
+ /** Start a plugin's Bun host and register its tools and commands. */
41
+ async mount(component, plugin, options = {}) {
42
+ if (component.entryPath === undefined)
43
+ throw new Error(`code component "${component.name}" has no entry path`);
44
+ await this.http.listen();
45
+ const bun = await ensureBun(this.core.host.dataRoot);
46
+ await ensureDependencies(bun, plugin.root);
47
+ const directory = process.cwd();
48
+ const project = this.core.projectOf(directory);
49
+ const key = `${kebabCase(plugin.name)}-${randomUUID().slice(0, 8)}`;
50
+ const config = this.core.configFor(directory);
51
+ const ready = new Promise((resolve, reject) => { this.core.waiting.set(key, { resolve, reject }); });
52
+ // No auto-install: a plugin uses the dependencies installed beside it, as in OpenCode's plugin cache.
53
+ // A plugin resolves its modules from its own install, as in OpenCode: the DSH process's NODE_PATH does not reach it.
54
+ const { NODE_PATH: _nodePath, ...inherited } = process.env;
55
+ let child;
56
+ try {
57
+ child = spawn(bun, ['--no-install', HOST_SCRIPT], {
58
+ cwd: plugin.root,
59
+ windowsHide: true,
60
+ env: {
61
+ ...inherited,
62
+ HF_OC_ENTRY: component.entryPath,
63
+ HF_OC_SERVER: this.http.base,
64
+ HF_OC_KEY: key,
65
+ HF_OC_SDK: sdkClient(),
66
+ HF_OC_INPUT: JSON.stringify({ directory, worktree: project.worktree, project: { id: project.id, worktree: project.worktree, vcs: 'git', time: { created: project.created } }, options, config, auth: this.core.storedAuth() }),
67
+ },
68
+ });
69
+ }
70
+ catch (error) {
71
+ this.core.waiting.delete(key);
72
+ throw error;
73
+ }
74
+ // The Bun host ends with this process, however it ends.
75
+ const stop = () => { if (child.exitCode === null)
76
+ child.kill(); };
77
+ process.once('exit', stop);
78
+ const record = { key, componentId: component.id, pluginName: plugin.name, root: plugin.root, url: '', child, hooks: new Set(), tools: [], config: {}, events: Promise.resolve(), log: '' };
79
+ const keep = (chunk) => { record.log = (record.log + chunk.toString()).slice(-8000); };
80
+ child.stdout?.on('data', keep);
81
+ child.stderr?.on('data', keep);
82
+ // An asynchronous spawn failure (a missing or non-executable Bun) arrives as `error`; unhandled it would take DSH down.
83
+ child.on('error', (error) => {
84
+ process.removeListener('exit', stop);
85
+ record.log = `${record.log}${error.message}\n`.slice(-8000);
86
+ this.core.waiting.get(key)?.reject(new Error(`the plugin's Bun host could not run: ${error.message}`));
87
+ this.core.waiting.delete(key);
88
+ if (this.core.hosts.get(key) === record)
89
+ this.core.hosts.delete(key);
90
+ });
91
+ child.once('exit', () => { process.removeListener('exit', stop); });
92
+ child.on('exit', (code) => {
93
+ this.core.waiting.get(key)?.reject(new Error(`the plugin's Bun host exited with ${String(code)} before it was ready: ${record.log.trim().split(/\r?\n/u).slice(-6).join(' | ')}`));
94
+ this.core.waiting.delete(key);
95
+ if (this.core.hosts.get(key) === record)
96
+ this.core.hosts.delete(key);
97
+ });
98
+ const timer = setTimeout(() => {
99
+ this.core.waiting.get(key)?.reject(new Error(`the plugin did not finish loading in ${String(Math.round(this.loadTimeoutMs / 1000))}s: ${record.log.trim().split(/\r?\n/u).slice(-6).join(' | ')}`));
100
+ }, this.loadTimeoutMs);
101
+ const disposers = [];
102
+ // Whatever fails from here on leaves nothing behind: no process, no tool, no host record.
103
+ const rollback = () => {
104
+ clearTimeout(timer);
105
+ this.core.waiting.delete(key);
106
+ for (const dispose of disposers.splice(0).reverse()) {
107
+ try {
108
+ dispose();
109
+ }
110
+ catch { /* already gone */ }
111
+ }
112
+ if (this.core.hosts.get(key) === record)
113
+ this.core.hosts.delete(key);
114
+ process.removeListener('exit', stop);
115
+ if (child.exitCode === null && !child.killed)
116
+ child.kill();
117
+ };
118
+ try {
119
+ const body = await ready;
120
+ clearTimeout(timer);
121
+ this.core.waiting.delete(key);
122
+ if (typeof body['error'] === 'string')
123
+ throw new Error(`OpenCode plugin ${plugin.name} failed to load: ${body['error'].split('\n')[0] ?? ''}`);
124
+ record.url = `http://127.0.0.1:${String(body['port'])}`;
125
+ const loaded = Array.isArray(body['plugins']) ? body['plugins'].filter(isRecord) : [];
126
+ record.hooks = new Set(loaded.flatMap(item => (Array.isArray(item['hooks']) ? item['hooks'].map(String) : [])));
127
+ record.tools = (Array.isArray(body['tools']) ? body['tools'].filter(isRecord) : []).map(tool => ({
128
+ name: String(tool['name']),
129
+ description: String(tool['description'] ?? ''),
130
+ parameters: isRecord(tool['parameters']) ? tool['parameters'] : { type: 'object', additionalProperties: true },
131
+ }));
132
+ record.config = isRecord(body['config']) ? body['config'] : {};
133
+ this.core.hosts.set(key, record);
134
+ const registered = [];
135
+ const registry = dshService(this.core.ctx, 'tools');
136
+ for (const tool of record.tools) {
137
+ if (registry === undefined)
138
+ break;
139
+ let name = tool.name;
140
+ try {
141
+ disposers.push(registry.register(this.toolDefinition(record, tool, name)));
142
+ }
143
+ catch {
144
+ name = uniqueName(kebabCase(`${plugin.name}-${tool.name}`).replace(/-/gu, '_'), new Set(registered), `${plugin.id}:${tool.name}`);
145
+ disposers.push(registry.register(this.toolDefinition(record, tool, name)));
146
+ }
147
+ registered.push(name);
148
+ }
149
+ const commands = this.addedCommands(component, config, record.config);
150
+ const configChanged = [...new Set([...Object.keys(config), ...Object.keys(record.config)])]
151
+ .filter(key => JSON.stringify(config[key]) !== JSON.stringify(record.config[key])).sort();
152
+ return {
153
+ tools: registered,
154
+ hooks: [...record.hooks],
155
+ commands,
156
+ configChanged,
157
+ dispose: async () => {
158
+ for (const dispose of disposers.splice(0))
159
+ dispose();
160
+ this.core.hosts.delete(key);
161
+ // Events already queued for the plugin (a turn's last session.idle / session.updated) are delivered first:
162
+ // its `dispose` ends the Bun host, and a queued event would then fail. At most two seconds.
163
+ await Promise.race([record.events, new Promise(resolve => setTimeout(resolve, 2000).unref())]);
164
+ record.stopping = true;
165
+ // The plugin's `dispose` hooks get five seconds; then the process is stopped.
166
+ const disposed = await Promise.race([
167
+ this.core.post(record, '/dispose', {}, { timeoutMs: 5000 }).catch((error) => ({ ok: false, error: messageOf(error) })),
168
+ new Promise(resolve => setTimeout(() => { resolve({ ok: false, error: 'dispose did not answer in 5s' }); }, 5000).unref()),
169
+ ]);
170
+ this.recordDisposal(record, disposed);
171
+ await new Promise((resolve) => {
172
+ if (child.exitCode !== null)
173
+ return resolve();
174
+ const timer = setTimeout(() => { child.kill(); resolve(); }, 3000);
175
+ child.once('exit', () => { clearTimeout(timer); resolve(); });
176
+ });
177
+ },
178
+ };
179
+ }
180
+ catch (error) {
181
+ rollback();
182
+ throw error;
183
+ }
184
+ }
185
+ /**
186
+ * How a plugin's unload went (its `dispose` hooks, the process ending), appended to
187
+ * `<dataRoot>/disposed.jsonl`: the record of an uninstalled plugin is gone from the ledger.
188
+ */
189
+ recordDisposal(record, answer) {
190
+ const line = { componentId: record.componentId, plugin: record.pluginName, ok: answer['ok'] === true, ran: Number(answer['ran'] ?? 0), ...(typeof answer['error'] === 'string' ? { error: answer['error'] } : {}), at: new Date().toISOString() };
191
+ try {
192
+ mkdirSync(this.core.host.dataRoot, { recursive: true });
193
+ appendFileSync(join(this.core.host.dataRoot, 'disposed.jsonl'), `${JSON.stringify(line)}\n`);
194
+ }
195
+ catch {
196
+ // Evidence only.
197
+ }
198
+ }
199
+ /** Evidence: the commands a plugin's `config` hook added, under their DSH names, with the templates the hook gave them. */
200
+ recordAddedCommands(componentId, commands) {
201
+ const file = join(this.core.host.dataRoot, 'added-commands.json');
202
+ try {
203
+ mkdirSync(this.core.host.dataRoot, { recursive: true });
204
+ const all = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {};
205
+ all[componentId] = commands;
206
+ writeFileSync(file, `${JSON.stringify(all, null, 2)}\n`);
207
+ }
208
+ catch {
209
+ // Evidence only.
210
+ }
211
+ }
212
+ /** Commands a plugin's `config` hook added, as command components. */
213
+ addedCommands(component, before, after) {
214
+ const was = isRecord(before['command']) ? before['command'] : {};
215
+ const now = isRecord(after['command']) ? after['command'] : {};
216
+ const out = [];
217
+ for (const [name, spec] of Object.entries(now)) {
218
+ if (name in was || !isRecord(spec) || typeof spec['template'] !== 'string')
219
+ continue;
220
+ out.push({
221
+ name,
222
+ component: {
223
+ id: `${component.id}:command:${name}`,
224
+ kind: 'command',
225
+ name,
226
+ path: name,
227
+ description: typeof spec['description'] === 'string' ? spec['description'] : '',
228
+ bodyPath: component.entryPath ?? '',
229
+ body: spec['template'],
230
+ frontmatter: {
231
+ ...(typeof spec['agent'] === 'string' ? { agent: spec['agent'] } : {}),
232
+ ...(typeof spec['model'] === 'string' ? { model: spec['model'] } : {}),
233
+ ...(spec['subtask'] === true ? { context: 'fork' } : {}),
234
+ },
235
+ },
236
+ });
237
+ }
238
+ return out;
239
+ }
240
+ toolDefinition(record, tool, name) {
241
+ return {
242
+ name,
243
+ description: tool.description,
244
+ parameters: tool.parameters,
245
+ output: {
246
+ schema: {},
247
+ render: (_args, value) => [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value) }],
248
+ },
249
+ execute: async (args, exec) => {
250
+ const agent = exec.agent;
251
+ const sessionId = agent?.session.header.id ?? '';
252
+ const cwd = agent !== undefined ? await this.core.host.directory(agent, exec.signal).catch(() => agent.session.header.cwd ?? process.cwd()) : process.cwd();
253
+ const callId = exec.callId ?? `call_${randomUUID()}`;
254
+ const onAbort = () => { void this.core.post(record, '/abort', { callID: callId }).catch(() => undefined); };
255
+ exec.signal.addEventListener('abort', onAbort, { once: true });
256
+ try {
257
+ const answer = await this.core.post(record, '/tool', {
258
+ name: tool.name,
259
+ args,
260
+ context: { sessionID: sessionId, messageID: `msg_${callId}`, agent: agent === undefined ? 'build' : this.core.agentOf(agent), directory: cwd, worktree: this.core.projectOf(cwd).worktree, callID: callId },
261
+ }, { timeoutMs: null });
262
+ if (typeof answer['error'] === 'string') {
263
+ this.core.host.observe(record.componentId, `opencode:tool:${tool.name}`, false, answer['error'].split('\n')[0] ?? '');
264
+ throw new Error(answer['error']);
265
+ }
266
+ this.core.host.observe(record.componentId, `opencode:tool:${tool.name}`, true, `${tool.name} returned`);
267
+ const value = answer['result'];
268
+ if (typeof value === 'string')
269
+ return value;
270
+ if (isRecord(value)) {
271
+ const attachments = Array.isArray(value['attachments']) ? value['attachments'].filter(isRecord) : [];
272
+ const files = attachments.map(file => `\n[attachment ${String(file['filename'] ?? file['mime'] ?? 'file')}: ${String(file['url'] ?? '').slice(0, 120)}]`).join('');
273
+ return `${String(value['output'] ?? '')}${files}`;
274
+ }
275
+ return JSON.stringify(value ?? '');
276
+ }
277
+ finally {
278
+ exec.signal.removeEventListener('abort', onAbort);
279
+ }
280
+ },
281
+ };
282
+ }
283
+ }
@@ -0,0 +1,27 @@
1
+ import { type Server } from 'node:http';
2
+ import type { OpenCodeCore } from './core.js';
3
+ /** The OpenCode-compatible server plugins' `client` talks to, backed by DSH's sessions. */
4
+ export declare class OpenCodeServer {
5
+ private readonly core;
6
+ private readonly tui;
7
+ server: Server | undefined;
8
+ base: string;
9
+ private listening;
10
+ constructor(core: OpenCodeCore);
11
+ listen(): Promise<void>;
12
+ private handle;
13
+ private pluginOf;
14
+ /** The Bun hosts' own calls: readiness, a tool's permission request, a tool's metadata. */
15
+ private internal;
16
+ /** OpenCode's server routes, as DSH serves them; undefined when not served. */
17
+ private route;
18
+ private projectView;
19
+ /** `session.prompt`: a message into the session; with a reply, the assistant's last message once the turn ends. */
20
+ private prompt;
21
+ /** Resolve once a turn that began after `seq` has ended. */
22
+ private turnEnded;
23
+ private lastAssistant;
24
+ /** `session.create`: a new root session on the default model, in the plugin's directory. */
25
+ private createSession;
26
+ private deleteSession;
27
+ }