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

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 (172) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/README.md +739 -116
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +18 -7
  6. package/dist/agents.js +19 -10
  7. package/dist/app.js +101 -26
  8. package/dist/background.d.ts +29 -0
  9. package/dist/background.js +397 -0
  10. package/dist/box-egress-vm.d.ts +125 -0
  11. package/dist/box-egress-vm.js +350 -0
  12. package/dist/box-egress.d.ts +99 -0
  13. package/dist/box-egress.js +259 -0
  14. package/dist/box-image.d.ts +1 -1
  15. package/dist/box-image.js +9 -7
  16. package/dist/box-relay-vm.d.ts +84 -0
  17. package/dist/box-relay-vm.js +410 -0
  18. package/dist/box-relay.d.ts +8 -5
  19. package/dist/box-relay.js +14 -9
  20. package/dist/boxes.d.ts +28 -5
  21. package/dist/boxes.js +44 -18
  22. package/dist/browser-cost.d.ts +41 -0
  23. package/dist/browser-cost.js +158 -0
  24. package/dist/cap.d.ts +130 -21
  25. package/dist/cap.js +339 -67
  26. package/dist/cli.js +30 -4
  27. package/dist/coding-tools.d.ts +7 -3
  28. package/dist/coding-tools.js +16 -10
  29. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  30. package/dist/console/assets/index-CnJBf7Lc.js +486 -0
  31. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/content-filter.d.ts +7 -0
  34. package/dist/content-filter.js +23 -0
  35. package/dist/decision-rows.d.ts +11 -3
  36. package/dist/decision-rows.js +18 -11
  37. package/dist/decisions.d.ts +3 -3
  38. package/dist/decisions.js +4 -3
  39. package/dist/errors.d.ts +2 -0
  40. package/dist/errors.js +5 -2
  41. package/dist/files.d.ts +9 -1
  42. package/dist/files.js +10 -2
  43. package/dist/grade.d.ts +11 -11
  44. package/dist/grade.js +43 -55
  45. package/dist/graph-served.d.ts +23 -0
  46. package/dist/graph-served.js +75 -0
  47. package/dist/graph-view.d.ts +7 -5
  48. package/dist/graph-view.js +10 -3
  49. package/dist/harness-app.d.ts +4 -2
  50. package/dist/harness-app.js +110 -19
  51. package/dist/harness-opencode/adapter.d.ts +45 -0
  52. package/dist/harness-opencode/adapter.js +272 -0
  53. package/dist/harness-opencode/binary.d.ts +18 -0
  54. package/dist/harness-opencode/binary.js +87 -0
  55. package/dist/harness-opencode/config.d.ts +24 -0
  56. package/dist/harness-opencode/config.js +61 -0
  57. package/dist/harness-opencode/harness.d.ts +77 -0
  58. package/dist/harness-opencode/harness.js +620 -0
  59. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  60. package/dist/harness-opencode/host/mcp.js +208 -0
  61. package/dist/harness-opencode/host/policy.d.ts +71 -0
  62. package/dist/harness-opencode/host/policy.js +419 -0
  63. package/dist/harness-opencode/host/server.d.ts +55 -0
  64. package/dist/harness-opencode/host/server.js +165 -0
  65. package/dist/harness-opencode/index.d.ts +9 -0
  66. package/dist/harness-opencode/index.js +6 -0
  67. package/dist/harness-opencode/verify.d.ts +32 -0
  68. package/dist/harness-opencode/verify.js +75 -0
  69. package/dist/harness-opencode/versions.d.ts +33 -0
  70. package/dist/harness-opencode/versions.js +64 -0
  71. package/dist/harness.d.ts +4 -1
  72. package/dist/harness.js +5 -2
  73. package/dist/host-check.d.ts +12 -0
  74. package/dist/host-check.js +34 -0
  75. package/dist/host-tools.d.ts +12 -2
  76. package/dist/host-tools.js +26 -12
  77. package/dist/host.js +6 -2
  78. package/dist/hosted-search.js +5 -1
  79. package/dist/import.d.ts +2 -2
  80. package/dist/import.js +4 -3
  81. package/dist/key-check.d.ts +3 -2
  82. package/dist/key-check.js +7 -3
  83. package/dist/key-refusal.js +8 -4
  84. package/dist/key-words.d.ts +37 -0
  85. package/dist/key-words.js +40 -0
  86. package/dist/learn/check.d.ts +10 -1
  87. package/dist/learn/check.js +19 -1
  88. package/dist/learn/grade.d.ts +6 -2
  89. package/dist/learn/grade.js +28 -14
  90. package/dist/learn/index.d.ts +3 -3
  91. package/dist/learn/index.js +3 -3
  92. package/dist/learn/notes.js +2 -1
  93. package/dist/learn/reflect.d.ts +2 -2
  94. package/dist/learn/reflect.js +53 -5
  95. package/dist/learn/secrets.js +28 -8
  96. package/dist/learn/skills.d.ts +19 -4
  97. package/dist/learn/skills.js +95 -6
  98. package/dist/learned-workflow.d.ts +59 -0
  99. package/dist/learned-workflow.js +191 -0
  100. package/dist/learning-routes.d.ts +30 -1
  101. package/dist/learning-routes.js +173 -19
  102. package/dist/learning-run.d.ts +8 -6
  103. package/dist/learning-run.js +70 -27
  104. package/dist/learning-words.d.ts +12 -5
  105. package/dist/learning-words.js +34 -13
  106. package/dist/learning.d.ts +52 -3
  107. package/dist/learning.js +204 -4
  108. package/dist/mcp-gateway.d.ts +96 -0
  109. package/dist/mcp-gateway.js +408 -0
  110. package/dist/mcp-meta.d.ts +17 -0
  111. package/dist/mcp-meta.js +38 -0
  112. package/dist/mcp-servers.d.ts +33 -9
  113. package/dist/mcp-servers.js +58 -10
  114. package/dist/mcp.js +5 -5
  115. package/dist/model.d.ts +13 -11
  116. package/dist/model.js +11 -10
  117. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  118. package/dist/openapi.js +407 -54
  119. package/dist/page.d.ts +2 -0
  120. package/dist/page.js +3 -0
  121. package/dist/paid-calls.d.ts +5 -1
  122. package/dist/paid-calls.js +1 -1
  123. package/dist/pause.d.ts +2 -0
  124. package/dist/place.d.ts +29 -5
  125. package/dist/place.js +51 -11
  126. package/dist/print.d.ts +7 -0
  127. package/dist/print.js +13 -0
  128. package/dist/propose.d.ts +2 -0
  129. package/dist/propose.js +38 -8
  130. package/dist/request-start.d.ts +12 -4
  131. package/dist/request-start.js +139 -15
  132. package/dist/run-box.d.ts +56 -4
  133. package/dist/run-box.js +183 -23
  134. package/dist/runnable.d.ts +13 -3
  135. package/dist/runnable.js +63 -6
  136. package/dist/runs.d.ts +266 -37
  137. package/dist/runs.js +884 -90
  138. package/dist/secrets.d.ts +27 -0
  139. package/dist/secrets.js +38 -2
  140. package/dist/server.d.ts +141 -36
  141. package/dist/server.js +562 -118
  142. package/dist/sign-ins.d.ts +99 -0
  143. package/dist/sign-ins.js +288 -0
  144. package/dist/skills.d.ts +16 -4
  145. package/dist/skills.js +35 -7
  146. package/dist/stats.d.ts +7 -2
  147. package/dist/stats.js +28 -7
  148. package/dist/tool-gate.d.ts +281 -0
  149. package/dist/tool-gate.js +585 -0
  150. package/dist/tool-keys.d.ts +48 -11
  151. package/dist/tool-keys.js +46 -8
  152. package/dist/tool-plane.d.ts +116 -27
  153. package/dist/tool-plane.js +232 -50
  154. package/dist/tools.d.ts +69 -14
  155. package/dist/tools.js +148 -26
  156. package/dist/trigger-secrets.d.ts +32 -0
  157. package/dist/trigger-secrets.js +143 -0
  158. package/dist/triggers.d.ts +439 -0
  159. package/dist/triggers.js +863 -0
  160. package/dist/turn-end.d.ts +3 -2
  161. package/dist/turn-end.js +3 -2
  162. package/dist/usage-lines.d.ts +26 -0
  163. package/dist/usage-lines.js +28 -0
  164. package/dist/validate.d.ts +2 -0
  165. package/dist/validate.js +11 -2
  166. package/dist/web-fetch.js +3 -3
  167. package/dist/webhooks.d.ts +11 -4
  168. package/dist/webhooks.js +17 -1
  169. package/launcher/agentrun-serve +1 -1
  170. package/package.json +16 -14
  171. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  172. package/dist/console/assets/index-By-jkqki.css +0 -1
