@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.
- package/CHANGELOG.md +238 -0
- package/README.md +739 -116
- package/dist/adapters.d.ts +35 -6
- package/dist/adapters.js +152 -26
- package/dist/agents.d.ts +18 -7
- package/dist/agents.js +19 -10
- package/dist/app.js +101 -26
- package/dist/background.d.ts +29 -0
- package/dist/background.js +397 -0
- package/dist/box-egress-vm.d.ts +125 -0
- package/dist/box-egress-vm.js +350 -0
- package/dist/box-egress.d.ts +99 -0
- package/dist/box-egress.js +259 -0
- package/dist/box-image.d.ts +1 -1
- package/dist/box-image.js +9 -7
- package/dist/box-relay-vm.d.ts +84 -0
- package/dist/box-relay-vm.js +410 -0
- package/dist/box-relay.d.ts +8 -5
- package/dist/box-relay.js +14 -9
- package/dist/boxes.d.ts +28 -5
- package/dist/boxes.js +44 -18
- package/dist/browser-cost.d.ts +41 -0
- package/dist/browser-cost.js +158 -0
- package/dist/cap.d.ts +130 -21
- package/dist/cap.js +339 -67
- package/dist/cli.js +30 -4
- package/dist/coding-tools.d.ts +7 -3
- package/dist/coding-tools.js +16 -10
- package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
- package/dist/console/assets/index-CnJBf7Lc.js +486 -0
- package/dist/console/assets/index-DUHbWcIP.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/content-filter.d.ts +7 -0
- package/dist/content-filter.js +23 -0
- package/dist/decision-rows.d.ts +11 -3
- package/dist/decision-rows.js +18 -11
- package/dist/decisions.d.ts +3 -3
- package/dist/decisions.js +4 -3
- package/dist/errors.d.ts +2 -0
- package/dist/errors.js +5 -2
- package/dist/files.d.ts +9 -1
- package/dist/files.js +10 -2
- package/dist/grade.d.ts +11 -11
- package/dist/grade.js +43 -55
- package/dist/graph-served.d.ts +23 -0
- package/dist/graph-served.js +75 -0
- package/dist/graph-view.d.ts +7 -5
- package/dist/graph-view.js +10 -3
- package/dist/harness-app.d.ts +4 -2
- package/dist/harness-app.js +110 -19
- package/dist/harness-opencode/adapter.d.ts +45 -0
- package/dist/harness-opencode/adapter.js +272 -0
- package/dist/harness-opencode/binary.d.ts +18 -0
- package/dist/harness-opencode/binary.js +87 -0
- package/dist/harness-opencode/config.d.ts +24 -0
- package/dist/harness-opencode/config.js +61 -0
- package/dist/harness-opencode/harness.d.ts +77 -0
- package/dist/harness-opencode/harness.js +620 -0
- package/dist/harness-opencode/host/mcp.d.ts +40 -0
- package/dist/harness-opencode/host/mcp.js +208 -0
- package/dist/harness-opencode/host/policy.d.ts +71 -0
- package/dist/harness-opencode/host/policy.js +419 -0
- package/dist/harness-opencode/host/server.d.ts +55 -0
- package/dist/harness-opencode/host/server.js +165 -0
- package/dist/harness-opencode/index.d.ts +9 -0
- package/dist/harness-opencode/index.js +6 -0
- package/dist/harness-opencode/verify.d.ts +32 -0
- package/dist/harness-opencode/verify.js +75 -0
- package/dist/harness-opencode/versions.d.ts +33 -0
- package/dist/harness-opencode/versions.js +64 -0
- package/dist/harness.d.ts +4 -1
- package/dist/harness.js +5 -2
- package/dist/host-check.d.ts +12 -0
- package/dist/host-check.js +34 -0
- package/dist/host-tools.d.ts +12 -2
- package/dist/host-tools.js +26 -12
- package/dist/host.js +6 -2
- package/dist/hosted-search.js +5 -1
- package/dist/import.d.ts +2 -2
- package/dist/import.js +4 -3
- package/dist/key-check.d.ts +3 -2
- package/dist/key-check.js +7 -3
- package/dist/key-refusal.js +8 -4
- package/dist/key-words.d.ts +37 -0
- package/dist/key-words.js +40 -0
- package/dist/learn/check.d.ts +10 -1
- package/dist/learn/check.js +19 -1
- package/dist/learn/grade.d.ts +6 -2
- package/dist/learn/grade.js +28 -14
- package/dist/learn/index.d.ts +3 -3
- package/dist/learn/index.js +3 -3
- package/dist/learn/notes.js +2 -1
- package/dist/learn/reflect.d.ts +2 -2
- package/dist/learn/reflect.js +53 -5
- package/dist/learn/secrets.js +28 -8
- package/dist/learn/skills.d.ts +19 -4
- package/dist/learn/skills.js +95 -6
- package/dist/learned-workflow.d.ts +59 -0
- package/dist/learned-workflow.js +191 -0
- package/dist/learning-routes.d.ts +30 -1
- package/dist/learning-routes.js +173 -19
- package/dist/learning-run.d.ts +8 -6
- package/dist/learning-run.js +70 -27
- package/dist/learning-words.d.ts +12 -5
- package/dist/learning-words.js +34 -13
- package/dist/learning.d.ts +52 -3
- package/dist/learning.js +204 -4
- package/dist/mcp-gateway.d.ts +96 -0
- package/dist/mcp-gateway.js +408 -0
- package/dist/mcp-meta.d.ts +17 -0
- package/dist/mcp-meta.js +38 -0
- package/dist/mcp-servers.d.ts +33 -9
- package/dist/mcp-servers.js +58 -10
- package/dist/mcp.js +5 -5
- package/dist/model.d.ts +13 -11
- package/dist/model.js +11 -10
- package/dist/openapi/agentrun-v2.openapi.json +1 -0
- package/dist/openapi.js +407 -54
- package/dist/page.d.ts +2 -0
- package/dist/page.js +3 -0
- package/dist/paid-calls.d.ts +5 -1
- package/dist/paid-calls.js +1 -1
- package/dist/pause.d.ts +2 -0
- package/dist/place.d.ts +29 -5
- package/dist/place.js +51 -11
- package/dist/print.d.ts +7 -0
- package/dist/print.js +13 -0
- package/dist/propose.d.ts +2 -0
- package/dist/propose.js +38 -8
- package/dist/request-start.d.ts +12 -4
- package/dist/request-start.js +139 -15
- package/dist/run-box.d.ts +56 -4
- package/dist/run-box.js +183 -23
- package/dist/runnable.d.ts +13 -3
- package/dist/runnable.js +63 -6
- package/dist/runs.d.ts +266 -37
- package/dist/runs.js +884 -90
- package/dist/secrets.d.ts +27 -0
- package/dist/secrets.js +38 -2
- package/dist/server.d.ts +141 -36
- package/dist/server.js +562 -118
- package/dist/sign-ins.d.ts +99 -0
- package/dist/sign-ins.js +288 -0
- package/dist/skills.d.ts +16 -4
- package/dist/skills.js +35 -7
- package/dist/stats.d.ts +7 -2
- package/dist/stats.js +28 -7
- package/dist/tool-gate.d.ts +281 -0
- package/dist/tool-gate.js +585 -0
- package/dist/tool-keys.d.ts +48 -11
- package/dist/tool-keys.js +46 -8
- package/dist/tool-plane.d.ts +116 -27
- package/dist/tool-plane.js +232 -50
- package/dist/tools.d.ts +69 -14
- package/dist/tools.js +148 -26
- package/dist/trigger-secrets.d.ts +32 -0
- package/dist/trigger-secrets.js +143 -0
- package/dist/triggers.d.ts +439 -0
- package/dist/triggers.js +863 -0
- package/dist/turn-end.d.ts +3 -2
- package/dist/turn-end.js +3 -2
- package/dist/usage-lines.d.ts +26 -0
- package/dist/usage-lines.js +28 -0
- package/dist/validate.d.ts +2 -0
- package/dist/validate.js +11 -2
- package/dist/web-fetch.js +3 -3
- package/dist/webhooks.d.ts +11 -4
- package/dist/webhooks.js +17 -1
- package/launcher/agentrun-serve +1 -1
- package/package.json +16 -14
- package/dist/console/assets/index-BN7oVcO4.js +0 -445
- package/dist/console/assets/index-By-jkqki.css +0 -1
package/dist/harness-app.js
CHANGED
|
@@ -21,18 +21,25 @@
|
|
|
21
21
|
// A message the door accepts is on the root before the door says so, and its end (sent to the session, or dropped by a
|
|
22
22
|
// stop) after: one that waited for a turn's end when the process died is sent at the next open. Its end is written once
|
|
23
23
|
// the session has it, so a process that dies between the two sends it again rather than never.
|
|
24
|
+
//
|
|
25
|
+
// A host tool call the tool gate parks for a person's approval (tool-gate.ts) ends its turn: no model request leaves
|
|
26
|
+
// after it, and the turn is interrupted once its result is in, then settled as a stopped one is, its end interrupted.
|
|
27
|
+
// The answer's resume is a message of its own, sent as a person's is; a turn the park ended is not resumed at the next
|
|
28
|
+
// open while the call still waits.
|
|
29
|
+
import { existsSync, writeFileSync } from "node:fs";
|
|
24
30
|
import { randomUUID } from "node:crypto";
|
|
25
31
|
import { AssistantEntry, ROOT_CONVERSATION_ID, ToolResultEntry, UserEntry } from "@earendil-works/pi-durable";
|
|
26
32
|
import { modelPortFor, RUNNER_RECORDS } from "@parcha/agentrun-kernel";
|
|
27
33
|
import { confineOf } from "./adapters.js";
|
|
28
34
|
import { hostTools } from "./host-tools.js";
|
|
29
|
-
import {
|
|
35
|
+
import { endsTurn } from "./tool-gate.js";
|
|
36
|
+
import { CAP_REFUSAL_CODE, CAP_REFUSED_FIELD, capToolSpend, holdsInFlight, sideSpend, takePaidRefusal, useSpend } from "./cap.js";
|
|
30
37
|
import { durableSessions } from "./sessions.js";
|
|
31
38
|
import { handsParallel, planeOf } from "./tool-plane.js";
|
|
32
39
|
import { parallelOf } from "./web-fetch.js";
|
|
33
40
|
import { WEB_SEARCH_TOOL } from "./web-search.js";
|
|
34
41
|
import { ADAPTER_API, MESSAGE, MESSAGE_END, TURN_END } from "./turn-end.js";
|
|
35
|
-
import { REQUEST_CONTINUED, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_STARTED, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
|
|
42
|
+
import { originOf, REQUEST_CONTINUED, REQUEST_COST_LATE, REQUEST_COST_PENDING, REQUEST_STARTED, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
|
|
36
43
|
/** The root's marker of a paid request already written as a pi.assistant entry. */
|
|
37
44
|
export const BOOKED = "adapter.request";
|
|
38
45
|
/** The cost of a request whose answer was written at unknown cost, and its tokens, written once it came in: the timeline
|
|
@@ -95,8 +102,9 @@ function assistantMessage(harness, model, request, text, calls, error) {
|
|
|
95
102
|
* `budgetUsd`: the run's spend cap. `cancelled`: whether the run was cancelled (request-start.ts `cancelledIn`): once it
|
|
96
103
|
* says so, no model request leaves, as on pi. `cwd`: the run's workspace, the directory its file tools confine to, where
|
|
97
104
|
* the harness works too (the adapter's io.cwd), so a path the model builds from its working directory is one the tools
|
|
98
|
-
* take (in a box, coding-tools.ts names it at the box's work dir).
|
|
99
|
-
|
|
105
|
+
* take (in a box, coding-tools.ts names it at the box's work dir). `gate`: the run's tool gate, which each host tool
|
|
106
|
+
* call passes. */
|
|
107
|
+
export function adapterRun(make, harness, spec, context, budgetUsd, tools = [], dir, cap, cancelled = () => false, cwd, coding, stopRecord, gate, extra = []) {
|
|
100
108
|
const plane = planeOf(process.env);
|
|
101
109
|
// The web tools' Parallel key, when one resolves to Parallel, read as the run's app loads, before its process starts
|
|
102
110
|
// one of its own (web-fetch.ts).
|
|
@@ -111,18 +119,29 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
111
119
|
// That `refused` is the cap's, not the cancel's: its error entry gets a start mark of its own first, as pi's does, so the
|
|
112
120
|
// run's usage counts no request for it.
|
|
113
121
|
let capRefused = false;
|
|
122
|
+
// A refusal for room's figures, for its start mark (cap.ts RefusalFigures).
|
|
123
|
+
let refusedFigures;
|
|
114
124
|
const CANCELLED = "the run was cancelled: the model request was not sent";
|
|
115
125
|
// What the run's paid tools charged, in earlier processes (read at the open) and this one: null once one is unknown.
|
|
116
126
|
let charged = 0;
|
|
117
127
|
// Each admitted request's worst case until its cost is booked: the booking's spend counts it only then.
|
|
118
128
|
const inFlight = holdsInFlight();
|
|
129
|
+
// The run's spend as a paid tool's check reads it (useSpend, set at the open): a paid call refused under it pauses the
|
|
130
|
+
// run at this run's next request (guard).
|
|
131
|
+
let spend;
|
|
119
132
|
const plus = (a, b) => (a === null || b === null ? null : a + b);
|
|
120
133
|
const guard = (request) => {
|
|
121
134
|
const byCancel = cancelled();
|
|
122
|
-
|
|
135
|
+
// What the run spent: the booking's, its paid tools' charges, and its own model requests' beside the harness's (a
|
|
136
|
+
// learned workflow's: cap.ts sideSpend); theirs in flight are held with the paid calls' (paidHolds, capBefore).
|
|
137
|
+
// A paid call the cap just refused for room (cap.ts takePaidRefusal): this request is refused in its words, so the
|
|
138
|
+
// turn ends there and the run waits on a raise, as at a model request's refusal. A refusal no cap fixes comes first.
|
|
139
|
+
const paid = byCancel || !cap || request.spentUsd === null ? undefined : takePaidRefusal(spend);
|
|
140
|
+
const answer = byCancel ? { refuse: CANCELLED } : paid ? { refuse: `${CAP_REFUSAL_CODE}${paid.words}`, spentUsd: paid.figures.spentUsd, needsUsd: paid.figures.needsUsd } : cap?.beforeRequest({ ...request, spentUsd: plus(plus(request.spentUsd, charged), sideSpend()) });
|
|
123
141
|
if (answer && "refuse" in answer) {
|
|
124
142
|
refused = answer.refuse;
|
|
125
143
|
capRefused = !byCancel;
|
|
144
|
+
refusedFigures = !byCancel && "needsUsd" in answer && typeof answer.needsUsd === "number" && typeof answer.spentUsd === "number" ? { spentUsd: answer.spentUsd, needsUsd: answer.needsUsd } : undefined;
|
|
126
145
|
return answer;
|
|
127
146
|
}
|
|
128
147
|
// Admitted, limited to the output what is left of the cap buys (which the runner hands the model proxy, and holds it
|
|
@@ -148,6 +167,12 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
148
167
|
};
|
|
149
168
|
// A paid request whose cost could not be written: the booking admits no request after it, and the turn stops on it.
|
|
150
169
|
let halted;
|
|
170
|
+
// The call the gate parked, until the next message starts a turn: no request leaves meanwhile, and the turn is
|
|
171
|
+
// interrupted once the call's result is in. Not a failure: the turn ends as the person's answer will resume it.
|
|
172
|
+
let parked;
|
|
173
|
+
const PARKED = new Error("the turn ended: a tool call waits for a person's approval");
|
|
174
|
+
// Each call's arguments, by its id, for a park named by tool and arguments (endsTurn).
|
|
175
|
+
const argsOf = new Map();
|
|
151
176
|
const results = new Map();
|
|
152
177
|
let run;
|
|
153
178
|
let session;
|
|
@@ -304,6 +329,7 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
304
329
|
text += event.delta;
|
|
305
330
|
else if (event.type === "tool_start") {
|
|
306
331
|
const call = { type: "toolCall", id: event.callId, name: event.name, arguments: (event.args ?? {}) };
|
|
332
|
+
argsOf.set(event.callId, event.args ?? {});
|
|
307
333
|
// A call of the current request's answer after that answer's entry was written (at its first call's end): written
|
|
308
334
|
// now as the answer's continuation, so its result never comes before it and the next answer never holds it.
|
|
309
335
|
const request = current;
|
|
@@ -324,6 +350,9 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
324
350
|
data: { diagnostics: [] },
|
|
325
351
|
});
|
|
326
352
|
}).then(() => undefined));
|
|
353
|
+
// The parked call's result is in: its turn ends here, settled once the interrupt is done (runTurns).
|
|
354
|
+
if (endsTurn(parked, { callId: event.callId, tool: event.name, args: argsOf.get(event.callId) }) && !stopping)
|
|
355
|
+
stopping = session?.interrupt();
|
|
327
356
|
}
|
|
328
357
|
};
|
|
329
358
|
/** The session's requests, from its runner records, by number: the model each asked for, and the usage of each it
|
|
@@ -349,11 +378,13 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
349
378
|
};
|
|
350
379
|
/** The person's message: the session's new turn, then its entry and its end on the root. */
|
|
351
380
|
const sendOf = (message) => async () => {
|
|
381
|
+
parked = undefined;
|
|
382
|
+
argsOf.clear();
|
|
352
383
|
await message.recorded;
|
|
353
384
|
taking = message.id;
|
|
354
385
|
await session.send(message.content);
|
|
355
386
|
await later(() => commit(async (tx) => {
|
|
356
|
-
await tx.appendEntry(UserEntry, ROOT_CONVERSATION_ID, { model: [{ role: "user", content: [{ type: "text", text: message.content }], timestamp: now() }] });
|
|
387
|
+
await tx.appendEntry(UserEntry, ROOT_CONVERSATION_ID, { model: [{ role: "user", content: [{ type: "text", text: message.content }], timestamp: now() }], ...(message.origin ? { data: { origin: message.origin } } : {}) });
|
|
357
388
|
await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE_END, data: { key: spec.key, id: message.id, sent: true } });
|
|
358
389
|
}).then(() => undefined));
|
|
359
390
|
};
|
|
@@ -369,6 +400,10 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
369
400
|
let failed;
|
|
370
401
|
let status = "failed";
|
|
371
402
|
answer = carry;
|
|
403
|
+
// A turn of its own: a paid call's refusal a stop left pending (its turn stopped before its next request) is
|
|
404
|
+
// let go, so this turn's first request is judged as any other, never paused for a call the person moved on from.
|
|
405
|
+
if (spend)
|
|
406
|
+
takePaidRefusal(spend);
|
|
372
407
|
try {
|
|
373
408
|
await start();
|
|
374
409
|
const end = await session.turnEnd();
|
|
@@ -396,8 +431,21 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
396
431
|
// its error and ends failed. The run's status is its last turn's end (turns.ts): with no message waiting, the run
|
|
397
432
|
// fails on this error, as a pi run does; a message waiting behind it is still sent, and when that turn completes,
|
|
398
433
|
// the run completes with its answer, this failure kept in the timeline.
|
|
399
|
-
|
|
434
|
+
// A turn the gate parked ends interrupted, never failed on the request its park refused.
|
|
435
|
+
const why = refused ?? halted?.message ?? (failed === undefined || parked !== undefined ? undefined : `${harness}: ${failed}`);
|
|
436
|
+
if (parked !== undefined && why === undefined)
|
|
437
|
+
status = "interrupted";
|
|
438
|
+
// A test's seam, unset in a server (AGENTRUN_SERVE_TEST_CRASH_AFTER_ANSWER, a file that marks it once): a parked
|
|
439
|
+
// turn holds its end until the answer's message is recorded, then the process goes by a signal, as a crash
|
|
440
|
+
// between the two would leave the run.
|
|
441
|
+
if (CRASH_SEAM && parked !== undefined && !existsSync(CRASH_SEAM)) {
|
|
442
|
+
await answerIn;
|
|
443
|
+
writeFileSync(CRASH_SEAM, "");
|
|
444
|
+
process.kill(process.pid, "SIGKILL");
|
|
445
|
+
}
|
|
400
446
|
const unsent = refused !== undefined && capRefused;
|
|
447
|
+
const figures = unsent ? refusedFigures : undefined;
|
|
448
|
+
refusedFigures = undefined;
|
|
401
449
|
refused = undefined;
|
|
402
450
|
capRefused = false;
|
|
403
451
|
const pending = open.size > 0;
|
|
@@ -409,7 +457,7 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
409
457
|
if (why !== undefined) {
|
|
410
458
|
// A refusal of the cap's: a start mark of its own first, as pi's is, so the run's usage counts no request for it.
|
|
411
459
|
if (unsent)
|
|
412
|
-
await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_STARTED, data: { [CAP_REFUSED_FIELD]: true } });
|
|
460
|
+
await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: REQUEST_STARTED, data: { [CAP_REFUSED_FIELD]: true, ...(figures ? { spentUsd: figures.spentUsd, needsUsd: figures.needsUsd } : {}) } });
|
|
413
461
|
await tx.appendEntry(AssistantEntry, ROOT_CONVERSATION_ID, { model: [assistantMessage(harness, undefined, undefined, "", [], why)] });
|
|
414
462
|
}
|
|
415
463
|
const data = {
|
|
@@ -436,6 +484,24 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
436
484
|
emit?.({ type: "run_end" });
|
|
437
485
|
})();
|
|
438
486
|
};
|
|
487
|
+
/** The gate's resume (tool-gate.ts): the answer as a message of its own, recorded with the gate's mark in one commit,
|
|
488
|
+
* then sent as a person's is. */
|
|
489
|
+
const CRASH_SEAM = process.env.AGENTRUN_SERVE_TEST_CRASH_AFTER_ANSWER;
|
|
490
|
+
let answerRecorded;
|
|
491
|
+
const answerIn = new Promise((resolve) => (answerRecorded = resolve));
|
|
492
|
+
const resume = async (id, content, mark) => {
|
|
493
|
+
await opened;
|
|
494
|
+
const message = { id: `approval-${id}`, content, recorded: commit(async (tx) => {
|
|
495
|
+
await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE, data: { key: spec.key, id: `approval-${id}`, content } });
|
|
496
|
+
await mark(tx);
|
|
497
|
+
}) };
|
|
498
|
+
await message.recorded;
|
|
499
|
+
answerRecorded?.();
|
|
500
|
+
if (turn)
|
|
501
|
+
queue.push(message);
|
|
502
|
+
else
|
|
503
|
+
runTurns(sendOf(message));
|
|
504
|
+
};
|
|
439
505
|
const door = {
|
|
440
506
|
attach(given) {
|
|
441
507
|
emit = given;
|
|
@@ -449,7 +515,8 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
449
515
|
return { accepted: false, reason: "busy" };
|
|
450
516
|
const id = randomUUID();
|
|
451
517
|
const content = textOf(input.content);
|
|
452
|
-
const
|
|
518
|
+
const origin = input.origin;
|
|
519
|
+
const message = { id, content, ...(origin ? { origin } : {}), recorded: commit(async (tx) => void (await tx.appendEntry(ROOT_CONVERSATION_ID, { kind: MESSAGE, data: { key: spec.key, id, content, ...(origin ? { origin } : {}) } }))) };
|
|
453
520
|
if (turn)
|
|
454
521
|
queue.push(message);
|
|
455
522
|
else
|
|
@@ -525,7 +592,7 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
525
592
|
else if (entry.kind === PRICED_LATE && typeof data.request === "number")
|
|
526
593
|
priced.add(data.request);
|
|
527
594
|
else if (entry.kind === MESSAGE && typeof data.id === "string")
|
|
528
|
-
accepted.set(data.id, { id: data.id, content: String(data.content ?? ""), recorded: Promise.resolve() });
|
|
595
|
+
accepted.set(data.id, { id: data.id, content: String(data.content ?? ""), ...(originOf(data.origin) ? { origin: data.origin } : {}), recorded: Promise.resolve() });
|
|
529
596
|
else if (entry.kind === MESSAGE_END && typeof data.id === "string") {
|
|
530
597
|
accepted.delete(data.id);
|
|
531
598
|
if (data.sent === true)
|
|
@@ -556,7 +623,7 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
556
623
|
...(budgetUsd !== undefined ? { budgetUsd } : {}),
|
|
557
624
|
beforeRequest: guard,
|
|
558
625
|
onEvent: onModel,
|
|
559
|
-
stopped: () => halted ?? cancelStop(),
|
|
626
|
+
stopped: () => halted ?? cancelStop() ?? (parked === undefined ? undefined : PARKED),
|
|
560
627
|
stop: (reason, message) => {
|
|
561
628
|
const error = new Error(message ?? reason);
|
|
562
629
|
if (reason === "model_error" && !halted) {
|
|
@@ -570,13 +637,18 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
570
637
|
await booking.bookCut();
|
|
571
638
|
// A paid tool's check before it spends: the session's requests, each booked once the proxy has answered (waited
|
|
572
639
|
// for, as at a turn's end), one still in flight at the worst case the cap held for it (as pi's spend counts it),
|
|
573
|
-
// with the run's charges; its charge joins them.
|
|
640
|
+
// with the run's charges and its own model requests' (sideSpend); its charge joins them. The run's own model
|
|
641
|
+
// requests read the same total at once (`now`: capModels' `joined`), a request in flight held, never less.
|
|
574
642
|
if (budgetUsd !== undefined) {
|
|
575
|
-
|
|
643
|
+
const now = () => plus(plus(plus(booking.spentUsd(), charged), sideSpend()), inFlight.total());
|
|
644
|
+
spend = {
|
|
576
645
|
cap: budgetUsd,
|
|
577
|
-
spent: async () => (await bookings(BOOKING_WAIT_MS), plus(plus(booking.spentUsd(), charged),
|
|
646
|
+
spent: async () => (await bookings(BOOKING_WAIT_MS), plus(plus(booking.spentUsd(), charged), sideSpend())),
|
|
647
|
+
held: () => inFlight.total(),
|
|
578
648
|
add: (usd) => void (charged = plus(charged, usd)),
|
|
579
|
-
|
|
649
|
+
now,
|
|
650
|
+
};
|
|
651
|
+
useSpend(spend);
|
|
580
652
|
}
|
|
581
653
|
// Each request the session booked and the root has no entry for: its cost, with no content.
|
|
582
654
|
// Each request the session booked and the root does not have, or has at unknown cost only: written now, once.
|
|
@@ -584,14 +656,31 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
584
656
|
if (!written.has(request) || (unpriced.has(request) && !priced.has(request)))
|
|
585
657
|
costed.push({ request, usage });
|
|
586
658
|
await flush();
|
|
587
|
-
|
|
659
|
+
// The calls that wait for a person's approval, read before any turn goes on.
|
|
660
|
+
await gate?.load(durable, context, coding, extra);
|
|
661
|
+
// The park every gated call of the run's takes, built once: the host tools' here, and the MCP gateway's, which takes
|
|
662
|
+
// the same object beside them (`{ gate, park }`). A call parked by its id or by its tool and arguments ends its turn.
|
|
663
|
+
const park = { commit: (change) => commit(change), parked: (callId) => void (parked = { callId }), parkedBy: (match) => void (parked = match), turn: () => taking };
|
|
664
|
+
// An MCP call from the harness's own client takes the same park, and its result is kept by its call id too, for the
|
|
665
|
+
// root's record of it, as a host tool's is.
|
|
666
|
+
const gateway = spec.mcp;
|
|
667
|
+
const mcp = gateway && { ...gateway, call: async (...[server, tool, args, call]) => {
|
|
668
|
+
const result = await gateway.call(server, tool, args, { ...call, ...(gate ? { park } : {}) });
|
|
669
|
+
if (call.callId)
|
|
670
|
+
results.set(call.callId, { text: result.content.map((block) => block.text).join("\n\n"), isError: result.isError === true });
|
|
671
|
+
return result;
|
|
672
|
+
} };
|
|
673
|
+
session = await adapter.open({ ...spec, ...(mcp ? { mcp } : {}), tools: hostTools(durable, tools, context, results, coding, gate ? { gate, park } : undefined, extra) }, { writer, models: booking.models, signal: stop.signal, onEvent, ...(dir ? { dir } : {}), ...(cwd ? { cwd } : {}) });
|
|
588
674
|
// A turn the person stopped is still open in the session (an interrupt writes no end there), and it is not resumed.
|
|
589
675
|
// The run's stop record names the person's newest message when they stopped: with no message on the root newer than
|
|
590
676
|
// it, the open turn is the stopped one. The session settles it, ended interrupted, and the next message is a turn of
|
|
591
677
|
// its own. A turn a crash or a drain cut has no stop record newer than the newest message, and is resumed as before.
|
|
592
|
-
|
|
678
|
+
// A turn the gate parked is settled as a stopped one: its call waits for its answer, which resumes the run. So is
|
|
679
|
+
// one whose parked call was answered before a process went: its request names the turn (gate.parkedIn), so the
|
|
680
|
+
// answer's message, queued, follows it, and the turn is never run again.
|
|
681
|
+
const stopped = (stopRecord?.stopped_at !== undefined
|
|
593
682
|
? lastUser !== undefined && lastUser <= placeOf(stopRecord.stopped_at)
|
|
594
|
-
: stopRecord?.stopped_after !== undefined && stopRecord.stopped_after === users;
|
|
683
|
+
: stopRecord?.stopped_after !== undefined && stopRecord.stopped_after === users) || gate?.waiting() === true || gate?.parkedIn(unended?.message) === true;
|
|
595
684
|
// An adapter written before settleOpenTurn has none: its stopped turn is recovered, as before.
|
|
596
685
|
if (session.state === "open_turn" && stopped && typeof session.settleOpenTurn === "function")
|
|
597
686
|
await session.settleOpenTurn();
|
|
@@ -615,12 +704,14 @@ export function adapterRun(make, harness, spec, context, budgetUsd, tools = [],
|
|
|
615
704
|
await restore(restored);
|
|
616
705
|
openedDone();
|
|
617
706
|
// Its answer so far is the root's, which a recovery that streams no new text keeps as the turn's.
|
|
618
|
-
if (session.state === "open_turn")
|
|
707
|
+
if (session.state === "open_turn" && !gate?.waiting())
|
|
619
708
|
runTurns(() => session.recover(), unended?.answer ?? undefined);
|
|
620
709
|
else if (queue.length) {
|
|
621
710
|
const next = sendOf(queue.shift());
|
|
622
711
|
runTurns(restored ? async () => (await restore(restored), await next()) : next);
|
|
623
712
|
}
|
|
713
|
+
// The answers from now on: each resumes the session with one message of its own.
|
|
714
|
+
gate?.start(resume);
|
|
624
715
|
},
|
|
625
716
|
};
|
|
626
717
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { type HostSkill } from "@parcha/agentrun-kernel";
|
|
2
|
+
import type { AgentAdapter } from "@parcha/agentrun-kernel";
|
|
3
|
+
import { type ModelProxyOptions } from "@parcha/agentrun-kernel/host";
|
|
4
|
+
import type { ConfineChild } from "./host/server.js";
|
|
5
|
+
export interface OpenCodeProvider {
|
|
6
|
+
/** The provider's origin (`https://api.openai.com`, or a gateway's base): the proxy forwards to its `/v1/responses` only. */
|
|
7
|
+
origin: string;
|
|
8
|
+
/** The provider key, read per request in this process. It never reaches OpenCode's process. */
|
|
9
|
+
credential: () => Promise<string> | string;
|
|
10
|
+
}
|
|
11
|
+
export interface OpenCodeAdapterOptions {
|
|
12
|
+
/** The provider's model id, or one per tier (`default` when a node names none). */
|
|
13
|
+
model: string | {
|
|
14
|
+
default: string;
|
|
15
|
+
fast?: string;
|
|
16
|
+
strong?: string;
|
|
17
|
+
};
|
|
18
|
+
provider: OpenCodeProvider;
|
|
19
|
+
/** Start OpenCode under the host's confinement (a `setpriv --no-new-privs` prefix, say). It may only add in front of
|
|
20
|
+
* the pinned binary and its arguments, and never touches its environment. */
|
|
21
|
+
confine?: ConfineChild;
|
|
22
|
+
/** The price of a response; null (or no function) records its cost as unknown. */
|
|
23
|
+
price?: ModelProxyOptions["price"];
|
|
24
|
+
/** The most output tokens one request may ask for. Default 32 000. */
|
|
25
|
+
maxOutputTokens?: number;
|
|
26
|
+
/** The model's context window. Default 272 000. */
|
|
27
|
+
contextWindow?: number;
|
|
28
|
+
/** Where sessions keep their private directories when the host lends none (`io.dir`): one per session key. */
|
|
29
|
+
sessionsDir?: string;
|
|
30
|
+
/** The host's skills, listed to the model by name and description and read with `read_skill_file`, and no others. */
|
|
31
|
+
skills?: readonly HostSkill[];
|
|
32
|
+
/** How long a drive waits for OpenCode's event stream to open, on each of its three tries. Default 10 s. */
|
|
33
|
+
eventConnectMs?: number;
|
|
34
|
+
log?: (message: string, fields?: Record<string, unknown>) => void;
|
|
35
|
+
/** For tests: a command that speaks `opencode serve`'s protocol instead of OpenCode (needs AGENTRUN_OPENCODE_STANDIN=1
|
|
36
|
+
* under a test runner). */
|
|
37
|
+
standIn?: {
|
|
38
|
+
command: string;
|
|
39
|
+
args?: string[];
|
|
40
|
+
env?: Record<string, string>;
|
|
41
|
+
};
|
|
42
|
+
/** For tests: the fetch the model proxy forwards with. */
|
|
43
|
+
fetch?: typeof fetch;
|
|
44
|
+
}
|
|
45
|
+
export declare function openCodeAdapter(options: OpenCodeAdapterOptions): AgentAdapter;
|
|
@@ -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;
|