@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,95 @@
1
+ /**
2
+ * Plain-data helpers for the mods engine: events and results cross between a
3
+ * mod's environment and the host as deeply frozen plain data.
4
+ * @module @kirkchinese/harness-forge/mods
5
+ */
6
+ /** Whether a value is a RegExp, from any realm. */
7
+ export function isRegExp(value) {
8
+ return Object.prototype.toString.call(value) === '[object RegExp]';
9
+ }
10
+ /** Whether a value is a plain object (not an array, RegExp or null), from any realm. */
11
+ export function isRecord(value) {
12
+ return typeof value === 'object' && value !== null && !Array.isArray(value) && !isRegExp(value);
13
+ }
14
+ /** Whether a value is a promise-like, from any realm. */
15
+ export function isThenable(value) {
16
+ return (typeof value === 'object' || typeof value === 'function') && value !== null && typeof value.then === 'function';
17
+ }
18
+ const MAX_DEPTH = 28_000;
19
+ /**
20
+ * Deeply freeze a value in place and return it. Functions (a Button's
21
+ * `onPress`) stay callable; they are frozen as objects only.
22
+ */
23
+ export function deepFreeze(value, depth = 0) {
24
+ if (depth > MAX_DEPTH)
25
+ throw new Error(`nesting deeper than ${String(MAX_DEPTH)} levels is not supported`);
26
+ if (typeof value !== 'object' || value === null || Object.isFrozen(value))
27
+ return value;
28
+ for (const key of Reflect.ownKeys(value))
29
+ deepFreeze(value[key], depth + 1);
30
+ return Object.freeze(value);
31
+ }
32
+ /**
33
+ * A frozen copy of an event as it crosses into the chain: plain objects and
34
+ * arrays are copied; functions, RegExps and other objects are kept by
35
+ * reference (a render tree's callbacks must stay the plugin's own).
36
+ */
37
+ export function frozenCopy(value, depth = 0) {
38
+ if (depth > MAX_DEPTH)
39
+ throw new Error(`nesting deeper than ${String(MAX_DEPTH)} levels is not supported`);
40
+ if (Array.isArray(value))
41
+ return Object.freeze(value.map(item => frozenCopy(item, depth + 1)));
42
+ if (isRecord(value) && isPlain(value)) {
43
+ const out = {};
44
+ for (const [key, item] of Object.entries(value))
45
+ out[key] = frozenCopy(item, depth + 1);
46
+ return Object.freeze(out);
47
+ }
48
+ return value;
49
+ }
50
+ function isPlain(value) {
51
+ const proto = Object.getPrototypeOf(value);
52
+ return proto === null || Object.getPrototypeOf(proto) === null;
53
+ }
54
+ /** JSON round trip, as `$.store.set` keeps values. */
55
+ export function jsonCopy(value) {
56
+ if (value === undefined)
57
+ return undefined;
58
+ const text = JSON.stringify(value, (_key, item) => {
59
+ if (typeof item === 'function')
60
+ throw new Error('a function is not JSON data');
61
+ if (typeof item === 'bigint')
62
+ throw new Error('a bigint is not JSON data');
63
+ return item;
64
+ });
65
+ return text === undefined ? undefined : JSON.parse(text);
66
+ }
67
+ /** Structural equality over plain data (cross-realm), as `toEqual` reads it. */
68
+ export function plainEqual(a, b) {
69
+ if (Object.is(a, b))
70
+ return true;
71
+ if (typeof a !== typeof b || a === null || b === null || typeof a !== 'object')
72
+ return false;
73
+ if (Array.isArray(a) !== Array.isArray(b))
74
+ return false;
75
+ if (Array.isArray(a)) {
76
+ const other = b;
77
+ return a.length === other.length && a.every((item, index) => plainEqual(item, other[index]));
78
+ }
79
+ const left = Object.keys(a).filter(key => a[key] !== undefined);
80
+ const right = Object.keys(b).filter(key => b[key] !== undefined);
81
+ return left.length === right.length && left.every(key => plainEqual(a[key], b[key]));
82
+ }
83
+ /** An error's text as Claude Code's notices print it: `Error: boom`. */
84
+ export function errorLine(error) {
85
+ if (typeof error === 'object' && error !== null && 'message' in error) {
86
+ const named = error.name;
87
+ const name = typeof named === 'string' ? named : 'Error';
88
+ return `${name}: ${String(error.message)}`;
89
+ }
90
+ return String(error);
91
+ }
92
+ /** An error's message alone. */
93
+ export function messageOf(error) {
94
+ return typeof error === 'object' && error !== null && 'message' in error ? String(error.message) : String(error);
95
+ }
@@ -0,0 +1,40 @@
1
+ export { npmLaunch, type Launch, type NpmEnvironment } from '../forge/npm.js';
2
+ /** What decides which platform package fits this machine. */
3
+ export interface BunPlatform {
4
+ readonly os: NodeJS.Platform;
5
+ readonly arch: string;
6
+ /** Linux with musl libc (Alpine). */
7
+ readonly musl?: boolean;
8
+ /** Whether the CPU runs AVX2 code; `undefined` when that is not known. */
9
+ readonly avx2?: boolean;
10
+ }
11
+ /** One npm package that holds a Bun binary, and where the binary is inside it. */
12
+ export interface BunPackage {
13
+ readonly name: string;
14
+ readonly exe: string;
15
+ }
16
+ /**
17
+ * The platform packages whose binary suits `platform`, best first, as the `bun`
18
+ * package's own installer chooses them: by OS, CPU and libc, with the
19
+ * `-baseline` build (no AVX2 needed) as the fallback, or first on a CPU known
20
+ * to lack AVX2. Empty for a platform Bun is not built for.
21
+ */
22
+ export declare function bunPackages(platform: BunPlatform): BunPackage[];
23
+ /** What {@link ensureBun} does outside its own logic; tests replace it. */
24
+ export interface BunHost {
25
+ readonly platform: BunPlatform;
26
+ /** The first of `candidates` that is a working Bun. */
27
+ working(candidates: readonly string[]): string | undefined;
28
+ /** `npm install <name>` into `prefix`. */
29
+ install(name: string, prefix: string): Promise<void>;
30
+ }
31
+ /** The Bun OpenCode plugins would use, without installing one. */
32
+ export declare function findBun(dataRoot: string, host?: BunHost): string | undefined;
33
+ /** Find Bun, installing it under `dataRoot` when the machine has none. */
34
+ export declare function ensureBun(dataRoot: string, host?: BunHost): Promise<string>;
35
+ /**
36
+ * Install a plugin's dependencies the way OpenCode installs a plugin package:
37
+ * production dependencies, no lifecycle scripts of the plugin's own repository.
38
+ * A plugin whose dependencies are present already is left as it is.
39
+ */
40
+ export declare function ensureDependencies(bun: string, root: string): Promise<void>;
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Bun for OpenCode plugins: OpenCode runs its plugins in Bun, so Harness
3
+ * Forge does too. A Bun on PATH or in `~/.bun` is used; otherwise one is
4
+ * installed once into Harness Forge's data directory from npm.
5
+ *
6
+ * The install is the platform package (`@oven/bun-linux-x64`, ...), which
7
+ * holds the real binary and has no install script. The `bun` package would
8
+ * need its postinstall script to put that binary in place, and npm setups that
9
+ * block install scripts (`ignore-scripts=true`, the script policies of newer
10
+ * npm) leave a placeholder that does not run.
11
+ * @module @kirkchinese/harness-forge/opencode
12
+ */
13
+ import { spawnSync } from 'node:child_process';
14
+ import { existsSync, readFileSync } from 'node:fs';
15
+ import { homedir } from 'node:os';
16
+ import { join } from 'node:path';
17
+ import { npmInstall, runProcess } from '../forge/npm.js';
18
+ export { npmLaunch } from '../forge/npm.js';
19
+ const EXE = process.platform === 'win32' ? 'bun.exe' : 'bun';
20
+ /**
21
+ * The platform packages whose binary suits `platform`, best first, as the `bun`
22
+ * package's own installer chooses them: by OS, CPU and libc, with the
23
+ * `-baseline` build (no AVX2 needed) as the fallback, or first on a CPU known
24
+ * to lack AVX2. Empty for a platform Bun is not built for.
25
+ */
26
+ export function bunPackages(platform) {
27
+ const arch = platform.arch === 'x64' ? 'x64' : platform.arch === 'arm64' ? 'aarch64' : undefined;
28
+ if (arch === undefined)
29
+ return [];
30
+ const base = (() => {
31
+ switch (platform.os) {
32
+ case 'darwin': return `bun-darwin-${arch}`;
33
+ case 'linux': return `bun-linux-${arch}${platform.musl === true ? '-musl' : ''}`;
34
+ case 'android': return `bun-linux-${arch}-android`;
35
+ case 'freebsd': return `bun-freebsd-${arch}`;
36
+ case 'win32': return `bun-windows-${arch}`;
37
+ default: return undefined;
38
+ }
39
+ })();
40
+ if (base === undefined)
41
+ return [];
42
+ const exe = platform.os === 'win32' ? 'bin/bun.exe' : 'bin/bun';
43
+ const full = { name: `@oven/${base}`, exe };
44
+ // Only x64 has baseline builds (arm64 and Android have none).
45
+ const baseline = arch === 'x64' && platform.os !== 'android' && platform.os !== 'freebsd' ? [{ name: `@oven/${base}-baseline`, exe }] : [];
46
+ return platform.avx2 === false ? [...baseline, full] : [full, ...baseline];
47
+ }
48
+ /** Whether this process runs on glibc-less Linux, the way the `bun` package decides it. */
49
+ function isMusl() {
50
+ if (process.platform !== 'linux')
51
+ return false;
52
+ try {
53
+ const report = process.report?.getReport()?.header;
54
+ if (report !== undefined)
55
+ return report.glibcVersionRuntime === undefined;
56
+ }
57
+ catch {
58
+ // Fall through to the Alpine marker.
59
+ }
60
+ return existsSync('/etc/alpine-release');
61
+ }
62
+ /** The machine's platform, with the CPU's AVX2 support where it can be read cheaply (Linux). */
63
+ function currentPlatform() {
64
+ let avx2;
65
+ if (process.platform === 'linux') {
66
+ try {
67
+ avx2 = /\bavx2\b/u.test(readFileSync('/proc/cpuinfo', 'utf8'));
68
+ }
69
+ catch {
70
+ avx2 = undefined;
71
+ }
72
+ }
73
+ return { os: process.platform, arch: process.arch, musl: isMusl(), ...avx2 !== undefined ? { avx2 } : {} };
74
+ }
75
+ /** The first Bun that answers `--version`. */
76
+ function working(candidates) {
77
+ for (const candidate of candidates) {
78
+ const probe = spawnSync(candidate, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 20_000 });
79
+ if (probe.status === 0 && /^\d+\.\d+/u.test(probe.stdout.trim()))
80
+ return candidate;
81
+ }
82
+ return undefined;
83
+ }
84
+ const defaultHost = {
85
+ get platform() { return currentPlatform(); },
86
+ working,
87
+ // No install scripts run: the platform package has none, and a policy that blocks them must not matter.
88
+ install: (name, prefix) => npmInstall([name], prefix),
89
+ };
90
+ /** Where a Bun is looked for, in order: the person's, then the one Harness Forge installed. */
91
+ function candidates(dataRoot, packages) {
92
+ const prefix = join(dataRoot, 'bun');
93
+ return [
94
+ ...(process.env['BUN_PATH'] !== undefined ? [process.env['BUN_PATH']] : []),
95
+ 'bun',
96
+ join(homedir(), '.bun', 'bin', EXE),
97
+ ...packages.map(item => localBinary(prefix, item)),
98
+ // Earlier versions installed the `bun` package; its binary counts when it works.
99
+ join(prefix, 'node_modules', 'bun', 'bin', 'bun.exe'),
100
+ ];
101
+ }
102
+ function localBinary(prefix, item) {
103
+ return join(prefix, 'node_modules', ...item.name.split('/'), ...item.exe.split('/'));
104
+ }
105
+ /** The Bun OpenCode plugins would use, without installing one. */
106
+ export function findBun(dataRoot, host = defaultHost) {
107
+ return host.working(candidates(dataRoot, bunPackages(host.platform)));
108
+ }
109
+ /** Find Bun, installing it under `dataRoot` when the machine has none. */
110
+ export async function ensureBun(dataRoot, host = defaultHost) {
111
+ const prefix = join(dataRoot, 'bun');
112
+ const packages = bunPackages(host.platform);
113
+ const localOf = (item) => localBinary(prefix, item);
114
+ const found = host.working(candidates(dataRoot, packages));
115
+ if (found !== undefined)
116
+ return found;
117
+ const problems = [];
118
+ if (packages.length === 0)
119
+ problems.push(`Bun has no build for ${host.platform.os} ${host.platform.arch}`);
120
+ for (const item of packages) {
121
+ try {
122
+ await host.install(item.name, prefix);
123
+ }
124
+ catch (error) {
125
+ problems.push(`${item.name}: ${error instanceof Error ? error.message : String(error)}`);
126
+ continue;
127
+ }
128
+ const installed = host.working([localOf(item)]);
129
+ if (installed !== undefined)
130
+ return installed;
131
+ problems.push(`${item.name} was installed into ${prefix} but does not run`);
132
+ }
133
+ throw new Error(`Bun is needed to run OpenCode plugins and could not be installed automatically (${problems.join('; ')}). Install Bun (https://bun.sh), or set BUN_PATH to a working bun executable, then restart DSH.`);
134
+ }
135
+ /**
136
+ * Install a plugin's dependencies the way OpenCode installs a plugin package:
137
+ * production dependencies, no lifecycle scripts of the plugin's own repository.
138
+ * A plugin whose dependencies are present already is left as it is.
139
+ */
140
+ export async function ensureDependencies(bun, root) {
141
+ const manifest = join(root, 'package.json');
142
+ if (!existsSync(manifest))
143
+ return;
144
+ let declared = {};
145
+ try {
146
+ const parsed = JSON.parse(readFileSync(manifest, 'utf8'));
147
+ declared = { ...(parsed['dependencies'] ?? {}), ...(parsed['peerDependencies'] ?? {}) };
148
+ }
149
+ catch {
150
+ return;
151
+ }
152
+ const missing = Object.keys(declared).filter(name => !existsSync(join(root, 'node_modules', ...name.split('/'))));
153
+ if (missing.length === 0)
154
+ return;
155
+ await runProcess(bun, ['install', '--production', '--ignore-scripts'], root, 600_000);
156
+ }
@@ -0,0 +1,53 @@
1
+ /** OpenCode's name for a DSH tool; MCP and plugin tools keep theirs. */
2
+ export declare function openCodeToolName(dshName: string): string;
3
+ /** OpenCode's permission name for a DSH tool (`bash`, `edit`, `webfetch`, ...). */
4
+ export declare function permissionType(dshName: string): string;
5
+ /** A DSH call's arguments as OpenCode's tool of the same name takes them. */
6
+ export declare function openCodeArgs(dshName: string, args: unknown, cwd: string): Record<string, unknown>;
7
+ /** OpenCode-named arguments back as the DSH tool takes them; DSH-only fields keep their values. */
8
+ export declare function dshArgs(dshName: string, original: unknown, updated: Record<string, unknown>): Record<string, unknown>;
9
+ /** The DSH facts one OpenCode view is built from. */
10
+ export interface SessionFacts {
11
+ readonly id: string;
12
+ readonly cwd: string;
13
+ readonly projectId: string;
14
+ readonly worktree: string;
15
+ readonly parentId?: string;
16
+ readonly title: string;
17
+ readonly created: number;
18
+ readonly updated: number;
19
+ readonly provider: string;
20
+ readonly model: string;
21
+ readonly agent: string;
22
+ }
23
+ /** OpenCode's `Session`. */
24
+ export declare function sessionInfo(facts: SessionFacts): Record<string, unknown>;
25
+ /** One logged event of a DSH session, as read back. */
26
+ export interface LoggedEvent {
27
+ readonly type: string;
28
+ readonly seq: number;
29
+ readonly time: number;
30
+ readonly data: unknown;
31
+ }
32
+ /** One OpenCode message with its parts. */
33
+ export interface MessageWithParts {
34
+ readonly info: Record<string, unknown>;
35
+ readonly parts: Array<Record<string, unknown>>;
36
+ }
37
+ /** OpenCode's user message (info) for one DSH user message. */
38
+ export declare function userInfo(facts: SessionFacts, message: Record<string, unknown>, time: number): Record<string, unknown>;
39
+ /** OpenCode's parts for one DSH user message: text and file parts, synthetic unless typed by a person. */
40
+ export declare function userParts(sessionId: string, message: Record<string, unknown>): Array<Record<string, unknown>>;
41
+ /**
42
+ * A DSH session log as OpenCode's messages: each user message, and each
43
+ * step's assistant message with its text, reasoning and tool parts (a tool
44
+ * part completed or errored by its logged result).
45
+ */
46
+ export declare function messagesOf(facts: SessionFacts, events: readonly LoggedEvent[]): MessageWithParts[];
47
+ /** OpenCode's tool part for one DSH tool call, running until its result settles it. */
48
+ export declare function toolPart(base: Record<string, unknown>, call: Record<string, unknown>, result: {
49
+ text: string;
50
+ isError: boolean;
51
+ time: number;
52
+ } | undefined, cwd: string, time: number): Record<string, unknown>;
53
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,255 @@
1
+ /**
2
+ * DSH ↔ OpenCode vocabulary: tool names and arguments as OpenCode's own tools
3
+ * name them, and a DSH session log as OpenCode's sessions, messages and parts
4
+ * (`@opencode-ai/sdk` v1 types).
5
+ * @module @kirkchinese/harness-forge/opencode
6
+ */
7
+ import { isAbsolute, resolve } from 'node:path';
8
+ /** DSH tool → OpenCode's built-in tool of the same job. */
9
+ const TOOL_NAMES = {
10
+ bash: 'bash',
11
+ pwsh: 'bash',
12
+ read: 'read',
13
+ read_image: 'read',
14
+ write: 'write',
15
+ edit: 'edit',
16
+ glob: 'glob',
17
+ grep: 'grep',
18
+ web_fetch: 'webfetch',
19
+ web_search: 'websearch',
20
+ todo_write: 'todowrite',
21
+ subagent: 'task',
22
+ subagent_fork: 'task',
23
+ agent: 'task',
24
+ skill: 'skill',
25
+ ask_user_question: 'question',
26
+ };
27
+ /** OpenCode's name for a DSH tool; MCP and plugin tools keep theirs. */
28
+ export function openCodeToolName(dshName) {
29
+ return TOOL_NAMES[dshName] ?? dshName;
30
+ }
31
+ /** OpenCode's permission name for a DSH tool (`bash`, `edit`, `webfetch`, ...). */
32
+ export function permissionType(dshName) {
33
+ const name = openCodeToolName(dshName);
34
+ return name === 'write' ? 'edit' : name;
35
+ }
36
+ const absolute = (path, cwd) => (typeof path === 'string' && path.length > 0 && !isAbsolute(path) ? resolve(cwd, path) : path);
37
+ /** A DSH call's arguments as OpenCode's tool of the same name takes them. */
38
+ export function openCodeArgs(dshName, args, cwd) {
39
+ const input = isRecord(args) ? args : {};
40
+ switch (openCodeToolName(dshName)) {
41
+ case 'bash':
42
+ return {
43
+ command: input['command'],
44
+ description: input['description'] ?? '',
45
+ ...(typeof input['timeoutMs'] === 'number' ? { timeout: input['timeoutMs'] } : {}),
46
+ ...(typeof input['workdir'] === 'string' ? { workdir: input['workdir'] } : {}),
47
+ };
48
+ case 'read':
49
+ return { filePath: absolute(input['file_path'] ?? input['path'], cwd), ...pick(input, { offset: 'offset', limit: 'limit' }) };
50
+ case 'write':
51
+ return { filePath: absolute(input['file_path'], cwd), content: input['content'] };
52
+ case 'edit':
53
+ return {
54
+ filePath: absolute(input['file_path'], cwd),
55
+ oldString: input['old_string'],
56
+ newString: input['new_string'],
57
+ ...(input['replace_all'] === true ? { replaceAll: true } : {}),
58
+ };
59
+ case 'glob':
60
+ return { pattern: input['pattern'], ...(typeof input['path'] === 'string' ? { path: absolute(input['path'], cwd) } : {}) };
61
+ case 'grep':
62
+ return {
63
+ pattern: input['pattern'],
64
+ ...(typeof input['path'] === 'string' ? { path: absolute(input['path'], cwd) } : {}),
65
+ ...(typeof input['include'] === 'string' ? { include: input['include'] } : {}),
66
+ };
67
+ case 'webfetch':
68
+ return { url: input['url'], format: 'markdown' };
69
+ case 'websearch': {
70
+ const queries = Array.isArray(input['queries']) ? input['queries'].map(String) : [];
71
+ return { query: queries[0] ?? '' };
72
+ }
73
+ case 'task':
74
+ return { description: input['description'] ?? '', prompt: input['prompt'], subagent_type: input['agent_preset'] ?? 'general' };
75
+ case 'skill':
76
+ return { name: input['name'] };
77
+ default:
78
+ return { ...input };
79
+ }
80
+ }
81
+ /** OpenCode-named arguments back as the DSH tool takes them; DSH-only fields keep their values. */
82
+ export function dshArgs(dshName, original, updated) {
83
+ const base = isRecord(original) ? original : {};
84
+ switch (openCodeToolName(dshName)) {
85
+ case 'bash':
86
+ return {
87
+ ...base,
88
+ command: updated['command'] ?? base['command'],
89
+ ...(typeof updated['description'] === 'string' ? { description: updated['description'] } : {}),
90
+ ...(typeof updated['timeout'] === 'number' ? { timeoutMs: updated['timeout'] } : {}),
91
+ ...(typeof updated['workdir'] === 'string' ? { workdir: updated['workdir'] } : {}),
92
+ };
93
+ case 'read':
94
+ return { ...base, file_path: updated['filePath'] ?? base['file_path'], ...pick(updated, { offset: 'offset', limit: 'limit' }) };
95
+ case 'write':
96
+ return { ...base, file_path: updated['filePath'] ?? base['file_path'], content: updated['content'] ?? base['content'] };
97
+ case 'edit':
98
+ return {
99
+ ...base,
100
+ file_path: updated['filePath'] ?? base['file_path'],
101
+ old_string: updated['oldString'] ?? base['old_string'],
102
+ new_string: updated['newString'] ?? base['new_string'],
103
+ ...(typeof updated['replaceAll'] === 'boolean' ? { replace_all: updated['replaceAll'] } : {}),
104
+ };
105
+ case 'glob':
106
+ case 'grep':
107
+ return { ...base, ...updated };
108
+ case 'webfetch':
109
+ return { ...base, url: updated['url'] ?? base['url'] };
110
+ case 'websearch':
111
+ return { ...base, queries: typeof updated['query'] === 'string' ? [updated['query']] : base['queries'] };
112
+ case 'task':
113
+ return { ...base, prompt: updated['prompt'] ?? base['prompt'], description: updated['description'] ?? base['description'] };
114
+ case 'skill':
115
+ return { ...base, name: updated['name'] ?? base['name'] };
116
+ default:
117
+ return updated;
118
+ }
119
+ }
120
+ function pick(input, names) {
121
+ const out = {};
122
+ for (const [from, to] of Object.entries(names))
123
+ if (input[from] !== undefined)
124
+ out[to] = input[from];
125
+ return out;
126
+ }
127
+ /** OpenCode's `Session`. */
128
+ export function sessionInfo(facts) {
129
+ return {
130
+ id: facts.id,
131
+ projectID: facts.projectId,
132
+ directory: facts.cwd,
133
+ ...(facts.parentId !== undefined ? { parentID: facts.parentId } : {}),
134
+ title: facts.title,
135
+ version: '1.19.6',
136
+ time: { created: facts.created, updated: facts.updated },
137
+ };
138
+ }
139
+ /** Block arrays of a DSH message. */
140
+ function blocksOf(message) {
141
+ return isRecord(message) && Array.isArray(message['content']) ? message['content'].filter(isRecord) : [];
142
+ }
143
+ /** OpenCode's user message (info) for one DSH user message. */
144
+ export function userInfo(facts, message, time) {
145
+ return {
146
+ id: String(message['id'] ?? `msg_${time}`),
147
+ sessionID: facts.id,
148
+ role: 'user',
149
+ time: { created: time },
150
+ agent: facts.agent,
151
+ model: { providerID: facts.provider, modelID: facts.model },
152
+ };
153
+ }
154
+ /** OpenCode's parts for one DSH user message: text and file parts, synthetic unless typed by a person. */
155
+ export function userParts(sessionId, message) {
156
+ const messageId = String(message['id'] ?? '');
157
+ const source = isRecord(message['source']) ? message['source'] : {};
158
+ const synthetic = source['kind'] !== 'user' || source['synthetic'] === true;
159
+ return blocksOf(message).flatMap((block, index) => {
160
+ const base = { id: `prt_${messageId}_${index}`, sessionID: sessionId, messageID: messageId };
161
+ if (block['type'] === 'text')
162
+ return [{ ...base, type: 'text', text: String(block['text'] ?? ''), ...(synthetic ? { synthetic: true } : {}) }];
163
+ if (block['type'] === 'image' || block['type'] === 'file') {
164
+ const attachment = isRecord(block['attachment']) ? block['attachment'] : {};
165
+ return [{ ...base, type: 'file', mime: String(attachment['mediaType'] ?? attachment['mimeType'] ?? 'application/octet-stream'), url: String(attachment['url'] ?? attachment['uri'] ?? ''), ...(typeof attachment['name'] === 'string' ? { filename: attachment['name'] } : {}) }];
166
+ }
167
+ return [];
168
+ });
169
+ }
170
+ /**
171
+ * A DSH session log as OpenCode's messages: each user message, and each
172
+ * step's assistant message with its text, reasoning and tool parts (a tool
173
+ * part completed or errored by its logged result).
174
+ */
175
+ export function messagesOf(facts, events) {
176
+ const out = [];
177
+ const results = new Map();
178
+ for (const event of events) {
179
+ if (event.type !== 'tool/result' || !isRecord(event.data))
180
+ continue;
181
+ const message = isRecord(event.data['message']) ? event.data['message'] : {};
182
+ const text = blocksOf(message).filter(block => block['type'] === 'text').map(block => String(block['text'] ?? '')).join('');
183
+ results.set(String(message['toolCallId'] ?? ''), { text, isError: message['isError'] === true, time: event.time });
184
+ }
185
+ let lastUser = '';
186
+ for (const event of events) {
187
+ if (event.type === 'user/message' && isRecord(event.data)) {
188
+ const info = userInfo(facts, event.data, event.time);
189
+ lastUser = String(info['id']);
190
+ out.push({ info, parts: userParts(facts.id, event.data) });
191
+ continue;
192
+ }
193
+ if (event.type !== 'assistant/message' || !isRecord(event.data))
194
+ continue;
195
+ const data = event.data;
196
+ const message = isRecord(data['message']) ? data['message'] : {};
197
+ const id = String(message['id'] ?? `msg_${String(data['turn'])}_${String(data['step'])}`);
198
+ const usage = isRecord(data['usage']) ? data['usage'] : {};
199
+ const blocks = blocksOf(message);
200
+ const calls = blocks.filter(block => block['type'] === 'tool-call');
201
+ const info = {
202
+ id,
203
+ sessionID: facts.id,
204
+ role: 'assistant',
205
+ time: { created: event.time, completed: event.time },
206
+ parentID: lastUser,
207
+ modelID: facts.model,
208
+ providerID: facts.provider,
209
+ mode: facts.agent,
210
+ path: { cwd: facts.cwd, root: facts.worktree },
211
+ cost: 0,
212
+ tokens: {
213
+ input: Number(usage['inputTokens'] ?? 0),
214
+ output: Number(usage['outputTokens'] ?? 0),
215
+ reasoning: Number(usage['reasoningTokens'] ?? 0),
216
+ cache: { read: Number(usage['cacheReadTokens'] ?? 0), write: Number(usage['cacheWriteTokens'] ?? 0) },
217
+ },
218
+ finish: calls.length > 0 ? 'tool-calls' : data['interrupted'] === true ? 'aborted' : 'stop',
219
+ };
220
+ const parts = blocks.flatMap((block, index) => {
221
+ const base = { id: `prt_${id}_${index}`, sessionID: facts.id, messageID: id };
222
+ if (block['type'] === 'text')
223
+ return [{ ...base, type: 'text', text: String(block['text'] ?? ''), time: { start: event.time, end: event.time } }];
224
+ if (block['type'] === 'reasoning')
225
+ return [{ ...base, type: 'reasoning', text: String(block['text'] ?? ''), time: { start: event.time, end: event.time } }];
226
+ if (block['type'] === 'tool-call')
227
+ return [toolPart(base, block, results.get(String(block['id'] ?? '')), facts.cwd, event.time)];
228
+ return [];
229
+ });
230
+ out.push({ info, parts });
231
+ }
232
+ return out;
233
+ }
234
+ /** OpenCode's tool part for one DSH tool call, running until its result settles it. */
235
+ export function toolPart(base, call, result, cwd, time) {
236
+ const dshName = String(call['name'] ?? '');
237
+ let args = {};
238
+ try {
239
+ args = typeof call['arguments'] === 'string' ? JSON.parse(call['arguments']) : call['arguments'];
240
+ }
241
+ catch {
242
+ args = {};
243
+ }
244
+ const input = openCodeArgs(dshName, args, cwd);
245
+ const tool = openCodeToolName(dshName);
246
+ const state = result === undefined
247
+ ? { status: 'running', input, time: { start: time } }
248
+ : result.isError
249
+ ? { status: 'error', input, error: result.text, time: { start: time, end: result.time } }
250
+ : { status: 'completed', input, output: result.text, title: tool, metadata: {}, time: { start: time, end: result.time } };
251
+ return { ...base, type: 'tool', callID: String(call['id'] ?? ''), tool, state };
252
+ }
253
+ export function isRecord(value) {
254
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
255
+ }
@@ -0,0 +1,9 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { Disposer } from '../forge/contract.js';
3
+ import { type HarnessForge } from '../forge/service.js';
4
+ export declare const name = "harness-forge-opencode";
5
+ export declare const inject: string[];
6
+ /** The OpenCode row. */
7
+ export declare function apply(ctx: Context): void;
8
+ /** Start the OpenCode row on the shared service. Returns its teardown. */
9
+ export declare function startOpenCode(ctx: Context, forge: HarnessForge): Disposer;