@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.30

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 (152) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/README.md +564 -97
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +11 -5
  6. package/dist/agents.js +16 -10
  7. package/dist/app.js +80 -20
  8. package/dist/background.d.ts +28 -0
  9. package/dist/background.js +376 -0
  10. package/dist/box-egress.d.ts +98 -0
  11. package/dist/box-egress.js +259 -0
  12. package/dist/box-image.d.ts +1 -1
  13. package/dist/box-image.js +9 -7
  14. package/dist/box-relay-vm.d.ts +80 -0
  15. package/dist/box-relay-vm.js +389 -0
  16. package/dist/box-relay.d.ts +8 -5
  17. package/dist/box-relay.js +14 -9
  18. package/dist/boxes.d.ts +21 -3
  19. package/dist/boxes.js +14 -7
  20. package/dist/browser-cost.d.ts +41 -0
  21. package/dist/browser-cost.js +158 -0
  22. package/dist/cap.d.ts +129 -21
  23. package/dist/cap.js +338 -67
  24. package/dist/coding-tools.d.ts +7 -3
  25. package/dist/coding-tools.js +16 -10
  26. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  27. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  28. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  29. package/dist/console/index.html +2 -2
  30. package/dist/content-filter.d.ts +7 -0
  31. package/dist/content-filter.js +23 -0
  32. package/dist/decision-rows.d.ts +11 -3
  33. package/dist/decision-rows.js +18 -11
  34. package/dist/errors.d.ts +2 -0
  35. package/dist/errors.js +5 -2
  36. package/dist/files.d.ts +6 -1
  37. package/dist/files.js +7 -2
  38. package/dist/grade.d.ts +7 -10
  39. package/dist/grade.js +31 -51
  40. package/dist/graph-served.d.ts +23 -0
  41. package/dist/graph-served.js +75 -0
  42. package/dist/graph-view.d.ts +7 -5
  43. package/dist/graph-view.js +10 -3
  44. package/dist/harness-app.d.ts +4 -2
  45. package/dist/harness-app.js +101 -19
  46. package/dist/harness-opencode/adapter.d.ts +45 -0
  47. package/dist/harness-opencode/adapter.js +272 -0
  48. package/dist/harness-opencode/binary.d.ts +18 -0
  49. package/dist/harness-opencode/binary.js +87 -0
  50. package/dist/harness-opencode/config.d.ts +24 -0
  51. package/dist/harness-opencode/config.js +61 -0
  52. package/dist/harness-opencode/harness.d.ts +77 -0
  53. package/dist/harness-opencode/harness.js +620 -0
  54. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  55. package/dist/harness-opencode/host/mcp.js +208 -0
  56. package/dist/harness-opencode/host/policy.d.ts +71 -0
  57. package/dist/harness-opencode/host/policy.js +419 -0
  58. package/dist/harness-opencode/host/server.d.ts +55 -0
  59. package/dist/harness-opencode/host/server.js +165 -0
  60. package/dist/harness-opencode/index.d.ts +9 -0
  61. package/dist/harness-opencode/index.js +6 -0
  62. package/dist/harness-opencode/verify.d.ts +32 -0
  63. package/dist/harness-opencode/verify.js +75 -0
  64. package/dist/harness-opencode/versions.d.ts +33 -0
  65. package/dist/harness-opencode/versions.js +64 -0
  66. package/dist/harness.d.ts +4 -1
  67. package/dist/harness.js +5 -2
  68. package/dist/host-tools.d.ts +12 -2
  69. package/dist/host-tools.js +26 -12
  70. package/dist/host.js +6 -2
  71. package/dist/hosted-search.js +5 -1
  72. package/dist/import.d.ts +2 -2
  73. package/dist/import.js +4 -3
  74. package/dist/key-check.d.ts +3 -2
  75. package/dist/key-check.js +7 -3
  76. package/dist/key-refusal.js +8 -4
  77. package/dist/learn/check.d.ts +10 -1
  78. package/dist/learn/check.js +19 -1
  79. package/dist/learn/grade.d.ts +3 -2
  80. package/dist/learn/grade.js +25 -13
  81. package/dist/learn/index.d.ts +2 -2
  82. package/dist/learn/index.js +2 -2
  83. package/dist/learn/notes.js +2 -1
  84. package/dist/learn/reflect.d.ts +2 -2
  85. package/dist/learn/reflect.js +51 -5
  86. package/dist/learn/secrets.js +28 -8
  87. package/dist/learn/skills.d.ts +17 -4
  88. package/dist/learn/skills.js +79 -6
  89. package/dist/learned-workflow.d.ts +59 -0
  90. package/dist/learned-workflow.js +191 -0
  91. package/dist/learning-run.d.ts +7 -5
  92. package/dist/learning-run.js +45 -23
  93. package/dist/learning-words.d.ts +6 -3
  94. package/dist/learning-words.js +8 -5
  95. package/dist/learning.d.ts +44 -3
  96. package/dist/learning.js +148 -3
  97. package/dist/mcp-servers.d.ts +7 -4
  98. package/dist/mcp-servers.js +5 -0
  99. package/dist/mcp.js +5 -5
  100. package/dist/model.d.ts +13 -11
  101. package/dist/model.js +11 -10
  102. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  103. package/dist/openapi.js +358 -48
  104. package/dist/paid-calls.d.ts +5 -1
  105. package/dist/paid-calls.js +1 -1
  106. package/dist/pause.d.ts +2 -0
  107. package/dist/place.d.ts +27 -4
  108. package/dist/place.js +42 -10
  109. package/dist/propose.d.ts +2 -0
  110. package/dist/propose.js +38 -8
  111. package/dist/request-start.d.ts +12 -4
  112. package/dist/request-start.js +139 -15
  113. package/dist/run-box.d.ts +56 -4
  114. package/dist/run-box.js +173 -23
  115. package/dist/runnable.d.ts +5 -2
  116. package/dist/runnable.js +12 -4
  117. package/dist/runs.d.ts +258 -36
  118. package/dist/runs.js +830 -89
  119. package/dist/secrets.d.ts +12 -0
  120. package/dist/secrets.js +18 -0
  121. package/dist/server.d.ts +131 -35
  122. package/dist/server.js +467 -105
  123. package/dist/sign-ins.d.ts +99 -0
  124. package/dist/sign-ins.js +288 -0
  125. package/dist/skills.d.ts +16 -4
  126. package/dist/skills.js +35 -7
  127. package/dist/stats.d.ts +7 -2
  128. package/dist/stats.js +28 -7
  129. package/dist/tool-gate.d.ts +266 -0
  130. package/dist/tool-gate.js +554 -0
  131. package/dist/tool-keys.d.ts +46 -10
  132. package/dist/tool-keys.js +44 -2
  133. package/dist/tool-plane.d.ts +112 -27
  134. package/dist/tool-plane.js +205 -47
  135. package/dist/tools.d.ts +69 -14
  136. package/dist/tools.js +143 -24
  137. package/dist/trigger-secrets.d.ts +32 -0
  138. package/dist/trigger-secrets.js +143 -0
  139. package/dist/triggers.d.ts +439 -0
  140. package/dist/triggers.js +863 -0
  141. package/dist/turn-end.d.ts +3 -2
  142. package/dist/turn-end.js +3 -2
  143. package/dist/usage-lines.d.ts +26 -0
  144. package/dist/usage-lines.js +28 -0
  145. package/dist/validate.d.ts +2 -0
  146. package/dist/validate.js +11 -2
  147. package/dist/webhooks.d.ts +11 -4
  148. package/dist/webhooks.js +17 -1
  149. package/launcher/agentrun-serve +1 -1
  150. package/package.json +19 -13
  151. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  152. package/dist/console/assets/index-By-jkqki.css +0 -1
