@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,353 @@
1
+ /**
2
+ * The OpenCode-compatible server: the routes the plugin's SDK client calls
3
+ * (sessions, prompts, files, logs, toasts) and the Bun hosts' own calls.
4
+ * @module @kirkchinese/harness-forge/opencode
5
+ */
6
+ import { randomUUID } from 'node:crypto';
7
+ import { readFileSync } from 'node:fs';
8
+ import { createServer } from 'node:http';
9
+ import { homedir } from 'node:os';
10
+ import { join, resolve } from 'node:path';
11
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
12
+ import { appendNotice } from '../../hooks/notice.js';
13
+ import { isRecord, messagesOf, sessionInfo, userInfo, userParts } from '../convert.js';
14
+ import { dshService } from '../../dsh/host.js';
15
+ import { messageOf } from '../../shared/util.js';
16
+ /** The source of a message an OpenCode plugin added to a session (`client.session.prompt` with `noReply`). */
17
+ const PLUGIN_SOURCE = 'opencode-plugin';
18
+ const FULL_ACCESS = new Set(['danger-full-access', 'full-access']);
19
+ /** The OpenCode-compatible server plugins' `client` talks to, backed by DSH's sessions. */
20
+ export class OpenCodeServer {
21
+ core;
22
+ tui = { prompt: '' };
23
+ server;
24
+ base = '';
25
+ listening;
26
+ constructor(core) {
27
+ this.core = core;
28
+ }
29
+ // ---------------------------------------------------------------------------
30
+ // The OpenCode-compatible server
31
+ // ---------------------------------------------------------------------------
32
+ listen() {
33
+ this.listening ??= new Promise((resolve, reject) => {
34
+ const server = createServer((req, res) => { void this.handle(req, res); });
35
+ server.on('error', reject);
36
+ server.listen(0, '127.0.0.1', () => {
37
+ const address = server.address();
38
+ this.base = `http://127.0.0.1:${String(typeof address === 'object' && address !== null ? address.port : 0)}`;
39
+ this.server = server;
40
+ resolve();
41
+ });
42
+ });
43
+ return this.listening;
44
+ }
45
+ async handle(req, res) {
46
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
47
+ const body = req.method === 'GET' || req.method === 'HEAD' ? {} : await readBody(req);
48
+ const plugin = this.pluginOf(req);
49
+ try {
50
+ const internal = /^\/__hf\/([^/]+)\/([a-z]+)$/u.exec(url.pathname);
51
+ if (internal !== null)
52
+ return send(res, 200, await this.internal(internal[1] ?? '', internal[2] ?? '', body));
53
+ if (url.pathname === '/event' || url.pathname === '/global/event') {
54
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive' });
55
+ res.write(`data: ${JSON.stringify({ type: 'server.connected', properties: {} })}\n\n`);
56
+ this.core.streams.add(res);
57
+ req.on('close', () => { this.core.streams.delete(res); });
58
+ return;
59
+ }
60
+ const routed = await this.route(req.method ?? 'GET', url, body);
61
+ if (routed === undefined) {
62
+ if (plugin !== undefined)
63
+ this.core.host.observe(plugin.componentId, `opencode:client:${req.method ?? 'GET'} ${templateOf(url.pathname)}`, false, 'Harness Forge does not serve this OpenCode route');
64
+ return send(res, 501, { name: 'UnknownError', data: { message: `${req.method ?? 'GET'} ${url.pathname} is not served by Harness Forge's OpenCode server` } });
65
+ }
66
+ if (plugin !== undefined)
67
+ this.core.host.observe(plugin.componentId, `opencode:client:${req.method ?? 'GET'} ${templateOf(url.pathname)}`, true, 'served');
68
+ return send(res, routed.status ?? 200, routed.body);
69
+ }
70
+ catch (error) {
71
+ return send(res, 400, { name: 'UnknownError', data: { message: messageOf(error) } });
72
+ }
73
+ }
74
+ pluginOf(req) {
75
+ const key = req.headers['x-hf-plugin'];
76
+ return typeof key === 'string' ? this.core.hosts.get(key) ?? [...this.core.hosts.values()].find(plugin => plugin.key === key) : undefined;
77
+ }
78
+ /** The Bun hosts' own calls: readiness, a tool's permission request, a tool's metadata. */
79
+ async internal(key, action, body) {
80
+ if (action === 'ready') {
81
+ this.core.waiting.get(key)?.resolve(body);
82
+ return { ok: true };
83
+ }
84
+ if (action === 'metadata')
85
+ return { ok: true };
86
+ if (action === 'ask') {
87
+ const agent = this.core.agents()?.get(String(body['sessionID'] ?? ''));
88
+ if (agent === undefined)
89
+ return { allowed: false, reason: 'the session is gone' };
90
+ const presets = dshService(this.core.ctx, 'permissionPresets');
91
+ let preset;
92
+ try {
93
+ preset = presets?.current(agent.session);
94
+ }
95
+ catch {
96
+ preset = undefined;
97
+ }
98
+ if (preset !== undefined && FULL_ACCESS.has(preset))
99
+ return { allowed: true };
100
+ const approval = dshService(this.core.ctx, 'approval');
101
+ if (approval === undefined)
102
+ return { allowed: true };
103
+ const request = isRecord(body['request']) ? body['request'] : {};
104
+ const patterns = Array.isArray(request['patterns']) ? request['patterns'].map(String).join(', ') : '';
105
+ const outcome = await approval.request({
106
+ agent,
107
+ toolName: String(body['tool'] ?? 'tool'),
108
+ ...(typeof body['callID'] === 'string' ? { callId: body['callID'] } : {}),
109
+ reason: `${String(request['permission'] ?? 'permission')}${patterns.length > 0 ? `: ${patterns}` : ''}`,
110
+ });
111
+ return outcome === 'allowed-once' ? { allowed: true } : { allowed: false, reason: 'The user rejected permission to use this specific tool call.' };
112
+ }
113
+ return { ok: false };
114
+ }
115
+ /** OpenCode's server routes, as DSH serves them; undefined when not served. */
116
+ async route(method, url, body) {
117
+ const path = url.pathname.replace(/\/+$/u, '') || '/';
118
+ const agents = this.core.agents();
119
+ const sessionMatch = /^\/session\/([^/]+)(?:\/(.+))?$/u.exec(path);
120
+ const sessionId = sessionMatch === null ? undefined : decodeURIComponent(sessionMatch[1] ?? '');
121
+ const rest = sessionMatch?.[2];
122
+ const agent = sessionId === undefined ? undefined : agents?.get(sessionId);
123
+ const need = () => {
124
+ if (agent === undefined)
125
+ throw new Error(`Session not found: ${sessionId ?? ''}`);
126
+ return agent;
127
+ };
128
+ const directory = url.searchParams.get('directory') ?? process.cwd();
129
+ const ok = (value) => ({ body: value });
130
+ if (method === 'GET' && path === '/session')
131
+ return ok((agents?.list() ?? []).map(item => sessionInfo(this.core.facts(item))));
132
+ if (method === 'GET' && path === '/session/status') {
133
+ return ok(Object.fromEntries((agents?.list() ?? []).map(item => [item.session.header.id, { type: item.status === 'idle' ? 'idle' : 'busy' }])));
134
+ }
135
+ if (method === 'POST' && path === '/session')
136
+ return ok(await this.createSession(body, directory));
137
+ if (sessionMatch !== null) {
138
+ if (method === 'GET' && rest === undefined)
139
+ return ok(sessionInfo(this.core.facts(need())));
140
+ if (method === 'DELETE' && rest === undefined)
141
+ return ok(await this.deleteSession(sessionId ?? ''));
142
+ if (method === 'PATCH' && rest === undefined) {
143
+ const titles = dshService(this.core.ctx, 'sessionTitle');
144
+ if (typeof body['title'] === 'string')
145
+ titles?.rename(need().session, body['title']);
146
+ return ok(sessionInfo(this.core.facts(need())));
147
+ }
148
+ if (method === 'GET' && rest === 'children')
149
+ return ok((agents?.list() ?? []).filter(item => this.core.facts(item).parentId === sessionId).map(item => sessionInfo(this.core.facts(item))));
150
+ if (method === 'GET' && rest === 'message') {
151
+ const limit = Number(url.searchParams.get('limit') ?? 0);
152
+ const messages = messagesOf(this.core.facts(need()), this.core.events(need()));
153
+ return ok(limit > 0 ? messages.slice(-limit) : messages);
154
+ }
155
+ if (method === 'GET' && rest?.startsWith('message/') === true) {
156
+ const id = decodeURIComponent(rest.slice('message/'.length));
157
+ const found = messagesOf(this.core.facts(need()), this.core.events(need())).find(message => message.info['id'] === id);
158
+ if (found === undefined)
159
+ throw new Error(`Message not found: ${id}`);
160
+ return ok(found);
161
+ }
162
+ if (method === 'POST' && rest === 'message')
163
+ return ok(await this.prompt(need(), body, true));
164
+ if (method === 'POST' && rest === 'prompt_async') {
165
+ await this.prompt(need(), body, false);
166
+ return { status: 204, body: undefined };
167
+ }
168
+ if (method === 'POST' && rest === 'abort') {
169
+ need().cancel({ kind: 'user' });
170
+ return ok(true);
171
+ }
172
+ if (method === 'POST' && rest === 'command') {
173
+ const commands = dshService(this.core.ctx, 'commands');
174
+ const line = `/${String(body['command'] ?? '')}${typeof body['arguments'] === 'string' && body['arguments'].length > 0 ? ` ${body['arguments']}` : ''}`;
175
+ await commands?.execute(need(), line, [], new AbortController().signal);
176
+ await need().whenIdle();
177
+ return ok(this.lastAssistant(need()));
178
+ }
179
+ if (method === 'GET' && rest === 'todo')
180
+ return ok([]);
181
+ return undefined;
182
+ }
183
+ if (method === 'GET' && path === '/config')
184
+ return ok(this.core.configFor(directory));
185
+ if (method === 'GET' && (path === '/config/providers' || path === '/provider')) {
186
+ const selection = this.core.defaultModel();
187
+ const providers = selection === undefined ? [] : [{ id: selection.provider, name: selection.provider, env: [], models: { [selection.model]: { id: selection.model, providerID: selection.provider, name: selection.model, release_date: '', attachment: false, reasoning: true, temperature: true, tool_call: true, limit: { context: 0, output: 0 }, options: {} } } }];
188
+ const defaults = selection === undefined ? {} : { [selection.provider]: selection.model };
189
+ return ok(path === '/provider' ? { all: providers, default: defaults, connected: providers.map(provider => provider.id) } : { providers, default: defaults });
190
+ }
191
+ if (method === 'GET' && path === '/project')
192
+ return ok([this.projectView(directory)]);
193
+ if (method === 'GET' && path === '/project/current')
194
+ return ok(this.projectView(directory));
195
+ if (method === 'GET' && path === '/path') {
196
+ const configHome = process.env['XDG_CONFIG_HOME'] ?? join(homedir(), '.config');
197
+ return ok({ state: join(this.core.host.dataRoot, 'opencode'), config: join(configHome, 'opencode'), worktree: this.core.projectOf(directory).worktree, directory });
198
+ }
199
+ if (method === 'GET' && path === '/agent') {
200
+ return ok([{ name: 'build', description: 'DSH default agent', mode: 'primary', builtIn: true, permission: { edit: 'allow', bash: {}, webfetch: 'allow' }, tools: {}, options: {} }]);
201
+ }
202
+ if (method === 'GET' && path === '/command') {
203
+ const commands = dshService(this.core.ctx, 'commands');
204
+ const root = agents?.roots()[0];
205
+ return ok(root === undefined ? [] : (commands?.list(root) ?? []).map(command => ({ name: command.name, description: command.description ?? '', template: '' })));
206
+ }
207
+ if (method === 'GET' && path === '/file/content') {
208
+ const file = resolve(directory, url.searchParams.get('path') ?? '');
209
+ return ok({ type: 'text', content: readFileSync(file, 'utf8') });
210
+ }
211
+ if (method === 'POST' && path === '/log') {
212
+ const level = String(body['level'] ?? 'info');
213
+ this.core.ctx.logger[level === 'error' ? 'error' : level === 'warn' ? 'warn' : 'info'](`[opencode:${String(body['service'] ?? 'plugin')}] ${String(body['message'] ?? '')}`);
214
+ return ok(true);
215
+ }
216
+ if (method === 'POST' && path === '/tui/show-toast') {
217
+ const root = agents?.roots().at(-1);
218
+ const text = `${typeof body['title'] === 'string' ? `${body['title']}: ` : ''}${String(body['message'] ?? '')}`;
219
+ if (root !== undefined)
220
+ appendNotice(root.session, { kind: 'system-message', event: 'tui.toast', plugin: 'opencode', text });
221
+ this.core.emit({ type: 'tui.toast.show', properties: body });
222
+ return ok(true);
223
+ }
224
+ if (method === 'POST' && path === '/tui/append-prompt') {
225
+ this.tui.prompt += String(body['text'] ?? '');
226
+ this.core.emit({ type: 'tui.prompt.append', properties: { text: String(body['text'] ?? '') } });
227
+ return ok(true);
228
+ }
229
+ if (method === 'POST' && path === '/tui/clear-prompt') {
230
+ this.tui.prompt = '';
231
+ return ok(true);
232
+ }
233
+ if (method === 'POST' && path === '/tui/submit-prompt') {
234
+ const root = agents?.roots().at(-1);
235
+ if (root !== undefined && this.tui.prompt.length > 0)
236
+ root.followup(createUserMessage({ content: [{ type: 'text', text: this.tui.prompt }], source: { kind: 'user' } }));
237
+ this.tui.prompt = '';
238
+ return ok(true);
239
+ }
240
+ if (method === 'POST' && path === '/tui/execute-command') {
241
+ const root = agents?.roots().at(-1);
242
+ const commands = dshService(this.core.ctx, 'commands');
243
+ if (root !== undefined)
244
+ await commands?.execute(root, `/${String(body['command'] ?? '').replace(/^\//u, '')}`, [], new AbortController().signal);
245
+ return ok(true);
246
+ }
247
+ return undefined;
248
+ }
249
+ projectView(directory) {
250
+ const project = this.core.projectOf(directory);
251
+ return { id: project.id, worktree: project.worktree, vcs: 'git', time: { created: project.created } };
252
+ }
253
+ /** `session.prompt`: a message into the session; with a reply, the assistant's last message once the turn ends. */
254
+ async prompt(agent, body, wait) {
255
+ const sessionId = agent.session.header.id;
256
+ const parts = Array.isArray(body['parts']) ? body['parts'].filter(isRecord) : [];
257
+ const content = parts.flatMap(part => (part['type'] === 'text' ? [{ type: 'text', text: String(part['text'] ?? '') }] : []));
258
+ if (typeof body['system'] === 'string' && body['system'].length > 0)
259
+ content.unshift({ type: 'text', text: `<system>\n${body['system']}\n</system>` });
260
+ const plugin = 'opencode';
261
+ const message = createUserMessage({ content, source: body['noReply'] === true ? { kind: PLUGIN_SOURCE, plugin } : { kind: 'user' } });
262
+ if (body['noReply'] === true) {
263
+ const admitting = this.core.admitting.get(sessionId);
264
+ if (admitting !== undefined)
265
+ admitting.push(message);
266
+ else
267
+ agent.inject(message);
268
+ const facts = this.core.facts(agent);
269
+ return { info: userInfo(facts, message, Date.now()), parts: userParts(sessionId, message) };
270
+ }
271
+ const before = agent.session.seq;
272
+ agent.followup(message);
273
+ if (!wait)
274
+ return undefined;
275
+ await this.turnEnded(agent, before);
276
+ return this.lastAssistant(agent);
277
+ }
278
+ /** Resolve once a turn that began after `seq` has ended. */
279
+ async turnEnded(agent, seq) {
280
+ for (let attempt = 0; attempt < 6000; attempt++) {
281
+ for (let at = seq; at < agent.session.seq; at++)
282
+ if (agent.session.eventAt(at)?.type === 'turn/end')
283
+ return;
284
+ await agent.whenIdle();
285
+ await new Promise(resolve => setTimeout(resolve, 100));
286
+ }
287
+ }
288
+ lastAssistant(agent) {
289
+ const messages = messagesOf(this.core.facts(agent), this.core.events(agent));
290
+ return [...messages].reverse().find(message => message.info['role'] === 'assistant') ?? {};
291
+ }
292
+ /** `session.create`: a new root session on the default model, in the plugin's directory. */
293
+ async createSession(body, directory) {
294
+ const agents = this.core.agents();
295
+ if (agents === undefined)
296
+ throw new Error('DSH has no agent registry');
297
+ const selection = this.core.defaultModel();
298
+ if (selection === undefined)
299
+ throw new Error('DSH has no model selected');
300
+ const sessionId = `session-${randomUUID().replaceAll('-', '')}`;
301
+ const handle = await agents.create({ sessionId, meta: { cwd: directory }, agentOptions: { provider: selection.provider, model: selection.model } });
302
+ const parentId = typeof body['parentID'] === 'string' ? body['parentID'] : undefined;
303
+ this.core.created.set(sessionId, { dispose: () => handle.dispose(), ...(parentId !== undefined ? { parentId } : {}) });
304
+ if (typeof body['title'] === 'string') {
305
+ const titles = dshService(this.core.ctx, 'sessionTitle');
306
+ try {
307
+ titles?.rename(handle.agent.session, body['title']);
308
+ }
309
+ catch {
310
+ // An untitled session is still a session.
311
+ }
312
+ }
313
+ return sessionInfo(this.core.facts(handle.agent));
314
+ }
315
+ async deleteSession(sessionId) {
316
+ const owned = this.core.created.get(sessionId);
317
+ if (owned === undefined)
318
+ throw new Error(`Session ${sessionId} was not created by a plugin; DSH keeps the sessions a person opened`);
319
+ const agent = this.core.agents()?.get(sessionId);
320
+ const info = agent === undefined ? { id: sessionId } : sessionInfo(this.core.facts(agent));
321
+ this.core.created.delete(sessionId);
322
+ await owned.dispose();
323
+ this.core.emit({ type: 'session.deleted', properties: { info } });
324
+ return true;
325
+ }
326
+ }
327
+ /** A route's template, for evidence: ids become `{id}`. */
328
+ function templateOf(path) {
329
+ return path.replace(/^\/session\/[^/]+/u, '/session/{id}').replace(/\/message\/[^/]+$/u, '/message/{messageID}');
330
+ }
331
+ async function readBody(req) {
332
+ const chunks = [];
333
+ for await (const chunk of req)
334
+ chunks.push(chunk);
335
+ if (chunks.length === 0)
336
+ return {};
337
+ try {
338
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
339
+ return isRecord(parsed) ? parsed : {};
340
+ }
341
+ catch {
342
+ return {};
343
+ }
344
+ }
345
+ function send(res, status, body) {
346
+ if (status === 204 || body === undefined) {
347
+ res.writeHead(status === 200 ? 204 : status);
348
+ res.end();
349
+ return;
350
+ }
351
+ res.writeHead(status, { 'content-type': 'application/json' });
352
+ res.end(JSON.stringify(body));
353
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The OpenCode runtime's types: what it needs from Harness Forge, what a
3
+ * mount returns, and structural views of the DSH objects it touches.
4
+ * @module @kirkchinese/harness-forge/opencode
5
+ */
6
+ import type { ChildProcess } from 'node:child_process';
7
+ import type { CommandComponent } from '@kirkchinese/harness-forge-core';
8
+ import type { LoggedEvent } from '../convert.js';
9
+ /** What the runtime needs from Harness Forge. */
10
+ export interface OpenCodeRuntimeHost {
11
+ readonly dataRoot: string;
12
+ /** Runtime evidence for a component. */
13
+ observe(componentId: string, signal: string, ok: boolean, detail: string): void;
14
+ directory(agent: unknown, signal: AbortSignal): Promise<string>;
15
+ /** Replace a pending call's arguments (the hooks broker runs the tool with them). */
16
+ rewrite(callId: string, args: Record<string, unknown>): void;
17
+ /** The foreign name of a DSH agent preset. */
18
+ agentName(presetId: string): string | undefined;
19
+ }
20
+ /** One running OpenCode plugin. */
21
+ export interface PluginHost {
22
+ readonly key: string;
23
+ readonly componentId: string;
24
+ readonly pluginName: string;
25
+ readonly root: string;
26
+ url: string;
27
+ child: ChildProcess;
28
+ hooks: Set<string>;
29
+ tools: Array<{
30
+ name: string;
31
+ description: string;
32
+ parameters: Record<string, unknown>;
33
+ }>;
34
+ config: Record<string, unknown>;
35
+ /** Events wait for the previous one, so a plugin sees them in order. */
36
+ events: Promise<void>;
37
+ log: string;
38
+ /** Being stopped (unloaded, or DSH exiting) once queued events had their time: what is cut off is not the plugin's failure. */
39
+ stopping?: boolean;
40
+ }
41
+ export interface Agent {
42
+ readonly session: {
43
+ readonly header: {
44
+ readonly id: string;
45
+ readonly cwd?: string;
46
+ readonly parentSession?: string;
47
+ readonly createdAt?: unknown;
48
+ readonly delegationDepth?: number;
49
+ };
50
+ readonly seq: number;
51
+ eventAt(seq: number): LoggedEvent | undefined;
52
+ };
53
+ readonly options?: {
54
+ readonly provider?: string;
55
+ readonly model?: string;
56
+ };
57
+ readonly ctx?: {
58
+ get?(name: string): unknown;
59
+ };
60
+ followup(message: unknown): void;
61
+ inject(message: unknown): void;
62
+ cancel(cause: {
63
+ kind: string;
64
+ reason?: string;
65
+ }, options?: {
66
+ keepInbox?: boolean;
67
+ }): void;
68
+ whenIdle(): Promise<void>;
69
+ }
70
+ export interface Agents {
71
+ get(id: string): Agent | undefined;
72
+ list(): Agent[];
73
+ roots(): Agent[];
74
+ create(options: Record<string, unknown>): Promise<{
75
+ agent: Agent;
76
+ dispose(): Promise<void>;
77
+ }>;
78
+ }
79
+ export interface ToolRegistry {
80
+ register(definition: Record<string, unknown>): () => void;
81
+ }
82
+ export interface ToolExec {
83
+ readonly name: string;
84
+ readonly arguments: unknown;
85
+ readonly callId?: string;
86
+ readonly agent?: Agent;
87
+ readonly signal: AbortSignal;
88
+ }
89
+ export interface Message {
90
+ readonly id?: string;
91
+ readonly source?: {
92
+ readonly kind?: string;
93
+ };
94
+ readonly content: ReadonlyArray<Record<string, unknown>>;
95
+ }
96
+ /** A plugin's command (from its `config` hook) as Harness Forge registers it. */
97
+ export interface OpenCodeCommand {
98
+ readonly component: CommandComponent;
99
+ readonly name: string;
100
+ }
101
+ /** One mounted OpenCode plugin. */
102
+ export interface OpenCodeMount {
103
+ readonly tools: readonly string[];
104
+ readonly hooks: readonly string[];
105
+ readonly commands: readonly OpenCodeCommand[];
106
+ /** Top-level configuration keys the plugin's `config` hook changed; only `command` is applied in DSH. */
107
+ readonly configChanged: readonly string[];
108
+ readonly dispose: () => Promise<void>;
109
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,55 @@
1
+ /**
2
+ * OpenCode plugins in DSH. Each plugin runs in its own Bun process
3
+ * (`runtime/opencode-host.mjs`), loaded as OpenCode loads it; its `client`
4
+ * talks to an OpenCode-compatible server served here, backed by DSH's
5
+ * sessions; its hooks are raised where DSH does the same work:
6
+ *
7
+ * | OpenCode | DSH |
8
+ * | --- | --- |
9
+ * | `tool` | a DSH tool per entry, arguments checked by the plugin's own schema |
10
+ * | `chat.message` | `agent/pre-step`, before a prompt enters; parts it adds or changes enter with it |
11
+ * | `chat.params` | `agent/request` (temperature, output tokens) |
12
+ * | `tool.execute.before` / `.after` | `tools/pre-execute` / `tools/post-execute`, in OpenCode's tool names and arguments |
13
+ * | `permission.ask` | `approval/request` |
14
+ * | `shell.env` | the shell tool's environment (through the hooks broker) |
15
+ * | `command.execute.before` | an OpenCode command's prompt before it is submitted |
16
+ * | `experimental.chat.system.transform`, `tool.definition` | `system-prompt/assemble` |
17
+ * | `config` | the plugin's commands added to DSH |
18
+ * | `event` | session, message, part, permission, command, file and compaction events from the session log |
19
+ * @module @kirkchinese/harness-forge/opencode
20
+ */
21
+ import type { Context } from '@deepseek-ai/cordis';
22
+ import type { CodeComponent, ForeignPlugin } from '@kirkchinese/harness-forge-core';
23
+ import type { Agent, OpenCodeMount, OpenCodeRuntimeHost, ToolExec } from './runtime/types.js';
24
+ export type { OpenCodeCommand, OpenCodeMount, OpenCodeRuntimeHost } from './runtime/types.js';
25
+ /** The OpenCode plugin runtime of one DSH process. */
26
+ export declare class OpenCodeRuntime {
27
+ private readonly ctx;
28
+ private readonly core;
29
+ private readonly http;
30
+ private readonly mounter;
31
+ private readonly bridge;
32
+ constructor(ctx: Context, host: OpenCodeRuntimeHost);
33
+ /** Start a plugin's Bun host and register its tools and commands. */
34
+ mount(component: CodeComponent, plugin: ForeignPlugin, options?: Record<string, unknown>): Promise<OpenCodeMount>;
35
+ /** Evidence: the commands a plugin's `config` hook added, under their DSH names, with the templates the hook gave them. */
36
+ recordAddedCommands(componentId: string, commands: ReadonlyArray<{
37
+ readonly name: string;
38
+ readonly foreignName: string;
39
+ readonly template: string;
40
+ }>): void;
41
+ /** Listen on the host. Returns the disposer. */
42
+ install(): () => Promise<void>;
43
+ /** `shell.env`: the variables plugins add to a shell call's environment. */
44
+ shellEnv(exec: ToolExec): Promise<Record<string, string>>;
45
+ /**
46
+ * `command.execute.before` for an OpenCode command about to be submitted:
47
+ * the plugin sees the command and the parts of its prompt, and may change them.
48
+ */
49
+ beforeCommand(agent: Agent, command: {
50
+ name: string;
51
+ args: string;
52
+ }, prompt: string): Promise<string[] | {
53
+ stopped: string;
54
+ }>;
55
+ }
@@ -0,0 +1,79 @@
1
+ import { onDsh } from '../dsh/host.js';
2
+ import { OpenCodeCore } from './runtime/core.js';
3
+ import { EventBridge } from './runtime/events.js';
4
+ import { PluginMounter } from './runtime/mount.js';
5
+ import { OpenCodeServer } from './runtime/server.js';
6
+ /** The OpenCode plugin runtime of one DSH process. */
7
+ export class OpenCodeRuntime {
8
+ ctx;
9
+ core;
10
+ http;
11
+ mounter;
12
+ bridge;
13
+ constructor(ctx, host) {
14
+ this.ctx = ctx;
15
+ this.core = new OpenCodeCore(ctx, host);
16
+ this.http = new OpenCodeServer(this.core);
17
+ this.mounter = new PluginMounter(this.core, this.http);
18
+ this.bridge = new EventBridge(this.core);
19
+ }
20
+ /** Start a plugin's Bun host and register its tools and commands. */
21
+ mount(component, plugin, options = {}) {
22
+ return this.mounter.mount(component, plugin, options);
23
+ }
24
+ /** Evidence: the commands a plugin's `config` hook added, under their DSH names, with the templates the hook gave them. */
25
+ recordAddedCommands(componentId, commands) {
26
+ this.mounter.recordAddedCommands(componentId, commands);
27
+ }
28
+ /** Listen on the host. Returns the disposer. */
29
+ install() {
30
+ const on = (name, listener, options) => onDsh(this.ctx, name, listener, { ...options, owner: 'opencode' });
31
+ const disposers = [
32
+ on('agent/created', ((payload) => { this.bridge.sessionCreated(payload.agent); })),
33
+ on('session/event', ((session, event) => { this.bridge.sessionEvent(session.id, event); })),
34
+ on('agent/pre-step', ((payload, next) => this.bridge.preStep(payload, next)), { prepend: true }),
35
+ on('agent/request', ((payload, next) => this.bridge.request(payload, next))),
36
+ on('tools/pre-execute', ((exec, next) => this.bridge.preExecute(exec, next)), { prepend: true }),
37
+ on('tools/post-execute', ((exec, result, next) => this.bridge.postExecute(exec, result, next)), { prepend: true }),
38
+ on('tools/result', ((exec, result) => { this.bridge.toolResult(exec, result); })),
39
+ on('approval/request', ((request, next) => this.bridge.approval(request, next)), { prepend: true }),
40
+ on('system-prompt/assemble', ((_assembly, _context, next) => this.bridge.assemble(next))),
41
+ ];
42
+ return async () => {
43
+ for (const dispose of disposers)
44
+ dispose();
45
+ // A turn's last events (session.idle, session.updated) may still be on their way to the plugins: deliver what is
46
+ // queued before the hosts stop, at most two seconds.
47
+ await Promise.race([
48
+ Promise.allSettled([...this.core.hosts.values()].map(plugin => plugin.events)),
49
+ new Promise(resolve => setTimeout(resolve, 2000).unref()),
50
+ ]);
51
+ for (const plugin of this.core.hosts.values())
52
+ plugin.stopping = true;
53
+ for (const stream of this.core.streams)
54
+ stream.end();
55
+ this.core.streams.clear();
56
+ // Stop the hosts and let them exit (at most three seconds): an exited host holds no file of its plugin.
57
+ await Promise.all([...this.core.hosts.values()].map(plugin => new Promise((resolve) => {
58
+ if (plugin.child.exitCode !== null || plugin.child.signalCode !== null)
59
+ return resolve();
60
+ const timer = setTimeout(resolve, 3000).unref();
61
+ plugin.child.once('exit', () => { clearTimeout(timer); resolve(); });
62
+ plugin.child.kill();
63
+ })));
64
+ this.core.hosts.clear();
65
+ this.http.server?.close();
66
+ };
67
+ }
68
+ /** `shell.env`: the variables plugins add to a shell call's environment. */
69
+ shellEnv(exec) {
70
+ return this.bridge.shellEnv(exec);
71
+ }
72
+ /**
73
+ * `command.execute.before` for an OpenCode command about to be submitted:
74
+ * the plugin sees the command and the parts of its prompt, and may change them.
75
+ */
76
+ beforeCommand(agent, command, prompt) {
77
+ return this.bridge.beforeCommand(agent, command, prompt);
78
+ }
79
+ }
@@ -0,0 +1,30 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { type ForeignComponent, type ForeignPlugin, type Gap } from '@kirkchinese/harness-forge-core';
3
+ /** The preset of DSH's creation mode ("Let the agent create a plugin" in the Plugin Manager). */
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. */
6
+ export interface PortLocation {
7
+ readonly workspaceId?: string;
8
+ readonly cwd?: string;
9
+ }
10
+ /** The session title for a brief: its heading, without the Markdown marker DSH would otherwise show in the sidebar. */
11
+ export declare function briefTitle(brief: string): string;
12
+ /**
13
+ * The files of one part on disk: its own files, and the whole directory of a
14
+ * skill or a code entry, whose neighbours it runs. A part declared in the
15
+ * plugin's manifest itself lists the manifest.
16
+ */
17
+ export declare function partFiles(plugin: ForeignPlugin, component: ForeignComponent): string[];
18
+ /** 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;
20
+ /** 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;
22
+ /**
23
+ * Start a creation-mode session and send it the task, as the Plugin
24
+ * Manager's creation entry and a typed message would.
25
+ * @param title - the session's name; the task's first line when absent.
26
+ * @returns the new session's id.
27
+ */
28
+ export declare function startCreatorSession(ctx: Context, task: string, location?: PortLocation, title?: string): Promise<{
29
+ sessionId: string;
30
+ }>;