@tangle-network/agent-runtime 0.264.0 → 0.271.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-Bx4kfVU3.d.ts → activation-BrJmwTLB.d.ts} +4 -4
- package/dist/{activation-DHFdvps3.js → activation-DGbFPGR3.js} +2 -2
- package/dist/{activation-DHFdvps3.js.map → activation-DGbFPGR3.js.map} +1 -1
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +2 -2
- package/dist/{coordination-driver-Bz-H17bC.js → coordination-driver-iBGMKDvB.js} +90 -50
- package/dist/coordination-driver-iBGMKDvB.js.map +1 -0
- package/dist/{delegate-CwbWhX5W.js → delegate-DOqUvaIz.js} +3 -3
- package/dist/delegate-DOqUvaIz.js.map +1 -0
- package/dist/durable.d.ts +5 -4
- package/dist/durable.js +3 -3
- package/dist/durable.js.map +1 -1
- package/dist/{graph-5NrpTg0h.js → graph-DnMcepkN.js} +12 -7
- package/dist/graph-DnMcepkN.js.map +1 -0
- package/dist/{improvement-cycle-WRWcFyuO.js → improvement-cycle-1IyRJo5h.js} +9 -9
- package/dist/improvement-cycle-1IyRJo5h.js.map +1 -0
- package/dist/{index-9wXpbjbX.d.ts → index-CL1dduJd.d.ts} +123 -73
- package/dist/index.d.ts +7 -7
- package/dist/index.js +7 -7
- package/dist/intelligence.d.ts +9 -3
- package/dist/intelligence.js +11 -5
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +4 -4
- package/dist/kernel.js +9 -9
- package/dist/{loop-runner-bin-DC1Lm0nM.js → loop-runner-bin-BPZ9tt1W.js} +3 -3
- package/dist/{loop-runner-bin-DC1Lm0nM.js.map → loop-runner-bin-BPZ9tt1W.js.map} +1 -1
- package/dist/{loop-runner-bin-DPewOZMn.d.ts → loop-runner-bin-O_vM1w8Y.d.ts} +3 -3
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +12 -6
- package/dist/mcp/index.js +7 -7
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/{memory-server-Cn8LbAxO.js → memory-server-DXQ8IxGR.js} +2 -2
- package/dist/{memory-server-Cn8LbAxO.js.map → memory-server-DXQ8IxGR.js.map} +1 -1
- package/dist/{openai-tools-ByTMUJcD.d.ts → openai-tools-DWHxpwx2.d.ts} +2 -2
- package/dist/profiles.d.ts +2 -2
- package/dist/{provision-supervisor-BZ6_uBGR.js → provision-supervisor-Cy8pqE95.js} +4 -4
- package/dist/{provision-supervisor-BZ6_uBGR.js.map → provision-supervisor-Cy8pqE95.js.map} +1 -1
- package/dist/{runtime-CUZC75EX.js → runtime-DVjIH1eo.js} +1160 -18
- package/dist/runtime-DVjIH1eo.js.map +1 -0
- package/dist/{server-KpdpN627.js → server-CN9vzbSe.js} +4 -4
- package/dist/{server-KpdpN627.js.map → server-CN9vzbSe.js.map} +1 -1
- package/dist/{stream-agent-turn-D1zelVx6.d.ts → stream-agent-turn-DbEsKgb_.d.ts} +200 -3
- package/dist/{structural-rollout-D17I5CwF.js → structural-rollout-I92sIfNl.js} +2 -2
- package/dist/{structural-rollout-D17I5CwF.js.map → structural-rollout-I92sIfNl.js.map} +1 -1
- package/dist/{substrate-qQphD9f0.d.ts → substrate-CbC03Vzo.d.ts} +2 -2
- package/dist/{supervise-_DTVHXPC.js → supervise-DJ_1i9vj.js} +85 -30
- package/dist/supervise-DJ_1i9vj.js.map +1 -0
- package/dist/{supervisor-C26k7X5-.js → supervisor-Cvd5mf7x.js} +1276 -488
- package/dist/supervisor-Cvd5mf7x.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +14 -14
- package/dist/testing.js.map +1 -1
- package/dist/{tool-server-x9NEhvHZ.js → tool-server-Dqer2M4_.js} +30 -12
- package/dist/tool-server-Dqer2M4_.js.map +1 -0
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/{types-BV14WTyW.d.ts → types-Bo7z5aG5.d.ts} +311 -75
- package/package.json +3 -2
- package/dist/coordination-driver-Bz-H17bC.js.map +0 -1
- package/dist/delegate-CwbWhX5W.js.map +0 -1
- package/dist/graph-5NrpTg0h.js.map +0 -1
- package/dist/improvement-cycle-WRWcFyuO.js.map +0 -1
- package/dist/runtime-CUZC75EX.js.map +0 -1
- package/dist/supervise-_DTVHXPC.js.map +0 -1
- package/dist/supervisor-C26k7X5-.js.map +0 -1
- package/dist/tool-server-x9NEhvHZ.js.map +0 -1
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { At as insideCursorNamespace, Dn as runAgentRounds, Dt as SpawnEventIndex, Et as InMemorySpawnJournal, Fn as canonicalObservedModelParts, Gn as unavailableSignalOfFailure, Gr as harnessInvocation, Ii as executableAgentProfileSnapshot, Kn as createPushTraceSource, Li as executableAgentSpecSnapshot, Lt as isTraceAnalysisStore, M as settledToIteration, Mn as readPromptOptions, Nn as routerBrain, On as createSandboxLineage, Ot as assertContentAddress, Pn as runBrainLoop, Ri as detachedFrozen, Rn as LEAF_CONTINUATION_TASK, Sa as armDeadlineTimer, Tn as defaultSelectWinner, Tt as InMemoryResultBlobStore, Un as sandboxClientAsProvider, Wn as unavailablePauseMs, Xi as notifySandboxEventObserver, _i as writeAllBytes, _t as createExecutorRegistry, aa as isAbortError, b as withDriverExecutor, ca as sleep, dt as rollingDispatch, ea as addSpend, gi as readCommittedJsonLines, gt as createExecutor, hi as prepareJsonlAppend, hr as contentAddress, ia as hasCompleteCacheBreakdown, jn as assertBoxlessPromptOptions, kn as probeSandboxCapabilities, kt as encodeResultBlob, la as stringifySafe, ma as zeroSpend, na as cloneSpend, r as createSupervisor, sa as randomSuffix, ta as chargedTokens, yt as createWorktreeCliExecutor, zi as detachedSnapshot } from "./supervisor-Cvd5mf7x.js";
|
|
2
2
|
import { m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-DodWX-cb.js";
|
|
3
|
-
import { E as profileChatClient, S as ObservationError, T as renderReport, b as sample, k as strategyAuthorMethod, v as refine, w as observe, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-
|
|
4
|
-
import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-BbSCSak0.js";
|
|
3
|
+
import { E as profileChatClient, S as ObservationError, T as renderReport, b as sample, k as strategyAuthorMethod, v as refine, w as observe, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-I92sIfNl.js";
|
|
4
|
+
import { a as concreteProfileModel, c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-BbSCSak0.js";
|
|
5
5
|
import { C as canonicalCandidateDigest$1, D as immutableCandidateValue, k as sha256Bytes$1, m as captureMaterializedWorkspace } from "./workspace-archive-C9lgf77y.js";
|
|
6
6
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
|
|
7
7
|
import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction--F3v1oo8.js";
|
|
8
|
-
import
|
|
9
|
-
import "./
|
|
8
|
+
import "./coordination-driver-iBGMKDvB.js";
|
|
9
|
+
import { C as gateOnDeliverable, r as supervise, w as mapExecutorResult } from "./supervise-DJ_1i9vj.js";
|
|
10
10
|
import "./run-layout-vwd4SwX_.js";
|
|
11
|
-
import "./provision-supervisor-
|
|
12
|
-
import "./delegate-
|
|
13
|
-
import "./graph-
|
|
11
|
+
import "./provision-supervisor-Cy8pqE95.js";
|
|
12
|
+
import "./delegate-DOqUvaIz.js";
|
|
13
|
+
import "./graph-DnMcepkN.js";
|
|
14
14
|
import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
15
15
|
import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, createTraceAnalyst, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
16
16
|
import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
|
|
@@ -19,11 +19,13 @@ import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
|
|
|
19
19
|
import { appendFileSync, chmodSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
20
20
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
21
21
|
import { cp, mkdir, mkdtemp, readFile, realpath, stat, writeFile } from "node:fs/promises";
|
|
22
|
+
import { materializeProfile } from "@tangle-network/agent-profile-materialize";
|
|
22
23
|
import { tmpdir } from "node:os";
|
|
23
24
|
import { isDeepStrictEqual, promisify } from "node:util";
|
|
24
25
|
import { collectAgentResponseText } from "@tangle-network/sandbox";
|
|
25
26
|
import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
|
|
26
27
|
import { createInterface } from "node:readline";
|
|
28
|
+
import { harnessSystemPromptIntents as harnessSystemPromptIntents$1 } from "@tangle-network/agent-interface/harness-capabilities";
|
|
27
29
|
import { pathToFileURL } from "node:url";
|
|
28
30
|
import { gzipSync } from "node:zlib";
|
|
29
31
|
import { createContext, runInContext } from "node:vm";
|
|
@@ -846,6 +848,173 @@ async function materializeLocalMcp(profile, opts = {}) {
|
|
|
846
848
|
};
|
|
847
849
|
}
|
|
848
850
|
//#endregion
|
|
851
|
+
//#region src/durable/spawn-journal-sql.ts
|
|
852
|
+
/**
|
|
853
|
+
* SQL-backed durable stores for supervised runs — `SqlSpawnJournal` and `SqlResultBlobStore`
|
|
854
|
+
* over the same minimal statement seam `SqlConversationJournal` uses (D1, postgres, sqlite,
|
|
855
|
+
* libSQL; positional `?` placeholders). This closes the orchestration-durability gap recorded in
|
|
856
|
+
* `conformance/durability/STATUS.md`: until now the spawn layer was file-only.
|
|
857
|
+
*
|
|
858
|
+
* Parity with the JSONL file stores, by construction:
|
|
859
|
+
* • same corruption guards — `beginTree` precedes events (enforced by the schema: an event row
|
|
860
|
+
* names a tree row), duplicate cursor seqs and duplicate materialization receipts are refused
|
|
861
|
+
* by the same `SpawnEventIndex` the file journal replays through, on both append and load;
|
|
862
|
+
* • same content-address law for blobs — a `put` whose ref does not hash to the artifact is
|
|
863
|
+
* refused, a re-put of the same ref asserts the identical bytes;
|
|
864
|
+
* • load order is insertion order (`INTEGER PRIMARY KEY AUTOINCREMENT`), the SQL analogue of
|
|
865
|
+
* the JSONL append-only spine.
|
|
866
|
+
*
|
|
867
|
+
* Durability note: this suite and its process-kill test run against `node:sqlite`, whose
|
|
868
|
+
* autocommit commits survive SIGKILL (process death, not OS crash). A deployment that must
|
|
869
|
+
* survive power loss sets its driver's synchronous mode (`PRAGMA synchronous=FULL` + WAL) at the
|
|
870
|
+
* adapter; agent-runtime takes no opinion.
|
|
871
|
+
*
|
|
872
|
+
* @experimental — draft: cross-process ownership is single-writer by convention (the same
|
|
873
|
+
* limitation `createFileRunContext` documents); a machine-visible ownership lease is follow-up.
|
|
874
|
+
*/
|
|
875
|
+
const TREES_DDL = (table) => `
|
|
876
|
+
CREATE TABLE IF NOT EXISTS ${table}_trees (
|
|
877
|
+
root TEXT PRIMARY KEY,
|
|
878
|
+
begun_at TEXT NOT NULL
|
|
879
|
+
)
|
|
880
|
+
`;
|
|
881
|
+
const EVENTS_DDL = (table) => `
|
|
882
|
+
CREATE TABLE IF NOT EXISTS ${table}_events (
|
|
883
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
884
|
+
root TEXT NOT NULL REFERENCES ${table}_trees (root),
|
|
885
|
+
body TEXT NOT NULL
|
|
886
|
+
)
|
|
887
|
+
`;
|
|
888
|
+
const BLOBS_DDL = (table) => `
|
|
889
|
+
CREATE TABLE IF NOT EXISTS ${table}_blobs (
|
|
890
|
+
ref TEXT PRIMARY KEY,
|
|
891
|
+
body TEXT NOT NULL
|
|
892
|
+
)
|
|
893
|
+
`;
|
|
894
|
+
/** SQL-backed `SpawnJournal`. One row per event; insertion order is replay order. */
|
|
895
|
+
var SqlSpawnJournal = class {
|
|
896
|
+
db;
|
|
897
|
+
table;
|
|
898
|
+
cache = /* @__PURE__ */ new Map();
|
|
899
|
+
appendTail = Promise.resolve();
|
|
900
|
+
constructor(db, table = "runtime_spawn_journal") {
|
|
901
|
+
this.db = db;
|
|
902
|
+
this.table = table;
|
|
903
|
+
}
|
|
904
|
+
/** Create the journal's tables if absent. Idempotent. */
|
|
905
|
+
async migrate() {
|
|
906
|
+
await this.db.exec(TREES_DDL(this.table));
|
|
907
|
+
await this.db.exec(EVENTS_DDL(this.table));
|
|
908
|
+
}
|
|
909
|
+
async loadTree(root) {
|
|
910
|
+
if ((await this.db.query(`SELECT begun_at FROM ${this.table}_trees WHERE root = ?`, [root])).length === 0) return void 0;
|
|
911
|
+
const rows = await this.db.query(`SELECT id, body FROM ${this.table}_events WHERE root = ? ORDER BY id`, [root]);
|
|
912
|
+
const index = new SpawnEventIndex(root);
|
|
913
|
+
const events = [];
|
|
914
|
+
for (const row of rows) {
|
|
915
|
+
const event = JSON.parse(row.body);
|
|
916
|
+
index.assert(event);
|
|
917
|
+
index.add(event);
|
|
918
|
+
events.push(event);
|
|
919
|
+
}
|
|
920
|
+
return events;
|
|
921
|
+
}
|
|
922
|
+
async beginTree(root, at) {
|
|
923
|
+
return this.serializeAppend(async () => {
|
|
924
|
+
await this.ensureMigrated();
|
|
925
|
+
const existing = await this.db.query(`SELECT begun_at FROM ${this.table}_trees WHERE root = ?`, [root]);
|
|
926
|
+
if (existing.length > 0) {
|
|
927
|
+
const begunAt = existing[0]?.begun_at;
|
|
928
|
+
if (begunAt !== at) throw new Error(`spawn tree '${root}' already begun in SQL at ${begunAt}; refusing to overwrite with ${at}`);
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
await this.db.exec(`INSERT INTO ${this.table}_trees (root, begun_at) VALUES (?, ?)`, [root, at]);
|
|
932
|
+
this.cache.set(root, {
|
|
933
|
+
maxId: 0,
|
|
934
|
+
index: new SpawnEventIndex(root)
|
|
935
|
+
});
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
async appendEvent(root, ev) {
|
|
939
|
+
const event = detachedSnapshot(ev, "spawn event");
|
|
940
|
+
return this.serializeAppend(async () => {
|
|
941
|
+
await this.ensureMigrated();
|
|
942
|
+
const state = await this.validationIndex(root);
|
|
943
|
+
state.index.assert(event);
|
|
944
|
+
if ((await this.db.exec(`INSERT INTO ${this.table}_events (root, body) VALUES (?, ?)`, [root, JSON.stringify(event)])).rowsAffected !== 1) throw new Error(`spawn journal SQL: append of an event for tree '${root}' affected no rows`);
|
|
945
|
+
state.index.add(event);
|
|
946
|
+
state.maxId = await this.maxEventId(root);
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
async validationIndex(root) {
|
|
950
|
+
if ((await this.db.query(`SELECT begun_at FROM ${this.table}_trees WHERE root = ?`, [root])).length === 0) throw new Error(`appendEvent called for unknown spawn tree '${root}'; call beginTree first`);
|
|
951
|
+
const max = await this.maxEventId(root);
|
|
952
|
+
const cached = this.cache.get(root);
|
|
953
|
+
if (cached && cached.maxId === max) return cached;
|
|
954
|
+
const index = new SpawnEventIndex(root);
|
|
955
|
+
if (max > 0) {
|
|
956
|
+
const rows = await this.db.query(`SELECT body FROM ${this.table}_events WHERE root = ? ORDER BY id`, [root]);
|
|
957
|
+
for (const row of rows) {
|
|
958
|
+
const event = JSON.parse(row.body);
|
|
959
|
+
index.assert(event);
|
|
960
|
+
index.add(event);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
const state = {
|
|
964
|
+
maxId: max,
|
|
965
|
+
index
|
|
966
|
+
};
|
|
967
|
+
this.cache.set(root, state);
|
|
968
|
+
return state;
|
|
969
|
+
}
|
|
970
|
+
async maxEventId(root) {
|
|
971
|
+
return (await this.db.query(`SELECT MAX(id) AS max FROM ${this.table}_events WHERE root = ?`, [root]))[0]?.max ?? 0;
|
|
972
|
+
}
|
|
973
|
+
migrated = false;
|
|
974
|
+
async ensureMigrated() {
|
|
975
|
+
if (this.migrated) return;
|
|
976
|
+
await this.migrate();
|
|
977
|
+
this.migrated = true;
|
|
978
|
+
}
|
|
979
|
+
serializeAppend(operation) {
|
|
980
|
+
const append = this.appendTail.then(operation);
|
|
981
|
+
this.appendTail = append.catch(() => void 0);
|
|
982
|
+
return append;
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
/** SQL-backed `ResultBlobStore`. One content-addressed row per settled result. */
|
|
986
|
+
var SqlResultBlobStore = class {
|
|
987
|
+
db;
|
|
988
|
+
table;
|
|
989
|
+
migrated = false;
|
|
990
|
+
constructor(db, table = "runtime_result_blobs") {
|
|
991
|
+
this.db = db;
|
|
992
|
+
this.table = table;
|
|
993
|
+
}
|
|
994
|
+
async migrate() {
|
|
995
|
+
await this.db.exec(BLOBS_DDL(this.table));
|
|
996
|
+
}
|
|
997
|
+
async put(outRef, artifact) {
|
|
998
|
+
await this.ensureMigrated();
|
|
999
|
+
const { text } = encodeResultBlob(outRef, artifact);
|
|
1000
|
+
if ((await this.db.exec(`INSERT OR IGNORE INTO ${this.table}_blobs (ref, body) VALUES (?, ?)`, [outRef, text])).rowsAffected === 1) return;
|
|
1001
|
+
assertContentAddress(outRef, await this.get(outRef));
|
|
1002
|
+
}
|
|
1003
|
+
async get(outRef) {
|
|
1004
|
+
await this.ensureMigrated();
|
|
1005
|
+
const rows = await this.db.query(`SELECT body FROM ${this.table}_blobs WHERE ref = ?`, [outRef]);
|
|
1006
|
+
if (rows.length === 0) return void 0;
|
|
1007
|
+
const artifact = JSON.parse(rows[0]?.body ?? "null");
|
|
1008
|
+
assertContentAddress(outRef, artifact);
|
|
1009
|
+
return artifact;
|
|
1010
|
+
}
|
|
1011
|
+
async ensureMigrated() {
|
|
1012
|
+
if (this.migrated) return;
|
|
1013
|
+
await this.migrate();
|
|
1014
|
+
this.migrated = true;
|
|
1015
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
//#endregion
|
|
849
1018
|
//#region src/runtime/audit-intent.ts
|
|
850
1019
|
/** Default system instruction for intent-auditor agents: diagnose diverged/drifting trajectories. */
|
|
851
1020
|
const defaultAuditorInstruction = "You audit whether an AI agent is on the RIGHT ROUTE — not whether it works hard, but whether its actions serve the stated intents. Infer the REVEALED intent from the action pattern (what the trajectory is actually optimizing). Compare against the declared task intent, the user intent when given, and the meta-intent when given. Flawless execution down the wrong route is DIVERGED. Busy-work that neither advances nor harms is DRIFTING. Judge only from the trajectory — be specific about which actions ground your verdict. Recommend abort only when continuing cannot serve the intent.";
|
|
@@ -3192,7 +3361,7 @@ function fanout(items, opts) {
|
|
|
3192
3361
|
if (res.ok) opened += 1;
|
|
3193
3362
|
else rejected.push(`${unit.opts.label}: not admitted (${res.reason})`);
|
|
3194
3363
|
}
|
|
3195
|
-
drained = opened === 0 ? emptyRound() : await drain(scope);
|
|
3364
|
+
drained = opened === 0 ? emptyRound() : await drain$1(scope);
|
|
3196
3365
|
}
|
|
3197
3366
|
if (opened === 0) return blocked(rejected.length > 0 ? rejected : ["fanout: budget admitted no item (fanout fully rejected)"]);
|
|
3198
3367
|
if (drained.done.length === 0) return blocked(orderedBlockers(drained.blockers, rejected, "fanout: every item settled without a usable result"));
|
|
@@ -3454,7 +3623,7 @@ function splitOnce(text, sep) {
|
|
|
3454
3623
|
if (at < 0) return [text, ""];
|
|
3455
3624
|
return [text.slice(0, at), text.slice(at + sep.length)];
|
|
3456
3625
|
}
|
|
3457
|
-
async function drain(scope) {
|
|
3626
|
+
async function drain$1(scope) {
|
|
3458
3627
|
const iterations = [];
|
|
3459
3628
|
const done = [];
|
|
3460
3629
|
const blockers = [];
|
|
@@ -3894,7 +4063,7 @@ async function runPersonified(options) {
|
|
|
3894
4063
|
executors,
|
|
3895
4064
|
...options.rootIdentity !== void 0 ? { rootIdentity: options.rootIdentity } : {},
|
|
3896
4065
|
...options.maxDepth !== void 0 ? { maxDepth: options.maxDepth } : {},
|
|
3897
|
-
...options.
|
|
4066
|
+
...options.workerSlots !== void 0 ? { workerSlots: options.workerSlots } : {},
|
|
3898
4067
|
...options.maxRestarts !== void 0 ? { maxRestarts: options.maxRestarts } : {},
|
|
3899
4068
|
...options.withinMs !== void 0 ? { withinMs: options.withinMs } : {},
|
|
3900
4069
|
...options.teardownConfirmMs !== void 0 ? { teardownConfirmMs: options.teardownConfirmMs } : {},
|
|
@@ -4731,7 +4900,7 @@ async function openSandboxRun(client, options, deliverable) {
|
|
|
4731
4900
|
eventTypes: eventTypeCounts(result.events),
|
|
4732
4901
|
...result.readError !== void 0 ? { readError: result.readError } : {}
|
|
4733
4902
|
} : {},
|
|
4734
|
-
...error !== void 0 ? { error: errorMessage(error) } : {}
|
|
4903
|
+
...error !== void 0 ? { error: errorMessage$1(error) } : {}
|
|
4735
4904
|
});
|
|
4736
4905
|
async function settle(box, events, turnIndex, turnKind) {
|
|
4737
4906
|
const collected = [];
|
|
@@ -4839,7 +5008,7 @@ async function openSandboxRun(client, options, deliverable) {
|
|
|
4839
5008
|
payload: {
|
|
4840
5009
|
...runPayload(),
|
|
4841
5010
|
turnCount,
|
|
4842
|
-
error: errorMessage(error)
|
|
5011
|
+
error: errorMessage$1(error)
|
|
4843
5012
|
}
|
|
4844
5013
|
});
|
|
4845
5014
|
throw error;
|
|
@@ -4883,7 +5052,7 @@ async function openSandboxRun(client, options, deliverable) {
|
|
|
4883
5052
|
payload: {
|
|
4884
5053
|
...runPayload(),
|
|
4885
5054
|
turnCount,
|
|
4886
|
-
error: errorMessage(error)
|
|
5055
|
+
error: errorMessage$1(error)
|
|
4887
5056
|
}
|
|
4888
5057
|
});
|
|
4889
5058
|
throw error;
|
|
@@ -4921,10 +5090,958 @@ function hashText(value) {
|
|
|
4921
5090
|
}
|
|
4922
5091
|
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
4923
5092
|
}
|
|
4924
|
-
function errorMessage(error) {
|
|
5093
|
+
function errorMessage$1(error) {
|
|
4925
5094
|
return error instanceof Error ? error.message : String(error);
|
|
4926
5095
|
}
|
|
4927
5096
|
//#endregion
|
|
5097
|
+
//#region src/runtime/shared-box.ts
|
|
5098
|
+
/**
|
|
5099
|
+
* Shared-box placement: many harness workers in one Sandbox box, each as its own process.
|
|
5100
|
+
*
|
|
5101
|
+
* The default provider placement gives every worker its own Sandbox box. A box costs a create
|
|
5102
|
+
* call, a sidecar, an egress proxy, a preview link and a memory reservation sized for the box,
|
|
5103
|
+
* while one opencode worker uses about half a gigabyte. This module packs workers into a small
|
|
5104
|
+
* pool of boxes instead. Each worker runs `opencode run` as a separate process with its own
|
|
5105
|
+
* working directory and its own HOME, so each worker has its own harness session, its own
|
|
5106
|
+
* materialized profile and its own transcript files.
|
|
5107
|
+
*
|
|
5108
|
+
* Why processes and not sidecar sessions: the sidecar serves every session in one box from one
|
|
5109
|
+
* workspace and writes each session's profile into the same files. Measured 2026-09-24 on
|
|
5110
|
+
* sandbox-ff52a989e7c9: eight concurrent sessions with different instructions, and seven of eight
|
|
5111
|
+
* answered with another session's instructions. A process with its own directory, its own HOME and
|
|
5112
|
+
* `OPENCODE_DISABLE_PROJECT_CONFIG` reads only its own configuration: sixteen of sixteen concurrent
|
|
5113
|
+
* workers answered with their own instructions and wrote only into their own directory.
|
|
5114
|
+
*
|
|
5115
|
+
* The boundary is cooperative, not a security boundary. Every worker runs as the same Linux user,
|
|
5116
|
+
* so a worker can read a co-tenant's files through its shell. A profile that writes a repository,
|
|
5117
|
+
* runs untrusted code, holds a credential of its own, or must stay blind to its siblings keeps a
|
|
5118
|
+
* dedicated box: {@link SharedBoxPlacement.refusal} names the profile features this placement
|
|
5119
|
+
* cannot carry, and Runtime then uses the dedicated provider.
|
|
5120
|
+
*
|
|
5121
|
+
* A worker whose model provider refuses a turn for capacity keeps its process's session and
|
|
5122
|
+
* directory, pauses by the driver's rule, and continues the same opencode session, the way a
|
|
5123
|
+
* dedicated leaf does (`ProviderExecutorOptions.unavailablePause`). Measured 2026-09-24: 15 of 23
|
|
5124
|
+
* down children of play anomaly-referee-v3d ended on `provider_quota_exhausted`, and opencode
|
|
5125
|
+
* itself gives up on a refused model after about 70 seconds of its own retries.
|
|
5126
|
+
*
|
|
5127
|
+
* The workers of one box share the box's router key. Each worker names itself to the router with
|
|
5128
|
+
* the `x-tangle-client` header, which the router stores as `clientName` on every usage row, so a
|
|
5129
|
+
* keeper can price one worker from the key's per-client rows (`tangle-admin router-spend --key
|
|
5130
|
+
* <box key>`). A request without the header stays charged to the box.
|
|
5131
|
+
*
|
|
5132
|
+
* `workersPerBox` is the one structural cap, and it protects the box. A Tangle box has a fixed
|
|
5133
|
+
* 512-task pids limit. An idle box uses about 118 tasks and one opencode worker about 34, so
|
|
5134
|
+
* twelve workers reach the limit. At that limit the sidecar's own process spawn fails with EAGAIN
|
|
5135
|
+
* and the sidecar restarts, which ends every worker in the box (measured on the same box: 28
|
|
5136
|
+
* workers crashed the sidecar twice; 16 workers crashed it once).
|
|
5137
|
+
*/
|
|
5138
|
+
/**
|
|
5139
|
+
* The most workers one default box carries at once.
|
|
5140
|
+
*
|
|
5141
|
+
* It keeps a worker count that the 512-task pids limit of a Tangle box can hold with headroom
|
|
5142
|
+
* for the sidecar's own processes and the workers' tool shells: 118 idle tasks plus 8 workers at
|
|
5143
|
+
* about 34 tasks each is 390. Memory is not the binding limit: 8 workers used about 4 GB in a
|
|
5144
|
+
* 16 GB box. Raise it only for a box whose pids limit was raised with it.
|
|
5145
|
+
*/
|
|
5146
|
+
const DEFAULT_SHARED_BOX_WORKERS = 8;
|
|
5147
|
+
/** The box shape the default placement creates: memory for 8 workers at about 0.5 GB each plus
|
|
5148
|
+
* the sidecar, and 4 cores, because the workers wait on the model most of the time. */
|
|
5149
|
+
const DEFAULT_SHARED_BOX_RESOURCES = Object.freeze({
|
|
5150
|
+
cpuCores: 4,
|
|
5151
|
+
memoryMB: 8192
|
|
5152
|
+
});
|
|
5153
|
+
const DEFAULT_WORKER_ROOT = "/home/agent/workers";
|
|
5154
|
+
const HARNESS = "opencode";
|
|
5155
|
+
const SHARED_PROVIDER_NAME = "tangle-shared-box";
|
|
5156
|
+
const DEFAULT_EXEC_TIMEOUT_MS = 12e4;
|
|
5157
|
+
/** The request header the router records as a usage row's `clientName`. */
|
|
5158
|
+
const ROUTER_CLIENT_HEADER = "x-tangle-client";
|
|
5159
|
+
/**
|
|
5160
|
+
* The router client name of the worker that runs supervised node `nodeId`.
|
|
5161
|
+
*
|
|
5162
|
+
* The node id is already in the spawn journal, so a keeper joins a router row to a node without
|
|
5163
|
+
* a new record: the row whose `clientName` is `agent-runtime-node/<nodeId>` is that node's spend.
|
|
5164
|
+
*/
|
|
5165
|
+
function sharedWorkerClientName(nodeId) {
|
|
5166
|
+
if (!/^[!-~]+$/u.test(nodeId)) throw new ValidationError("sharedWorkerClientName: a node id must be visible ASCII");
|
|
5167
|
+
return `agent-runtime-node/${nodeId}`;
|
|
5168
|
+
}
|
|
5169
|
+
/**
|
|
5170
|
+
* Attempts for one Sandbox API call that failed on the way to the box.
|
|
5171
|
+
*
|
|
5172
|
+
* Every call re-verifies the API key with the platform, and a burst of workers makes that check
|
|
5173
|
+
* time out: 8 of 64 workers failed with `502 platform_unavailable` (reason `platform_timeout`) in
|
|
5174
|
+
* one burst on 2026-09-24, and 3 more lost their transcript enumeration the same way. The check
|
|
5175
|
+
* refuses the request before it reaches the box, so repeating it is safe; five attempts over about
|
|
5176
|
+
* fifteen seconds rode out every such failure measured.
|
|
5177
|
+
*/
|
|
5178
|
+
const TRANSIENT_ATTEMPTS = 5;
|
|
5179
|
+
const TRANSIENT_BASE_DELAY_MS = 1e3;
|
|
5180
|
+
/** A failure that a repeated request can change: the platform, the gateway or the network. */
|
|
5181
|
+
function isTransientSandboxFailure(error) {
|
|
5182
|
+
if (error === null || typeof error !== "object") return false;
|
|
5183
|
+
const record = error;
|
|
5184
|
+
if (typeof record.status === "number" && [
|
|
5185
|
+
408,
|
|
5186
|
+
425,
|
|
5187
|
+
429,
|
|
5188
|
+
500,
|
|
5189
|
+
502,
|
|
5190
|
+
503,
|
|
5191
|
+
504
|
|
5192
|
+
].includes(record.status)) return true;
|
|
5193
|
+
const text = `${String(record.code ?? "")} ${String(record.name ?? "")} ${String(record.message ?? "")}`;
|
|
5194
|
+
return /platform_unavailable|platform_timeout|platform_unreachable|fetch failed|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|UND_ERR|bad gateway|gateway timeout/iu.test(text);
|
|
5195
|
+
}
|
|
5196
|
+
async function transientRetry(operation, options = {}) {
|
|
5197
|
+
const delayMs = options.delayMs ?? TRANSIENT_BASE_DELAY_MS;
|
|
5198
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
5199
|
+
return await operation(attempt);
|
|
5200
|
+
} catch (error) {
|
|
5201
|
+
if (attempt >= TRANSIENT_ATTEMPTS || !isTransientSandboxFailure(error)) throw error;
|
|
5202
|
+
options.signal?.throwIfAborted();
|
|
5203
|
+
await sleep(delayMs * 2 ** (attempt - 1), options.signal);
|
|
5204
|
+
}
|
|
5205
|
+
}
|
|
5206
|
+
/**
|
|
5207
|
+
* Why a shared box cannot carry `profile`, or `undefined` when it can.
|
|
5208
|
+
*
|
|
5209
|
+
* A shared box carries a profile whose whole behavior reaches an opencode process through its own
|
|
5210
|
+
* working directory, its own configuration and the box's own model credential. Everything else
|
|
5211
|
+
* keeps a dedicated box: another harness, a model the box credential cannot reach, a replaced
|
|
5212
|
+
* system prompt, MCP servers, connections, hooks, subagents, extensions, tool grants, and any
|
|
5213
|
+
* resource the materializer does not lower into the worker's directory.
|
|
5214
|
+
*/
|
|
5215
|
+
function sharedBoxRefusal(profile) {
|
|
5216
|
+
if (profile.harness !== HARNESS) return `harness ${String(profile.harness)} is not ${HARNESS}`;
|
|
5217
|
+
if (concreteProfileModel(profile) === void 0) return "profile names no concrete model";
|
|
5218
|
+
if (profile.model?.provider === void 0) return "profile names no model provider";
|
|
5219
|
+
if (profile.model?.reasoningEffort !== void 0) {
|
|
5220
|
+
if (tryInvocation(profile) === void 0) return "model.reasoningEffort has no opencode variant";
|
|
5221
|
+
}
|
|
5222
|
+
if (profile.prompt?.systemPrompt !== void 0) return "prompt.systemPrompt replaces a system prompt";
|
|
5223
|
+
for (const field of [
|
|
5224
|
+
"mcp",
|
|
5225
|
+
"connections",
|
|
5226
|
+
"hooks",
|
|
5227
|
+
"subagents",
|
|
5228
|
+
"extensions",
|
|
5229
|
+
"confidential",
|
|
5230
|
+
"modes"
|
|
5231
|
+
]) if (profile[field] !== void 0) return `profile declares ${field}`;
|
|
5232
|
+
if (profile.tools !== void 0 && Object.keys(profile.tools).length > 0) return "profile grants tools";
|
|
5233
|
+
const resources = profile.resources;
|
|
5234
|
+
if (resources !== void 0) {
|
|
5235
|
+
for (const field of [
|
|
5236
|
+
"skills",
|
|
5237
|
+
"agents",
|
|
5238
|
+
"commands",
|
|
5239
|
+
"tools"
|
|
5240
|
+
]) if (resources[field] !== void 0) return `profile declares resources.${field}`;
|
|
5241
|
+
for (const file of resources.files ?? []) if (file.resource.kind !== "inline") return `resource file ${file.path} is not inline`;
|
|
5242
|
+
if (resources.instructions !== void 0 && typeof resources.instructions !== "string" && resources.instructions.kind !== "inline") return "resources.instructions is not inline";
|
|
5243
|
+
}
|
|
5244
|
+
let plan;
|
|
5245
|
+
try {
|
|
5246
|
+
plan = materializeProfile(profile, HARNESS);
|
|
5247
|
+
} catch (error) {
|
|
5248
|
+
return `opencode materialization failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
5249
|
+
}
|
|
5250
|
+
if (plan.unsupported.length > 0) return `opencode cannot carry ${plan.unsupported.map((row) => row.dimension).join(", ")}`;
|
|
5251
|
+
if (Object.keys(plan.env).length > 0 || plan.flags.length > 0) return "profile needs launch environment or flags";
|
|
5252
|
+
for (const file of plan.files) {
|
|
5253
|
+
if (file.root === "agent") return `profile writes ${file.relPath} into the harness home`;
|
|
5254
|
+
if ((file.secretSlots?.length ?? 0) > 0) return `profile file ${file.relPath} carries a secret`;
|
|
5255
|
+
if (isUnsafeRelativePath(file.relPath)) return `profile file ${file.relPath} leaves its directory`;
|
|
5256
|
+
}
|
|
5257
|
+
}
|
|
5258
|
+
function tryInvocation(profile) {
|
|
5259
|
+
try {
|
|
5260
|
+
return harnessInvocation(HARNESS, invocationProfile(profile), "probe").args;
|
|
5261
|
+
} catch {
|
|
5262
|
+
return;
|
|
5263
|
+
}
|
|
5264
|
+
}
|
|
5265
|
+
/**
|
|
5266
|
+
* The profile the invocation table reads. The prompt reaches opencode through its configuration
|
|
5267
|
+
* and the model through the provider this placement declares, so only the reasoning effort is
|
|
5268
|
+
* left for the table to lower into `--variant`.
|
|
5269
|
+
*/
|
|
5270
|
+
function invocationProfile(profile) {
|
|
5271
|
+
const { prompt: _prompt, model, ...rest } = profile;
|
|
5272
|
+
return {
|
|
5273
|
+
...rest,
|
|
5274
|
+
...model?.reasoningEffort === void 0 ? {} : { model: { reasoningEffort: model.reasoningEffort } }
|
|
5275
|
+
};
|
|
5276
|
+
}
|
|
5277
|
+
function isUnsafeRelativePath(path) {
|
|
5278
|
+
return path.length === 0 || path.startsWith("/") || path.split("/").some((segment) => segment === ".." || segment === "");
|
|
5279
|
+
}
|
|
5280
|
+
/**
|
|
5281
|
+
* Place accepted workers as processes in a pool of shared Sandbox boxes.
|
|
5282
|
+
*
|
|
5283
|
+
* The pool fills a box before it creates the next one and deletes a box when its last worker
|
|
5284
|
+
* releases it. Runtime reaches this placement through `createExecutor({ backend: 'provider',
|
|
5285
|
+
* shared })`: a profile that {@link SharedBoxPlacement.refusal} accepts runs here, and every other
|
|
5286
|
+
* profile keeps the dedicated provider.
|
|
5287
|
+
*/
|
|
5288
|
+
function sharedBoxPlacement(options) {
|
|
5289
|
+
const workersPerBox = options.workersPerBox ?? 8;
|
|
5290
|
+
if (!Number.isSafeInteger(workersPerBox) || workersPerBox < 1) throw new ValidationError("sharedBoxPlacement: workersPerBox must be a positive integer");
|
|
5291
|
+
const workerRoot = options.workerRoot ?? DEFAULT_WORKER_ROOT;
|
|
5292
|
+
if (!workerRoot.startsWith("/") || isUnsafeRelativePath(workerRoot.slice(1))) throw new ValidationError("sharedBoxPlacement: workerRoot must be an absolute, normalized path");
|
|
5293
|
+
const boxOptions = {
|
|
5294
|
+
resources: { ...DEFAULT_SHARED_BOX_RESOURCES },
|
|
5295
|
+
...options.box ?? {}
|
|
5296
|
+
};
|
|
5297
|
+
if (boxOptions.backend !== void 0) throw new ValidationError("sharedBoxPlacement: box.backend is owned by Runtime");
|
|
5298
|
+
const identity = {
|
|
5299
|
+
id: "shared-box",
|
|
5300
|
+
digest: canonicalCandidateDigest({
|
|
5301
|
+
kind: "shared-box-placement.v1",
|
|
5302
|
+
harness: HARNESS,
|
|
5303
|
+
workersPerBox,
|
|
5304
|
+
workerRoot,
|
|
5305
|
+
box: publicBoxOptions(boxOptions)
|
|
5306
|
+
})
|
|
5307
|
+
};
|
|
5308
|
+
const retryDelayMs = options.retryDelayMs ?? TRANSIENT_BASE_DELAY_MS;
|
|
5309
|
+
const pool = createBoxPool(options.client, boxOptions, workersPerBox, retryDelayMs);
|
|
5310
|
+
const providerFor = (worker = {}) => {
|
|
5311
|
+
const clientName = worker.nodeId === void 0 ? void 0 : sharedWorkerClientName(worker.nodeId);
|
|
5312
|
+
return sandboxClientAsProvider({ async create(createOptions) {
|
|
5313
|
+
const profile = workerProfile(createOptions);
|
|
5314
|
+
const refusal = sharedBoxRefusal(profile);
|
|
5315
|
+
if (refusal !== void 0) throw new ValidationError(`sharedBoxPlacement: ${refusal}`);
|
|
5316
|
+
assertWorkerCreateOptions(createOptions);
|
|
5317
|
+
const lease = await pool.acquire();
|
|
5318
|
+
try {
|
|
5319
|
+
return await createWorker(lease, workerRoot, profile, {
|
|
5320
|
+
retryDelayMs,
|
|
5321
|
+
clientName,
|
|
5322
|
+
unavailablePause: options.unavailablePause ?? {}
|
|
5323
|
+
});
|
|
5324
|
+
} catch (error) {
|
|
5325
|
+
await lease.release();
|
|
5326
|
+
throw error;
|
|
5327
|
+
}
|
|
5328
|
+
} }, {
|
|
5329
|
+
name: SHARED_PROVIDER_NAME,
|
|
5330
|
+
capabilities: sharedBoxCapabilities()
|
|
5331
|
+
});
|
|
5332
|
+
};
|
|
5333
|
+
return {
|
|
5334
|
+
providerFor,
|
|
5335
|
+
identity,
|
|
5336
|
+
refusal: sharedBoxRefusal,
|
|
5337
|
+
stats: () => pool.stats(),
|
|
5338
|
+
close: () => pool.close()
|
|
5339
|
+
};
|
|
5340
|
+
}
|
|
5341
|
+
function publicBoxOptions(box) {
|
|
5342
|
+
const { env, secrets, ...rest } = box;
|
|
5343
|
+
return {
|
|
5344
|
+
...rest,
|
|
5345
|
+
...env === void 0 ? {} : { environmentVariableNames: Object.keys(env).sort() },
|
|
5346
|
+
...secrets === void 0 ? {} : { secrets }
|
|
5347
|
+
};
|
|
5348
|
+
}
|
|
5349
|
+
function sharedBoxCapabilities() {
|
|
5350
|
+
return {
|
|
5351
|
+
profile: {
|
|
5352
|
+
namedProfiles: false,
|
|
5353
|
+
systemPrompt: {
|
|
5354
|
+
...harnessSystemPromptIntents$1(HARNESS),
|
|
5355
|
+
replace: false
|
|
5356
|
+
},
|
|
5357
|
+
instructions: true,
|
|
5358
|
+
tools: false,
|
|
5359
|
+
permissions: true,
|
|
5360
|
+
mcp: false,
|
|
5361
|
+
subagents: false,
|
|
5362
|
+
resources: {
|
|
5363
|
+
files: true,
|
|
5364
|
+
instructions: true
|
|
5365
|
+
},
|
|
5366
|
+
runtimeUpdate: false,
|
|
5367
|
+
validation: false
|
|
5368
|
+
},
|
|
5369
|
+
streaming: {
|
|
5370
|
+
live: true,
|
|
5371
|
+
replay: false,
|
|
5372
|
+
detach: false,
|
|
5373
|
+
turnIdempotency: false
|
|
5374
|
+
},
|
|
5375
|
+
sessions: {
|
|
5376
|
+
continue: false,
|
|
5377
|
+
list: false,
|
|
5378
|
+
messages: false
|
|
5379
|
+
},
|
|
5380
|
+
workspace: {
|
|
5381
|
+
read: true,
|
|
5382
|
+
write: true,
|
|
5383
|
+
exec: true,
|
|
5384
|
+
git: false,
|
|
5385
|
+
upload: false,
|
|
5386
|
+
download: false
|
|
5387
|
+
},
|
|
5388
|
+
branching: {
|
|
5389
|
+
checkpoint: false,
|
|
5390
|
+
fork: false
|
|
5391
|
+
},
|
|
5392
|
+
placement: true,
|
|
5393
|
+
usage: true,
|
|
5394
|
+
confidential: false
|
|
5395
|
+
};
|
|
5396
|
+
}
|
|
5397
|
+
function workerProfile(createOptions) {
|
|
5398
|
+
const raw = (createOptions?.backend)?.profile;
|
|
5399
|
+
const parsed = agentProfileSchema.safeParse(raw);
|
|
5400
|
+
if (!parsed.success) throw new ValidationError("sharedBoxPlacement: an exact AgentProfile is required at create");
|
|
5401
|
+
return parsed.data;
|
|
5402
|
+
}
|
|
5403
|
+
/**
|
|
5404
|
+
* A worker create carries only what a slot in a shared box can honor. Box-level settings belong
|
|
5405
|
+
* to the placement's own box options, and a per-worker request for them is refused rather than
|
|
5406
|
+
* dropped: a worker that asked for an environment variable, a repository or its own resources
|
|
5407
|
+
* would otherwise run without them and report nothing.
|
|
5408
|
+
*/
|
|
5409
|
+
function assertWorkerCreateOptions(createOptions) {
|
|
5410
|
+
const options = createOptions ?? {};
|
|
5411
|
+
for (const key of [
|
|
5412
|
+
"git",
|
|
5413
|
+
"fromSnapshot",
|
|
5414
|
+
"fromSandboxId",
|
|
5415
|
+
"environment",
|
|
5416
|
+
"cwd",
|
|
5417
|
+
"resources"
|
|
5418
|
+
]) if (options[key] !== void 0) throw new ValidationError(`sharedBoxPlacement: a shared worker cannot set ${key}`);
|
|
5419
|
+
const env = options.env;
|
|
5420
|
+
if (env !== void 0 && Object.keys(env).length > 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot set env");
|
|
5421
|
+
const secrets = options.secrets;
|
|
5422
|
+
if (Array.isArray(secrets) && secrets.length > 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot request secrets");
|
|
5423
|
+
const backend = options.backend;
|
|
5424
|
+
if (backend?.runtimeAttachments !== void 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot carry runtime attachments");
|
|
5425
|
+
if (backend?.type !== void 0 && backend.type !== HARNESS) throw new ValidationError(`sharedBoxPlacement: backend ${String(backend.type)} is not ${HARNESS}`);
|
|
5426
|
+
}
|
|
5427
|
+
function createBoxPool(client, boxOptions, workersPerBox, retryDelayMs) {
|
|
5428
|
+
const poolId = randomUUID();
|
|
5429
|
+
const boxes = [];
|
|
5430
|
+
const history = [];
|
|
5431
|
+
let seq = 0;
|
|
5432
|
+
let placed = 0;
|
|
5433
|
+
let peak = 0;
|
|
5434
|
+
let closing = false;
|
|
5435
|
+
const retire = async (entry) => {
|
|
5436
|
+
if (entry.retired) return void 0;
|
|
5437
|
+
entry.retired = true;
|
|
5438
|
+
const index = boxes.indexOf(entry);
|
|
5439
|
+
if (index >= 0) boxes.splice(index, 1);
|
|
5440
|
+
let handle;
|
|
5441
|
+
try {
|
|
5442
|
+
handle = await entry.ready;
|
|
5443
|
+
} catch {
|
|
5444
|
+
return;
|
|
5445
|
+
}
|
|
5446
|
+
try {
|
|
5447
|
+
await transientRetry(() => handle.delete(), { delayMs: retryDelayMs });
|
|
5448
|
+
entry.deleted = true;
|
|
5449
|
+
return {
|
|
5450
|
+
boxId: handle.id,
|
|
5451
|
+
deleted: true
|
|
5452
|
+
};
|
|
5453
|
+
} catch (error) {
|
|
5454
|
+
return {
|
|
5455
|
+
boxId: handle.id,
|
|
5456
|
+
deleted: false,
|
|
5457
|
+
error: error instanceof Error ? error.message : String(error)
|
|
5458
|
+
};
|
|
5459
|
+
}
|
|
5460
|
+
};
|
|
5461
|
+
return {
|
|
5462
|
+
async acquire() {
|
|
5463
|
+
if (closing) throw new ValidationError("sharedBoxPlacement: the placement is closed");
|
|
5464
|
+
let entry = boxes.find((candidate) => !candidate.retired && candidate.workers < workersPerBox);
|
|
5465
|
+
if (entry === void 0) {
|
|
5466
|
+
const boxSeq = seq++;
|
|
5467
|
+
const request = {
|
|
5468
|
+
...boxOptions,
|
|
5469
|
+
name: boxOptions.name ?? `shared-box-${poolId.slice(0, 8)}-${boxSeq}`,
|
|
5470
|
+
idempotencyKey: `shared-box-${poolId}-${boxSeq}`,
|
|
5471
|
+
backend: {
|
|
5472
|
+
type: HARNESS,
|
|
5473
|
+
profile: {
|
|
5474
|
+
name: "shared-box",
|
|
5475
|
+
harness: HARNESS
|
|
5476
|
+
}
|
|
5477
|
+
}
|
|
5478
|
+
};
|
|
5479
|
+
const requestedAt = Date.now();
|
|
5480
|
+
const created = {
|
|
5481
|
+
seq: boxSeq,
|
|
5482
|
+
ready: transientRetry(() => client.create(request), { delayMs: retryDelayMs }).then((box) => box),
|
|
5483
|
+
workers: 0,
|
|
5484
|
+
served: 0,
|
|
5485
|
+
retired: false,
|
|
5486
|
+
deleted: false
|
|
5487
|
+
};
|
|
5488
|
+
created.ready.then((box) => {
|
|
5489
|
+
created.id = box.id;
|
|
5490
|
+
created.createMs = Date.now() - requestedAt;
|
|
5491
|
+
}, () => {
|
|
5492
|
+
const index = boxes.indexOf(created);
|
|
5493
|
+
if (index >= 0) boxes.splice(index, 1);
|
|
5494
|
+
created.retired = true;
|
|
5495
|
+
});
|
|
5496
|
+
boxes.push(created);
|
|
5497
|
+
history.push(created);
|
|
5498
|
+
entry = created;
|
|
5499
|
+
}
|
|
5500
|
+
const leased = entry;
|
|
5501
|
+
leased.workers += 1;
|
|
5502
|
+
leased.served += 1;
|
|
5503
|
+
placed += 1;
|
|
5504
|
+
peak = Math.max(peak, leased.workers);
|
|
5505
|
+
let box;
|
|
5506
|
+
try {
|
|
5507
|
+
box = await leased.ready;
|
|
5508
|
+
} catch (error) {
|
|
5509
|
+
leased.workers -= 1;
|
|
5510
|
+
throw error;
|
|
5511
|
+
}
|
|
5512
|
+
let released = false;
|
|
5513
|
+
return {
|
|
5514
|
+
box,
|
|
5515
|
+
async release() {
|
|
5516
|
+
if (released) return;
|
|
5517
|
+
released = true;
|
|
5518
|
+
leased.workers -= 1;
|
|
5519
|
+
if (leased.workers === 0 && !closing) await retire(leased);
|
|
5520
|
+
}
|
|
5521
|
+
};
|
|
5522
|
+
},
|
|
5523
|
+
stats() {
|
|
5524
|
+
return {
|
|
5525
|
+
boxesCreated: history.length,
|
|
5526
|
+
boxesLive: history.filter((entry) => !entry.retired).length,
|
|
5527
|
+
workersPlaced: placed,
|
|
5528
|
+
workersLive: history.reduce((sum, entry) => sum + entry.workers, 0),
|
|
5529
|
+
peakWorkersPerBox: peak,
|
|
5530
|
+
boxes: history.filter((entry) => entry.id !== void 0).map((entry) => ({
|
|
5531
|
+
id: entry.id,
|
|
5532
|
+
workersServed: entry.served,
|
|
5533
|
+
deleted: entry.deleted,
|
|
5534
|
+
createMs: entry.createMs ?? 0
|
|
5535
|
+
}))
|
|
5536
|
+
};
|
|
5537
|
+
},
|
|
5538
|
+
async close() {
|
|
5539
|
+
closing = true;
|
|
5540
|
+
return (await Promise.all(history.map((entry) => retire(entry)))).filter((receipt) => receipt !== void 0);
|
|
5541
|
+
}
|
|
5542
|
+
};
|
|
5543
|
+
}
|
|
5544
|
+
/** The environment one worker's processes see: its own directory, HOME and XDG roots. */
|
|
5545
|
+
function workerEnv(paths) {
|
|
5546
|
+
return [
|
|
5547
|
+
"OPENCODE_DISABLE_PROJECT_CONFIG=1",
|
|
5548
|
+
`OPENCODE_CONFIG_DIR=${paths.dir}/.opencode`,
|
|
5549
|
+
`PWD=${paths.dir}`,
|
|
5550
|
+
`HOME=${paths.home}`,
|
|
5551
|
+
`XDG_DATA_HOME=${paths.home}/.local/share`,
|
|
5552
|
+
`XDG_CONFIG_HOME=${paths.home}/.config`,
|
|
5553
|
+
`XDG_STATE_HOME=${paths.home}/.local/state`,
|
|
5554
|
+
`XDG_CACHE_HOME=${paths.cache}`
|
|
5555
|
+
];
|
|
5556
|
+
}
|
|
5557
|
+
async function createWorker(lease, root, createProfile, placement) {
|
|
5558
|
+
const { clientName, unavailablePause } = placement;
|
|
5559
|
+
const box = resilientBox(lease.box, placement.retryDelayMs);
|
|
5560
|
+
const workerId = `w-${randomUUID()}`;
|
|
5561
|
+
const paths = {
|
|
5562
|
+
dir: `${root}/${workerId}`,
|
|
5563
|
+
home: `${root}/${workerId}/.home`,
|
|
5564
|
+
cache: `${root}/.cache`
|
|
5565
|
+
};
|
|
5566
|
+
const made = await box.exec(`mkdir -p '${paths.home}' '${paths.cache}'`, { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS });
|
|
5567
|
+
if ((made.exitCode ?? 1) !== 0) throw new Error(`sharedBoxPlacement: could not create ${paths.dir}: ${made.stderr ?? ""}`);
|
|
5568
|
+
const env = workerEnv(paths);
|
|
5569
|
+
let running;
|
|
5570
|
+
let turnActive = false;
|
|
5571
|
+
let released = false;
|
|
5572
|
+
const started = /* @__PURE__ */ new Set();
|
|
5573
|
+
const run = async (args, timeoutMs, extraEnv) => {
|
|
5574
|
+
const process = await box.spawnInDirectory("/usr/bin/env", [...env, ...args], {
|
|
5575
|
+
cwd: paths.dir,
|
|
5576
|
+
...extraEnv === void 0 ? {} : { env: extraEnv },
|
|
5577
|
+
timeoutMs
|
|
5578
|
+
}, started);
|
|
5579
|
+
started.add(process.pid);
|
|
5580
|
+
return process;
|
|
5581
|
+
};
|
|
5582
|
+
const collect = async (process) => {
|
|
5583
|
+
const [stdout, stderr, exitCode] = await Promise.all([
|
|
5584
|
+
drain(box.output(process, "stdout")),
|
|
5585
|
+
drain(box.output(process, "stderr")),
|
|
5586
|
+
box.wait(process)
|
|
5587
|
+
]);
|
|
5588
|
+
return {
|
|
5589
|
+
exitCode,
|
|
5590
|
+
stdout,
|
|
5591
|
+
stderr
|
|
5592
|
+
};
|
|
5593
|
+
};
|
|
5594
|
+
const resolvePath = (path) => {
|
|
5595
|
+
if (path.startsWith("/")) return path;
|
|
5596
|
+
if (isUnsafeRelativePath(path)) throw new ValidationError(`sharedBoxPlacement: path ${path} leaves the worker directory`);
|
|
5597
|
+
return `${paths.dir}/${path}`;
|
|
5598
|
+
};
|
|
5599
|
+
/**
|
|
5600
|
+
* One turn: one or more opencode runs of the same session. The first runs `message`; a later run
|
|
5601
|
+
* continues the session after the model provider refused a run for capacity.
|
|
5602
|
+
*/
|
|
5603
|
+
async function* turn(message, turnProfile, options) {
|
|
5604
|
+
const signal = options?.signal;
|
|
5605
|
+
const timeoutMs = options?.timeoutMs ?? 0;
|
|
5606
|
+
const turnDeadline = timeoutMs > 0 ? Date.now() + timeoutMs : void 0;
|
|
5607
|
+
let sessionId;
|
|
5608
|
+
const subagents = /* @__PURE__ */ new Set();
|
|
5609
|
+
let refusalsInARow = 0;
|
|
5610
|
+
let prompt = message;
|
|
5611
|
+
for (let invocation = 1;; invocation += 1) {
|
|
5612
|
+
const launch = await materializeWorker(box, paths, turnProfile, prompt, options?.backend?.model, clientName, sessionId);
|
|
5613
|
+
signal?.throwIfAborted();
|
|
5614
|
+
const remainingMs = turnDeadline === void 0 ? 0 : Math.max(1, turnDeadline - Date.now());
|
|
5615
|
+
const process = await run(launch.args, remainingMs, { OPENCODE_CONFIG_CONTENT: launch.config });
|
|
5616
|
+
running = process;
|
|
5617
|
+
const onAbort = () => {
|
|
5618
|
+
process.kill("SIGKILL", { tree: true }).catch(() => void 0);
|
|
5619
|
+
};
|
|
5620
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
5621
|
+
const stderr = drain(box.output(process, "stderr"));
|
|
5622
|
+
const lines = lineReader();
|
|
5623
|
+
const parsed = createOpencodeEventParser(launch.model);
|
|
5624
|
+
let exitCode;
|
|
5625
|
+
let errorText;
|
|
5626
|
+
try {
|
|
5627
|
+
for await (const chunk of box.output(process, "stdout")) for (const line of lines.push(chunk)) yield* parsed.line(line);
|
|
5628
|
+
for (const line of lines.end()) yield* parsed.line(line);
|
|
5629
|
+
exitCode = await box.wait(process);
|
|
5630
|
+
errorText = (await stderr).slice(-4e3);
|
|
5631
|
+
} finally {
|
|
5632
|
+
signal?.removeEventListener("abort", onAbort);
|
|
5633
|
+
running = void 0;
|
|
5634
|
+
}
|
|
5635
|
+
sessionId = parsed.sessionId() ?? sessionId;
|
|
5636
|
+
for (const child of parsed.subagentSessionIds()) subagents.add(child);
|
|
5637
|
+
const failure = parsed.failure(exitCode, errorText);
|
|
5638
|
+
const refusal = failure === void 0 || unavailablePause === false || signal?.aborted ? void 0 : unavailableSignalOfFailure({ error: failure });
|
|
5639
|
+
refusalsInARow = parsed.madeProgress() ? 1 : refusalsInARow + 1;
|
|
5640
|
+
const pauseMs = refusal === void 0 || unavailablePause === false ? 0 : unavailablePauseMs(refusalsInARow, unavailablePause);
|
|
5641
|
+
if (refusal === void 0 || turnDeadline !== void 0 && Date.now() + pauseMs >= turnDeadline) {
|
|
5642
|
+
if (sessionId !== void 0) await exportSession(run, collect, paths, sessionId);
|
|
5643
|
+
for (const child of subagents) if (child !== sessionId) await exportSession(run, collect, paths, child);
|
|
5644
|
+
signal?.throwIfAborted();
|
|
5645
|
+
yield* parsed.finish(exitCode, errorText, invocation);
|
|
5646
|
+
return;
|
|
5647
|
+
}
|
|
5648
|
+
await sleep(pauseMs, signal);
|
|
5649
|
+
signal?.throwIfAborted();
|
|
5650
|
+
if (released) throw new ValidationError("sharedBoxPlacement: this worker was released");
|
|
5651
|
+
prompt = sessionId === void 0 ? message : LEAF_CONTINUATION_TASK;
|
|
5652
|
+
}
|
|
5653
|
+
}
|
|
5654
|
+
return {
|
|
5655
|
+
id: `${box.id}/${workerId}`,
|
|
5656
|
+
name: workerId,
|
|
5657
|
+
status: "running",
|
|
5658
|
+
metadata: {
|
|
5659
|
+
sharedBoxId: box.id,
|
|
5660
|
+
workerId,
|
|
5661
|
+
workerDir: paths.dir
|
|
5662
|
+
},
|
|
5663
|
+
async *streamPrompt(message, options) {
|
|
5664
|
+
if (released) throw new ValidationError("sharedBoxPlacement: this worker was released");
|
|
5665
|
+
if (turnActive) throw new ValidationError("sharedBoxPlacement: a worker runs one turn at a time");
|
|
5666
|
+
const turnProfile = options?.backend?.profile === void 0 ? createProfile : agentProfileSchema.parse(options.backend.profile);
|
|
5667
|
+
if (canonicalAgentProfileDigest(turnProfile) !== canonicalAgentProfileDigest(createProfile) && sharedBoxRefusal(turnProfile) !== void 0) throw new ValidationError(`sharedBoxPlacement: ${sharedBoxRefusal(turnProfile)}`);
|
|
5668
|
+
if (options?.backend?.type !== void 0 && options.backend.type !== HARNESS) throw new ValidationError(`sharedBoxPlacement: backend ${options.backend.type} is not ${HARNESS}`);
|
|
5669
|
+
turnActive = true;
|
|
5670
|
+
try {
|
|
5671
|
+
yield* turn(message, turnProfile, options);
|
|
5672
|
+
} finally {
|
|
5673
|
+
turnActive = false;
|
|
5674
|
+
}
|
|
5675
|
+
},
|
|
5676
|
+
async exec(command, options) {
|
|
5677
|
+
const process = await run([
|
|
5678
|
+
"/bin/sh",
|
|
5679
|
+
"-c",
|
|
5680
|
+
command
|
|
5681
|
+
], options?.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS);
|
|
5682
|
+
return await collect(process);
|
|
5683
|
+
},
|
|
5684
|
+
async read(path) {
|
|
5685
|
+
return await box.fs.read(resolvePath(path));
|
|
5686
|
+
},
|
|
5687
|
+
async write(path, content) {
|
|
5688
|
+
await box.fs.write(resolvePath(path), content);
|
|
5689
|
+
},
|
|
5690
|
+
async refresh() {},
|
|
5691
|
+
async delete() {
|
|
5692
|
+
if (released) return;
|
|
5693
|
+
released = true;
|
|
5694
|
+
try {
|
|
5695
|
+
await running?.kill("SIGKILL", { tree: true });
|
|
5696
|
+
await box.exec(`rm -rf '${paths.dir}'`, { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS });
|
|
5697
|
+
} finally {
|
|
5698
|
+
await lease.release();
|
|
5699
|
+
}
|
|
5700
|
+
}
|
|
5701
|
+
};
|
|
5702
|
+
}
|
|
5703
|
+
/**
|
|
5704
|
+
* The Sandbox calls one worker makes, each repeated on a transient failure.
|
|
5705
|
+
*
|
|
5706
|
+
* A launch is repeated only after the pool confirms the box did not start it: a failed request
|
|
5707
|
+
* may have reached the box before its answer was lost, so the repeat first looks for a process
|
|
5708
|
+
* in the worker's own directory that this worker did not start yet, and adopts it. A process log
|
|
5709
|
+
* that breaks mid-stream is read again from the start, because the box replays a process's
|
|
5710
|
+
* buffered output, and the part already delivered is skipped.
|
|
5711
|
+
*/
|
|
5712
|
+
function resilientBox(box, delayMs) {
|
|
5713
|
+
const retry = (operation) => transientRetry(operation, { delayMs });
|
|
5714
|
+
return {
|
|
5715
|
+
id: box.id,
|
|
5716
|
+
exec: (command, options) => retry(() => box.exec(command, options)),
|
|
5717
|
+
fs: {
|
|
5718
|
+
read: (path) => retry(() => box.fs.read(path)),
|
|
5719
|
+
write: (path, content) => retry(() => box.fs.write(path, content))
|
|
5720
|
+
},
|
|
5721
|
+
async spawnInDirectory(executable, args, options, known) {
|
|
5722
|
+
return await transientRetry(async (attempt) => {
|
|
5723
|
+
if (attempt > 1) {
|
|
5724
|
+
const launched = (await box.process.list()).find((entry) => entry.cwd === options.cwd && entry.command === executable && !known.has(entry.pid));
|
|
5725
|
+
const adopted = launched === void 0 ? null : await box.process.get(launched.pid);
|
|
5726
|
+
if (adopted !== null) return adopted;
|
|
5727
|
+
}
|
|
5728
|
+
return await box.process.spawnExact(executable, args, options);
|
|
5729
|
+
}, { delayMs });
|
|
5730
|
+
},
|
|
5731
|
+
async wait(process) {
|
|
5732
|
+
return await retry(async () => {
|
|
5733
|
+
try {
|
|
5734
|
+
return await process.wait();
|
|
5735
|
+
} catch (error) {
|
|
5736
|
+
if (!isTransientSandboxFailure(error)) throw error;
|
|
5737
|
+
const again = await box.process.get(process.pid);
|
|
5738
|
+
if (again === null) throw error;
|
|
5739
|
+
return await again.wait();
|
|
5740
|
+
}
|
|
5741
|
+
});
|
|
5742
|
+
},
|
|
5743
|
+
async *output(process, stream) {
|
|
5744
|
+
let delivered = 0;
|
|
5745
|
+
let source = process;
|
|
5746
|
+
for (let attempt = 1;; attempt += 1) {
|
|
5747
|
+
let seen = 0;
|
|
5748
|
+
try {
|
|
5749
|
+
for await (const chunk of source[stream]()) {
|
|
5750
|
+
const fresh = seen + chunk.length <= delivered ? "" : chunk.slice(Math.max(0, delivered - seen));
|
|
5751
|
+
seen += chunk.length;
|
|
5752
|
+
if (fresh.length > 0) {
|
|
5753
|
+
delivered += fresh.length;
|
|
5754
|
+
yield fresh;
|
|
5755
|
+
}
|
|
5756
|
+
}
|
|
5757
|
+
return;
|
|
5758
|
+
} catch (error) {
|
|
5759
|
+
if (attempt >= TRANSIENT_ATTEMPTS || !isTransientSandboxFailure(error)) throw error;
|
|
5760
|
+
await sleep(delayMs * 2 ** (attempt - 1));
|
|
5761
|
+
source = await retry(() => box.process.get(process.pid)) ?? source;
|
|
5762
|
+
}
|
|
5763
|
+
}
|
|
5764
|
+
},
|
|
5765
|
+
delete: () => retry(() => box.delete())
|
|
5766
|
+
};
|
|
5767
|
+
}
|
|
5768
|
+
async function drain(stream) {
|
|
5769
|
+
let text = "";
|
|
5770
|
+
for await (const chunk of stream) text += chunk;
|
|
5771
|
+
return text;
|
|
5772
|
+
}
|
|
5773
|
+
function lineReader() {
|
|
5774
|
+
let pending = "";
|
|
5775
|
+
return {
|
|
5776
|
+
push(chunk) {
|
|
5777
|
+
pending += chunk;
|
|
5778
|
+
const lines = pending.split("\n");
|
|
5779
|
+
pending = lines.pop() ?? "";
|
|
5780
|
+
return lines.filter((line) => line.trim().length > 0);
|
|
5781
|
+
},
|
|
5782
|
+
end() {
|
|
5783
|
+
const rest = pending.trim();
|
|
5784
|
+
pending = "";
|
|
5785
|
+
return rest.length > 0 ? [rest] : [];
|
|
5786
|
+
}
|
|
5787
|
+
};
|
|
5788
|
+
}
|
|
5789
|
+
/**
|
|
5790
|
+
* Write the worker's materialized profile into its directory and build its launch.
|
|
5791
|
+
*
|
|
5792
|
+
* The files come from the same materializer the Sandbox sidecar uses, so a shared worker gets the
|
|
5793
|
+
* same instruction file, permissions and resource files a dedicated box would. The generated
|
|
5794
|
+
* `opencode.json` is passed as `OPENCODE_CONFIG_CONTENT` with its instruction paths made absolute,
|
|
5795
|
+
* because opencode resolves an instruction path in that variable against nothing.
|
|
5796
|
+
*/
|
|
5797
|
+
async function materializeWorker(box, paths, profile, task, turnModel, clientName, continueSession) {
|
|
5798
|
+
const refusal = sharedBoxRefusal(profile);
|
|
5799
|
+
if (refusal !== void 0) throw new ValidationError(`sharedBoxPlacement: ${refusal}`);
|
|
5800
|
+
if (turnModel?.authFiles !== void 0 || turnModel?.authMode === "oauth") throw new ValidationError("sharedBoxPlacement: a shared worker cannot carry auth files");
|
|
5801
|
+
const plan = materializeProfile(profile, HARNESS);
|
|
5802
|
+
let generated = {};
|
|
5803
|
+
for (const file of plan.files) {
|
|
5804
|
+
if (file.relPath === "opencode.json" && file.source === "generated") {
|
|
5805
|
+
generated = JSON.parse(file.content);
|
|
5806
|
+
continue;
|
|
5807
|
+
}
|
|
5808
|
+
if (continueSession === void 0) await box.fs.write(`${paths.dir}/${file.relPath}`, file.content);
|
|
5809
|
+
}
|
|
5810
|
+
const instructions = Array.isArray(generated.instructions) ? generated.instructions.map((entry) => typeof entry === "string" && !entry.startsWith("/") ? `${paths.dir}/${entry}` : entry) : void 0;
|
|
5811
|
+
const providerId = profile.model.provider;
|
|
5812
|
+
const modelId = profileProviderModel(profile);
|
|
5813
|
+
const apiKeyEnv = typeof turnModel?.apiKeyEnv === "string" ? turnModel.apiKeyEnv : "OPENCODE_MODEL_API_KEY";
|
|
5814
|
+
const baseURL = typeof turnModel?.baseUrl === "string" ? turnModel.baseUrl : "{env:OPENCODE_MODEL_BASE_URL}";
|
|
5815
|
+
const config = {
|
|
5816
|
+
$schema: "https://opencode.ai/config.json",
|
|
5817
|
+
...generated,
|
|
5818
|
+
...instructions === void 0 ? {} : { instructions },
|
|
5819
|
+
permission: {
|
|
5820
|
+
external_directory: {
|
|
5821
|
+
"*": "deny",
|
|
5822
|
+
"/tmp/**": "allow"
|
|
5823
|
+
},
|
|
5824
|
+
...generated.permission ?? {}
|
|
5825
|
+
},
|
|
5826
|
+
provider: { [providerId]: {
|
|
5827
|
+
npm: "@ai-sdk/openai-compatible",
|
|
5828
|
+
name: providerId,
|
|
5829
|
+
options: {
|
|
5830
|
+
baseURL,
|
|
5831
|
+
apiKey: `{env:${apiKeyEnv}}`,
|
|
5832
|
+
...clientName === void 0 ? {} : { headers: { [ROUTER_CLIENT_HEADER]: clientName } }
|
|
5833
|
+
},
|
|
5834
|
+
models: { [modelId]: { name: modelId } }
|
|
5835
|
+
} }
|
|
5836
|
+
};
|
|
5837
|
+
const invocation = harnessInvocation(HARNESS, invocationProfile(profile), task, { dangerouslySkipPermissions: true });
|
|
5838
|
+
const model = `${providerId}/${modelId}`;
|
|
5839
|
+
if (continueSession !== void 0 && !/^[A-Za-z0-9_-]+$/u.test(continueSession)) throw new ValidationError(`sharedBoxPlacement: session id ${continueSession} is not opencode's`);
|
|
5840
|
+
return {
|
|
5841
|
+
args: [
|
|
5842
|
+
invocation.command,
|
|
5843
|
+
...invocation.args,
|
|
5844
|
+
...continueSession === void 0 ? [] : ["--session", continueSession],
|
|
5845
|
+
"--format",
|
|
5846
|
+
"json",
|
|
5847
|
+
"-m",
|
|
5848
|
+
model
|
|
5849
|
+
],
|
|
5850
|
+
config: JSON.stringify(config),
|
|
5851
|
+
model
|
|
5852
|
+
};
|
|
5853
|
+
}
|
|
5854
|
+
/**
|
|
5855
|
+
* Save the harness's own record of the session where the transcript capture reads it.
|
|
5856
|
+
*
|
|
5857
|
+
* Current opencode keeps sessions in a SQLite database, which the capture cannot carry as text.
|
|
5858
|
+
* `opencode export` writes the same session as JSON.
|
|
5859
|
+
*/
|
|
5860
|
+
async function exportSession(run, collect, paths, sessionId) {
|
|
5861
|
+
if (!SESSION_ID.test(sessionId)) return;
|
|
5862
|
+
await collect(await run([
|
|
5863
|
+
"/bin/sh",
|
|
5864
|
+
"-c",
|
|
5865
|
+
"mkdir -p \"$(dirname \"$2\")\" && exec opencode export \"$1\" > \"$2\"",
|
|
5866
|
+
"export-session",
|
|
5867
|
+
sessionId,
|
|
5868
|
+
`${paths.home}/.local/share/opencode/export/${sessionId}.json`
|
|
5869
|
+
], DEFAULT_EXEC_TIMEOUT_MS));
|
|
5870
|
+
}
|
|
5871
|
+
const SESSION_ID = /^[A-Za-z0-9_-]+$/u;
|
|
5872
|
+
/** A subagent's session id in a `task` result (`<task id="ses_…">`) or failure (`task_id: ses_…`). */
|
|
5873
|
+
const TASK_SESSION = /(?:<task id="|task_id: )(ses_[A-Za-z0-9]+)/u;
|
|
5874
|
+
/**
|
|
5875
|
+
* The session a harness subagent ran in, named by its parent's `task` tool part.
|
|
5876
|
+
*
|
|
5877
|
+
* opencode starts each subagent in a child session and refuses a nested one unless the
|
|
5878
|
+
* configuration raises `subagent_depth` above 1, so under the default the parent's parts name
|
|
5879
|
+
* every subagent session. A running part carries the id in `state.metadata.sessionId`; a finished
|
|
5880
|
+
* one also carries it in its output, and a failed one in its error.
|
|
5881
|
+
*/
|
|
5882
|
+
function subagentSessionOf(part) {
|
|
5883
|
+
if (part.type !== "tool" || part.tool !== "task") return void 0;
|
|
5884
|
+
const state = part.state;
|
|
5885
|
+
if (state === void 0 || state === null || typeof state !== "object") return void 0;
|
|
5886
|
+
const { metadata, output, error } = state;
|
|
5887
|
+
const named = metadata !== null && typeof metadata === "object" ? metadata.sessionId : void 0;
|
|
5888
|
+
if (typeof named === "string" && SESSION_ID.test(named)) return named;
|
|
5889
|
+
for (const text of [output, error]) {
|
|
5890
|
+
const match = typeof text === "string" ? TASK_SESSION.exec(text) : null;
|
|
5891
|
+
if (match !== null) return match[1];
|
|
5892
|
+
}
|
|
5893
|
+
}
|
|
5894
|
+
/**
|
|
5895
|
+
* Translate opencode's JSON event lines into the Sandbox event wire the provider executor reads.
|
|
5896
|
+
*
|
|
5897
|
+
* Every part becomes `message.part.updated`, which is how the sidecar forwards opencode parts, so
|
|
5898
|
+
* the existing trace and progress readers decode them unchanged. Each `step-finish` part also
|
|
5899
|
+
* becomes one canonical `llm_call` receipt with its token counts. opencode reports no dollar
|
|
5900
|
+
* receipt for a custom provider, so every receipt says the cost is unknown and Runtime prices the
|
|
5901
|
+
* tokens as an estimate instead of a bill.
|
|
5902
|
+
*/
|
|
5903
|
+
function createOpencodeEventParser(model) {
|
|
5904
|
+
let sessionId;
|
|
5905
|
+
let finalMessageId;
|
|
5906
|
+
const textByMessage = /* @__PURE__ */ new Map();
|
|
5907
|
+
const subagentSessions = /* @__PURE__ */ new Set();
|
|
5908
|
+
const errors = [];
|
|
5909
|
+
let malformed = 0;
|
|
5910
|
+
let spentTokens = false;
|
|
5911
|
+
const failureOf = (exitCode, stderr) => {
|
|
5912
|
+
if (exitCode !== 0) {
|
|
5913
|
+
const said = [...errors, stderr.trim().slice(-1e3)].filter((text) => text.length > 0);
|
|
5914
|
+
return `opencode exited ${exitCode}${said.length > 0 ? `: ${said.join("; ")}` : ""}`;
|
|
5915
|
+
}
|
|
5916
|
+
return errors.length > 0 && finalMessageId === void 0 ? errors.join("; ") : void 0;
|
|
5917
|
+
};
|
|
5918
|
+
return {
|
|
5919
|
+
sessionId: () => sessionId,
|
|
5920
|
+
subagentSessionIds: () => [...subagentSessions],
|
|
5921
|
+
/** Why this run failed, or `undefined` when it answered. */
|
|
5922
|
+
failure: failureOf,
|
|
5923
|
+
/** Whether this run spent any model tokens before it ended. */
|
|
5924
|
+
madeProgress: () => spentTokens,
|
|
5925
|
+
*line(raw) {
|
|
5926
|
+
let event;
|
|
5927
|
+
try {
|
|
5928
|
+
event = JSON.parse(raw);
|
|
5929
|
+
} catch {
|
|
5930
|
+
malformed += 1;
|
|
5931
|
+
return;
|
|
5932
|
+
}
|
|
5933
|
+
if (typeof event.sessionID === "string") sessionId ??= event.sessionID;
|
|
5934
|
+
if (event.type === "error") {
|
|
5935
|
+
const message = errorMessage(event.error);
|
|
5936
|
+
errors.push(message);
|
|
5937
|
+
yield {
|
|
5938
|
+
type: "error",
|
|
5939
|
+
data: { message }
|
|
5940
|
+
};
|
|
5941
|
+
return;
|
|
5942
|
+
}
|
|
5943
|
+
const part = event.part;
|
|
5944
|
+
if (part === void 0 || part === null || typeof part !== "object") return;
|
|
5945
|
+
const subagent = subagentSessionOf(part);
|
|
5946
|
+
if (subagent !== void 0) subagentSessions.add(subagent);
|
|
5947
|
+
yield {
|
|
5948
|
+
type: "message.part.updated",
|
|
5949
|
+
data: { part }
|
|
5950
|
+
};
|
|
5951
|
+
const messageId = typeof part.messageID === "string" ? part.messageID : void 0;
|
|
5952
|
+
if (part.type === "text" && messageId !== void 0 && typeof part.text === "string") {
|
|
5953
|
+
const texts = textByMessage.get(messageId) ?? [];
|
|
5954
|
+
texts.push(part.text);
|
|
5955
|
+
textByMessage.set(messageId, texts);
|
|
5956
|
+
}
|
|
5957
|
+
if (part.type === "step-finish") {
|
|
5958
|
+
if (messageId !== void 0) finalMessageId = messageId;
|
|
5959
|
+
const receipt = stepReceipt(part, model);
|
|
5960
|
+
if (receipt !== void 0) {
|
|
5961
|
+
const data = receipt.data;
|
|
5962
|
+
if ((data?.tokensIn ?? 0) > 0 || (data?.tokensOut ?? 0) > 0) spentTokens = true;
|
|
5963
|
+
yield receipt;
|
|
5964
|
+
}
|
|
5965
|
+
}
|
|
5966
|
+
},
|
|
5967
|
+
/** The turn's terminal frames, from its last run. `runs` counts the runs of the session. */
|
|
5968
|
+
*finish(exitCode, stderr, runs = 1) {
|
|
5969
|
+
const finalText = (finalMessageId === void 0 ? void 0 : textByMessage.get(finalMessageId)?.join("")) ?? "";
|
|
5970
|
+
const failure = failureOf(exitCode, stderr);
|
|
5971
|
+
const counted = {
|
|
5972
|
+
...malformed > 0 ? { malformedLines: malformed } : {},
|
|
5973
|
+
...runs > 1 ? { sessionRuns: runs } : {}
|
|
5974
|
+
};
|
|
5975
|
+
if (failure !== void 0) {
|
|
5976
|
+
yield {
|
|
5977
|
+
type: "result",
|
|
5978
|
+
data: {
|
|
5979
|
+
success: false,
|
|
5980
|
+
status: "failed",
|
|
5981
|
+
error: failure,
|
|
5982
|
+
finalText,
|
|
5983
|
+
...counted
|
|
5984
|
+
}
|
|
5985
|
+
};
|
|
5986
|
+
yield {
|
|
5987
|
+
type: "done",
|
|
5988
|
+
data: { outcome: { type: "failed" } }
|
|
5989
|
+
};
|
|
5990
|
+
return;
|
|
5991
|
+
}
|
|
5992
|
+
yield {
|
|
5993
|
+
type: "result",
|
|
5994
|
+
data: {
|
|
5995
|
+
success: true,
|
|
5996
|
+
finalText,
|
|
5997
|
+
...counted
|
|
5998
|
+
}
|
|
5999
|
+
};
|
|
6000
|
+
yield {
|
|
6001
|
+
type: "done",
|
|
6002
|
+
data: { outcome: { type: "completed" } }
|
|
6003
|
+
};
|
|
6004
|
+
}
|
|
6005
|
+
};
|
|
6006
|
+
}
|
|
6007
|
+
function stepReceipt(part, model) {
|
|
6008
|
+
const tokens = part.tokens;
|
|
6009
|
+
if (tokens === void 0 || tokens === null || typeof tokens !== "object") return void 0;
|
|
6010
|
+
const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
6011
|
+
const cache = tokens.cache ?? {};
|
|
6012
|
+
const input = count(tokens.input);
|
|
6013
|
+
const output = count(tokens.output);
|
|
6014
|
+
const reasoning = count(tokens.reasoning) ?? 0;
|
|
6015
|
+
const cacheRead = count(cache.read) ?? 0;
|
|
6016
|
+
const cacheWrite = count(cache.write) ?? 0;
|
|
6017
|
+
const known = input !== void 0 && output !== void 0;
|
|
6018
|
+
return {
|
|
6019
|
+
type: "llm_call",
|
|
6020
|
+
...typeof part.id === "string" ? { id: part.id } : {},
|
|
6021
|
+
data: {
|
|
6022
|
+
usageMode: "delta",
|
|
6023
|
+
model,
|
|
6024
|
+
...known ? {
|
|
6025
|
+
tokensIn: input + cacheRead + cacheWrite,
|
|
6026
|
+
tokensOut: output + reasoning,
|
|
6027
|
+
...reasoning > 0 ? { reasoningTokens: reasoning } : {}
|
|
6028
|
+
} : { tokensKnown: false },
|
|
6029
|
+
costKnown: false
|
|
6030
|
+
}
|
|
6031
|
+
};
|
|
6032
|
+
}
|
|
6033
|
+
function errorMessage(error) {
|
|
6034
|
+
if (typeof error === "string") return error;
|
|
6035
|
+
if (error !== null && typeof error === "object") {
|
|
6036
|
+
const record = error;
|
|
6037
|
+
const data = record.data;
|
|
6038
|
+
const text = typeof data?.message === "string" ? data.message : typeof record.message === "string" ? record.message : typeof record.name === "string" ? record.name : "opencode reported an error";
|
|
6039
|
+
const status = data?.statusCode;
|
|
6040
|
+
return typeof status === "number" && Number.isSafeInteger(status) ? `${text} (status code ${status})` : text;
|
|
6041
|
+
}
|
|
6042
|
+
return "opencode reported an error";
|
|
6043
|
+
}
|
|
6044
|
+
//#endregion
|
|
4928
6045
|
//#region src/runtime/authored-code.ts
|
|
4929
6046
|
/**
|
|
4930
6047
|
* The ONE lint over model-authored source.
|
|
@@ -6081,6 +7198,31 @@ function signalPass(value, required) {
|
|
|
6081
7198
|
return !required;
|
|
6082
7199
|
}
|
|
6083
7200
|
//#endregion
|
|
7201
|
+
//#region src/runtime/supervise/run-context-sql.ts
|
|
7202
|
+
/**
|
|
7203
|
+
*
|
|
7204
|
+
* `createSqlRunContext` — the SQL-backed durable bundle a `createSupervisor().run` (or a
|
|
7205
|
+
* `runGraph`/`supervise` call that accepts injected stores) needs: a `SqlSpawnJournal`, a
|
|
7206
|
+
* `SqlResultBlobStore` (both over one `SqlStatements` seam — the same adapter shape
|
|
7207
|
+
* `SqlConversationJournal` takes), and a fresh `createExecutorRegistry()`, with `resume: true`
|
|
7208
|
+
* so spreading the context makes the run loadTree-first.
|
|
7209
|
+
*
|
|
7210
|
+
* The SQL analogue of `createFileRunContext`: where that bundle owns a directory, this one owns
|
|
7211
|
+
* tables in a database the caller already operates. The durable coordination side-log and
|
|
7212
|
+
* cancellation observers remain file-based behind `runDir`; a SQL coordination log is follow-up.
|
|
7213
|
+
*
|
|
7214
|
+
* @experimental
|
|
7215
|
+
*/
|
|
7216
|
+
/** Build a durable run context over one SQL statement seam. Tables are created on first use. */
|
|
7217
|
+
function createSqlRunContext(db) {
|
|
7218
|
+
return {
|
|
7219
|
+
journal: new SqlSpawnJournal(db),
|
|
7220
|
+
blobs: new SqlResultBlobStore(db),
|
|
7221
|
+
executors: createExecutorRegistry(),
|
|
7222
|
+
resume: true
|
|
7223
|
+
};
|
|
7224
|
+
}
|
|
7225
|
+
//#endregion
|
|
6084
7226
|
//#region src/runtime/supervise/trajectory-recorder.ts
|
|
6085
7227
|
/**
|
|
6086
7228
|
*
|
|
@@ -6727,7 +7869,7 @@ async function superviseSurface(profile, task, opts) {
|
|
|
6727
7869
|
makeWorkerAgent,
|
|
6728
7870
|
deliverable,
|
|
6729
7871
|
budget,
|
|
6730
|
-
|
|
7872
|
+
workerSlots: opts.workerSlots ?? 1,
|
|
6731
7873
|
perWorker: {
|
|
6732
7874
|
maxIterations: innerTurns + 2,
|
|
6733
7875
|
maxTokens: workerMaxTokens
|
|
@@ -7364,6 +8506,6 @@ function tail(s) {
|
|
|
7364
8506
|
return s.slice(-400);
|
|
7365
8507
|
}
|
|
7366
8508
|
//#endregion
|
|
7367
|
-
export {
|
|
8509
|
+
export { trajectoryReport as $, resolveMcpServerLaunch as $t, chatTransportExecutor as A, loopDispatch as At, strategyAuthorSystemPrompt as B, renderLeaderboardSvg as Bt, withUntrackedArtifacts as C, HarvestError as Ct, runCoderChecks as D, localSandboxClient as Dt, patchDelivered as E, resolveSandboxClient as Et, runStrategyEvolution as F, stopSentinel as Ft, sharedBoxRefusal as G, SqlSpawnJournal as Gt, DEFAULT_SHARED_BOX_WORKERS as H, auditIntent as Ht, selectChampion as I, leaderboard as It, openSandboxRun as J, materializeLocalMcp as Jt, sharedWorkerClientName as K, McpSpawnFault as Kt, assertStrategyContract as L, pairwiseSignificance as Lt, createChatSessionStore as M, completionAuthorizes as Mt, discriminatingMeans as N, deterministicCompletion as Nt, codeModeSupervisorTools as O, inlineSandboxClient as Ot, pickChampion as P, sentinelCompletion as Pt, equalKOnCost as Q, mcpSecretEnvMetadataKey as Qt, authorStrategy as R, renderLeaderboardHtml as Rt, copyUntrackedIntoClone as S, inProcessSandboxClient as St, createSqlRunContext as T, defineLeaderboard as Tt, ROUTER_CLIENT_HEADER as U, defaultAuditorInstruction as Ut, DEFAULT_SHARED_BOX_RESOURCES as V, renderPairwiseMarkdown as Vt, sharedBoxPlacement as W, SqlResultBlobStore as Wt, runBenchmark as X, sanitizeMcpToolSchema as Xt, printBenchmarkReport as Y, createMcpEnvironment as Yt, promotionGate as Z, envKeyProvider as Zt, NOTE_MAX_CHARS as _, buildSteerContext as _t, localShell as a, FileCorpus as at, composeWorkerEvidence as b, observationFromRegistry as bt, createVerifierEnvironment as c, fanout as ct, harvestSurfaceDiffs as d, panel as dt, resolveSecretEnv as en, definePersona as et, analystsFromRegistry as f, pipeline as ft, EVIDENCE_MAX_CHARS as g, assertTraceDerivedFindings as gt, worktreeFanout as h, widen as ht, jjWorkspace as i, registerShape as it, chatWorkerSeam as j, superviseDispatch as jt, unsafeInProcessRunner as k, loopCampaignDispatch as kt, boxSurfaceReader as l, flatWidenGate as lt, superviseSurface as m, verify as mt, makeFinding$1 as n, createTangleSandboxExactProcessProvider as nn, builtinShapes as nt, runInWorkspace as o, InMemoryCorpus as ot, failuresAnalyst as p, selectValidWinner as pt, SandboxRunAbortError as q, connectStdioMcp as qt, gitWorkspace as r, createShapeRegistry as rt, createWaterfallCollector as s, renderCorpusToInstructions as st, computeFindingId$1 as t, secretEnvOfMcpServer as tn, runPersonified as tt, fsSurfaceReader as u, loopUntil as ut, VERIFY_TAIL_CHARS as v, createScopeAnalyst as vt, analyzeTrace as w, harvestCorpus as wt, settledWorkerOut as x, runIsolatedCheck as xt, closingWorkerNote as y, registryScopeAnalyst as yt, strategyAuthorContract as z, renderLeaderboardMarkdown as zt };
|
|
7368
8510
|
|
|
7369
|
-
//# sourceMappingURL=runtime-
|
|
8511
|
+
//# sourceMappingURL=runtime-DVjIH1eo.js.map
|