@@ -0,0 +1,419 @@
1
+ import { providerInputOverhead, ProxyRefusal } from "@parcha/agentrun-kernel/host";
2
+ /** The prefix OpenCode gives the adapter's MCP tools: the server is `hands`. */
3
+ export const TOOL_PREFIX = "hands_";
4
+ export const OPENCODE_RESPONSES_ROUTES = Object.freeze([
5
+ { method: "POST", path: "/v1/responses", headers: ["accept"] },
6
+ ]);
7
+ /** The keys a Responses request from the pinned build may carry; anything else is refused. */
8
+ export const BODY_KEYS = new Set(["model", "input", "tools", "tool_choice", "parallel_tool_calls", "reasoning", "store", "stream", "include", "prompt_cache_key", "max_output_tokens", "text", "temperature", "top_p"]);
9
+ /** What `include` may ask for: the encrypted reasoning a stateless request sends back on the next one. */
10
+ const INCLUDE = new Set(["reasoning.encrypted_content"]);
11
+ const TEXT_KEYS = new Set(["format", "verbosity"]);
12
+ const VERBOSITY = new Set(["low", "medium", "high"]);
13
+ const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ /** The session's own function tools, every other function dropped; a tool of any other kind is refused. */
15
+ function ownTools(tools, allowed) {
16
+ if (!Array.isArray(tools))
17
+ throw new ProxyRefusal(400, "tools is not a list");
18
+ const out = [];
19
+ for (const tool of tools) {
20
+ if (!isPlain(tool))
21
+ throw new ProxyRefusal(400, "a tool definition is not an object");
22
+ if (tool.type !== "function")
23
+ throw new ProxyRefusal(403, "a provider-hosted or unknown kind of tool is not offered to this session's model");
24
+ if (typeof tool.name === "string" && allowed.has(tool.name))
25
+ out.push(tool);
26
+ }
27
+ return out;
28
+ }
29
+ function toolChoice(choice, allowed) {
30
+ if (choice === "auto" || choice === "none" || choice === "required")
31
+ return choice;
32
+ if (isPlain(choice) && choice.type === "function" && typeof choice.name === "string" && allowed.has(choice.name))
33
+ return choice;
34
+ throw new ProxyRefusal(400, "tool_choice names a mode or tool this session does not offer");
35
+ }
36
+ function textOptions(text) {
37
+ const refuse = () => { throw new ProxyRefusal(400, "text carries something other than a format and a verbosity"); };
38
+ if (!isPlain(text) || !Object.keys(text).every((key) => TEXT_KEYS.has(key)))
39
+ refuse();
40
+ const { format, verbosity } = text;
41
+ if (verbosity !== undefined && !(typeof verbosity === "string" && VERBOSITY.has(verbosity)))
42
+ refuse();
43
+ if (format !== undefined && !(isPlain(format) && (format.type === "text" || format.type === "json_schema")))
44
+ refuse();
45
+ return text;
46
+ }
47
+ /** A Responses usage object in the proxy's terms, or undefined when it is not one. */
48
+ function usageFrom(usage) {
49
+ if (!isPlain(usage))
50
+ return undefined;
51
+ const count = (value) => (typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined);
52
+ const input = count(usage.input_tokens);
53
+ const output = count(usage.output_tokens);
54
+ if (input === undefined || output === undefined)
55
+ return undefined;
56
+ const details = isPlain(usage.input_tokens_details) ? usage.input_tokens_details : {};
57
+ const cacheRead = count(details.cached_tokens) ?? 0;
58
+ const cacheWrite = count(details.cache_write_tokens) ?? 0;
59
+ return { input: Math.max(0, input - cacheRead - cacheWrite), output, cacheRead, cacheWrite };
60
+ }
61
+ /** The object starting at `text[start]` (a `{`), as JSON text, or undefined when it does not close in `text`. */
62
+ function objectAt(text, start) {
63
+ let depth = 0;
64
+ for (let i = start; i < text.length; i++) {
65
+ const c = text[i];
66
+ if (c === "\"") {
67
+ for (i++; i < text.length && text[i] !== "\""; i++)
68
+ if (text[i] === "\\")
69
+ i++;
70
+ }
71
+ else if (c === "{")
72
+ depth++;
73
+ else if (c === "}" && --depth === 0)
74
+ return text.slice(start, i + 1);
75
+ }
76
+ return undefined;
77
+ }
78
+ const PAID_END = new Set(["response.completed", "response.incomplete"]);
79
+ // The content-filter stop, read as codex's policy reads it (run-adapters-codex host/policy.ts, the same Responses API),
80
+ // in its form that also reads a gateway's data-only events.
81
+ /**
82
+ * Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
83
+ * `incomplete` response whose `incomplete_details.reason` is `content_filter`. Read by parsing each `data:` line on its
84
+ * own, as usageOf reads the usage, never by matching text; an answer cut at its output limit (`max_output_tokens`) is not one.
85
+ *
86
+ * The terminal event carries the whole response (its output, encrypted reasoning included), so its line can be longer
87
+ * than the proxy keeps of an answer; then the proxy's start of that line is read. The response's fields come in a fixed
88
+ * order, `id`, `object`, `created_at`, `status`, `background`, `error`, `incomplete_details`, then `instructions`, the
89
+ * tools and the output, so `incomplete_details` is near the line's start. It is read only on a line that is the event's
90
+ * own: one the SSE `event: response.incomplete` names (OpenAI's API), or whose data says `"type":"response.incomplete"`
91
+ * before its `"response":{` (a gateway that sends each event as its data alone: LiteLLM), as the first
92
+ * `"incomplete_details":{` after `"response":{` (one JSON object), whatever the JSON's spacing.
93
+ */
94
+ export function filtered(text, lineStarts = []) {
95
+ let end = terminalResponse(text.split("\n"), false);
96
+ if (end === undefined) {
97
+ const whole = text.trimStart();
98
+ if (whole.startsWith("{")) {
99
+ try {
100
+ const body = JSON.parse(whole);
101
+ if (isPlain(body) && body.object === "response")
102
+ end = body;
103
+ }
104
+ catch { }
105
+ }
106
+ }
107
+ end ??= terminalResponse(lineStarts, true);
108
+ return isPlain(end) && end.status === "incomplete" && isPlain(end.incomplete_details) && end.incomplete_details.reason === "content_filter";
109
+ }
110
+ /** The response of the last terminal event in `lines` (`filtered`), each `data:` line parsed on its own; with `starts`,
111
+ * the lines are kept starts, and one that is a `response.incomplete` event's (by its name, or its data's type ahead of
112
+ * its response) is read from its start. */
113
+ function terminalResponse(lines, starts) {
114
+ let end;
115
+ let named = false;
116
+ for (const line of lines) {
117
+ if (line.startsWith("event:")) {
118
+ named = line.slice(6).trim() === "response.incomplete";
119
+ continue;
120
+ }
121
+ if (!line.startsWith("data:"))
122
+ continue;
123
+ const data = line.slice(5).trim();
124
+ const incomplete = named || ownIncomplete(data);
125
+ named = false;
126
+ if (!data.startsWith("{"))
127
+ continue;
128
+ try {
129
+ const event = JSON.parse(data);
130
+ if (isPlain(event) && typeof event.type === "string" && PAID_END.has(event.type))
131
+ end = event.response;
132
+ }
133
+ catch {
134
+ // A line the window cut (skipped), or a kept start the event's name says is the stop's.
135
+ if (starts && incomplete)
136
+ end = startOfResponse(data) ?? end;
137
+ }
138
+ }
139
+ return end;
140
+ }
141
+ const RESPONSE_KEY = /"response"\s*:\s*\{/;
142
+ const INCOMPLETE_TYPE = /"type"\s*:\s*"response\.incomplete"/;
143
+ const DETAILS_KEY = /"incomplete_details"\s*:\s*\{/;
144
+ /** Whether a kept start's data is a `response.incomplete` event's own: its `type` says so ahead of its `response` (a
145
+ * quote of it in an answer's text is escaped, so it never reads as one). */
146
+ function ownIncomplete(data) {
147
+ const type = data.search(INCOMPLETE_TYPE);
148
+ const response = data.search(RESPONSE_KEY);
149
+ return type >= 0 && (response < 0 || type < response);
150
+ }
151
+ /** The status and `incomplete_details` of the response a `response.incomplete` event's line starts with (`filtered`), or
152
+ * undefined when the line's kept start does not hold them. */
153
+ function startOfResponse(data) {
154
+ const response = data.search(RESPONSE_KEY);
155
+ if (response < 0)
156
+ return undefined;
157
+ const found = DETAILS_KEY.exec(data.slice(response));
158
+ if (!found)
159
+ return undefined;
160
+ const json = objectAt(data, response + found.index + found[0].length - 1);
161
+ if (json === undefined)
162
+ return undefined;
163
+ try {
164
+ return { status: "incomplete", incomplete_details: JSON.parse(json) };
165
+ }
166
+ catch {
167
+ return undefined;
168
+ }
169
+ }
170
+ /** The usage of the response an answer ends with: its `response.completed` (or `response.incomplete`) event, each `data:`
171
+ * line parsed on its own, or a whole JSON body's; for a line the proxy's 64 KiB window cut, the last `"usage":{` object
172
+ * in the text. Undefined, an unknown cost, when there is none. */
173
+ export function usageOf(text) {
174
+ let found;
175
+ let ended = false;
176
+ for (const line of text.split("\n")) {
177
+ if (!line.startsWith("data:"))
178
+ continue;
179
+ const data = line.slice(5).trim();
180
+ if (!data.startsWith("{"))
181
+ continue;
182
+ let event;
183
+ try {
184
+ event = JSON.parse(data);
185
+ }
186
+ catch {
187
+ continue; // a line the window cut
188
+ }
189
+ if (isPlain(event) && typeof event.type === "string" && PAID_END.has(event.type)) {
190
+ ended = true;
191
+ found = isPlain(event.response) ? event.response.usage : undefined;
192
+ }
193
+ }
194
+ if (ended)
195
+ return usageFrom(found);
196
+ const whole = text.trimStart();
197
+ if (whole.startsWith("{")) {
198
+ try {
199
+ const body = JSON.parse(whole);
200
+ if (isPlain(body) && body.object === "response")
201
+ return usageFrom(body.usage);
202
+ }
203
+ catch { }
204
+ }
205
+ const mark = "\"usage\":{";
206
+ const at = text.lastIndexOf(mark);
207
+ if (at < 0)
208
+ return undefined;
209
+ const json = objectAt(text, at + mark.length - 1);
210
+ if (json === undefined)
211
+ return undefined;
212
+ try {
213
+ return usageFrom(JSON.parse(json));
214
+ }
215
+ catch {
216
+ return undefined;
217
+ }
218
+ }
219
+ /** The items of `type` in `value`, at any depth. */
220
+ function itemsIn(value, type) {
221
+ if (Array.isArray(value))
222
+ return value.reduce((n, item) => n + itemsIn(item, type), 0);
223
+ if (!isPlain(value))
224
+ return 0;
225
+ return (value.type === type ? 1 : 0) + Object.values(value).reduce((n, item) => n + itemsIn(item, type), 0);
226
+ }
227
+ /** The input tokens the provider bills for `body` that it does not carry (codex's figure: the same Responses API). A file
228
+ * input has no stated bound, so a body with one cannot be measured. */
229
+ export function responsesServerInputOverhead(body) {
230
+ if (itemsIn(body.input, "input_file") > 0)
231
+ throw new Error("a file input's billed size has no stated bound");
232
+ return providerInputOverhead("openai-responses", { tools: Array.isArray(body.tools) && body.tools.length > 0, images: itemsIn(body.input, "input_image") });
233
+ }
234
+ /** An event that is not whole by this many characters is not read. */
235
+ const EVENT_CAP = 4 * 1024 * 1024;
236
+ /** Reads an answer's server-sent events as they pass and tells `onCall` of each function call it carries. */
237
+ function watchCalls(onCall) {
238
+ let line = "";
239
+ let held = false;
240
+ let data = [];
241
+ let size = 0;
242
+ let broken = false;
243
+ const dispatch = () => {
244
+ const text = data.join("\n");
245
+ data = [];
246
+ size = 0;
247
+ if (!text.includes("function_call"))
248
+ return;
249
+ let event;
250
+ try {
251
+ event = JSON.parse(text);
252
+ }
253
+ catch {
254
+ return;
255
+ }
256
+ const item = isPlain(event) && event.type === "response.output_item.done" && isPlain(event.item) ? event.item : undefined;
257
+ if (item?.type === "function_call" && typeof item.call_id === "string" && typeof item.name === "string") {
258
+ onCall({ callId: item.call_id, name: item.name, arguments: typeof item.arguments === "string" ? item.arguments : "{}" });
259
+ }
260
+ };
261
+ const endLine = () => {
262
+ const done = line;
263
+ line = "";
264
+ if (done === "")
265
+ return dispatch();
266
+ if (done.startsWith("data:")) {
267
+ const value = done.slice(done.startsWith("data: ") ? 6 : 5);
268
+ size += value.length + 1;
269
+ if (size > EVENT_CAP)
270
+ broken = true;
271
+ else
272
+ data.push(value);
273
+ }
274
+ };
275
+ return {
276
+ chunk(text) {
277
+ if (broken)
278
+ return;
279
+ for (let i = 0; i < text.length; i++) {
280
+ const ch = text[i];
281
+ if (held) {
282
+ held = false;
283
+ if (ch === "\n")
284
+ continue;
285
+ }
286
+ if (ch === "\n")
287
+ endLine();
288
+ else if (ch === "\r") {
289
+ endLine();
290
+ held = true;
291
+ }
292
+ else {
293
+ line += ch;
294
+ if (line.length > EVENT_CAP)
295
+ broken = true;
296
+ }
297
+ if (broken)
298
+ return;
299
+ }
300
+ },
301
+ };
302
+ }
303
+ /** The tokens a request keeps for its answer when a spend cap limits its output. */
304
+ export const ANSWER_TOKENS_LEAST = 1024;
305
+ /** What a reasoning request at each effort is allowed for its reasoning beside its answer, when its output is limited:
306
+ * OpenAI's reasoning shares `max_output_tokens` and takes no budget, so a limit under its reasoning comes back
307
+ * incomplete with no answer. The figures are codex's (pi-ai's thinking budgets by level, xhigh at high's). */
308
+ export const REASONING_TOKENS_ALLOWED = Object.freeze({ minimal: 1024, low: 2048, medium: 8192, high: 16384, xhigh: 16384 });
309
+ /** The output tokens a Responses body asks for at most: its `max_output_tokens`, as `apply` clamped it. */
310
+ export function responsesOutputAsked(body) {
311
+ const asked = body.max_output_tokens;
312
+ return typeof asked === "number" && Number.isSafeInteger(asked) && asked > 0 ? asked : undefined;
313
+ }
314
+ /** The least output a Responses body may be limited to and still answer: 1,024 tokens, plus its reasoning effort's
315
+ * allowance when it reasons. */
316
+ export function responsesOutputLeast(body) {
317
+ const effort = isPlain(body.reasoning) && typeof body.reasoning.effort === "string" ? body.reasoning.effort : undefined;
318
+ return ANSWER_TOKENS_LEAST + (effort === undefined ? 0 : (REASONING_TOKENS_ALLOWED[effort] ?? 0));
319
+ }
320
+ // What a stopped request counts, read as codex's policy reads it (run-adapters-codex host/policy.ts, the same Responses
321
+ // API): the reasoning its body lets it bill unseen, and the reasoning and the content each streamed event carries.
322
+ /** The reasoning tokens a Responses request may bill that its stream never shows (only a summary of its reasoning
323
+ * streams): its effort's budget; none at effort `none`; and with no effort the body says (the model then reasons at its
324
+ * own default, or not at all), its output limit, `fallback` when the body names none: the conservative side. An
325
+ * estimate, as the efforts' budgets are not limits the provider keeps: a stopped request counts the part of it that
326
+ * did not stream (less `responsesReasoningBytes` of what it sent), never past its hold. */
327
+ export function responsesReasoningHidden(body, fallback) {
328
+ const effort = isPlain(body.reasoning) && typeof body.reasoning.effort === "string" ? body.reasoning.effort : undefined;
329
+ if (effort === "none")
330
+ return 0;
331
+ const budget = effort === undefined ? undefined : REASONING_TOKENS_ALLOWED[effort];
332
+ return budget ?? responsesOutputAsked(body) ?? fallback;
333
+ }
334
+ /** The Responses stream's events whose deltas are reasoning: its summary, and its reasoning text where a model sends it. */
335
+ const REASONING_DELTAS = new Set(["response.reasoning_summary_text.delta", "response.reasoning_text.delta"]);
336
+ /** The bytes of reasoning one Responses stream event carries: a reasoning delta's text, UTF-8; 0 for answer text, a
337
+ * function call's arguments and every other event. */
338
+ export function responsesReasoningBytes(event) {
339
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
340
+ if (!data.startsWith("{"))
341
+ return 0;
342
+ const parsed = JSON.parse(data);
343
+ return typeof parsed.type === "string" && REASONING_DELTAS.has(parsed.type) && typeof parsed.delta === "string" ? Buffer.byteLength(parsed.delta, "utf8") : 0;
344
+ }
345
+ /** The Responses stream's events whose deltas are content: answer text, reasoning, and a tool call's input. */
346
+ const CONTENT_DELTAS = new Set([
347
+ "response.output_text.delta", "response.reasoning_summary_text.delta", "response.reasoning_text.delta",
348
+ "response.function_call_arguments.delta", "response.custom_tool_call_input.delta",
349
+ ]);
350
+ /** The bytes of content one Responses stream event carries: a content delta's text, UTF-8, never the framing around it
351
+ * (its sequence number, item id, indexes, logprobs, obfuscation); 0 for every other event. */
352
+ export function responsesContentBytes(event) {
353
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
354
+ if (!data.startsWith("{"))
355
+ return 0;
356
+ const parsed = JSON.parse(data);
357
+ return typeof parsed.type === "string" && CONTENT_DELTAS.has(parsed.type) && typeof parsed.delta === "string" ? Buffer.byteLength(parsed.delta, "utf8") : 0;
358
+ }
359
+ /** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
360
+ export function limitResponsesOutput(body, max) {
361
+ const asked = responsesOutputAsked(body);
362
+ return { ...body, max_output_tokens: asked === undefined ? max : Math.min(asked, max) };
363
+ }
364
+ export function openCodePolicy(options) {
365
+ const allowed = new Set(options.tools.map((name) => `${TOOL_PREFIX}${name}`));
366
+ const maxOutputTokens = options.maxOutputTokens ?? 32_000;
367
+ return {
368
+ id: "opencode",
369
+ routes: OPENCODE_RESPONSES_ROUTES,
370
+ keyOf(headers) {
371
+ const auth = String(headers.authorization ?? "");
372
+ return auth.startsWith("Bearer ") ? auth.slice(7) : "";
373
+ },
374
+ authHeaders: (credential) => ({ authorization: `Bearer ${credential}` }),
375
+ apply(body) {
376
+ if (!isPlain(body))
377
+ throw new ProxyRefusal(400, "the body is not a JSON object");
378
+ const out = {};
379
+ for (const [key, value] of Object.entries(body)) {
380
+ if (!BODY_KEYS.has(key))
381
+ throw new ProxyRefusal(400, "the body has a field the OpenCode policy does not allow");
382
+ out[key] = value;
383
+ }
384
+ if (out.include !== undefined && (!Array.isArray(out.include) || !out.include.every((item) => typeof item === "string" && INCLUDE.has(item)))) {
385
+ throw new ProxyRefusal(400, "include asks for an item the OpenCode policy does not allow");
386
+ }
387
+ if (out.stream !== undefined && typeof out.stream !== "boolean")
388
+ throw new ProxyRefusal(400, "stream is not a boolean");
389
+ if (out.reasoning !== undefined && !isPlain(out.reasoning))
390
+ throw new ProxyRefusal(400, "reasoning is not an object");
391
+ if (out.text !== undefined)
392
+ out.text = textOptions(out.text);
393
+ if (out.tools !== undefined)
394
+ out.tools = ownTools(out.tools, allowed);
395
+ if (Array.isArray(out.tools) && out.tools.length === 0) {
396
+ // No tool of the session's left: none is offered, and no choice of one.
397
+ delete out.tools;
398
+ delete out.tool_choice;
399
+ }
400
+ if (out.tool_choice !== undefined)
401
+ out.tool_choice = toolChoice(out.tool_choice, allowed);
402
+ const asked = typeof out.max_output_tokens === "number" && out.max_output_tokens > 0 ? out.max_output_tokens : maxOutputTokens;
403
+ return { ...out, model: options.model, store: false, max_output_tokens: Math.min(asked, maxOutputTokens) };
404
+ },
405
+ usageOf,
406
+ filtered,
407
+ watch: options.onCall ? () => watchCalls(options.onCall) : undefined,
408
+ modelOf: () => options.model,
409
+ // Under a spend cap the host admits each request with what is left can buy, which goes into max_output_tokens.
410
+ outputAsked: responsesOutputAsked,
411
+ outputLeast: responsesOutputLeast,
412
+ limitOutput: limitResponsesOutput,
413
+ serverInputOverhead: responsesServerInputOverhead,
414
+ // A stop counts the content it streamed, not the wire, and the part of its reasoning budget that did not stream.
415
+ reasoningHidden: (body) => responsesReasoningHidden(body, maxOutputTokens),
416
+ reasoningBytesOf: responsesReasoningBytes,
417
+ contentBytesOf: responsesContentBytes,
418
+ };
419
+ }
@@ -0,0 +1,55 @@
1
+ import { type ParentWatch } from "@parcha/agentrun-kernel/host";
2
+ /** The variables a child takes from this process, when they are set. */
3
+ export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
4
+ /** A command and its arguments, as the drive starts it. */
5
+ export interface ChildCommand {
6
+ command: string;
7
+ args: string[];
8
+ }
9
+ /** The host's confinement of a child: the same command and arguments, started under the host's own (a
10
+ * `setpriv --no-new-privs` prefix, say). It may only add in front, and never sees or changes the child's environment. */
11
+ export type ConfineChild = (child: Readonly<ChildCommand>) => ChildCommand;
12
+ /** The command `confine` makes of `child`, refused unless it ends with the child's command and arguments unchanged. */
13
+ export declare function confined(child: ChildCommand, confine: ConfineChild | undefined): ChildCommand;
14
+ /** The child's environment: the allowlist from `from`, then what the caller names. */
15
+ export declare function childEnv(from: Readonly<Record<string, string | undefined>>, extra?: Readonly<Record<string, string>>): Record<string, string>;
16
+ export interface OpenCodeServerOptions {
17
+ command: string;
18
+ args: string[];
19
+ cwd: string;
20
+ /** What the child gets beyond the allowlist. */
21
+ env: Record<string, string>;
22
+ /** The environment the allowlist reads. Default `process.env`. */
23
+ from?: Readonly<Record<string, string | undefined>>;
24
+ password: string;
25
+ confine?: ConfineChild;
26
+ parentWatch?: ParentWatch;
27
+ /** How long OpenCode may take to say it listens. Default 60 s. */
28
+ startMs?: number;
29
+ signal: AbortSignal;
30
+ log?: (message: string, fields?: Record<string, unknown>) => void;
31
+ }
32
+ export interface OpenCodeServer {
33
+ readonly url: string;
34
+ readonly pid: number | undefined;
35
+ /** A request to the server: its status and its JSON body (undefined when empty or not JSON). */
36
+ request(method: string, path: string, body?: unknown, signal?: AbortSignal): Promise<{
37
+ status: number;
38
+ body: unknown;
39
+ text: string;
40
+ }>;
41
+ /** The server's event stream: each event's JSON, until the stream ends or `signal` aborts. */
42
+ events(signal: AbortSignal): AsyncIterable<{
43
+ type?: string;
44
+ properties?: Record<string, unknown>;
45
+ }>;
46
+ readonly exited: Promise<{
47
+ code: number | null;
48
+ signal: string | null;
49
+ }>;
50
+ alive(): boolean;
51
+ stderrTail(): string;
52
+ kill(): void;
53
+ }
54
+ /** Start `opencode serve` and resolve once it says where it listens. */
55
+ export declare function startOpenCodeServer(options: OpenCodeServerOptions): Promise<OpenCodeServer>;
@@ -0,0 +1,165 @@
1
+ // One `opencode serve` for one drive of a session, and the HTTP client the drive speaks to it with. Written for AgentRun.
2
+ // - The child's environment is an allowlist: PATH, LANG and TZ from this process, then what the drive names (its private
3
+ // homes, its config, its server password and OpenCode's own switches). Nothing else is inherited, so no provider key,
4
+ // token or host secret reaches it.
5
+ // - It runs in its own process group, which `kill()` ends whole, and dies with this process: started with a watch on its
6
+ // parent (./host's parentWatched), inside the host's confinement, so a host that is SIGKILLed leaves no OpenCode behind.
7
+ // - Its port is the one it says it listens on (its line `opencode server listening on <loopback URL>`): `--port 0` is
8
+ // not a free port of the system's choosing to OpenCode, which takes its default when that is free.
9
+ // - Every request carries the server's basic auth (user `opencode`, the drive's own password), on connections of the
10
+ // drive's own, which end with it: none is ever used for the next drive's OpenCode.
11
+ import { spawn } from "node:child_process";
12
+ import { Agent, request as httpRequest } from "node:http";
13
+ import { createInterface } from "node:readline";
14
+ import { parentWatched } from "@parcha/agentrun-kernel/host";
15
+ /** The variables a child takes from this process, when they are set. */
16
+ export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
17
+ /** The command `confine` makes of `child`, refused unless it ends with the child's command and arguments unchanged. */
18
+ export function confined(child, confine) {
19
+ if (!confine)
20
+ return child;
21
+ const out = confine({ command: child.command, args: [...child.args] });
22
+ const argv = [out?.command, ...(Array.isArray(out?.args) ? out.args : [])];
23
+ const tail = argv.slice(argv.length - child.args.length - 1);
24
+ const kept = argv.length > child.args.length + 1 && tail.length === child.args.length + 1 && tail.every((a, i) => a === (i === 0 ? child.command : child.args[i - 1]));
25
+ if (typeof out?.command !== "string" || !argv.every((a) => typeof a === "string") || !kept)
26
+ throw new Error("opencode: the host's confinement must start the child's own command and arguments, after its own");
27
+ return { command: out.command, args: out.args };
28
+ }
29
+ /** The child's environment: the allowlist from `from`, then what the caller names. */
30
+ export function childEnv(from, extra = {}) {
31
+ const env = {};
32
+ for (const name of INHERITED_ENV) {
33
+ const value = from[name];
34
+ if (typeof value === "string")
35
+ env[name] = value;
36
+ }
37
+ return { ...env, ...extra };
38
+ }
39
+ const LISTENING = /opencode server listening on (http:\/\/127\.0\.0\.1:(\d+))\b/;
40
+ const STDERR_TAIL = 8 * 1024;
41
+ /** Start `opencode serve` and resolve once it says where it listens. */
42
+ export async function startOpenCodeServer(options) {
43
+ const run = confined(parentWatched({ command: options.command, args: options.args }, options.parentWatch), options.confine);
44
+ const child = spawn(run.command, run.args, { cwd: options.cwd, env: childEnv(options.from ?? process.env, options.env), detached: true, stdio: ["ignore", "pipe", "pipe"] });
45
+ let stderr = "";
46
+ child.stderr.setEncoding("utf8");
47
+ child.stderr.on("data", (chunk) => void (stderr = (stderr + chunk).slice(-STDERR_TAIL)));
48
+ let done = false;
49
+ const exited = new Promise((resolve) => {
50
+ child.once("error", (err) => {
51
+ stderr = (stderr + `\n${String(err.message)}`).slice(-STDERR_TAIL);
52
+ done = true;
53
+ resolve({ code: null, signal: null });
54
+ });
55
+ child.once("close", (code, signal) => {
56
+ done = true;
57
+ resolve({ code, signal });
58
+ });
59
+ });
60
+ const kill = () => {
61
+ if (done || child.pid === undefined)
62
+ return;
63
+ try {
64
+ process.kill(-child.pid, "SIGKILL");
65
+ }
66
+ catch {
67
+ try {
68
+ child.kill("SIGKILL");
69
+ }
70
+ catch { /* gone */ }
71
+ }
72
+ };
73
+ if (options.signal.aborted)
74
+ kill();
75
+ else
76
+ options.signal.addEventListener("abort", kill, { once: true });
77
+ // The port, from the line OpenCode prints when it listens; everything else it prints is kept for a failure's message.
78
+ const url = await new Promise((resolve, reject) => {
79
+ let out = "";
80
+ const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
81
+ const timer = setTimeout(() => finish(new Error(`OpenCode did not say it listens within ${Math.round((options.startMs ?? 60_000) / 1000)} s`)), options.startMs ?? 60_000);
82
+ const finish = (result) => {
83
+ clearTimeout(timer);
84
+ if (typeof result === "string")
85
+ resolve(result);
86
+ else {
87
+ kill();
88
+ reject(new Error(`opencode: ${result.message}: ${(out + stderr).trim().slice(-600) || "it printed nothing"}`));
89
+ }
90
+ };
91
+ lines.on("line", (line) => {
92
+ out = (out + line + "\n").slice(-STDERR_TAIL);
93
+ const listening = LISTENING.exec(line);
94
+ if (listening)
95
+ finish(listening[1]);
96
+ });
97
+ void exited.then(({ code, signal }) => finish(new Error(`OpenCode exited before it listened (${signal ?? `code ${code}`})`)));
98
+ });
99
+ const auth = `Basic ${Buffer.from(`opencode:${options.password}`).toString("base64")}`;
100
+ // The drive's own connections, ended with its OpenCode: a connection kept alive for a server that is gone is never used
101
+ // for the next one. A process-wide pool would hand the next drive's first request a socket to the killed process when
102
+ // the new OpenCode listens on the same port (it takes 4096 whenever that is free), and that request fails with a reset.
103
+ const agent = new Agent({ keepAlive: true });
104
+ const call = (method, path, body, accept, signal) => new Promise((resolve, reject) => {
105
+ const payload = body === undefined ? undefined : JSON.stringify(body);
106
+ const sent = httpRequest(`${url}${path}`, {
107
+ method,
108
+ agent,
109
+ signal,
110
+ headers: { authorization: auth, accept, ...(payload === undefined ? {} : { "content-type": "application/json", "content-length": Buffer.byteLength(payload) }) },
111
+ }, resolve);
112
+ sent.once("error", reject);
113
+ sent.end(payload);
114
+ });
115
+ const request = async (method, path, body, signal) => {
116
+ const response = await call(method, path, body, "application/json", signal ? AbortSignal.any([signal, options.signal]) : options.signal);
117
+ let text = "";
118
+ response.setEncoding("utf8");
119
+ for await (const chunk of response)
120
+ text += chunk;
121
+ let parsed;
122
+ try {
123
+ parsed = text ? JSON.parse(text) : undefined;
124
+ }
125
+ catch { }
126
+ return { status: response.statusCode ?? 0, body: parsed, text };
127
+ };
128
+ async function* events(signal) {
129
+ const response = await call("GET", "/event", undefined, "text/event-stream", AbortSignal.any([signal, options.signal]));
130
+ if (response.statusCode !== 200) {
131
+ response.resume();
132
+ throw new Error(`opencode: OpenCode's event stream answered ${response.statusCode}`);
133
+ }
134
+ response.setEncoding("utf8");
135
+ let buffer = "";
136
+ let data = [];
137
+ for await (const chunk of response) {
138
+ buffer += chunk;
139
+ for (let at = buffer.search(/\r\n|\r|\n/); at >= 0; at = buffer.search(/\r\n|\r|\n/)) {
140
+ const line = buffer.slice(0, at);
141
+ buffer = buffer.slice(at + (buffer.startsWith("\r\n", at) ? 2 : 1));
142
+ if (line === "") {
143
+ const text = data.join("\n");
144
+ data = [];
145
+ if (!text)
146
+ continue;
147
+ try {
148
+ yield JSON.parse(text);
149
+ }
150
+ catch {
151
+ options.log?.("opencode: an event that is not JSON was skipped", { bytes: text.length });
152
+ }
153
+ }
154
+ else if (line.startsWith("data:"))
155
+ data.push(line.slice(line.startsWith("data: ") ? 6 : 5));
156
+ }
157
+ }
158
+ }
159
+ // Its connections end with it.
160
+ const end = () => {
161
+ kill();
162
+ agent.destroy();
163
+ };
164
+ return { url, pid: child.pid, request, events, exited, alive: () => !done, stderrTail: () => stderr, kill: end };
165
+ }
@@ -0,0 +1,9 @@
1
+ export { openCodeAdapter } from "./adapter.js";
2
+ /** The check the adapter runs on the host's skills when it is made: @parcha/agentrun-kernel's own, as the other adapters'. */
3
+ export { skillProblems } from "@parcha/agentrun-kernel";
4
+ export type { HostSkill } from "@parcha/agentrun-kernel";
5
+ export type { OpenCodeAdapterOptions, OpenCodeProvider } from "./adapter.js";
6
+ export type { ChildCommand, ConfineChild } from "./host/server.js";
7
+ export { OPENCODE_VERSION, findOpenCode, openCodeBinary } from "./binary.js";
8
+ export { verifyOpenCode, verifyOpenCodeBinary } from "./verify.js";
9
+ export { OPENCODE_BINARY_SHA256, OPENCODE_INSTALL, OPENCODE_NPM_INTEGRITY, OpenCodeNotInstalled, OpenCodePinMismatch } from "./versions.js";
@@ -0,0 +1,6 @@
1
+ export { openCodeAdapter } from "./adapter.js";
2
+ /** The check the adapter runs on the host's skills when it is made: @parcha/agentrun-kernel's own, as the other adapters'. */
3
+ export { skillProblems } from "@parcha/agentrun-kernel";
4
+ export { OPENCODE_VERSION, findOpenCode, openCodeBinary } from "./binary.js";
5
+ export { verifyOpenCode, verifyOpenCodeBinary } from "./verify.js";
6
+ export { OPENCODE_BINARY_SHA256, OPENCODE_INSTALL, OPENCODE_NPM_INTEGRITY, OpenCodeNotInstalled, OpenCodePinMismatch } from "./versions.js";