@tangle-network/agent-runtime 0.279.0 → 0.281.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/{activation-B5NExoOz.d.ts → activation-BcTWDNOD.d.ts} +151 -25
  2. package/dist/{activation-BkUdrvqh.js → activation-C1ZAyQrQ.js} +2 -2
  3. package/dist/{activation-BkUdrvqh.js.map → activation-C1ZAyQrQ.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-BBL_OgRw.js → coordination-driver-B-HOpGN4.js} +2 -2
  7. package/dist/{coordination-driver-BBL_OgRw.js.map → coordination-driver-B-HOpGN4.js.map} +1 -1
  8. package/dist/{delegate-CZc7B-Tl.js → delegate-C1eIBN70.js} +2 -2
  9. package/dist/{delegate-CZc7B-Tl.js.map → delegate-C1eIBN70.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +768 -499
  12. package/dist/durable.js.map +1 -1
  13. package/dist/{graph-Ci8Ufs_f.js → graph-KjJaTmbO.js} +4 -4
  14. package/dist/{graph-Ci8Ufs_f.js.map → graph-KjJaTmbO.js.map} +1 -1
  15. package/dist/{improvement-cycle-Bi43xCVa.js → improvement-cycle-DCTCTmNl.js} +763 -43
  16. package/dist/improvement-cycle-DCTCTmNl.js.map +1 -0
  17. package/dist/{index-Dm8SHDGW.d.ts → index-BSSGMvUd.d.ts} +97 -144
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +8 -8
  20. package/dist/intelligence.d.ts +1 -1
  21. package/dist/intelligence.js +3 -3
  22. package/dist/kernel.d.ts +1 -1
  23. package/dist/kernel.js +8 -8
  24. package/dist/{loop-runner-bin-C9FJshTP.js → loop-runner-bin-Co2eBFbb.js} +3 -3
  25. package/dist/{loop-runner-bin-C9FJshTP.js.map → loop-runner-bin-Co2eBFbb.js.map} +1 -1
  26. package/dist/{loop-runner-bin-D6khQtoC.d.ts → loop-runner-bin-DgeZHpWJ.d.ts} +2 -2
  27. package/dist/loop-runner-bin.d.ts +1 -1
  28. package/dist/loop-runner-bin.js +1 -1
  29. package/dist/mcp/bin.js +3 -3
  30. package/dist/mcp/index.d.ts +1 -1
  31. package/dist/mcp/index.js +4 -4
  32. package/dist/platform.d.ts +34 -36
  33. package/dist/platform.js +122 -29
  34. package/dist/platform.js.map +1 -1
  35. package/dist/{provision-supervisor-BvnihiyB.js → provision-supervisor-CkN8RRjv.js} +3 -3
  36. package/dist/{provision-supervisor-BvnihiyB.js.map → provision-supervisor-CkN8RRjv.js.map} +1 -1
  37. package/dist/{runtime-DsAHXig2.js → runtime-B_yRPBjj.js} +16 -966
  38. package/dist/runtime-B_yRPBjj.js.map +1 -0
  39. package/dist/{server-Dyc1zvug.js → server-dOyG5Tw6.js} +3 -3
  40. package/dist/{server-Dyc1zvug.js.map → server-dOyG5Tw6.js.map} +1 -1
  41. package/dist/{structural-rollout-D-0X6lsU.js → shared-box-CZFdugL1.js} +959 -9
  42. package/dist/shared-box-CZFdugL1.js.map +1 -0
  43. package/dist/{supervise-DBQdrp7H.js → supervise-zt91I62x.js} +3 -3
  44. package/dist/{supervise-DBQdrp7H.js.map → supervise-zt91I62x.js.map} +1 -1
  45. package/dist/{supervisor-DtlPj9me.js → supervisor-UXgaPisu.js} +49 -58
  46. package/dist/supervisor-UXgaPisu.js.map +1 -0
  47. package/dist/testing.d.ts +1 -1
  48. package/dist/testing.js +12 -12
  49. package/dist/tui/index.d.ts +1 -1
  50. package/dist/tui/index.js +1 -1
  51. package/package.json +4 -4
  52. package/skills/profile-authoring/SKILL.md +210 -0
  53. package/skills/supervise/SKILL.md +2 -2
  54. package/dist/improvement-cycle-Bi43xCVa.js.map +0 -1
  55. package/dist/runtime-DsAHXig2.js.map +0 -1
  56. package/dist/structural-rollout-D-0X6lsU.js.map +0 -1
  57. package/dist/supervisor-DtlPj9me.js.map +0 -1
  58. package/skills/supervise/references/profile-authoring.md +0 -19
@@ -1,11 +1,13 @@
1
- import { At as createExecutor, Ba as promptOptionsFromAgentTurnInput, Bt as InMemoryResultBlobStore, Dt as captureReusableExecutorConfig, Ia as armDeadlineTimer, Ji as unknownExecutionBindingReceipt, Ki as runtimeOwnedPendingExecutorMaterialization, Li as knownExecutionBindingReceipt, M as withDriverExecutor, Pa as awaitAbortable, Pi as authoredProfileDigest, Ri as knownMaterializationReceipt, Ui as runtimeOwnedExecutorExecutionBinding, Va as providerMessageText, Vt as InMemorySpawnJournal, Wi as runtimeOwnedExecutorMaterialization, Xi as executableAgentProfileSnapshot, Yi as unknownMaterializationReceipt, Zn as observedModelMatchesDeclared, aa as createSandboxUsageLedger, ca as mapSandboxEvent, ea as projectSandboxOutcome, ia as createSandboxToolPartState, jt as createExecutorRegistry, la as mapSandboxToolEvent, r as createSupervisor, ra as canonicalStreamEventFromSandboxEvent, sa as isSandboxTerminalEvent, ta as readSandboxOutcome, za as promptFromAgentTurnInput } from "./supervisor-DtlPj9me.js";
1
+ import { Ba as promptOptionsFromAgentTurnInput, Ht as InMemorySpawnJournal, Ia as armDeadlineTimer, Ji as unknownExecutionBindingReceipt, Ki as runtimeOwnedPendingExecutorMaterialization, Li as knownExecutionBindingReceipt, M as withDriverExecutor, Mt as createExecutorRegistry, Ot as captureReusableExecutorConfig, Pa as awaitAbortable, Pi as authoredProfileDigest, Qn as observedModelMatchesDeclared, Ri as knownMaterializationReceipt, Sa as sleep, Ui as runtimeOwnedExecutorExecutionBinding, Va as providerMessageText, Vt as InMemoryResultBlobStore, Wi as runtimeOwnedExecutorMaterialization, Xi as executableAgentProfileSnapshot, Yi as unknownMaterializationReceipt, aa as createSandboxUsageLedger, ar as sandboxClientAsProvider, ca as mapSandboxEvent, ea as projectSandboxOutcome, er as LEAF_CONTINUATION_TASK, ia as createSandboxToolPartState, jt as createExecutor, la as mapSandboxToolEvent, oi as harnessInvocation, or as unavailablePauseMs, r as createSupervisor, ra as canonicalStreamEventFromSandboxEvent, sa as isSandboxTerminalEvent, sr as unavailableSignalOfFailure, ta as readSandboxOutcome, za as promptFromAgentTurnInput } from "./supervisor-UXgaPisu.js";
2
2
  import { m as ValidationError, p as SessionMismatchError, r as BackendTransportError } from "./errors-DodWX-cb.js";
3
- import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile } from "./model-policy-BbSCSak0.js";
3
+ import { a as concreteProfileModel, c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile } from "./model-policy-BbSCSak0.js";
4
4
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, renderInputPartsAsText } from "@tangle-network/agent-interface";
5
5
  import { costForTokenPricing, makeProposalFinding, scoreKnowledgeReadiness } from "@tangle-network/agent-eval";