@@ -0,0 +1,272 @@
1
+ // OpenCode as an AgentRun harness adapter. Written for AgentRun.
2
+ //
3
+ // A session is the OpenCode harness (harness.ts) driven over the session's own records (the kernel's openDrive on the
4
+ // writer the runner lends, `io.writer`): the pinned `opencode serve`, one per drive, with every OpenCode tool off, its
5
+ // model behind the session's loopback proxy (@parcha/agentrun-kernel/host) and the host's tools, exactly those `spec.tools`
6
+ // names, as its only tools, served over the adapter's own MCP server. Every paid request passes the runner's
7
+ // `beforeRequest` first, and its usage comes back through `afterRequest`.
8
+ //
9
+ // The host's skills (`skills`) are listed in the session's instructions by name and description, and the model reads a
10
+ // skill's files with `read_skill_file`: OpenCode's own skills are off.
11
+ import { createHash, randomUUID } from "node:crypto";
12
+ import { join } from "node:path";
13
+ import { READ_SKILL_FILE, readSkillFileTool, skillProblems, toolSchemaProblems } from "@parcha/agentrun-kernel";
14
+ import { abortedOutcome, openDrive, pendingSubmissions, SessionHalt } from "@parcha/agentrun-kernel/kernel";
15
+ import { recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
16
+ import { serialWriter } from "@parcha/agentrun-kernel/host";
17
+ import { OPENCODE_VERSION } from "./binary.js";
18
+ import { openCodeHarness, sentSubmissions } from "./harness.js";
19
+ import { TOOL_PREFIX } from "./host/policy.js";
20
+ import { verifyOpenCode } from "./verify.js";
21
+ /** A name OpenCode keeps whole for an MCP tool (it turns anything else into `_`), short enough that `hands_<name>` is a
22
+ * function name the Responses API takes (at most 64). */
23
+ const TOOL_NAME = new RegExp(`^[A-Za-z0-9_-]{1,${64 - TOOL_PREFIX.length}}$`);
24
+ /** How long a stop waits for OpenCode to end the turn itself before the drive is halted. */
25
+ const INTERRUPT_MS = 3_000;
26
+ /** `opencode serve` on this machine only, on a port of its choosing (its listening line says which). */
27
+ const SERVE_ARGS = ["serve", "--hostname", "127.0.0.1", "--port", "0"]; // key-gate: loopback-rule opencode serve listens on 127.0.0.1 only, on a port of its choosing
28
+ /** The kernel's tool for a host tool: the same name, schema and replay policy; a host's error result is the call's
29
+ * failure. The call runs as a kernel effect, whose intent is durable in the session's records before `execute` is
30
+ * entered, so a crash inside a `never` tool is always reported, never repeated. */
31
+ function kernelTool(tool) {
32
+ return {
33
+ name: tool.name,
34
+ description: tool.description,
35
+ inputSchema: tool.inputSchema,
36
+ replay: tool.replay,
37
+ async execute(input, io) {
38
+ // The effect's step is `tool:<the model's call id>#<attempt>`: the host sees the model's call id.
39
+ const callId = (io.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
40
+ const result = await tool.call(input, { callId, signal: io.signal });
41
+ if (result.isError)
42
+ throw new Error(result.text);
43
+ return result.images?.length ? { text: result.text, images: result.images } : result.text;
44
+ },
45
+ };
46
+ }
47
+ /** The adapter's event for a harness live event, if it has one: exactly the four a host reads. A call's `tool_end`
48
+ * carries the result text the log recorded; names are the host's own (the bridge is keyed by them). */
49
+ function adapterEvent(event) {
50
+ const e = event;
51
+ if (e?.type === "text" && typeof e.delta === "string")
52
+ return { type: "text", delta: e.delta };
53
+ if (e?.type === "tool_start" && typeof e.name === "string")
54
+ return { type: "tool_start", callId: String(e.callId ?? ""), name: e.name, args: e.args };
55
+ if (e?.type === "tool_end" && typeof e.name === "string")
56
+ return { type: "tool_end", callId: String(e.callId ?? ""), name: e.name, isError: e.isError === true, ...(typeof e.result === "string" ? { result: e.result } : {}), ...(e.truncated === true ? { truncated: true } : {}) };
57
+ return undefined;
58
+ }
59
+ const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
60
+ /** The skills as the instructions list them: each by name and description, read with `read_skill_file`. */
61
+ function skillsNote(skills) {
62
+ const lines = ["You have these skills. Read a skill's SKILL.md with read_skill_file before you use it, and the files it names the same way."];
63
+ for (const skill of skills) {
64
+ const head = /^---\n([\s\S]*?)\n---/.exec(skill.files["SKILL.md"] ?? "")?.[1] ?? "";
65
+ const description = /^description:\s*(.+)$/m.exec(head)?.[1]?.trim().replace(/^["']|["']$/g, "") ?? "";
66
+ lines.push(`- ${skill.name}: ${description}`);
67
+ }
68
+ return lines.join("\n");
69
+ }
70
+ export function openCodeAdapter(options) {
71
+ const skills = options.skills ?? [];
72
+ const skillsWrong = skillProblems(skills);
73
+ if (skillsWrong.length)
74
+ throw new Error(`opencode: ${skillsWrong.join("; ")}`);
75
+ // The binary is checked once, here, against the pins: a mismatch or a missing binary is the host's to report, before
76
+ // any run starts (OpenCodePinMismatch, OpenCodeNotInstalled). A test's stand-in runs no OpenCode.
77
+ if (options.standIn) {
78
+ if (process.env.AGENTRUN_OPENCODE_STANDIN !== "1")
79
+ throw new TypeError("opencode: a stand-in for OpenCode needs AGENTRUN_OPENCODE_STANDIN=1");
80
+ if (!process.env.NODE_TEST_CONTEXT && process.env.NODE_ENV !== "test")
81
+ throw new TypeError("opencode: a stand-in for OpenCode runs only under a test runner");
82
+ }
83
+ const checked = options.standIn ? undefined : verifyOpenCode().path;
84
+ const modelFor = (spec) => {
85
+ if (typeof options.model === "string")
86
+ return options.model;
87
+ return (spec.tier && spec.tier !== "default" ? options.model[spec.tier] : undefined) ?? options.model.default;
88
+ };
89
+ return {
90
+ id: "opencode",
91
+ version: OPENCODE_VERSION,
92
+ capabilities: () => ({ fork: false }),
93
+ check(spec) {
94
+ const problems = [];
95
+ if (spec.context === "fork")
96
+ problems.push("OpenCode sessions cannot fork another session's transcript; declare context: \"fresh\"");
97
+ const seen = new Set();
98
+ for (const tool of spec.tools) {
99
+ if (!TOOL_NAME.test(tool.name))
100
+ problems.push(`the tool name ${JSON.stringify(tool.name.slice(0, 80))} is not one OpenCode keeps whole (letters, digits, _ and -, at most ${64 - TOOL_PREFIX.length})`);
101
+ if (seen.has(tool.name))
102
+ problems.push(`the tool ${tool.name} is given twice`);
103
+ if (skills.length && tool.name === READ_SKILL_FILE)
104
+ problems.push(`the tool name ${READ_SKILL_FILE} is the adapter's own when it has skills`);
105
+ seen.add(tool.name);
106
+ try {
107
+ problems.push(...toolSchemaProblems(tool.name, tool.inputSchema));
108
+ }
109
+ catch (error) {
110
+ problems.push(`${tool.name}: /: the tool's schema could not be checked (${String(error?.message ?? error).slice(0, 120)})`);
111
+ }
112
+ }
113
+ return problems;
114
+ },
115
+ async open(spec, io) {
116
+ const problems = this.check(spec);
117
+ if (problems.length)
118
+ throw new Error(`opencode: ${problems.join("; ")}`);
119
+ const dir = io.dir ?? (options.sessionsDir ? join(options.sessionsDir, createHash("sha256").update(spec.key).digest("hex").slice(0, 32)) : undefined);
120
+ if (!dir)
121
+ throw new Error("opencode: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
122
+ // With skills the model also reads their files (read_skill_file), from the session's own copy of them.
123
+ const skillsDir = join(dir, "skills");
124
+ const tools = skills.length ? [...spec.tools, readSkillFileTool(skillsDir, skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) })))] : spec.tools;
125
+ if (skills.length) {
126
+ const { mkdirSync, writeFileSync } = await import("node:fs");
127
+ const { dirname } = await import("node:path");
128
+ for (const skill of skills) {
129
+ for (const [path, text] of Object.entries(skill.files)) {
130
+ const file = join(skillsDir, skill.name, path);
131
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
132
+ writeFileSync(file, text, { mode: 0o600 });
133
+ }
134
+ }
135
+ }
136
+ const instructions = [...spec.system, ...(skills.length ? [skillsNote(skills)] : [])].join("\n\n");
137
+ const effort = spec.effort ?? spec.thinking;
138
+ let control;
139
+ const harness = openCodeHarness({
140
+ tools: tools.map(kernelTool),
141
+ model: modelFor(spec),
142
+ ...(instructions ? { instructions } : {}),
143
+ ...(effort ? { effort: String(effort) } : {}),
144
+ dir,
145
+ ...(io.cwd ? { cwd: io.cwd } : {}),
146
+ // A stand-in is given the same server arguments as OpenCode, so it listens where OpenCode would.
147
+ command: options.standIn ? { command: options.standIn.command, args: [...(options.standIn.args ?? []), ...SERVE_ARGS], ...(options.standIn.env ? { env: options.standIn.env } : {}) } : { command: checked, args: [...SERVE_ARGS] },
148
+ ...(options.confine ? { confine: options.confine } : {}),
149
+ provider: options.provider,
150
+ hooks: io.models,
151
+ ...(options.price ? { price: options.price } : {}),
152
+ ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
153
+ contextWindow: options.contextWindow ?? 272_000,
154
+ ...(options.eventConnectMs ? { eventConnectMs: options.eventConnectMs } : {}),
155
+ ...(options.log ? { log: options.log } : {}),
156
+ ...(options.fetch ? { fetch: options.fetch } : {}),
157
+ }, (c) => void (control = c));
158
+ const live = (event) => {
159
+ const mapped = adapterEvent(event);
160
+ if (mapped)
161
+ io.onEvent(mapped);
162
+ };
163
+ // Every drive of this session writes through one serialized writer, so a drive opened after an interrupt reads only
164
+ // once the halted drive's last writes are in.
165
+ const writer = serialWriter(io.writer);
166
+ const open = () => openDrive({ writer, signal: io.signal, live });
167
+ let drive = await open();
168
+ const initial = drive.state();
169
+ // A turn is open while the session holds input no turn placed, or a turn with no end (its recovery note).
170
+ const holdsTurn = (folded) => Boolean(recoveryNote(folded)) || pendingSubmissions(folded).length > 0;
171
+ let state = holdsTurn(initial)
172
+ ? "open_turn"
173
+ : initial.submissions.length === 0 && turnsIn(drive).length === 0 ? "new" : "idle";
174
+ let running;
175
+ let closed = false;
176
+ // Whether this session's interrupt stopped the turn in flight (its end is not written: the turn stays open).
177
+ let interrupted = false;
178
+ const run = () => {
179
+ const before = turnsIn(drive).length;
180
+ const current = drive;
181
+ state = "idle";
182
+ interrupted = false;
183
+ running = (async () => {
184
+ let outcome;
185
+ try {
186
+ await harness.drive(current);
187
+ const ended = turnsIn(current).slice(before).at(-1)?.data;
188
+ // A turn its interrupt stopped has no end in the records (it stays open): interrupted.
189
+ outcome = ended?.status ? { status: ended.status, ...(ended.error ? { error: ended.error } : {}) } : interrupted ? { status: "interrupted" } : { status: "failed", error: "the turn ended with no outcome in the session's records" };
190
+ }
191
+ catch (error) {
192
+ // Stopped by the session or its host: interrupted. Halted by anything else: failed, naming why.
193
+ outcome = current.signal.aborted
194
+ ? abortedOutcome(current.signal, io.signal)
195
+ : { status: "failed", error: String(error?.message ?? error).slice(0, 500) };
196
+ // A stop that landed before this turn ran (while send() was still recording its prompt) found no turn to stop,
197
+ // and reads the session as it was: the turn is open now, its prompt pending, so it reads open_turn (#1565, as
198
+ // codex's adapter does).
199
+ if (current.signal.aborted)
200
+ state = holdsTurn(current.state()) ? "open_turn" : "idle";
201
+ }
202
+ io.onEvent({ type: "turn_end", status: outcome.status });
203
+ return outcome;
204
+ })();
205
+ return running;
206
+ };
207
+ // A drive that was halted holds the session no more: the next turn opens a fresh one, on the same writer.
208
+ const ready = async () => {
209
+ if (closed)
210
+ throw new Error("opencode: the session is closed");
211
+ if (running)
212
+ await running;
213
+ if (drive.signal.aborted && !io.signal.aborted)
214
+ drive = await open();
215
+ };
216
+ return {
217
+ get state() { return state; },
218
+ async send(text) {
219
+ await ready();
220
+ await drive.submit({ id: randomUUID(), kind: "prompt", text });
221
+ void run();
222
+ },
223
+ async recover() {
224
+ if (state !== "open_turn")
225
+ throw new Error("opencode: there is no turn to recover");
226
+ await ready();
227
+ void run();
228
+ },
229
+ async settleOpenTurn(options = {}) {
230
+ if (state !== "open_turn")
231
+ throw new Error("opencode: there is no turn to settle");
232
+ await ready();
233
+ // The turn's end in the session's own transcript, as a turn that ends writes it: the next open finds no open turn,
234
+ // and the next turn carries no recovery of this one. Nothing is sent, and OpenCode is not started. A prompt the turn
235
+ // placed and OpenCode was never sent (no send mark: the stop came between the two) is carried into the next
236
+ // message, as an unplaced one is; a follow-up's own is not.
237
+ const folded = drive.state();
238
+ const sent = sentSubmissions(folded);
239
+ const unsent = (recoveryNote(folded)?.turn.placed ?? []).filter((id) => !sent.has(id));
240
+ await settleTurn(drive, { unsent, ...(options.opening === undefined ? {} : { host: options.opening }) });
241
+ state = "idle";
242
+ },
243
+ async turnEnd() {
244
+ if (!running)
245
+ throw new Error("opencode: no turn is in flight");
246
+ return running;
247
+ },
248
+ async interrupt() {
249
+ // OpenCode is asked to end the turn (it stops spending), and no end is written for it, as codex's interrupt
250
+ // writes none: the turn stays open, its host settles it (a person's stop), or the next process resumes it (the
251
+ // server's own stop, #1578). If OpenCode does not end it within INTERRUPT_MS, the drive is halted, the same.
252
+ interrupted = true;
253
+ const stopped = control ? await control.interrupt(INTERRUPT_MS).catch(() => false) : false;
254
+ if (!stopped)
255
+ drive.halt?.(new SessionHalt("interrupted"));
256
+ await running?.catch(() => { });
257
+ // A turn the halt stopped is still open in the session (a halt writes no end, and a prompt it stopped before the
258
+ // drive placed it is still pending): open_turn, so a host that is done with it settles it here.
259
+ if (holdsTurn(drive.state()))
260
+ state = "open_turn";
261
+ },
262
+ async close() {
263
+ if (closed)
264
+ return;
265
+ closed = true;
266
+ drive.halt?.(new SessionHalt("closed"));
267
+ await running?.catch(() => { });
268
+ },
269
+ };
270
+ },
271
+ };
272
+ }
@@ -0,0 +1,18 @@
1
+ /** The OpenCode version this package is built and tested against (`opencode --version` prints it). */
2
+ export declare const OPENCODE_VERSION = "1.19.5";
3
+ /** The platform packages that may carry this machine's binary, most fitting first; none on a platform OpenCode does not
4
+ * ship. */
5
+ export declare function openCodePackages(platform?: NodeJS.Platform, arch?: NodeJS.Architecture): string[];
6
+ /**
7
+ * The binary to run, the platform package it came from and that package's version, or `undefined` if none is installed:
8
+ *
9
+ * 1. `OPENCODE_BIN`;
10
+ * 2. the first platform package (`openCodePackages`) installed next to the `opencode-ai` this package depends on.
11
+ */
12
+ export declare function findOpenCode(): {
13
+ path: string;
14
+ pkg?: string;
15
+ packageVersion?: string;
16
+ } | undefined;
17
+ /** The binary to run, or `undefined` if none is installed (see `findOpenCode`). */
18
+ export declare function openCodeBinary(): string | undefined;
@@ -0,0 +1,87 @@
1
+ // Where this machine's pinned OpenCode binary is. Written for AgentRun.
2
+ //
3
+ // `opencode-ai` is a small launcher plus one optional npm package per platform (`opencode-<platform>-<arch>`, with
4
+ // `-baseline` builds for x64 CPUs without AVX2 and `-musl` builds for musl Linux), each carrying the native binary at
5
+ // `bin/opencode` (`bin/opencode.exe` on Windows). The launcher's own postinstall links one of them to its `bin`, but an
6
+ // install with scripts off (`npm ci --ignore-scripts`) leaves that link a stub, so the platform package is found here
7
+ // directly, in the order the launcher's postinstall tries them.
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { createRequire } from "node:module";
10
+ import { dirname, join } from "node:path";
11
+ import { env } from "node:process";
12
+ /** The OpenCode version this package is built and tested against (`opencode --version` prints it). */
13
+ export const OPENCODE_VERSION = "1.19.5";
14
+ const PLATFORMS = { darwin: "darwin", linux: "linux", win32: "windows" };
15
+ /** Whether this x64 CPU has AVX2 (the non-baseline builds need it); true where it cannot be read. */
16
+ function avx2() {
17
+ if (process.platform !== "linux")
18
+ return true;
19
+ try {
20
+ return /\bavx2\b/.test(readFileSync("/proc/cpuinfo", "utf8"));
21
+ }
22
+ catch {
23
+ return true;
24
+ }
25
+ }
26
+ /** Whether this Linux runs on musl rather than glibc. */
27
+ function musl() {
28
+ const header = process.report?.getReport?.()?.header;
29
+ return process.platform === "linux" && !header?.glibcVersionRuntime;
30
+ }
31
+ /** The platform packages that may carry this machine's binary, most fitting first; none on a platform OpenCode does not
32
+ * ship. */
33
+ export function openCodePackages(platform = process.platform, arch = process.arch) {
34
+ const os = PLATFORMS[platform];
35
+ if (!os || (arch !== "x64" && arch !== "arm64"))
36
+ return [];
37
+ const base = `opencode-${os}-${arch}`;
38
+ if (os === "linux") {
39
+ const libc = musl() ? [`${base}-musl`, ...(arch === "x64" ? [`${base}-baseline-musl`] : [])] : [base, ...(arch === "x64" ? [`${base}-baseline`] : [])];
40
+ return arch === "x64" && !avx2() ? [...libc].reverse() : libc;
41
+ }
42
+ if (arch === "x64")
43
+ return avx2() ? [base, `${base}-baseline`] : [`${base}-baseline`, base];
44
+ return [base];
45
+ }
46
+ /** The binary's name inside a platform package. */
47
+ const binName = (platform = process.platform) => (platform === "win32" ? "opencode.exe" : "opencode");
48
+ /**
49
+ * The binary to run, the platform package it came from and that package's version, or `undefined` if none is installed:
50
+ *
51
+ * 1. `OPENCODE_BIN`;
52
+ * 2. the first platform package (`openCodePackages`) installed next to the `opencode-ai` this package depends on.
53
+ */
54
+ export function findOpenCode() {
55
+ if (env.OPENCODE_BIN)
56
+ return { path: env.OPENCODE_BIN };
57
+ let launcher;
58
+ try {
59
+ launcher = dirname(createRequire(import.meta.url).resolve("opencode-ai/package.json"));
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ const from = createRequire(join(launcher, "package.json"));
65
+ for (const pkg of openCodePackages()) {
66
+ try {
67
+ const dir = dirname(from.resolve(`${pkg}/package.json`));
68
+ const bin = join(dir, "bin", binName());
69
+ if (existsSync(bin))
70
+ return { path: bin, pkg, packageVersion: packageVersion(dir) };
71
+ }
72
+ catch { }
73
+ }
74
+ return undefined;
75
+ }
76
+ /** The binary to run, or `undefined` if none is installed (see `findOpenCode`). */
77
+ export function openCodeBinary() {
78
+ return findOpenCode()?.path;
79
+ }
80
+ function packageVersion(dir) {
81
+ try {
82
+ return JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).version;
83
+ }
84
+ catch {
85
+ return undefined;
86
+ }
87
+ }
@@ -0,0 +1,24 @@
1
+ export interface OpenCodeConfigOptions {
2
+ model: string;
3
+ /** The model proxy's base for the Responses API: its loopback origin and `/v1`. */
4
+ modelUrl: string;
5
+ modelKey: string;
6
+ /** The adapter's MCP endpoint and its key. */
7
+ mcpUrl: string;
8
+ mcpKey: string;
9
+ contextWindow: number;
10
+ maxOutputTokens: number;
11
+ instructions?: string;
12
+ effort?: string;
13
+ }
14
+ /** The longest an MCP call may go without progress: a day. The server reports progress every 15 s while a call runs. */
15
+ export declare const MCP_TIMEOUT_MS: number;
16
+ /** OpenCode's `tool_output` limits, from the host's result bound: a result within it holds at most that many characters
17
+ * (UTF-16 units), so at most that many lines plus one, and three bytes of UTF-8 to a character. */
18
+ export declare const TOOL_OUTPUT: Readonly<{
19
+ max_lines: number;
20
+ max_bytes: number;
21
+ }>;
22
+ /** The permission rules: everything denied, the adapter's MCP tools allowed (the last matching rule wins). */
23
+ export declare const PERMISSION: Readonly<Record<string, string>>;
24
+ export declare function openCodeConfig(options: OpenCodeConfigOptions): Record<string, unknown>;
@@ -0,0 +1,61 @@
1
+ // OpenCode's whole config for a session, in a 0600 file OPENCODE_CONFIG names. Written for AgentRun; every key is one the
2
+ // pinned build's config schema holds (an unknown key refuses the start).
3
+ // - One provider, `openai` (the AI SDK's Responses client), at the session's model proxy with the session's own key,
4
+ // and one model, the session's, which is also the small model: no request goes to any other.
5
+ // - One agent, `hands`, whose prompt is the session's instructions (in place of OpenCode's own) and the default; every
6
+ // built-in agent is off, the title and summary agents among them, so OpenCode makes no side request of its own.
7
+ // - Every OpenCode tool denied and only the adapter's MCP tools (`hands_*`) allowed; OpenCode's own sharing,
8
+ // snapshots, formatters, language servers, instruction files and automatic compaction off.
9
+ // - One MCP server, `hands`, the adapter's, with a call timeout long enough for a person to answer (progress resets it).
10
+ // - A host tool's result within the host's bound (HOST_RESULT_MAX_CHARS) reaches the model whole: OpenCode cuts a
11
+ // longer tool output (by default 2,000 lines or 51,200 bytes) and saves the rest to a file, which the session has no
12
+ // tool to read.
13
+ import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
14
+ /** The longest an MCP call may go without progress: a day. The server reports progress every 15 s while a call runs. */
15
+ export const MCP_TIMEOUT_MS = 24 * 60 * 60 * 1000;
16
+ /** OpenCode's `tool_output` limits, from the host's result bound: a result within it holds at most that many characters
17
+ * (UTF-16 units), so at most that many lines plus one, and three bytes of UTF-8 to a character. */
18
+ export const TOOL_OUTPUT = Object.freeze({ max_lines: HOST_RESULT_MAX_CHARS + 1, max_bytes: HOST_RESULT_MAX_CHARS * 3 });
19
+ /** The permission rules: everything denied, the adapter's MCP tools allowed (the last matching rule wins). */
20
+ export const PERMISSION = Object.freeze({ "*": "deny", "hands_*": "allow" });
21
+ const BUILT_IN_AGENTS = ["build", "plan", "general", "explore", "title", "summary", "compaction"];
22
+ export function openCodeConfig(options) {
23
+ const modelRef = `openai/${options.model}`;
24
+ return {
25
+ autoupdate: false,
26
+ share: "disabled",
27
+ snapshot: false,
28
+ formatter: false,
29
+ lsp: false,
30
+ instructions: [],
31
+ compaction: { auto: false },
32
+ tool_output: { ...TOOL_OUTPUT },
33
+ enabled_providers: ["openai"],
34
+ provider: {
35
+ openai: {
36
+ options: { baseURL: options.modelUrl, apiKey: options.modelKey },
37
+ models: {
38
+ [options.model]: {
39
+ name: options.model,
40
+ tool_call: true,
41
+ reasoning: options.effort !== undefined,
42
+ attachment: false,
43
+ limit: { context: options.contextWindow, output: options.maxOutputTokens },
44
+ ...(options.effort ? { options: { reasoningEffort: options.effort } } : {}),
45
+ },
46
+ },
47
+ },
48
+ },
49
+ model: modelRef,
50
+ small_model: modelRef,
51
+ default_agent: "hands",
52
+ agent: {
53
+ hands: { mode: "primary", ...(options.instructions ? { prompt: options.instructions } : {}), permission: { ...PERMISSION } },
54
+ ...Object.fromEntries(BUILT_IN_AGENTS.map((name) => [name, { disable: true }])),
55
+ },
56
+ permission: { ...PERMISSION },
57
+ mcp: {
58
+ hands: { type: "remote", url: options.mcpUrl, headers: { authorization: `Bearer ${options.mcpKey}` }, enabled: true, oauth: false, timeout: MCP_TIMEOUT_MS },
59
+ },
60
+ };
61
+ }
@@ -0,0 +1,77 @@
1
+ import type { DriveContext, HostTool, SessionState } from "@parcha/agentrun-kernel/kernel";
2
+ import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
3
+ import { type ConfineChild } from "./host/server.js";
4
+ /** The journal stream that holds OpenCode's own events for the session, as `/sync/history` gives them. */
5
+ export declare const SYNC_STREAM = "opencode.sync";
6
+ /** The journal stream that holds the message id each submission was sent under. */
7
+ export declare const PROMPT_STREAM = "opencode.prompt";
8
+ /** The submissions a drive of the session marked as sent to OpenCode (PROMPT_STREAM, written just before each send),
9
+ * with those a recovery's send carried (its `covers`). */
10
+ export declare function sentSubmissions(state: SessionState): Set<string>;
11
+ /** The session's private directories, under its own directory. */
12
+ export declare const PRIVATE_DIRS: readonly ["home", "config", "data", "cache", "state", "tmp"];
13
+ /** OpenCode's agent for the session: its prompt is the session's instructions, and its only tools are the host's. */
14
+ export declare const AGENT = "hands";
15
+ /** How long one try of a drive's event stream may take to say `server.connected`, and how many tries a drive has. */
16
+ export declare const EVENT_CONNECT_MS = 10000;
17
+ export declare const EVENT_TRIES = 3;
18
+ /** How long a drive that was not stopped waits, at its end, for the host tool calls still running to settle, when the
19
+ * kernel gives it no deadline (DriveContext.deadline). Codex waits for its in-flight calls the same way
20
+ * (run-adapters-codex/src/harness.ts:815-819 and :1125-1128), bounded by its own invocation deadline, which is
21
+ * codex-internal (invocationDeadline: the World's runtime deadline, else 10 minutes); this is opencode's own bound. */
22
+ export declare const CALLS_SETTLE_MS = 30000;
23
+ export interface OpenCodeHarnessOptions {
24
+ /** The kernel's tools: exactly the host's (and `read_skill_file` with skills). */
25
+ tools: HostTool[];
26
+ /** The provider's model id. */
27
+ model: string;
28
+ /** The session's instructions: OpenCode's agent prompt, in place of OpenCode's own. */
29
+ instructions?: string;
30
+ /** The reasoning effort, when the session names one. */
31
+ effort?: string;
32
+ /** The session's own directory: its private directories are made in it. */
33
+ dir: string;
34
+ /** The workspace OpenCode runs in (absolute), or `<dir>/work`. */
35
+ cwd?: string;
36
+ /** OpenCode, or a test's stand-in for it. */
37
+ command: {
38
+ command: string;
39
+ args: string[];
40
+ env?: Record<string, string>;
41
+ };
42
+ confine?: ConfineChild;
43
+ parentWatch?: ParentWatch;
44
+ /** The provider the proxy forwards to and its credential, read per request. */
45
+ provider: {
46
+ origin: string;
47
+ credential: () => Promise<string> | string;
48
+ };
49
+ hooks: ModelProxyHooks;
50
+ price?: ModelProxyOptions["price"];
51
+ maxOutputTokens?: number;
52
+ contextWindow: number;
53
+ /** How long one try of the event stream may take to open. Default EVENT_CONNECT_MS. */
54
+ eventConnectMs?: number;
55
+ log?: (message: string, fields?: Record<string, unknown>) => void;
56
+ /** For tests: the fetch the model proxy forwards with. */
57
+ fetch?: typeof fetch;
58
+ /** For tests: the environment the child's allowlist reads. */
59
+ env?: Readonly<Record<string, string | undefined>>;
60
+ }
61
+ /** What the adapter holds of the drive in flight, to stop its turn. */
62
+ export interface DriveControl {
63
+ /** Stop the turn in flight: OpenCode aborts it, and the drive ends once OpenCode's records of it are mirrored, with no
64
+ * end written for the turn (it stays open). Resolves true when that happened within `ms`, false when the drive must be
65
+ * halted instead. */
66
+ interrupt(ms: number): Promise<boolean>;
67
+ }
68
+ /** JSON text of `value` with every object's keys sorted: two argument objects that say the same are the same text. */
69
+ export declare function canonical(value: unknown): string;
70
+ /** A message id in OpenCode's own format (`msg_` + 12 hex of the time + 14 base62), which OpenCode orders messages by: it
71
+ * sorts after every id this process made before it. The random part comes from `seed` (the submission's id). */
72
+ export declare function messageId(seed: string, now?: number): string;
73
+ /** The OpenCode harness. `control` is told of each drive's stop hook while it runs. */
74
+ export declare function openCodeHarness(options: OpenCodeHarnessOptions, control?: (drive: DriveControl | undefined) => void): {
75
+ name: string;
76
+ drive(ctx: DriveContext): Promise<void>;
77
+ };