6
6
  import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
7
- import { randomBytes } from "node:crypto";
7
+ import { randomBytes, randomUUID } from "node:crypto";
8
+ import { materializeProfile } from "@tangle-network/agent-profile-materialize";
8
9
  import { assertProposalFindings } from "@tangle-network/agent-eval/analyst";
10
+ import { harnessSystemPromptIntents as harnessSystemPromptIntents$1 } from "@tangle-network/agent-interface/harness-capabilities";
9
11
  //#region src/sessions.ts
10
12
  /**
11
13
  *
@@ -1218,7 +1220,7 @@ function profileOptimizerModelCall(args) {
1218
1220
  } catch (error) {
1219
1221
  return {
1220
1222
  succeeded: false,
1221
- error: errorMessage(error),
1223
+ error: errorMessage$1(error),
1222
1224
  receipt: unknownOptimizerReceipt(binding.model),
1223
1225
  execution: {
1224
1226
  kind: "agent-runtime-profile-model-call",
@@ -1227,7 +1229,7 @@ function profileOptimizerModelCall(args) {
1227
1229
  callId: request.callId,
1228
1230
  endpointFormat: request.endpointFormat ?? null,
1229
1231
  executed: false,
1230
- error: errorMessage(error)
1232
+ error: errorMessage$1(error)
1231
1233
  }
1232
1234
  };
1233
1235
  }
@@ -1250,7 +1252,7 @@ function profileOptimizerModelCall(args) {
1250
1252
  execution
1251
1253
  };
1252
1254
  } catch (error) {
1253
- const message = `profile optimizer receipt normalization failed after execution: ${errorMessage(error)}`;
1255
+ const message = `profile optimizer receipt normalization failed after execution: ${errorMessage$1(error)}`;
1254
1256
  return {
1255
1257
  succeeded: false,
1256
1258
  error: message,
@@ -1514,7 +1516,7 @@ function optimizerTokenCount(value, label) {
1514
1516
  if (!Number.isSafeInteger(value) || value < 0) throw new Error(`profile optimizer ${label} must be a non-negative integer`);
1515
1517
  return value;
1516
1518
  }
1517
- function errorMessage(error) {
1519
+ function errorMessage$1(error) {
1518
1520
  return error instanceof Error ? error.message : String(error);
1519
1521
  }
1520
1522
  //#endregion
@@ -2868,6 +2870,954 @@ function structuralRollout(config = {}) {
2868
2870
  });
2869
2871
  }
2870
2872
  //#endregion
2871
- export { collectAgentTurn as A, defaultAnalystInstruction as C, profileOptimizerModelCall as D, profileChatClient as E, InMemoryRuntimeSessionStore as F, newRuntimeSession as I, nowIso as L, createIterableBackend as M, createSandboxPromptBackend as N, optimizerMethod as O, normalizeBackendStreamEvent as P, startOrResumeRuntimeSession as R, ObservationError as S, renderReport as T, depthStrategy as _, defaultStructuralRolloutPolicy as a, sample as b, officialChecksFromMeta as c, selectBestIndex as d, structuralRollout as f, defineStrategy as g, breadthStrategy as h, defaultExtractCandidate as i, streamAgentTurn as j, strategyAuthorMethod as k, resolveEntrySymbol as l, adaptiveRefine as m, compareCheckOutcomes as n, filterAuthoredAsserts as o, visibleCheckScore as p, composeCheckSources as r, modelAuthoredChecks as s, canDisplace as t, sandboxCheckRunner as u, refine as v, observe as w, sampleThenRefine as x, runAgentic as y, touchSession as z };
2873
+ //#region src/runtime/shared-box.ts
2874
+ /**
2875
+ * Shared-box placement: many harness workers in one Sandbox box, each as its own process.
2876
+ *
2877
+ * The default provider placement gives every worker its own Sandbox box. A box costs a create
2878
+ * call, a sidecar, an egress proxy, a preview link and a memory reservation sized for the box,
2879
+ * while one opencode worker uses about half a gigabyte. This module packs workers into a small
2880
+ * pool of boxes instead. Each worker runs `opencode run` as a separate process with its own
2881
+ * working directory and its own HOME, so each worker has its own harness session, its own
2882
+ * materialized profile and its own transcript files.
2883
+ *
2884
+ * Why processes and not sidecar sessions: the sidecar serves every session in one box from one
2885
+ * workspace and writes each session's profile into the same files. Measured 2026-09-24 on
2886
+ * sandbox-ff52a989e7c9: eight concurrent sessions with different instructions, and seven of eight
2887
+ * answered with another session's instructions. A process with its own directory, its own HOME and
2888
+ * `OPENCODE_DISABLE_PROJECT_CONFIG` reads only its own configuration: sixteen of sixteen concurrent
2889
+ * workers answered with their own instructions and wrote only into their own directory.
2890
+ *
2891
+ * The boundary is cooperative, not a security boundary. Every worker runs as the same Linux user,
2892
+ * so a worker can read a co-tenant's files through its shell. A profile that writes a repository,
2893
+ * runs untrusted code, holds a credential of its own, or must stay blind to its siblings keeps a
2894
+ * dedicated box: {@link SharedBoxPlacement.refusal} names the profile features this placement
2895
+ * cannot carry, and Runtime then uses the dedicated provider.
2896
+ *
2897
+ * A worker whose model provider refuses a turn for capacity keeps its process's session and
2898
+ * directory, pauses by the driver's rule, and continues the same opencode session, the way a
2899
+ * dedicated leaf does (`ProviderExecutorOptions.unavailablePause`). Measured 2026-09-24: 15 of 23
2900
+ * down children of play anomaly-referee-v3d ended on `provider_quota_exhausted`, and opencode
2901
+ * itself gives up on a refused model after about 70 seconds of its own retries.
2902
+ *
2903
+ * The workers of one box share the box's router key. Each worker names itself to the router with
2904
+ * the `x-tangle-client` header, which the router stores as `clientName` on every usage row, so a
2905
+ * keeper can price one worker from the key's per-client rows (`tangle-admin router-spend --key
2906
+ * <box key>`). A request without the header stays charged to the box.
2907
+ *
2908
+ * `workersPerBox` is the one structural cap, and it protects the box. A Tangle box has a fixed
2909
+ * 512-task pids limit. An idle box uses about 118 tasks and one opencode worker about 34, so
2910
+ * twelve workers reach the limit. At that limit the sidecar's own process spawn fails with EAGAIN
2911
+ * and the sidecar restarts, which ends every worker in the box (measured on the same box: 28
2912
+ * workers crashed the sidecar twice; 16 workers crashed it once).
2913
+ */
2914
+ /**
2915
+ * The most workers one default box carries at once.
2916
+ *
2917
+ * It keeps a worker count that the 512-task pids limit of a Tangle box can hold with headroom
2918
+ * for the sidecar's own processes and the workers' tool shells: 118 idle tasks plus 8 workers at
2919
+ * about 34 tasks each is 390. Memory is not the binding limit: 8 workers used about 4 GB in a
2920
+ * 16 GB box. Raise it only for a box whose pids limit was raised with it.
2921
+ */
2922
+ const DEFAULT_SHARED_BOX_WORKERS = 8;
2923
+ /** The box shape the default placement creates: memory for 8 workers at about 0.5 GB each plus
2924
+ * the sidecar, and 4 cores, because the workers wait on the model most of the time. */
2925
+ const DEFAULT_SHARED_BOX_RESOURCES = Object.freeze({
2926
+ cpuCores: 4,
2927
+ memoryMB: 8192
2928
+ });
2929
+ const DEFAULT_WORKER_ROOT = "/home/agent/workers";
2930
+ const HARNESS = "opencode";
2931
+ const SHARED_PROVIDER_NAME = "tangle-shared-box";
2932
+ const DEFAULT_EXEC_TIMEOUT_MS = 12e4;
2933
+ /** The request header the router records as a usage row's `clientName`. */
2934
+ const ROUTER_CLIENT_HEADER = "x-tangle-client";
2935
+ /**
2936
+ * The router client name of the worker that runs supervised node `nodeId`.
2937
+ *
2938
+ * The node id is already in the spawn journal, so a keeper joins a router row to a node without
2939
+ * a new record: the row whose `clientName` is `agent-runtime-node/<nodeId>` is that node's spend.
2940
+ */
2941
+ function sharedWorkerClientName(nodeId) {
2942
+ if (!/^[!-~]+$/u.test(nodeId)) throw new ValidationError("sharedWorkerClientName: a node id must be visible ASCII");
2943
+ return `agent-runtime-node/${nodeId}`;
2944
+ }
2945
+ /**
2946
+ * Attempts for one Sandbox API call that failed on the way to the box.
2947
+ *
2948
+ * Every call re-verifies the API key with the platform, and a burst of workers makes that check
2949
+ * time out: 8 of 64 workers failed with `502 platform_unavailable` (reason `platform_timeout`) in
2950
+ * one burst on 2026-09-24, and 3 more lost their transcript enumeration the same way. The check
2951
+ * refuses the request before it reaches the box, so repeating it is safe; five attempts over about
2952
+ * fifteen seconds rode out every such failure measured.
2953
+ */
2954
+ const TRANSIENT_ATTEMPTS = 5;
2955
+ const TRANSIENT_BASE_DELAY_MS = 1e3;
2956
+ /** A failure that a repeated request can change: the platform, the gateway or the network. */
2957
+ function isTransientSandboxFailure(error) {
2958
+ if (error === null || typeof error !== "object") return false;
2959
+ const record = error;
2960
+ if (typeof record.status === "number" && [
2961
+ 408,
2962
+ 425,
2963
+ 429,
2964
+ 500,
2965
+ 502,
2966
+ 503,
2967
+ 504
2968
+ ].includes(record.status)) return true;
2969
+ const text = `${String(record.code ?? "")} ${String(record.name ?? "")} ${String(record.message ?? "")}`;
2970
+ 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);
2971
+ }
2972
+ async function transientRetry(operation, options = {}) {
2973
+ const delayMs = options.delayMs ?? TRANSIENT_BASE_DELAY_MS;
2974
+ for (let attempt = 1;; attempt += 1) try {
2975
+ return await operation(attempt);
2976
+ } catch (error) {
2977
+ if (attempt >= TRANSIENT_ATTEMPTS || !isTransientSandboxFailure(error)) throw error;
2978
+ options.signal?.throwIfAborted();
2979
+ await sleep(delayMs * 2 ** (attempt - 1), options.signal);
2980
+ }
2981
+ }
2982
+ /**
2983
+ * Why a shared box cannot carry `profile`, or `undefined` when it can.
2984
+ *
2985
+ * A shared box carries a profile whose whole behavior reaches an opencode process through its own
2986
+ * working directory, its own configuration and the box's own model credential. Everything else
2987
+ * keeps a dedicated box: another harness, a model the box credential cannot reach, a replaced
2988
+ * system prompt, MCP servers, connections, hooks, subagents, extensions, tool grants, and any
2989
+ * resource the materializer does not lower into the worker's directory.
2990
+ */
2991
+ function sharedBoxRefusal(profile) {
2992
+ if (profile.harness !== HARNESS) return `harness ${String(profile.harness)} is not ${HARNESS}`;
2993
+ if (concreteProfileModel(profile) === void 0) return "profile names no concrete model";
2994
+ if (profile.model?.provider === void 0) return "profile names no model provider";
2995
+ if (profile.model?.reasoningEffort !== void 0) {
2996
+ if (tryInvocation(profile) === void 0) return "model.reasoningEffort has no opencode variant";
2997
+ }
2998
+ if (profile.prompt?.systemPrompt !== void 0) return "prompt.systemPrompt replaces a system prompt";
2999
+ for (const field of [
3000
+ "mcp",
3001
+ "connections",
3002
+ "hooks",
3003
+ "subagents",
3004
+ "extensions",
3005
+ "confidential",
3006
+ "modes"
3007
+ ]) if (profile[field] !== void 0) return `profile declares ${field}`;
3008
+ if (profile.tools !== void 0 && Object.keys(profile.tools).length > 0) return "profile grants tools";
3009
+ const resources = profile.resources;
3010
+ if (resources !== void 0) {
3011
+ for (const field of [
3012
+ "skills",
3013
+ "agents",
3014
+ "commands",
3015
+ "tools"
3016
+ ]) if (resources[field] !== void 0) return `profile declares resources.${field}`;
3017
+ for (const file of resources.files ?? []) if (file.resource.kind !== "inline") return `resource file ${file.path} is not inline`;
3018
+ if (resources.instructions !== void 0 && typeof resources.instructions !== "string" && resources.instructions.kind !== "inline") return "resources.instructions is not inline";
3019
+ }
3020
+ let plan;
3021
+ try {
3022
+ plan = materializeProfile(profile, HARNESS);
3023
+ } catch (error) {
3024
+ return `opencode materialization failed: ${error instanceof Error ? error.message : String(error)}`;
3025
+ }
3026
+ if (plan.unsupported.length > 0) return `opencode cannot carry ${plan.unsupported.map((row) => row.dimension).join(", ")}`;
3027
+ if (Object.keys(plan.env).length > 0 || plan.flags.length > 0) return "profile needs launch environment or flags";
3028
+ for (const file of plan.files) {
3029
+ if (file.root === "agent") return `profile writes ${file.relPath} into the harness home`;
3030
+ if ((file.secretSlots?.length ?? 0) > 0) return `profile file ${file.relPath} carries a secret`;
3031
+ if (isUnsafeRelativePath(file.relPath)) return `profile file ${file.relPath} leaves its directory`;
3032
+ }
3033
+ }
3034
+ function tryInvocation(profile) {
3035
+ try {
3036
+ return harnessInvocation(HARNESS, invocationProfile(profile), "probe").args;
3037
+ } catch {
3038
+ return;
3039
+ }
3040
+ }
3041
+ /**
3042
+ * The profile the invocation table reads. The prompt reaches opencode through its configuration
3043
+ * and the model through the provider this placement declares, so only the reasoning effort is
3044
+ * left for the table to lower into `--variant`.
3045
+ */
3046
+ function invocationProfile(profile) {
3047
+ const { prompt: _prompt, model, ...rest } = profile;
3048
+ return {
3049
+ ...rest,
3050
+ ...model?.reasoningEffort === void 0 ? {} : { model: { reasoningEffort: model.reasoningEffort } }
3051
+ };
3052
+ }
3053
+ function isUnsafeRelativePath(path) {
3054
+ return path.length === 0 || path.startsWith("/") || path.split("/").some((segment) => segment === ".." || segment === "");
3055
+ }
3056
+ /**
3057
+ * Place accepted workers as processes in a pool of shared Sandbox boxes.
3058
+ *
3059
+ * The pool fills a box before it creates the next one and deletes a box when its last worker
3060
+ * releases it. Runtime reaches this placement through `createExecutor({ backend: 'provider',
3061
+ * shared })`: a profile that {@link SharedBoxPlacement.refusal} accepts runs here, and every other
3062
+ * profile keeps the dedicated provider.
3063
+ */
3064
+ function sharedBoxPlacement(options) {
3065
+ const workersPerBox = options.workersPerBox ?? 8;
3066
+ if (!Number.isSafeInteger(workersPerBox) || workersPerBox < 1) throw new ValidationError("sharedBoxPlacement: workersPerBox must be a positive integer");
3067
+ const workerRoot = options.workerRoot ?? DEFAULT_WORKER_ROOT;
3068
+ if (!workerRoot.startsWith("/") || isUnsafeRelativePath(workerRoot.slice(1))) throw new ValidationError("sharedBoxPlacement: workerRoot must be an absolute, normalized path");
3069
+ const boxOptions = {
3070
+ resources: { ...DEFAULT_SHARED_BOX_RESOURCES },
3071
+ ...options.box ?? {}
3072
+ };
3073
+ if (boxOptions.backend !== void 0) throw new ValidationError("sharedBoxPlacement: box.backend is owned by Runtime");
3074
+ const identity = {
3075
+ id: "shared-box",
3076
+ digest: canonicalCandidateDigest({
3077
+ kind: "shared-box-placement.v1",
3078
+ harness: HARNESS,
3079
+ workersPerBox,
3080
+ workerRoot,
3081
+ box: publicBoxOptions(boxOptions)
3082
+ })
3083
+ };
3084
+ const retryDelayMs = options.retryDelayMs ?? TRANSIENT_BASE_DELAY_MS;
3085
+ const pool = createBoxPool(options.client, boxOptions, workersPerBox, retryDelayMs);
3086
+ const providerFor = (worker = {}) => {
3087
+ const clientName = worker.nodeId === void 0 ? void 0 : sharedWorkerClientName(worker.nodeId);
3088
+ return sandboxClientAsProvider({ async create(createOptions) {
3089
+ const profile = workerProfile(createOptions);
3090
+ const refusal = sharedBoxRefusal(profile);
3091
+ if (refusal !== void 0) throw new ValidationError(`sharedBoxPlacement: ${refusal}`);
3092
+ assertWorkerCreateOptions(createOptions);
3093
+ const lease = await pool.acquire();
3094
+ try {
3095
+ return await createWorker(lease, workerRoot, profile, {
3096
+ retryDelayMs,
3097
+ clientName,
3098
+ unavailablePause: options.unavailablePause ?? {}
3099
+ });
3100
+ } catch (error) {
3101
+ await lease.release();
3102
+ throw error;
3103
+ }
3104
+ } }, {
3105
+ name: SHARED_PROVIDER_NAME,
3106
+ capabilities: sharedBoxCapabilities()
3107
+ });
3108
+ };
3109
+ return {
3110
+ providerFor,
3111
+ identity,
3112
+ refusal: sharedBoxRefusal,
3113
+ stats: () => pool.stats(),
3114
+ close: () => pool.close()
3115
+ };
3116
+ }
3117
+ function publicBoxOptions(box) {
3118
+ const { env, secrets, ...rest } = box;
3119
+ return {
3120
+ ...rest,
3121
+ ...env === void 0 ? {} : { environmentVariableNames: Object.keys(env).sort() },
3122
+ ...secrets === void 0 ? {} : { secrets }
3123
+ };
3124
+ }
3125
+ function sharedBoxCapabilities() {
3126
+ return {
3127
+ profile: {
3128
+ namedProfiles: false,
3129
+ systemPrompt: {
3130
+ ...harnessSystemPromptIntents$1(HARNESS),
3131
+ replace: false
3132
+ },
3133
+ instructions: true,
3134
+ tools: false,
3135
+ permissions: true,
3136
+ mcp: false,
3137
+ subagents: false,
3138
+ resources: {
3139
+ files: true,
3140
+ instructions: true
3141
+ },
3142
+ runtimeUpdate: false,
3143
+ validation: false
3144
+ },
3145
+ streaming: {
3146
+ live: true,
3147
+ replay: false,
3148
+ detach: false,
3149
+ turnIdempotency: false
3150
+ },
3151
+ sessions: {
3152
+ continue: false,
3153
+ list: false,
3154
+ messages: false
3155
+ },
3156
+ workspace: {
3157
+ read: true,
3158
+ write: true,
3159
+ exec: true,
3160
+ git: false,
3161
+ upload: false,
3162
+ download: false
3163
+ },
3164
+ branching: {
3165
+ checkpoint: false,
3166
+ fork: false
3167
+ },
3168
+ placement: true,
3169
+ usage: true,
3170
+ confidential: false
3171
+ };
3172
+ }
3173
+ function workerProfile(createOptions) {
3174
+ const raw = (createOptions?.backend)?.profile;
3175
+ const parsed = agentProfileSchema.safeParse(raw);
3176
+ if (!parsed.success) throw new ValidationError("sharedBoxPlacement: an exact AgentProfile is required at create");
3177
+ return parsed.data;
3178
+ }
3179
+ /**
3180
+ * A worker create carries only what a slot in a shared box can honor. Box-level settings belong
3181
+ * to the placement's own box options, and a per-worker request for them is refused rather than
3182
+ * dropped: a worker that asked for an environment variable, a repository or its own resources
3183
+ * would otherwise run without them and report nothing.
3184
+ */
3185
+ function assertWorkerCreateOptions(createOptions) {
3186
+ const options = createOptions ?? {};
3187
+ for (const key of [
3188
+ "git",
3189
+ "fromSnapshot",
3190
+ "fromSandboxId",
3191
+ "environment",
3192
+ "cwd",
3193
+ "resources"
3194
+ ]) if (options[key] !== void 0) throw new ValidationError(`sharedBoxPlacement: a shared worker cannot set ${key}`);
3195
+ const env = options.env;
3196
+ if (env !== void 0 && Object.keys(env).length > 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot set env");
3197
+ const secrets = options.secrets;
3198
+ if (Array.isArray(secrets) && secrets.length > 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot request secrets");
3199
+ const backend = options.backend;
3200
+ if (backend?.runtimeAttachments !== void 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot carry runtime attachments");
3201
+ if (backend?.type !== void 0 && backend.type !== HARNESS) throw new ValidationError(`sharedBoxPlacement: backend ${String(backend.type)} is not ${HARNESS}`);
3202
+ }
3203
+ function createBoxPool(client, boxOptions, workersPerBox, retryDelayMs) {
3204
+ const poolId = randomUUID();
3205
+ const boxes = [];
3206
+ const history = [];
3207
+ let seq = 0;
3208
+ let placed = 0;
3209
+ let peak = 0;
3210
+ let closing = false;
3211
+ const retire = async (entry) => {
3212
+ if (entry.retired) return void 0;
3213
+ entry.retired = true;
3214
+ const index = boxes.indexOf(entry);
3215
+ if (index >= 0) boxes.splice(index, 1);
3216
+ let handle;
3217
+ try {
3218
+ handle = await entry.ready;
3219
+ } catch {
3220
+ return;
3221
+ }
3222
+ try {
3223
+ await transientRetry(() => handle.delete(), { delayMs: retryDelayMs });
3224
+ entry.deleted = true;
3225
+ return {
3226
+ boxId: handle.id,
3227
+ deleted: true
3228
+ };
3229
+ } catch (error) {
3230
+ return {
3231
+ boxId: handle.id,
3232
+ deleted: false,
3233
+ error: error instanceof Error ? error.message : String(error)
3234
+ };
3235
+ }
3236
+ };
3237
+ return {
3238
+ async acquire() {
3239
+ if (closing) throw new ValidationError("sharedBoxPlacement: the placement is closed");
3240
+ let entry = boxes.find((candidate) => !candidate.retired && candidate.workers < workersPerBox);
3241
+ if (entry === void 0) {
3242
+ const boxSeq = seq++;
3243
+ const request = {
3244
+ ...boxOptions,
3245
+ name: boxOptions.name ?? `shared-box-${poolId.slice(0, 8)}-${boxSeq}`,
3246
+ idempotencyKey: `shared-box-${poolId}-${boxSeq}`,
3247
+ backend: {
3248
+ type: HARNESS,
3249
+ profile: {
3250
+ name: "shared-box",
3251
+ harness: HARNESS
3252
+ }
3253
+ }
3254
+ };
3255
+ const requestedAt = Date.now();
3256
+ const created = {
3257
+ seq: boxSeq,
3258
+ ready: transientRetry(() => client.create(request), { delayMs: retryDelayMs }).then((box) => box),
3259
+ workers: 0,
3260
+ served: 0,
3261
+ retired: false,
3262
+ deleted: false
3263
+ };
3264
+ created.ready.then((box) => {
3265
+ created.id = box.id;
3266
+ created.createMs = Date.now() - requestedAt;
3267
+ }, () => {
3268
+ const index = boxes.indexOf(created);
3269
+ if (index >= 0) boxes.splice(index, 1);
3270
+ created.retired = true;
3271
+ });
3272
+ boxes.push(created);
3273
+ history.push(created);
3274
+ entry = created;
3275
+ }
3276
+ const leased = entry;
3277
+ leased.workers += 1;
3278
+ leased.served += 1;
3279
+ placed += 1;
3280
+ peak = Math.max(peak, leased.workers);
3281
+ let box;
3282
+ try {
3283
+ box = await leased.ready;
3284
+ } catch (error) {
3285
+ leased.workers -= 1;
3286
+ throw error;
3287
+ }
3288
+ let released = false;
3289
+ return {
3290
+ box,
3291
+ async release() {
3292
+ if (released) return;
3293
+ released = true;
3294
+ leased.workers -= 1;
3295
+ if (leased.workers === 0 && !closing) await retire(leased);
3296
+ }
3297
+ };
3298
+ },
3299
+ stats() {
3300
+ return {
3301
+ boxesCreated: history.length,
3302
+ boxesLive: history.filter((entry) => !entry.retired).length,
3303
+ workersPlaced: placed,
3304
+ workersLive: history.reduce((sum, entry) => sum + entry.workers, 0),
3305
+ peakWorkersPerBox: peak,
3306
+ boxes: history.filter((entry) => entry.id !== void 0).map((entry) => ({
3307
+ id: entry.id,
3308
+ workersServed: entry.served,
3309
+ deleted: entry.deleted,
3310
+ createMs: entry.createMs ?? 0
3311
+ }))
3312
+ };
3313
+ },
3314
+ async close() {
3315
+ closing = true;
3316
+ return (await Promise.all(history.map((entry) => retire(entry)))).filter((receipt) => receipt !== void 0);
3317
+ }
3318
+ };
3319
+ }
3320
+ /** The environment one worker's processes see: its own directory, HOME and XDG roots. */
3321
+ function workerEnv(paths) {
3322
+ return [
3323
+ "OPENCODE_DISABLE_PROJECT_CONFIG=1",
3324
+ `OPENCODE_CONFIG_DIR=${paths.dir}/.opencode`,
3325
+ `PWD=${paths.dir}`,
3326
+ `HOME=${paths.home}`,
3327
+ `XDG_DATA_HOME=${paths.home}/.local/share`,
3328
+ `XDG_CONFIG_HOME=${paths.home}/.config`,
3329
+ `XDG_STATE_HOME=${paths.home}/.local/state`,
3330
+ `XDG_CACHE_HOME=${paths.cache}`
3331
+ ];
3332
+ }
3333
+ async function createWorker(lease, root, createProfile, placement) {
3334
+ const { clientName, unavailablePause } = placement;
3335
+ const box = resilientBox(lease.box, placement.retryDelayMs);
3336
+ const workerId = `w-${randomUUID()}`;
3337
+ const paths = {
3338
+ dir: `${root}/${workerId}`,
3339
+ home: `${root}/${workerId}/.home`,
3340
+ cache: `${root}/.cache`
3341
+ };
3342
+ const made = await box.exec(`mkdir -p '${paths.home}' '${paths.cache}'`, { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS });
3343
+ if ((made.exitCode ?? 1) !== 0) throw new Error(`sharedBoxPlacement: could not create ${paths.dir}: ${made.stderr ?? ""}`);
3344
+ const env = workerEnv(paths);
3345
+ let running;
3346
+ let turnActive = false;
3347
+ let released = false;
3348
+ const started = /* @__PURE__ */ new Set();
3349
+ const run = async (args, timeoutMs, extraEnv) => {
3350
+ const process = await box.spawnInDirectory("/usr/bin/env", [...env, ...args], {
3351
+ cwd: paths.dir,
3352
+ ...extraEnv === void 0 ? {} : { env: extraEnv },
3353
+ timeoutMs
3354
+ }, started);
3355
+ started.add(process.pid);
3356
+ return process;
3357
+ };
3358
+ const collect = async (process) => {
3359
+ const [stdout, stderr, exitCode] = await Promise.all([
3360
+ drain(box.output(process, "stdout")),
3361
+ drain(box.output(process, "stderr")),
3362
+ box.wait(process)
3363
+ ]);
3364
+ return {
3365
+ exitCode,
3366
+ stdout,
3367
+ stderr
3368
+ };
3369
+ };
3370
+ const resolvePath = (path) => {
3371
+ if (path.startsWith("/")) return path;
3372
+ if (isUnsafeRelativePath(path)) throw new ValidationError(`sharedBoxPlacement: path ${path} leaves the worker directory`);
3373
+ return `${paths.dir}/${path}`;
3374
+ };
3375
+ /**
3376
+ * One turn: one or more opencode runs of the same session. The first runs `message`; a later run
3377
+ * continues the session after the model provider refused a run for capacity.
3378
+ */
3379
+ async function* turn(message, turnProfile, options) {
3380
+ const signal = options?.signal;
3381
+ const timeoutMs = options?.timeoutMs ?? 0;
3382
+ const turnDeadline = timeoutMs > 0 ? Date.now() + timeoutMs : void 0;
3383
+ let sessionId;
3384
+ const subagents = /* @__PURE__ */ new Set();
3385
+ let refusalsInARow = 0;
3386
+ let prompt = message;
3387
+ for (let invocation = 1;; invocation += 1) {
3388
+ const launch = await materializeWorker(box, paths, turnProfile, prompt, options?.backend?.model, clientName, sessionId);
3389
+ signal?.throwIfAborted();
3390
+ const remainingMs = turnDeadline === void 0 ? 0 : Math.max(1, turnDeadline - Date.now());
3391
+ const process = await run(launch.args, remainingMs, { OPENCODE_CONFIG_CONTENT: launch.config });
3392
+ running = process;
3393
+ const onAbort = () => {
3394
+ process.kill("SIGKILL", { tree: true }).catch(() => void 0);
3395
+ };
3396
+ signal?.addEventListener("abort", onAbort, { once: true });
3397
+ const stderr = drain(box.output(process, "stderr"));
3398
+ const lines = lineReader();
3399
+ const parsed = createOpencodeEventParser(launch.model);
3400
+ let exitCode;
3401
+ let errorText;
3402
+ try {
3403
+ for await (const chunk of box.output(process, "stdout")) for (const line of lines.push(chunk)) yield* parsed.line(line);
3404
+ for (const line of lines.end()) yield* parsed.line(line);
3405
+ exitCode = await box.wait(process);
3406
+ errorText = (await stderr).slice(-4e3);
3407
+ } finally {
3408
+ signal?.removeEventListener("abort", onAbort);
3409
+ running = void 0;
3410
+ }
3411
+ sessionId = parsed.sessionId() ?? sessionId;
3412
+ for (const child of parsed.subagentSessionIds()) subagents.add(child);
3413
+ const failure = parsed.failure(exitCode, errorText);
3414
+ const refusal = failure === void 0 || unavailablePause === false || signal?.aborted ? void 0 : unavailableSignalOfFailure({ error: failure });
3415
+ refusalsInARow = parsed.madeProgress() ? 1 : refusalsInARow + 1;
3416
+ const pauseMs = refusal === void 0 || unavailablePause === false ? 0 : unavailablePauseMs(refusalsInARow, unavailablePause);
3417
+ if (refusal === void 0 || turnDeadline !== void 0 && Date.now() + pauseMs >= turnDeadline) {
3418
+ if (sessionId !== void 0) await exportSession(run, collect, paths, sessionId);
3419
+ for (const child of subagents) if (child !== sessionId) await exportSession(run, collect, paths, child);
3420
+ signal?.throwIfAborted();
3421
+ yield* parsed.finish(exitCode, errorText, invocation);
3422
+ return;
3423
+ }
3424
+ await sleep(pauseMs, signal);
3425
+ signal?.throwIfAborted();
3426
+ if (released) throw new ValidationError("sharedBoxPlacement: this worker was released");
3427
+ prompt = sessionId === void 0 ? message : LEAF_CONTINUATION_TASK;
3428
+ }
3429
+ }
3430
+ return {
3431
+ id: `${box.id}/${workerId}`,
3432
+ name: workerId,
3433
+ status: "running",
3434
+ metadata: {
3435
+ sharedBoxId: box.id,
3436
+ workerId,
3437
+ workerDir: paths.dir
3438
+ },
3439
+ async *streamPrompt(message, options) {
3440
+ if (released) throw new ValidationError("sharedBoxPlacement: this worker was released");
3441
+ if (turnActive) throw new ValidationError("sharedBoxPlacement: a worker runs one turn at a time");
3442
+ const turnProfile = options?.backend?.profile === void 0 ? createProfile : agentProfileSchema.parse(options.backend.profile);
3443
+ if (canonicalAgentProfileDigest(turnProfile) !== canonicalAgentProfileDigest(createProfile) && sharedBoxRefusal(turnProfile) !== void 0) throw new ValidationError(`sharedBoxPlacement: ${sharedBoxRefusal(turnProfile)}`);
3444
+ if (options?.backend?.type !== void 0 && options.backend.type !== HARNESS) throw new ValidationError(`sharedBoxPlacement: backend ${options.backend.type} is not ${HARNESS}`);
3445
+ turnActive = true;
3446
+ try {
3447
+ yield* turn(message, turnProfile, options);
3448
+ } finally {
3449
+ turnActive = false;
3450
+ }
3451
+ },
3452
+ async exec(command, options) {
3453
+ const process = await run([
3454
+ "/bin/sh",
3455
+ "-c",
3456
+ command
3457
+ ], options?.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS);
3458
+ return await collect(process);
3459
+ },
3460
+ async read(path) {
3461
+ return await box.fs.read(resolvePath(path));
3462
+ },
3463
+ async write(path, content) {
3464
+ await box.fs.write(resolvePath(path), content);
3465
+ },
3466
+ async refresh() {},
3467
+ async delete() {
3468
+ if (released) return;
3469
+ released = true;
3470
+ try {
3471
+ await running?.kill("SIGKILL", { tree: true });
3472
+ await box.exec(`rm -rf '${paths.dir}'`, { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS });
3473
+ } finally {
3474
+ await lease.release();
3475
+ }
3476
+ }
3477
+ };
3478
+ }
3479
+ /**
3480
+ * The Sandbox calls one worker makes, each repeated on a transient failure.
3481
+ *
3482
+ * A launch is repeated only after the pool confirms the box did not start it: a failed request
3483
+ * may have reached the box before its answer was lost, so the repeat first looks for a process
3484
+ * in the worker's own directory that this worker did not start yet, and adopts it. A process log
3485
+ * that breaks mid-stream is read again from the start, because the box replays a process's
3486
+ * buffered output, and the part already delivered is skipped.
3487
+ */
3488
+ function resilientBox(box, delayMs) {
3489
+ const retry = (operation) => transientRetry(operation, { delayMs });
3490
+ return {
3491
+ id: box.id,
3492
+ exec: (command, options) => retry(() => box.exec(command, options)),
3493
+ fs: {
3494
+ read: (path) => retry(() => box.fs.read(path)),
3495
+ write: (path, content) => retry(() => box.fs.write(path, content))
3496
+ },
3497
+ async spawnInDirectory(executable, args, options, known) {
3498
+ return await transientRetry(async (attempt) => {
3499
+ if (attempt > 1) {
3500
+ const launched = (await box.process.list()).find((entry) => entry.cwd === options.cwd && entry.command === executable && !known.has(entry.pid));
3501
+ const adopted = launched === void 0 ? null : await box.process.get(launched.pid);
3502
+ if (adopted !== null) return adopted;
3503
+ }
3504
+ return await box.process.spawnExact(executable, args, options);
3505
+ }, { delayMs });
3506
+ },
3507
+ async wait(process) {
3508
+ return await retry(async () => {
3509
+ try {
3510
+ return await process.wait();
3511
+ } catch (error) {
3512
+ if (!isTransientSandboxFailure(error)) throw error;
3513
+ const again = await box.process.get(process.pid);
3514
+ if (again === null) throw error;
3515
+ return await again.wait();
3516
+ }
3517
+ });
3518
+ },
3519
+ async *output(process, stream) {
3520
+ let delivered = 0;
3521
+ let source = process;
3522
+ for (let attempt = 1;; attempt += 1) {
3523
+ let seen = 0;
3524
+ try {
3525
+ for await (const chunk of source[stream]()) {
3526
+ const fresh = seen + chunk.length <= delivered ? "" : chunk.slice(Math.max(0, delivered - seen));
3527
+ seen += chunk.length;
3528
+ if (fresh.length > 0) {
3529
+ delivered += fresh.length;
3530
+ yield fresh;
3531
+ }
3532
+ }
3533
+ return;
3534
+ } catch (error) {
3535
+ if (attempt >= TRANSIENT_ATTEMPTS || !isTransientSandboxFailure(error)) throw error;
3536
+ await sleep(delayMs * 2 ** (attempt - 1));
3537
+ source = await retry(() => box.process.get(process.pid)) ?? source;
3538
+ }
3539
+ }
3540
+ },
3541
+ delete: () => retry(() => box.delete())
3542
+ };
3543
+ }
3544
+ async function drain(stream) {
3545
+ let text = "";
3546
+ for await (const chunk of stream) text += chunk;
3547
+ return text;
3548
+ }
3549
+ function lineReader() {
3550
+ let pending = "";
3551
+ return {
3552
+ push(chunk) {
3553
+ pending += chunk;
3554
+ const lines = pending.split("\n");
3555
+ pending = lines.pop() ?? "";
3556
+ return lines.filter((line) => line.trim().length > 0);
3557
+ },
3558
+ end() {
3559
+ const rest = pending.trim();
3560
+ pending = "";
3561
+ return rest.length > 0 ? [rest] : [];
3562
+ }
3563
+ };
3564
+ }
3565
+ /**
3566
+ * Write the worker's materialized profile into its directory and build its launch.
3567
+ *
3568
+ * The files come from the same materializer the Sandbox sidecar uses, so a shared worker gets the
3569
+ * same instruction file, permissions and resource files a dedicated box would. The generated
3570
+ * `opencode.json` is passed as `OPENCODE_CONFIG_CONTENT` with its instruction paths made absolute,
3571
+ * because opencode resolves an instruction path in that variable against nothing.
3572
+ */
3573
+ async function materializeWorker(box, paths, profile, task, turnModel, clientName, continueSession) {
3574
+ const refusal = sharedBoxRefusal(profile);
3575
+ if (refusal !== void 0) throw new ValidationError(`sharedBoxPlacement: ${refusal}`);
3576
+ if (turnModel?.authFiles !== void 0 || turnModel?.authMode === "oauth") throw new ValidationError("sharedBoxPlacement: a shared worker cannot carry auth files");
3577
+ const plan = materializeProfile(profile, HARNESS);
3578
+ let generated = {};
3579
+ for (const file of plan.files) {
3580
+ if (file.relPath === "opencode.json" && file.source === "generated") {
3581
+ generated = JSON.parse(file.content);
3582
+ continue;
3583
+ }
3584
+ if (continueSession === void 0) await box.fs.write(`${paths.dir}/${file.relPath}`, file.content);
3585
+ }
3586
+ const instructions = Array.isArray(generated.instructions) ? generated.instructions.map((entry) => typeof entry === "string" && !entry.startsWith("/") ? `${paths.dir}/${entry}` : entry) : void 0;
3587
+ const providerId = profile.model.provider;
3588
+ const modelId = profileProviderModel(profile);
3589
+ const apiKeyEnv = typeof turnModel?.apiKeyEnv === "string" ? turnModel.apiKeyEnv : "OPENCODE_MODEL_API_KEY";
3590
+ const baseURL = typeof turnModel?.baseUrl === "string" ? turnModel.baseUrl : "{env:OPENCODE_MODEL_BASE_URL}";
3591
+ const config = {
3592
+ $schema: "https://opencode.ai/config.json",
3593
+ ...generated,
3594
+ ...instructions === void 0 ? {} : { instructions },
3595
+ permission: {
3596
+ external_directory: {
3597
+ "*": "deny",
3598
+ "/tmp/**": "allow"
3599
+ },
3600
+ ...generated.permission ?? {}
3601
+ },
3602
+ provider: { [providerId]: {
3603
+ npm: "@ai-sdk/openai-compatible",
3604
+ name: providerId,
3605
+ options: {
3606
+ baseURL,
3607
+ apiKey: `{env:${apiKeyEnv}}`,
3608
+ ...clientName === void 0 ? {} : { headers: { [ROUTER_CLIENT_HEADER]: clientName } }
3609
+ },
3610
+ models: { [modelId]: { name: modelId } }
3611
+ } }
3612
+ };
3613
+ const invocation = harnessInvocation(HARNESS, invocationProfile(profile), task, { dangerouslySkipPermissions: true });
3614
+ const model = `${providerId}/${modelId}`;
3615
+ if (continueSession !== void 0 && !/^[A-Za-z0-9_-]+$/u.test(continueSession)) throw new ValidationError(`sharedBoxPlacement: session id ${continueSession} is not opencode's`);
3616
+ return {
3617
+ args: [
3618
+ invocation.command,
3619
+ ...invocation.args,
3620
+ ...continueSession === void 0 ? [] : ["--session", continueSession],
3621
+ "--format",
3622
+ "json",
3623
+ "-m",
3624
+ model
3625
+ ],
3626
+ config: JSON.stringify(config),
3627
+ model
3628
+ };
3629
+ }
3630
+ /**
3631
+ * Save the harness's own record of the session where the transcript capture reads it.
3632
+ *
3633
+ * Current opencode keeps sessions in a SQLite database, which the capture cannot carry as text.
3634
+ * `opencode export` writes the same session as JSON.
3635
+ */
3636
+ async function exportSession(run, collect, paths, sessionId) {
3637
+ if (!SESSION_ID.test(sessionId)) return;
3638
+ await collect(await run([
3639
+ "/bin/sh",
3640
+ "-c",
3641
+ "mkdir -p \"$(dirname \"$2\")\" && exec opencode export \"$1\" > \"$2\"",
3642
+ "export-session",
3643
+ sessionId,
3644
+ `${paths.home}/.local/share/opencode/export/${sessionId}.json`
3645
+ ], DEFAULT_EXEC_TIMEOUT_MS));
3646
+ }
3647
+ const SESSION_ID = /^[A-Za-z0-9_-]+$/u;
3648
+ /** A subagent's session id in a `task` result (`<task id="ses_…">`) or failure (`task_id: ses_…`). */
3649
+ const TASK_SESSION = /(?:<task id="|task_id: )(ses_[A-Za-z0-9]+)/u;
3650
+ /**
3651
+ * The session a harness subagent ran in, named by its parent's `task` tool part.
3652
+ *
3653
+ * opencode starts each subagent in a child session and refuses a nested one unless the
3654
+ * configuration raises `subagent_depth` above 1, so under the default the parent's parts name
3655
+ * every subagent session. A running part carries the id in `state.metadata.sessionId`; a finished
3656
+ * one also carries it in its output, and a failed one in its error.
3657
+ */
3658
+ function subagentSessionOf(part) {
3659
+ if (part.type !== "tool" || part.tool !== "task") return void 0;
3660
+ const state = part.state;
3661
+ if (state === void 0 || state === null || typeof state !== "object") return void 0;
3662
+ const { metadata, output, error } = state;
3663
+ const named = metadata !== null && typeof metadata === "object" ? metadata.sessionId : void 0;
3664
+ if (typeof named === "string" && SESSION_ID.test(named)) return named;
3665
+ for (const text of [output, error]) {
3666
+ const match = typeof text === "string" ? TASK_SESSION.exec(text) : null;
3667
+ if (match !== null) return match[1];
3668
+ }
3669
+ }
3670
+ /**
3671
+ * Translate opencode's JSON event lines into the Sandbox event wire the provider executor reads.
3672
+ *
3673
+ * Every part becomes `message.part.updated`, which is how the sidecar forwards opencode parts, so
3674
+ * the existing trace and progress readers decode them unchanged. Each `step-finish` part also
3675
+ * becomes one canonical `llm_call` receipt with its token counts. opencode reports no dollar
3676
+ * receipt for a custom provider, so every receipt says the cost is unknown and Runtime prices the
3677
+ * tokens as an estimate instead of a bill.
3678
+ */
3679
+ function createOpencodeEventParser(model) {
3680
+ let sessionId;
3681
+ let finalMessageId;
3682
+ const textByMessage = /* @__PURE__ */ new Map();
3683
+ const subagentSessions = /* @__PURE__ */ new Set();
3684
+ const errors = [];
3685
+ let malformed = 0;
3686
+ let spentTokens = false;
3687
+ const failureOf = (exitCode, stderr) => {
3688
+ if (exitCode !== 0) {
3689
+ const said = [...errors, stderr.trim().slice(-1e3)].filter((text) => text.length > 0);
3690
+ return `opencode exited ${exitCode}${said.length > 0 ? `: ${said.join("; ")}` : ""}`;
3691
+ }
3692
+ return errors.length > 0 && finalMessageId === void 0 ? errors.join("; ") : void 0;
3693
+ };
3694
+ return {
3695
+ sessionId: () => sessionId,
3696
+ subagentSessionIds: () => [...subagentSessions],
3697
+ /** Why this run failed, or `undefined` when it answered. */
3698
+ failure: failureOf,
3699
+ /** Whether this run spent any model tokens before it ended. */
3700
+ madeProgress: () => spentTokens,
3701
+ *line(raw) {
3702
+ let event;
3703
+ try {
3704
+ event = JSON.parse(raw);
3705
+ } catch {
3706
+ malformed += 1;
3707
+ return;
3708
+ }
3709
+ if (typeof event.sessionID === "string") sessionId ??= event.sessionID;
3710
+ if (event.type === "error") {
3711
+ const message = errorMessage(event.error);
3712
+ errors.push(message);
3713
+ yield {
3714
+ type: "error",
3715
+ data: { message }
3716
+ };
3717
+ return;
3718
+ }
3719
+ const part = event.part;
3720
+ if (part === void 0 || part === null || typeof part !== "object") return;
3721
+ const subagent = subagentSessionOf(part);
3722
+ if (subagent !== void 0) subagentSessions.add(subagent);
3723
+ yield {
3724
+ type: "message.part.updated",
3725
+ data: { part }
3726
+ };
3727
+ const messageId = typeof part.messageID === "string" ? part.messageID : void 0;
3728
+ if (part.type === "text" && messageId !== void 0 && typeof part.text === "string") {
3729
+ const texts = textByMessage.get(messageId) ?? [];
3730
+ texts.push(part.text);
3731
+ textByMessage.set(messageId, texts);
3732
+ }
3733
+ if (part.type === "step-finish") {
3734
+ if (messageId !== void 0) finalMessageId = messageId;
3735
+ const receipt = stepReceipt(part, model);
3736
+ if (receipt !== void 0) {
3737
+ const data = receipt.data;
3738
+ if ((data?.tokensIn ?? 0) > 0 || (data?.tokensOut ?? 0) > 0) spentTokens = true;
3739
+ yield receipt;
3740
+ }
3741
+ }
3742
+ },
3743
+ /** The turn's terminal frames, from its last run. `runs` counts the runs of the session. */
3744
+ *finish(exitCode, stderr, runs = 1) {
3745
+ const finalText = (finalMessageId === void 0 ? void 0 : textByMessage.get(finalMessageId)?.join("")) ?? "";
3746
+ const failure = failureOf(exitCode, stderr);
3747
+ const counted = {
3748
+ ...malformed > 0 ? { malformedLines: malformed } : {},
3749
+ ...runs > 1 ? { sessionRuns: runs } : {}
3750
+ };
3751
+ if (failure !== void 0) {
3752
+ yield {
3753
+ type: "result",
3754
+ data: {
3755
+ success: false,
3756
+ status: "failed",
3757
+ error: failure,
3758
+ finalText,
3759
+ ...counted
3760
+ }
3761
+ };
3762
+ yield {
3763
+ type: "done",
3764
+ data: { outcome: { type: "failed" } }
3765
+ };
3766
+ return;
3767
+ }
3768
+ yield {
3769
+ type: "result",
3770
+ data: {
3771
+ success: true,
3772
+ finalText,
3773
+ ...counted
3774
+ }
3775
+ };
3776
+ yield {
3777
+ type: "done",
3778
+ data: { outcome: { type: "completed" } }
3779
+ };
3780
+ }
3781
+ };
3782
+ }
3783
+ function stepReceipt(part, model) {
3784
+ const tokens = part.tokens;
3785
+ if (tokens === void 0 || tokens === null || typeof tokens !== "object") return void 0;
3786
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
3787
+ const cache = tokens.cache ?? {};
3788
+ const input = count(tokens.input);
3789
+ const output = count(tokens.output);
3790
+ const reasoning = count(tokens.reasoning) ?? 0;
3791
+ const cacheRead = count(cache.read) ?? 0;
3792
+ const cacheWrite = count(cache.write) ?? 0;
3793
+ const known = input !== void 0 && output !== void 0;
3794
+ return {
3795
+ type: "llm_call",
3796
+ ...typeof part.id === "string" ? { id: part.id } : {},
3797
+ data: {
3798
+ usageMode: "delta",
3799
+ model,
3800
+ ...known ? {
3801
+ tokensIn: input + cacheRead + cacheWrite,
3802
+ tokensOut: output + reasoning,
3803
+ ...reasoning > 0 ? { reasoningTokens: reasoning } : {}
3804
+ } : { tokensKnown: false },
3805
+ costKnown: false
3806
+ }
3807
+ };
3808
+ }
3809
+ function errorMessage(error) {
3810
+ if (typeof error === "string") return error;
3811
+ if (error !== null && typeof error === "object") {
3812
+ const record = error;
3813
+ const data = record.data;
3814
+ const text = typeof data?.message === "string" ? data.message : typeof record.message === "string" ? record.message : typeof record.name === "string" ? record.name : "opencode reported an error";
3815
+ const status = data?.statusCode;
3816
+ return typeof status === "number" && Number.isSafeInteger(status) ? `${text} (status code ${status})` : text;
3817
+ }
3818
+ return "opencode reported an error";
3819
+ }
3820
+ //#endregion
3821
+ export { defaultAnalystInstruction as A, createSandboxPromptBackend as B, defineStrategy as C, sample as D, runAgentic as E, optimizerMethod as F, startOrResumeRuntimeSession as G, InMemoryRuntimeSessionStore as H, strategyAuthorMethod as I, touchSession as K, collectAgentTurn as L, renderReport as M, profileChatClient as N, sampleThenRefine as O, profileOptimizerModelCall as P, streamAgentTurn as R, breadthStrategy as S, refine as T, newRuntimeSession as U, normalizeBackendStreamEvent as V, nowIso as W, sandboxCheckRunner as _, sharedBoxPlacement as a, visibleCheckScore as b, canDisplace as c, defaultExtractCandidate as d, defaultStructuralRolloutPolicy as f, resolveEntrySymbol as g, officialChecksFromMeta as h, isTransientSandboxFailure as i, observe as j, ObservationError as k, compareCheckOutcomes as l, modelAuthoredChecks as m, DEFAULT_SHARED_BOX_WORKERS as n, sharedBoxRefusal as o, filterAuthoredAsserts as p, ROUTER_CLIENT_HEADER as r, sharedWorkerClientName as s, DEFAULT_SHARED_BOX_RESOURCES as t, composeCheckSources as u, selectBestIndex as v, depthStrategy as w, adaptiveRefine as x, structuralRollout as y, createIterableBackend as z };
2872
3822
 
2873
- //# sourceMappingURL=structural-rollout-D-0X6lsU.js.map
3823
+ //# sourceMappingURL=shared-box-CZFdugL1.js.map