@tangle-network/agent-runtime 0.263.0 → 0.266.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-D_sIIewf.js → activation-BERiJjx5.js} +2 -2
  2. package/dist/{activation-D_sIIewf.js.map → activation-BERiJjx5.js.map} +1 -1
  3. package/dist/{activation-DJlWM1JN.d.ts → activation-VpxSbDKJ.d.ts} +2 -2
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-L9zH0kBx.js → coordination-driver-DdZ-nh_4.js} +73 -39
  7. package/dist/coordination-driver-DdZ-nh_4.js.map +1 -0
  8. package/dist/{delegate-Cv-w2WgY.js → delegate-Ajx_PVyu.js} +3 -3
  9. package/dist/delegate-Ajx_PVyu.js.map +1 -0
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-Cusg4eAx.js → graph-CK50N9vG.js} +7 -5
  13. package/dist/graph-CK50N9vG.js.map +1 -0
  14. package/dist/{improvement-cycle-_IPwoII2.js → improvement-cycle-GRPoHLm1.js} +3 -3
  15. package/dist/{improvement-cycle-_IPwoII2.js.map → improvement-cycle-GRPoHLm1.js.map} +1 -1
  16. package/dist/{index-DLYBQFyl.d.ts → index-CU2mlMfc.d.ts} +61 -73
  17. package/dist/index.d.ts +6 -6
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +3 -3
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +4 -4
  22. package/dist/kernel.js +9 -9
  23. package/dist/{loop-runner-bin-BL8--Dzr.d.ts → loop-runner-bin-XKZXM08Q.d.ts} +3 -3
  24. package/dist/{loop-runner-bin-NWPIxiix.js → loop-runner-bin-cC16EPUq.js} +3 -3
  25. package/dist/{loop-runner-bin-NWPIxiix.js.map → loop-runner-bin-cC16EPUq.js.map} +1 -1
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +3 -3
  29. package/dist/mcp/index.d.ts +5 -5
  30. package/dist/mcp/index.js +4 -4
  31. package/dist/{openai-tools-B9x50W9Y.d.ts → openai-tools-D3ajI_D2.d.ts} +2 -2
  32. package/dist/profiles.d.ts +2 -2
  33. package/dist/{provision-supervisor-CIKvsWDa.js → provision-supervisor-Bf_bPaCv.js} +4 -4
  34. package/dist/{provision-supervisor-CIKvsWDa.js.map → provision-supervisor-Bf_bPaCv.js.map} +1 -1
  35. package/dist/{runtime-4NuCVO6X.js → runtime-hOLlAc1i.js} +938 -18
  36. package/dist/runtime-hOLlAc1i.js.map +1 -0
  37. package/dist/{server-BnYImvnx.js → server-DOb67ohd.js} +3 -3
  38. package/dist/{server-BnYImvnx.js.map → server-DOb67ohd.js.map} +1 -1
  39. package/dist/{stream-agent-turn-Y5rUc6Q-.d.ts → stream-agent-turn-Gw9hLpBn.d.ts} +182 -3
  40. package/dist/{structural-rollout-Bq3PNAun.js → structural-rollout-DV9YoQF6.js} +2 -2
  41. package/dist/{structural-rollout-Bq3PNAun.js.map → structural-rollout-DV9YoQF6.js.map} +1 -1
  42. package/dist/{substrate-Ce302oia.d.ts → substrate-CLt9S9ym.d.ts} +2 -2
  43. package/dist/{supervise-RF3_8PuR.js → supervise--njTtSL3.js} +82 -27
  44. package/dist/supervise--njTtSL3.js.map +1 -0
  45. package/dist/{supervisor-BeW08Ncp.js → supervisor-B8UMAXya.js} +995 -402
  46. package/dist/supervisor-B8UMAXya.js.map +1 -0
  47. package/dist/testing.d.ts +2 -2
  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/dist/{types-C-nszovv.d.ts → types-CrnwLVYQ.d.ts} +217 -38
  52. package/package.json +2 -2
  53. package/dist/coordination-driver-L9zH0kBx.js.map +0 -1
  54. package/dist/delegate-Cv-w2WgY.js.map +0 -1
  55. package/dist/graph-Cusg4eAx.js.map +0 -1
  56. package/dist/runtime-4NuCVO6X.js.map +0 -1
  57. package/dist/supervise-RF3_8PuR.js.map +0 -1
  58. package/dist/supervisor-BeW08Ncp.js.map +0 -1
@@ -1,16 +1,16 @@
1
- import { $i as stringifySafe, A as settledToIteration, An as canonicalObservedModelParts, Bi as notifySandboxEventObserver, Cn as createSandboxLineage, Di as executableAgentSpecSnapshot, Dn as readPromptOptions, Ei as executableAgentProfileSnapshot, En as assertBoxlessPromptOptions, Et as insideCursorNamespace, Gi as chargedTokens, Ji as hasCompleteCacheBreakdown, Ki as cloneSpend, Nt as isTraceAnalysisStore, Oi as detachedFrozen, On as routerBrain, Qi as sleep, Rn as createPushTraceSource, Sn as runAgentRounds, Tt as InMemorySpawnJournal, Wi as addSpend, Yi as isAbortError, Zi as randomSuffix, ai as prepareJsonlAppend, bn as defaultSelectWinner, fa as armDeadlineTimer, gt as createExecutorRegistry, ht as createExecutor, ia as zeroSpend, kn as runBrainLoop, n as createSupervisor, oi as readCommittedJsonLines, or as contentAddress, si as writeAllBytes, ut as rollingDispatch, vt as createWorktreeCliExecutor, wn as probeSandboxCapabilities, wt as InMemoryResultBlobStore, y as withDriverExecutor } from "./supervisor-BeW08Ncp.js";
1
+ import { $i as cloneSpend, An as routerBrain, Bn as sandboxClientAsProvider, Dt as insideCursorNamespace, En as probeSandboxCapabilities, Et as InMemorySpawnJournal, Fi as detachedFrozen, Fn as LEAF_CONTINUATION_TASK, Hn as unavailableSignalOfFailure, Hr as harnessInvocation, M as settledToIteration, Mn as canonicalObservedModelParts, Ni as executableAgentProfileSnapshot, On as assertBoxlessPromptOptions, Pi as executableAgentSpecSnapshot, Pt as isTraceAnalysisStore, Qi as chargedTokens, Sn as defaultSelectWinner, Tn as createSandboxLineage, Tt as InMemoryResultBlobStore, Un as createPushTraceSource, Vn as unavailablePauseMs, Zi as addSpend, _t as createExecutorRegistry, aa as sleep, b as withDriverExecutor, da as zeroSpend, dt as rollingDispatch, fi as prepareJsonlAppend, fr as contentAddress, gt as createExecutor, ia as randomSuffix, jn as runBrainLoop, kn as readPromptOptions, mi as writeAllBytes, na as isAbortError, oa as stringifySafe, pi as readCommittedJsonLines, qi as notifySandboxEventObserver, r as createSupervisor, ta as hasCompleteCacheBreakdown, wn as runAgentRounds, ya as armDeadlineTimer, yt as createWorktreeCliExecutor } from "./supervisor-B8UMAXya.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-Bq3PNAun.js";
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-DV9YoQF6.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 { C as gateOnDeliverable, r as supervise, w as mapExecutorResult } from "./supervise-RF3_8PuR.js";
9
- import "./coordination-driver-L9zH0kBx.js";
8
+ import "./coordination-driver-DdZ-nh_4.js";
9
+ import { C as gateOnDeliverable, r as supervise, w as mapExecutorResult } from "./supervise--njTtSL3.js";
10
10
  import "./run-layout-vwd4SwX_.js";
11
- import "./provision-supervisor-CIKvsWDa.js";
12
- import "./delegate-Cv-w2WgY.js";
13
- import "./graph-Cusg4eAx.js";
11
+ import "./provision-supervisor-Bf_bPaCv.js";
12
+ import "./delegate-Ajx_PVyu.js";
13
+ import "./graph-CK50N9vG.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";
@@ -3192,7 +3194,7 @@ function fanout(items, opts) {
3192
3194
  if (res.ok) opened += 1;
3193
3195
  else rejected.push(`${unit.opts.label}: not admitted (${res.reason})`);
3194
3196
  }
3195
- drained = opened === 0 ? emptyRound() : await drain(scope);
3197
+ drained = opened === 0 ? emptyRound() : await drain$1(scope);
3196
3198
  }
3197
3199
  if (opened === 0) return blocked(rejected.length > 0 ? rejected : ["fanout: budget admitted no item (fanout fully rejected)"]);
3198
3200
  if (drained.done.length === 0) return blocked(orderedBlockers(drained.blockers, rejected, "fanout: every item settled without a usable result"));
@@ -3454,7 +3456,7 @@ function splitOnce(text, sep) {
3454
3456
  if (at < 0) return [text, ""];
3455
3457
  return [text.slice(0, at), text.slice(at + sep.length)];
3456
3458
  }
3457
- async function drain(scope) {
3459
+ async function drain$1(scope) {
3458
3460
  const iterations = [];
3459
3461
  const done = [];
3460
3462
  const blockers = [];
@@ -3894,7 +3896,7 @@ async function runPersonified(options) {
3894
3896
  executors,
3895
3897
  ...options.rootIdentity !== void 0 ? { rootIdentity: options.rootIdentity } : {},
3896
3898
  ...options.maxDepth !== void 0 ? { maxDepth: options.maxDepth } : {},
3897
- ...options.maxLiveWorkers !== void 0 ? { maxLiveWorkers: options.maxLiveWorkers } : {},
3899
+ ...options.workerSlots !== void 0 ? { workerSlots: options.workerSlots } : {},
3898
3900
  ...options.maxRestarts !== void 0 ? { maxRestarts: options.maxRestarts } : {},
3899
3901
  ...options.withinMs !== void 0 ? { withinMs: options.withinMs } : {},
3900
3902
  ...options.teardownConfirmMs !== void 0 ? { teardownConfirmMs: options.teardownConfirmMs } : {},
@@ -4731,7 +4733,7 @@ async function openSandboxRun(client, options, deliverable) {
4731
4733
  eventTypes: eventTypeCounts(result.events),
4732
4734
  ...result.readError !== void 0 ? { readError: result.readError } : {}
4733
4735
  } : {},
4734
- ...error !== void 0 ? { error: errorMessage(error) } : {}
4736
+ ...error !== void 0 ? { error: errorMessage$1(error) } : {}
4735
4737
  });
4736
4738
  async function settle(box, events, turnIndex, turnKind) {
4737
4739
  const collected = [];
@@ -4839,7 +4841,7 @@ async function openSandboxRun(client, options, deliverable) {
4839
4841
  payload: {
4840
4842
  ...runPayload(),
4841
4843
  turnCount,
4842
- error: errorMessage(error)
4844
+ error: errorMessage$1(error)
4843
4845
  }
4844
4846
  });
4845
4847
  throw error;
@@ -4883,7 +4885,7 @@ async function openSandboxRun(client, options, deliverable) {
4883
4885
  payload: {
4884
4886
  ...runPayload(),
4885
4887
  turnCount,
4886
- error: errorMessage(error)
4888
+ error: errorMessage$1(error)
4887
4889
  }
4888
4890
  });
4889
4891
  throw error;
@@ -4921,10 +4923,928 @@ function hashText(value) {
4921
4923
  }
4922
4924
  return (hash >>> 0).toString(16).padStart(8, "0");
4923
4925
  }
4924
- function errorMessage(error) {
4926
+ function errorMessage$1(error) {
4925
4927
  return error instanceof Error ? error.message : String(error);
4926
4928
  }
4927
4929
  //#endregion
4930
+ //#region src/runtime/shared-box.ts
4931
+ /**
4932
+ * Shared-box placement: many harness workers in one Sandbox box, each as its own process.
4933
+ *
4934
+ * The default provider placement gives every worker its own Sandbox box. A box costs a create
4935
+ * call, a sidecar, an egress proxy, a preview link and a memory reservation sized for the box,
4936
+ * while one opencode worker uses about half a gigabyte. This module packs workers into a small
4937
+ * pool of boxes instead. Each worker runs `opencode run` as a separate process with its own
4938
+ * working directory and its own HOME, so each worker has its own harness session, its own
4939
+ * materialized profile and its own transcript files.
4940
+ *
4941
+ * Why processes and not sidecar sessions: the sidecar serves every session in one box from one
4942
+ * workspace and writes each session's profile into the same files. Measured 2026-09-24 on
4943
+ * sandbox-ff52a989e7c9: eight concurrent sessions with different instructions, and seven of eight
4944
+ * answered with another session's instructions. A process with its own directory, its own HOME and
4945
+ * `OPENCODE_DISABLE_PROJECT_CONFIG` reads only its own configuration: sixteen of sixteen concurrent
4946
+ * workers answered with their own instructions and wrote only into their own directory.
4947
+ *
4948
+ * The boundary is cooperative, not a security boundary. Every worker runs as the same Linux user,
4949
+ * so a worker can read a co-tenant's files through its shell. A profile that writes a repository,
4950
+ * runs untrusted code, holds a credential of its own, or must stay blind to its siblings keeps a
4951
+ * dedicated box: {@link SharedBoxPlacement.refusal} names the profile features this placement
4952
+ * cannot carry, and Runtime then uses the dedicated provider.
4953
+ *
4954
+ * A worker whose model provider refuses a turn for capacity keeps its process's session and
4955
+ * directory, pauses by the driver's rule, and continues the same opencode session, the way a
4956
+ * dedicated leaf does (`ProviderExecutorOptions.unavailablePause`). Measured 2026-09-24: 15 of 23
4957
+ * down children of play anomaly-referee-v3d ended on `provider_quota_exhausted`, and opencode
4958
+ * itself gives up on a refused model after about 70 seconds of its own retries.
4959
+ *
4960
+ * The workers of one box share the box's router key. Each worker names itself to the router with
4961
+ * the `x-tangle-client` header, which the router stores as `clientName` on every usage row, so a
4962
+ * keeper can price one worker from the key's per-client rows (`tangle-admin router-spend --key
4963
+ * <box key>`). A request without the header stays charged to the box.
4964
+ *
4965
+ * `workersPerBox` is the one structural cap, and it protects the box. A Tangle box has a fixed
4966
+ * 512-task pids limit. An idle box uses about 118 tasks and one opencode worker about 34, so
4967
+ * twelve workers reach the limit. At that limit the sidecar's own process spawn fails with EAGAIN
4968
+ * and the sidecar restarts, which ends every worker in the box (measured on the same box: 28
4969
+ * workers crashed the sidecar twice; 16 workers crashed it once).
4970
+ */
4971
+ /**
4972
+ * The most workers one default box carries at once.
4973
+ *
4974
+ * It keeps a worker count that the 512-task pids limit of a Tangle box can hold with headroom
4975
+ * for the sidecar's own processes and the workers' tool shells: 118 idle tasks plus 8 workers at
4976
+ * about 34 tasks each is 390. Memory is not the binding limit: 8 workers used about 4 GB in a
4977
+ * 16 GB box. Raise it only for a box whose pids limit was raised with it.
4978
+ */
4979
+ const DEFAULT_SHARED_BOX_WORKERS = 8;
4980
+ /** The box shape the default placement creates: memory for 8 workers at about 0.5 GB each plus
4981
+ * the sidecar, and 4 cores, because the workers wait on the model most of the time. */
4982
+ const DEFAULT_SHARED_BOX_RESOURCES = Object.freeze({
4983
+ cpuCores: 4,
4984
+ memoryMB: 8192
4985
+ });
4986
+ const DEFAULT_WORKER_ROOT = "/home/agent/workers";
4987
+ const HARNESS = "opencode";
4988
+ const SHARED_PROVIDER_NAME = "tangle-shared-box";
4989
+ const DEFAULT_EXEC_TIMEOUT_MS = 12e4;
4990
+ /** The request header the router records as a usage row's `clientName`. */
4991
+ const ROUTER_CLIENT_HEADER = "x-tangle-client";
4992
+ /**
4993
+ * The router client name of the worker that runs supervised node `nodeId`.
4994
+ *
4995
+ * The node id is already in the spawn journal, so a keeper joins a router row to a node without
4996
+ * a new record: the row whose `clientName` is `agent-runtime-node/<nodeId>` is that node's spend.
4997
+ */
4998
+ function sharedWorkerClientName(nodeId) {
4999
+ if (!/^[!-~]+$/u.test(nodeId)) throw new ValidationError("sharedWorkerClientName: a node id must be visible ASCII");
5000
+ return `agent-runtime-node/${nodeId}`;
5001
+ }
5002
+ /**
5003
+ * Attempts for one Sandbox API call that failed on the way to the box.
5004
+ *
5005
+ * Every call re-verifies the API key with the platform, and a burst of workers makes that check
5006
+ * time out: 8 of 64 workers failed with `502 platform_unavailable` (reason `platform_timeout`) in
5007
+ * one burst on 2026-09-24, and 3 more lost their transcript enumeration the same way. The check
5008
+ * refuses the request before it reaches the box, so repeating it is safe; five attempts over about
5009
+ * fifteen seconds rode out every such failure measured.
5010
+ */
5011
+ const TRANSIENT_ATTEMPTS = 5;
5012
+ const TRANSIENT_BASE_DELAY_MS = 1e3;
5013
+ /** A failure that a repeated request can change: the platform, the gateway or the network. */
5014
+ function isTransientSandboxFailure(error) {
5015
+ if (error === null || typeof error !== "object") return false;
5016
+ const record = error;
5017
+ if (typeof record.status === "number" && [
5018
+ 408,
5019
+ 425,
5020
+ 429,
5021
+ 500,
5022
+ 502,
5023
+ 503,
5024
+ 504
5025
+ ].includes(record.status)) return true;
5026
+ const text = `${String(record.code ?? "")} ${String(record.name ?? "")} ${String(record.message ?? "")}`;
5027
+ 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);
5028
+ }
5029
+ async function transientRetry(operation, options = {}) {
5030
+ const delayMs = options.delayMs ?? TRANSIENT_BASE_DELAY_MS;
5031
+ for (let attempt = 1;; attempt += 1) try {
5032
+ return await operation(attempt);
5033
+ } catch (error) {
5034
+ if (attempt >= TRANSIENT_ATTEMPTS || !isTransientSandboxFailure(error)) throw error;
5035
+ options.signal?.throwIfAborted();
5036
+ await sleep(delayMs * 2 ** (attempt - 1), options.signal);
5037
+ }
5038
+ }
5039
+ /**
5040
+ * Why a shared box cannot carry `profile`, or `undefined` when it can.
5041
+ *
5042
+ * A shared box carries a profile whose whole behavior reaches an opencode process through its own
5043
+ * working directory, its own configuration and the box's own model credential. Everything else
5044
+ * keeps a dedicated box: another harness, a model the box credential cannot reach, a replaced
5045
+ * system prompt, MCP servers, connections, hooks, subagents, extensions, tool grants, and any
5046
+ * resource the materializer does not lower into the worker's directory.
5047
+ */
5048
+ function sharedBoxRefusal(profile) {
5049
+ if (profile.harness !== HARNESS) return `harness ${String(profile.harness)} is not ${HARNESS}`;
5050
+ if (concreteProfileModel(profile) === void 0) return "profile names no concrete model";
5051
+ if (profile.model?.provider === void 0) return "profile names no model provider";
5052
+ if (profile.model?.reasoningEffort !== void 0) {
5053
+ if (tryInvocation(profile) === void 0) return "model.reasoningEffort has no opencode variant";
5054
+ }
5055
+ if (profile.prompt?.systemPrompt !== void 0) return "prompt.systemPrompt replaces a system prompt";
5056
+ for (const field of [
5057
+ "mcp",
5058
+ "connections",
5059
+ "hooks",
5060
+ "subagents",
5061
+ "extensions",
5062
+ "confidential",
5063
+ "modes"
5064
+ ]) if (profile[field] !== void 0) return `profile declares ${field}`;
5065
+ if (profile.tools !== void 0 && Object.keys(profile.tools).length > 0) return "profile grants tools";
5066
+ const resources = profile.resources;
5067
+ if (resources !== void 0) {
5068
+ for (const field of [
5069
+ "skills",
5070
+ "agents",
5071
+ "commands",
5072
+ "tools"
5073
+ ]) if (resources[field] !== void 0) return `profile declares resources.${field}`;
5074
+ for (const file of resources.files ?? []) if (file.resource.kind !== "inline") return `resource file ${file.path} is not inline`;
5075
+ if (resources.instructions !== void 0 && typeof resources.instructions !== "string" && resources.instructions.kind !== "inline") return "resources.instructions is not inline";
5076
+ }
5077
+ let plan;
5078
+ try {
5079
+ plan = materializeProfile(profile, HARNESS);
5080
+ } catch (error) {
5081
+ return `opencode materialization failed: ${error instanceof Error ? error.message : String(error)}`;
5082
+ }
5083
+ if (plan.unsupported.length > 0) return `opencode cannot carry ${plan.unsupported.map((row) => row.dimension).join(", ")}`;
5084
+ if (Object.keys(plan.env).length > 0 || plan.flags.length > 0) return "profile needs launch environment or flags";
5085
+ for (const file of plan.files) {
5086
+ if (file.root === "agent") return `profile writes ${file.relPath} into the harness home`;
5087
+ if ((file.secretSlots?.length ?? 0) > 0) return `profile file ${file.relPath} carries a secret`;
5088
+ if (isUnsafeRelativePath(file.relPath)) return `profile file ${file.relPath} leaves its directory`;
5089
+ }
5090
+ }
5091
+ function tryInvocation(profile) {
5092
+ try {
5093
+ return harnessInvocation(HARNESS, invocationProfile(profile), "probe").args;
5094
+ } catch {
5095
+ return;
5096
+ }
5097
+ }
5098
+ /**
5099
+ * The profile the invocation table reads. The prompt reaches opencode through its configuration
5100
+ * and the model through the provider this placement declares, so only the reasoning effort is
5101
+ * left for the table to lower into `--variant`.
5102
+ */
5103
+ function invocationProfile(profile) {
5104
+ const { prompt: _prompt, model, ...rest } = profile;
5105
+ return {
5106
+ ...rest,
5107
+ ...model?.reasoningEffort === void 0 ? {} : { model: { reasoningEffort: model.reasoningEffort } }
5108
+ };
5109
+ }
5110
+ function isUnsafeRelativePath(path) {
5111
+ return path.length === 0 || path.startsWith("/") || path.split("/").some((segment) => segment === ".." || segment === "");
5112
+ }
5113
+ /**
5114
+ * Place accepted workers as processes in a pool of shared Sandbox boxes.
5115
+ *
5116
+ * The pool fills a box before it creates the next one and deletes a box when its last worker
5117
+ * releases it. Runtime reaches this placement through `createExecutor({ backend: 'provider',
5118
+ * shared })`: a profile that {@link SharedBoxPlacement.refusal} accepts runs here, and every other
5119
+ * profile keeps the dedicated provider.
5120
+ */
5121
+ function sharedBoxPlacement(options) {
5122
+ const workersPerBox = options.workersPerBox ?? 8;
5123
+ if (!Number.isSafeInteger(workersPerBox) || workersPerBox < 1) throw new ValidationError("sharedBoxPlacement: workersPerBox must be a positive integer");
5124
+ const workerRoot = options.workerRoot ?? DEFAULT_WORKER_ROOT;
5125
+ if (!workerRoot.startsWith("/") || isUnsafeRelativePath(workerRoot.slice(1))) throw new ValidationError("sharedBoxPlacement: workerRoot must be an absolute, normalized path");
5126
+ const boxOptions = {
5127
+ resources: { ...DEFAULT_SHARED_BOX_RESOURCES },
5128
+ ...options.box ?? {}
5129
+ };
5130
+ if (boxOptions.backend !== void 0) throw new ValidationError("sharedBoxPlacement: box.backend is owned by Runtime");
5131
+ const identity = {
5132
+ id: "shared-box",
5133
+ digest: canonicalCandidateDigest({
5134
+ kind: "shared-box-placement.v1",
5135
+ harness: HARNESS,
5136
+ workersPerBox,
5137
+ workerRoot,
5138
+ box: publicBoxOptions(boxOptions)
5139
+ })
5140
+ };
5141
+ const retryDelayMs = options.retryDelayMs ?? TRANSIENT_BASE_DELAY_MS;
5142
+ const pool = createBoxPool(options.client, boxOptions, workersPerBox, retryDelayMs);
5143
+ const providerFor = (worker = {}) => {
5144
+ const clientName = worker.nodeId === void 0 ? void 0 : sharedWorkerClientName(worker.nodeId);
5145
+ return sandboxClientAsProvider({ async create(createOptions) {
5146
+ const profile = workerProfile(createOptions);
5147
+ const refusal = sharedBoxRefusal(profile);
5148
+ if (refusal !== void 0) throw new ValidationError(`sharedBoxPlacement: ${refusal}`);
5149
+ assertWorkerCreateOptions(createOptions);
5150
+ const lease = await pool.acquire();
5151
+ try {
5152
+ return await createWorker(lease, workerRoot, profile, {
5153
+ retryDelayMs,
5154
+ clientName,
5155
+ unavailablePause: options.unavailablePause ?? {}
5156
+ });
5157
+ } catch (error) {
5158
+ await lease.release();
5159
+ throw error;
5160
+ }
5161
+ } }, {
5162
+ name: SHARED_PROVIDER_NAME,
5163
+ capabilities: sharedBoxCapabilities()
5164
+ });
5165
+ };
5166
+ return {
5167
+ providerFor,
5168
+ identity,
5169
+ refusal: sharedBoxRefusal,
5170
+ stats: () => pool.stats(),
5171
+ close: () => pool.close()
5172
+ };
5173
+ }
5174
+ function publicBoxOptions(box) {
5175
+ const { env, secrets, ...rest } = box;
5176
+ return {
5177
+ ...rest,
5178
+ ...env === void 0 ? {} : { environmentVariableNames: Object.keys(env).sort() },
5179
+ ...secrets === void 0 ? {} : { secrets }
5180
+ };
5181
+ }
5182
+ function sharedBoxCapabilities() {
5183
+ return {
5184
+ profile: {
5185
+ namedProfiles: false,
5186
+ systemPrompt: {
5187
+ ...harnessSystemPromptIntents$1(HARNESS),
5188
+ replace: false
5189
+ },
5190
+ instructions: true,
5191
+ tools: false,
5192
+ permissions: true,
5193
+ mcp: false,
5194
+ subagents: false,
5195
+ resources: {
5196
+ files: true,
5197
+ instructions: true
5198
+ },
5199
+ runtimeUpdate: false,
5200
+ validation: false
5201
+ },
5202
+ streaming: {
5203
+ live: true,
5204
+ replay: false,
5205
+ detach: false,
5206
+ turnIdempotency: false
5207
+ },
5208
+ sessions: {
5209
+ continue: false,
5210
+ list: false,
5211
+ messages: false
5212
+ },
5213
+ workspace: {
5214
+ read: true,
5215
+ write: true,
5216
+ exec: true,
5217
+ git: false,
5218
+ upload: false,
5219
+ download: false
5220
+ },
5221
+ branching: {
5222
+ checkpoint: false,
5223
+ fork: false
5224
+ },
5225
+ placement: true,
5226
+ usage: true,
5227
+ confidential: false
5228
+ };
5229
+ }
5230
+ function workerProfile(createOptions) {
5231
+ const raw = (createOptions?.backend)?.profile;
5232
+ const parsed = agentProfileSchema.safeParse(raw);
5233
+ if (!parsed.success) throw new ValidationError("sharedBoxPlacement: an exact AgentProfile is required at create");
5234
+ return parsed.data;
5235
+ }
5236
+ /**
5237
+ * A worker create carries only what a slot in a shared box can honor. Box-level settings belong
5238
+ * to the placement's own box options, and a per-worker request for them is refused rather than
5239
+ * dropped: a worker that asked for an environment variable, a repository or its own resources
5240
+ * would otherwise run without them and report nothing.
5241
+ */
5242
+ function assertWorkerCreateOptions(createOptions) {
5243
+ const options = createOptions ?? {};
5244
+ for (const key of [
5245
+ "git",
5246
+ "fromSnapshot",
5247
+ "fromSandboxId",
5248
+ "environment",
5249
+ "cwd",
5250
+ "resources"
5251
+ ]) if (options[key] !== void 0) throw new ValidationError(`sharedBoxPlacement: a shared worker cannot set ${key}`);
5252
+ const env = options.env;
5253
+ if (env !== void 0 && Object.keys(env).length > 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot set env");
5254
+ const secrets = options.secrets;
5255
+ if (Array.isArray(secrets) && secrets.length > 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot request secrets");
5256
+ const backend = options.backend;
5257
+ if (backend?.runtimeAttachments !== void 0) throw new ValidationError("sharedBoxPlacement: a shared worker cannot carry runtime attachments");
5258
+ if (backend?.type !== void 0 && backend.type !== HARNESS) throw new ValidationError(`sharedBoxPlacement: backend ${String(backend.type)} is not ${HARNESS}`);
5259
+ }
5260
+ function createBoxPool(client, boxOptions, workersPerBox, retryDelayMs) {
5261
+ const poolId = randomUUID();
5262
+ const boxes = [];
5263
+ const history = [];
5264
+ let seq = 0;
5265
+ let placed = 0;
5266
+ let peak = 0;
5267
+ let closing = false;
5268
+ const retire = async (entry) => {
5269
+ if (entry.retired) return void 0;
5270
+ entry.retired = true;
5271
+ const index = boxes.indexOf(entry);
5272
+ if (index >= 0) boxes.splice(index, 1);
5273
+ let handle;
5274
+ try {
5275
+ handle = await entry.ready;
5276
+ } catch {
5277
+ return;
5278
+ }
5279
+ try {
5280
+ await transientRetry(() => handle.delete(), { delayMs: retryDelayMs });
5281
+ entry.deleted = true;
5282
+ return {
5283
+ boxId: handle.id,
5284
+ deleted: true
5285
+ };
5286
+ } catch (error) {
5287
+ return {
5288
+ boxId: handle.id,
5289
+ deleted: false,
5290
+ error: error instanceof Error ? error.message : String(error)
5291
+ };
5292
+ }
5293
+ };
5294
+ return {
5295
+ async acquire() {
5296
+ if (closing) throw new ValidationError("sharedBoxPlacement: the placement is closed");
5297
+ let entry = boxes.find((candidate) => !candidate.retired && candidate.workers < workersPerBox);
5298
+ if (entry === void 0) {
5299
+ const boxSeq = seq++;
5300
+ const request = {
5301
+ ...boxOptions,
5302
+ name: boxOptions.name ?? `shared-box-${poolId.slice(0, 8)}-${boxSeq}`,
5303
+ idempotencyKey: `shared-box-${poolId}-${boxSeq}`,
5304
+ backend: {
5305
+ type: HARNESS,
5306
+ profile: {
5307
+ name: "shared-box",
5308
+ harness: HARNESS
5309
+ }
5310
+ }
5311
+ };
5312
+ const requestedAt = Date.now();
5313
+ const created = {
5314
+ seq: boxSeq,
5315
+ ready: transientRetry(() => client.create(request), { delayMs: retryDelayMs }).then((box) => box),
5316
+ workers: 0,
5317
+ served: 0,
5318
+ retired: false,
5319
+ deleted: false
5320
+ };
5321
+ created.ready.then((box) => {
5322
+ created.id = box.id;
5323
+ created.createMs = Date.now() - requestedAt;
5324
+ }, () => {
5325
+ const index = boxes.indexOf(created);
5326
+ if (index >= 0) boxes.splice(index, 1);
5327
+ created.retired = true;
5328
+ });
5329
+ boxes.push(created);
5330
+ history.push(created);
5331
+ entry = created;
5332
+ }
5333
+ const leased = entry;
5334
+ leased.workers += 1;
5335
+ leased.served += 1;
5336
+ placed += 1;
5337
+ peak = Math.max(peak, leased.workers);
5338
+ let box;
5339
+ try {
5340
+ box = await leased.ready;
5341
+ } catch (error) {
5342
+ leased.workers -= 1;
5343
+ throw error;
5344
+ }
5345
+ let released = false;
5346
+ return {
5347
+ box,
5348
+ async release() {
5349
+ if (released) return;
5350
+ released = true;
5351
+ leased.workers -= 1;
5352
+ if (leased.workers === 0 && !closing) await retire(leased);
5353
+ }
5354
+ };
5355
+ },
5356
+ stats() {
5357
+ return {
5358
+ boxesCreated: history.length,
5359
+ boxesLive: history.filter((entry) => !entry.retired).length,
5360
+ workersPlaced: placed,
5361
+ workersLive: history.reduce((sum, entry) => sum + entry.workers, 0),
5362
+ peakWorkersPerBox: peak,
5363
+ boxes: history.filter((entry) => entry.id !== void 0).map((entry) => ({
5364
+ id: entry.id,
5365
+ workersServed: entry.served,
5366
+ deleted: entry.deleted,
5367
+ createMs: entry.createMs ?? 0
5368
+ }))
5369
+ };
5370
+ },
5371
+ async close() {
5372
+ closing = true;
5373
+ return (await Promise.all(history.map((entry) => retire(entry)))).filter((receipt) => receipt !== void 0);
5374
+ }
5375
+ };
5376
+ }
5377
+ /** The environment one worker's processes see: its own directory, HOME and XDG roots. */
5378
+ function workerEnv(paths) {
5379
+ return [
5380
+ "OPENCODE_DISABLE_PROJECT_CONFIG=1",
5381
+ `OPENCODE_CONFIG_DIR=${paths.dir}/.opencode`,
5382
+ `PWD=${paths.dir}`,
5383
+ `HOME=${paths.home}`,
5384
+ `XDG_DATA_HOME=${paths.home}/.local/share`,
5385
+ `XDG_CONFIG_HOME=${paths.home}/.config`,
5386
+ `XDG_STATE_HOME=${paths.home}/.local/state`,
5387
+ `XDG_CACHE_HOME=${paths.cache}`
5388
+ ];
5389
+ }
5390
+ async function createWorker(lease, root, createProfile, placement) {
5391
+ const { clientName, unavailablePause } = placement;
5392
+ const box = resilientBox(lease.box, placement.retryDelayMs);
5393
+ const workerId = `w-${randomUUID()}`;
5394
+ const paths = {
5395
+ dir: `${root}/${workerId}`,
5396
+ home: `${root}/${workerId}/.home`,
5397
+ cache: `${root}/.cache`
5398
+ };
5399
+ const made = await box.exec(`mkdir -p '${paths.home}' '${paths.cache}'`, { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS });
5400
+ if ((made.exitCode ?? 1) !== 0) throw new Error(`sharedBoxPlacement: could not create ${paths.dir}: ${made.stderr ?? ""}`);
5401
+ const env = workerEnv(paths);
5402
+ let running;
5403
+ let turnActive = false;
5404
+ let released = false;
5405
+ const started = /* @__PURE__ */ new Set();
5406
+ const run = async (args, timeoutMs, extraEnv) => {
5407
+ const process = await box.spawnInDirectory("/usr/bin/env", [...env, ...args], {
5408
+ cwd: paths.dir,
5409
+ ...extraEnv === void 0 ? {} : { env: extraEnv },
5410
+ timeoutMs
5411
+ }, started);
5412
+ started.add(process.pid);
5413
+ return process;
5414
+ };
5415
+ const collect = async (process) => {
5416
+ const [stdout, stderr, exitCode] = await Promise.all([
5417
+ drain(box.output(process, "stdout")),
5418
+ drain(box.output(process, "stderr")),
5419
+ box.wait(process)
5420
+ ]);
5421
+ return {
5422
+ exitCode,
5423
+ stdout,
5424
+ stderr
5425
+ };
5426
+ };
5427
+ const resolvePath = (path) => {
5428
+ if (path.startsWith("/")) return path;
5429
+ if (isUnsafeRelativePath(path)) throw new ValidationError(`sharedBoxPlacement: path ${path} leaves the worker directory`);
5430
+ return `${paths.dir}/${path}`;
5431
+ };
5432
+ /**
5433
+ * One turn: one or more opencode runs of the same session. The first runs `message`; a later run
5434
+ * continues the session after the model provider refused a run for capacity.
5435
+ */
5436
+ async function* turn(message, turnProfile, options) {
5437
+ const signal = options?.signal;
5438
+ const timeoutMs = options?.timeoutMs ?? 0;
5439
+ const turnDeadline = timeoutMs > 0 ? Date.now() + timeoutMs : void 0;
5440
+ let sessionId;
5441
+ let refusalsInARow = 0;
5442
+ let prompt = message;
5443
+ for (let invocation = 1;; invocation += 1) {
5444
+ const launch = await materializeWorker(box, paths, turnProfile, prompt, options?.backend?.model, clientName, sessionId);
5445
+ signal?.throwIfAborted();
5446
+ const remainingMs = turnDeadline === void 0 ? 0 : Math.max(1, turnDeadline - Date.now());
5447
+ const process = await run(launch.args, remainingMs, { OPENCODE_CONFIG_CONTENT: launch.config });
5448
+ running = process;
5449
+ const onAbort = () => {
5450
+ process.kill("SIGKILL", { tree: true }).catch(() => void 0);
5451
+ };
5452
+ signal?.addEventListener("abort", onAbort, { once: true });
5453
+ const stderr = drain(box.output(process, "stderr"));
5454
+ const lines = lineReader();
5455
+ const parsed = createOpencodeEventParser(launch.model);
5456
+ let exitCode;
5457
+ let errorText;
5458
+ try {
5459
+ for await (const chunk of box.output(process, "stdout")) for (const line of lines.push(chunk)) yield* parsed.line(line);
5460
+ for (const line of lines.end()) yield* parsed.line(line);
5461
+ exitCode = await box.wait(process);
5462
+ errorText = (await stderr).slice(-4e3);
5463
+ } finally {
5464
+ signal?.removeEventListener("abort", onAbort);
5465
+ running = void 0;
5466
+ }
5467
+ sessionId = parsed.sessionId() ?? sessionId;
5468
+ const failure = parsed.failure(exitCode, errorText);
5469
+ const refusal = failure === void 0 || unavailablePause === false || signal?.aborted ? void 0 : unavailableSignalOfFailure({ error: failure });
5470
+ refusalsInARow = parsed.madeProgress() ? 1 : refusalsInARow + 1;
5471
+ const pauseMs = refusal === void 0 || unavailablePause === false ? 0 : unavailablePauseMs(refusalsInARow, unavailablePause);
5472
+ if (refusal === void 0 || turnDeadline !== void 0 && Date.now() + pauseMs >= turnDeadline) {
5473
+ if (sessionId !== void 0) await exportSession(run, collect, paths, sessionId);
5474
+ signal?.throwIfAborted();
5475
+ yield* parsed.finish(exitCode, errorText, invocation);
5476
+ return;
5477
+ }
5478
+ await sleep(pauseMs, signal);
5479
+ signal?.throwIfAborted();
5480
+ if (released) throw new ValidationError("sharedBoxPlacement: this worker was released");
5481
+ prompt = sessionId === void 0 ? message : LEAF_CONTINUATION_TASK;
5482
+ }
5483
+ }
5484
+ return {
5485
+ id: `${box.id}/${workerId}`,
5486
+ name: workerId,
5487
+ status: "running",
5488
+ metadata: {
5489
+ sharedBoxId: box.id,
5490
+ workerId,
5491
+ workerDir: paths.dir
5492
+ },
5493
+ async *streamPrompt(message, options) {
5494
+ if (released) throw new ValidationError("sharedBoxPlacement: this worker was released");
5495
+ if (turnActive) throw new ValidationError("sharedBoxPlacement: a worker runs one turn at a time");
5496
+ const turnProfile = options?.backend?.profile === void 0 ? createProfile : agentProfileSchema.parse(options.backend.profile);
5497
+ if (canonicalCandidateDigest(turnProfile) !== canonicalCandidateDigest(createProfile) && sharedBoxRefusal(turnProfile) !== void 0) throw new ValidationError(`sharedBoxPlacement: ${sharedBoxRefusal(turnProfile)}`);
5498
+ if (options?.backend?.type !== void 0 && options.backend.type !== HARNESS) throw new ValidationError(`sharedBoxPlacement: backend ${options.backend.type} is not ${HARNESS}`);
5499
+ turnActive = true;
5500
+ try {
5501
+ yield* turn(message, turnProfile, options);
5502
+ } finally {
5503
+ turnActive = false;
5504
+ }
5505
+ },
5506
+ async exec(command, options) {
5507
+ const process = await run([
5508
+ "/bin/sh",
5509
+ "-c",
5510
+ command
5511
+ ], options?.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS);
5512
+ return await collect(process);
5513
+ },
5514
+ async read(path) {
5515
+ return await box.fs.read(resolvePath(path));
5516
+ },
5517
+ async write(path, content) {
5518
+ await box.fs.write(resolvePath(path), content);
5519
+ },
5520
+ async refresh() {},
5521
+ async delete() {
5522
+ if (released) return;
5523
+ released = true;
5524
+ try {
5525
+ await running?.kill("SIGKILL", { tree: true });
5526
+ await box.exec(`rm -rf '${paths.dir}'`, { timeoutMs: DEFAULT_EXEC_TIMEOUT_MS });
5527
+ } finally {
5528
+ await lease.release();
5529
+ }
5530
+ }
5531
+ };
5532
+ }
5533
+ /**
5534
+ * The Sandbox calls one worker makes, each repeated on a transient failure.
5535
+ *
5536
+ * A launch is repeated only after the pool confirms the box did not start it: a failed request
5537
+ * may have reached the box before its answer was lost, so the repeat first looks for a process
5538
+ * in the worker's own directory that this worker did not start yet, and adopts it. A process log
5539
+ * that breaks mid-stream is read again from the start, because the box replays a process's
5540
+ * buffered output, and the part already delivered is skipped.
5541
+ */
5542
+ function resilientBox(box, delayMs) {
5543
+ const retry = (operation) => transientRetry(operation, { delayMs });
5544
+ return {
5545
+ id: box.id,
5546
+ exec: (command, options) => retry(() => box.exec(command, options)),
5547
+ fs: {
5548
+ read: (path) => retry(() => box.fs.read(path)),
5549
+ write: (path, content) => retry(() => box.fs.write(path, content))
5550
+ },
5551
+ async spawnInDirectory(executable, args, options, known) {
5552
+ return await transientRetry(async (attempt) => {
5553
+ if (attempt > 1) {
5554
+ const launched = (await box.process.list()).find((entry) => entry.cwd === options.cwd && entry.command === executable && !known.has(entry.pid));
5555
+ const adopted = launched === void 0 ? null : await box.process.get(launched.pid);
5556
+ if (adopted !== null) return adopted;
5557
+ }
5558
+ return await box.process.spawnExact(executable, args, options);
5559
+ }, { delayMs });
5560
+ },
5561
+ async wait(process) {
5562
+ return await retry(async () => {
5563
+ try {
5564
+ return await process.wait();
5565
+ } catch (error) {
5566
+ if (!isTransientSandboxFailure(error)) throw error;
5567
+ const again = await box.process.get(process.pid);
5568
+ if (again === null) throw error;
5569
+ return await again.wait();
5570
+ }
5571
+ });
5572
+ },
5573
+ async *output(process, stream) {
5574
+ let delivered = 0;
5575
+ let source = process;
5576
+ for (let attempt = 1;; attempt += 1) {
5577
+ let seen = 0;
5578
+ try {
5579
+ for await (const chunk of source[stream]()) {
5580
+ const fresh = seen + chunk.length <= delivered ? "" : chunk.slice(Math.max(0, delivered - seen));
5581
+ seen += chunk.length;
5582
+ if (fresh.length > 0) {
5583
+ delivered += fresh.length;
5584
+ yield fresh;
5585
+ }
5586
+ }
5587
+ return;
5588
+ } catch (error) {
5589
+ if (attempt >= TRANSIENT_ATTEMPTS || !isTransientSandboxFailure(error)) throw error;
5590
+ await sleep(delayMs * 2 ** (attempt - 1));
5591
+ source = await retry(() => box.process.get(process.pid)) ?? source;
5592
+ }
5593
+ }
5594
+ },
5595
+ delete: () => retry(() => box.delete())
5596
+ };
5597
+ }
5598
+ async function drain(stream) {
5599
+ let text = "";
5600
+ for await (const chunk of stream) text += chunk;
5601
+ return text;
5602
+ }
5603
+ function lineReader() {
5604
+ let pending = "";
5605
+ return {
5606
+ push(chunk) {
5607
+ pending += chunk;
5608
+ const lines = pending.split("\n");
5609
+ pending = lines.pop() ?? "";
5610
+ return lines.filter((line) => line.trim().length > 0);
5611
+ },
5612
+ end() {
5613
+ const rest = pending.trim();
5614
+ pending = "";
5615
+ return rest.length > 0 ? [rest] : [];
5616
+ }
5617
+ };
5618
+ }
5619
+ /**
5620
+ * Write the worker's materialized profile into its directory and build its launch.
5621
+ *
5622
+ * The files come from the same materializer the Sandbox sidecar uses, so a shared worker gets the
5623
+ * same instruction file, permissions and resource files a dedicated box would. The generated
5624
+ * `opencode.json` is passed as `OPENCODE_CONFIG_CONTENT` with its instruction paths made absolute,
5625
+ * because opencode resolves an instruction path in that variable against nothing.
5626
+ */
5627
+ async function materializeWorker(box, paths, profile, task, turnModel, clientName, continueSession) {
5628
+ const refusal = sharedBoxRefusal(profile);
5629
+ if (refusal !== void 0) throw new ValidationError(`sharedBoxPlacement: ${refusal}`);
5630
+ if (turnModel?.authFiles !== void 0 || turnModel?.authMode === "oauth") throw new ValidationError("sharedBoxPlacement: a shared worker cannot carry auth files");
5631
+ const plan = materializeProfile(profile, HARNESS);
5632
+ let generated = {};
5633
+ for (const file of plan.files) {
5634
+ if (file.relPath === "opencode.json" && file.source === "generated") {
5635
+ generated = JSON.parse(file.content);
5636
+ continue;
5637
+ }
5638
+ if (continueSession === void 0) await box.fs.write(`${paths.dir}/${file.relPath}`, file.content);
5639
+ }
5640
+ const instructions = Array.isArray(generated.instructions) ? generated.instructions.map((entry) => typeof entry === "string" && !entry.startsWith("/") ? `${paths.dir}/${entry}` : entry) : void 0;
5641
+ const providerId = profile.model.provider;
5642
+ const modelId = profileProviderModel(profile);
5643
+ const apiKeyEnv = typeof turnModel?.apiKeyEnv === "string" ? turnModel.apiKeyEnv : "OPENCODE_MODEL_API_KEY";
5644
+ const baseURL = typeof turnModel?.baseUrl === "string" ? turnModel.baseUrl : "{env:OPENCODE_MODEL_BASE_URL}";
5645
+ const config = {
5646
+ $schema: "https://opencode.ai/config.json",
5647
+ ...generated,
5648
+ ...instructions === void 0 ? {} : { instructions },
5649
+ permission: {
5650
+ external_directory: {
5651
+ "*": "deny",
5652
+ "/tmp/**": "allow"
5653
+ },
5654
+ ...generated.permission ?? {}
5655
+ },
5656
+ provider: { [providerId]: {
5657
+ npm: "@ai-sdk/openai-compatible",
5658
+ name: providerId,
5659
+ options: {
5660
+ baseURL,
5661
+ apiKey: `{env:${apiKeyEnv}}`,
5662
+ ...clientName === void 0 ? {} : { headers: { [ROUTER_CLIENT_HEADER]: clientName } }
5663
+ },
5664
+ models: { [modelId]: { name: modelId } }
5665
+ } }
5666
+ };
5667
+ const invocation = harnessInvocation(HARNESS, invocationProfile(profile), task, { dangerouslySkipPermissions: true });
5668
+ const model = `${providerId}/${modelId}`;
5669
+ if (continueSession !== void 0 && !/^[A-Za-z0-9_-]+$/u.test(continueSession)) throw new ValidationError(`sharedBoxPlacement: session id ${continueSession} is not opencode's`);
5670
+ return {
5671
+ args: [
5672
+ invocation.command,
5673
+ ...invocation.args,
5674
+ ...continueSession === void 0 ? [] : ["--session", continueSession],
5675
+ "--format",
5676
+ "json",
5677
+ "-m",
5678
+ model
5679
+ ],
5680
+ config: JSON.stringify(config),
5681
+ model
5682
+ };
5683
+ }
5684
+ /**
5685
+ * Save the harness's own record of the session where the transcript capture reads it.
5686
+ *
5687
+ * Current opencode keeps sessions in a SQLite database, which the capture cannot carry as text.
5688
+ * `opencode export` writes the same session as JSON.
5689
+ */
5690
+ async function exportSession(run, collect, paths, sessionId) {
5691
+ if (!/^[A-Za-z0-9_-]+$/u.test(sessionId)) return;
5692
+ await collect(await run([
5693
+ "/bin/sh",
5694
+ "-c",
5695
+ "mkdir -p \"$(dirname \"$2\")\" && exec opencode export \"$1\" > \"$2\"",
5696
+ "export-session",
5697
+ sessionId,
5698
+ `${paths.home}/.local/share/opencode/export/${sessionId}.json`
5699
+ ], DEFAULT_EXEC_TIMEOUT_MS));
5700
+ }
5701
+ /**
5702
+ * Translate opencode's JSON event lines into the Sandbox event wire the provider executor reads.
5703
+ *
5704
+ * Every part becomes `message.part.updated`, which is how the sidecar forwards opencode parts, so
5705
+ * the existing trace and progress readers decode them unchanged. Each `step-finish` part also
5706
+ * becomes one canonical `llm_call` receipt with its token counts. opencode reports no dollar
5707
+ * receipt for a custom provider, so every receipt says the cost is unknown and Runtime prices the
5708
+ * tokens as an estimate instead of a bill.
5709
+ */
5710
+ function createOpencodeEventParser(model) {
5711
+ let sessionId;
5712
+ let finalMessageId;
5713
+ const textByMessage = /* @__PURE__ */ new Map();
5714
+ const errors = [];
5715
+ let malformed = 0;
5716
+ let spentTokens = false;
5717
+ const failureOf = (exitCode, stderr) => {
5718
+ if (exitCode !== 0) {
5719
+ const said = [...errors, stderr.trim().slice(-1e3)].filter((text) => text.length > 0);
5720
+ return `opencode exited ${exitCode}${said.length > 0 ? `: ${said.join("; ")}` : ""}`;
5721
+ }
5722
+ return errors.length > 0 && finalMessageId === void 0 ? errors.join("; ") : void 0;
5723
+ };
5724
+ return {
5725
+ sessionId: () => sessionId,
5726
+ /** Why this run failed, or `undefined` when it answered. */
5727
+ failure: failureOf,
5728
+ /** Whether this run spent any model tokens before it ended. */
5729
+ madeProgress: () => spentTokens,
5730
+ *line(raw) {
5731
+ let event;
5732
+ try {
5733
+ event = JSON.parse(raw);
5734
+ } catch {
5735
+ malformed += 1;
5736
+ return;
5737
+ }
5738
+ if (typeof event.sessionID === "string") sessionId ??= event.sessionID;
5739
+ if (event.type === "error") {
5740
+ const message = errorMessage(event.error);
5741
+ errors.push(message);
5742
+ yield {
5743
+ type: "error",
5744
+ data: { message }
5745
+ };
5746
+ return;
5747
+ }
5748
+ const part = event.part;
5749
+ if (part === void 0 || part === null || typeof part !== "object") return;
5750
+ yield {
5751
+ type: "message.part.updated",
5752
+ data: { part }
5753
+ };
5754
+ const messageId = typeof part.messageID === "string" ? part.messageID : void 0;
5755
+ if (part.type === "text" && messageId !== void 0 && typeof part.text === "string") {
5756
+ const texts = textByMessage.get(messageId) ?? [];
5757
+ texts.push(part.text);
5758
+ textByMessage.set(messageId, texts);
5759
+ }
5760
+ if (part.type === "step-finish") {
5761
+ if (messageId !== void 0) finalMessageId = messageId;
5762
+ const receipt = stepReceipt(part, model);
5763
+ if (receipt !== void 0) {
5764
+ const data = receipt.data;
5765
+ if ((data?.tokensIn ?? 0) > 0 || (data?.tokensOut ?? 0) > 0) spentTokens = true;
5766
+ yield receipt;
5767
+ }
5768
+ }
5769
+ },
5770
+ /** The turn's terminal frames, from its last run. `runs` counts the runs of the session. */
5771
+ *finish(exitCode, stderr, runs = 1) {
5772
+ const finalText = (finalMessageId === void 0 ? void 0 : textByMessage.get(finalMessageId)?.join("")) ?? "";
5773
+ const failure = failureOf(exitCode, stderr);
5774
+ const counted = {
5775
+ ...malformed > 0 ? { malformedLines: malformed } : {},
5776
+ ...runs > 1 ? { sessionRuns: runs } : {}
5777
+ };
5778
+ if (failure !== void 0) {
5779
+ yield {
5780
+ type: "result",
5781
+ data: {
5782
+ success: false,
5783
+ status: "failed",
5784
+ error: failure,
5785
+ finalText,
5786
+ ...counted
5787
+ }
5788
+ };
5789
+ yield {
5790
+ type: "done",
5791
+ data: { outcome: { type: "failed" } }
5792
+ };
5793
+ return;
5794
+ }
5795
+ yield {
5796
+ type: "result",
5797
+ data: {
5798
+ success: true,
5799
+ finalText,
5800
+ ...counted
5801
+ }
5802
+ };
5803
+ yield {
5804
+ type: "done",
5805
+ data: { outcome: { type: "completed" } }
5806
+ };
5807
+ }
5808
+ };
5809
+ }
5810
+ function stepReceipt(part, model) {
5811
+ const tokens = part.tokens;
5812
+ if (tokens === void 0 || tokens === null || typeof tokens !== "object") return void 0;
5813
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
5814
+ const cache = tokens.cache ?? {};
5815
+ const input = count(tokens.input);
5816
+ const output = count(tokens.output);
5817
+ const reasoning = count(tokens.reasoning) ?? 0;
5818
+ const cacheRead = count(cache.read) ?? 0;
5819
+ const cacheWrite = count(cache.write) ?? 0;
5820
+ const known = input !== void 0 && output !== void 0;
5821
+ return {
5822
+ type: "llm_call",
5823
+ ...typeof part.id === "string" ? { id: part.id } : {},
5824
+ data: {
5825
+ usageMode: "delta",
5826
+ model,
5827
+ ...known ? {
5828
+ tokensIn: input + cacheRead + cacheWrite,
5829
+ tokensOut: output + reasoning,
5830
+ ...reasoning > 0 ? { reasoningTokens: reasoning } : {}
5831
+ } : { tokensKnown: false },
5832
+ costKnown: false
5833
+ }
5834
+ };
5835
+ }
5836
+ function errorMessage(error) {
5837
+ if (typeof error === "string") return error;
5838
+ if (error !== null && typeof error === "object") {
5839
+ const record = error;
5840
+ const data = record.data;
5841
+ const text = typeof data?.message === "string" ? data.message : typeof record.message === "string" ? record.message : typeof record.name === "string" ? record.name : "opencode reported an error";
5842
+ const status = data?.statusCode;
5843
+ return typeof status === "number" && Number.isSafeInteger(status) ? `${text} (status code ${status})` : text;
5844
+ }
5845
+ return "opencode reported an error";
5846
+ }
5847
+ //#endregion
4928
5848
  //#region src/runtime/authored-code.ts
4929
5849
  /**
4930
5850
  * The ONE lint over model-authored source.
@@ -6727,7 +7647,7 @@ async function superviseSurface(profile, task, opts) {
6727
7647
  makeWorkerAgent,
6728
7648
  deliverable,
6729
7649
  budget,
6730
- maxLiveWorkers: opts.maxLiveWorkers ?? 1,
7650
+ workerSlots: opts.workerSlots ?? 1,
6731
7651
  perWorker: {
6732
7652
  maxIterations: innerTurns + 2,
6733
7653
  maxTokens: workerMaxTokens
@@ -7364,6 +8284,6 @@ function tail(s) {
7364
8284
  return s.slice(-400);
7365
8285
  }
7366
8286
  //#endregion
7367
- export { InMemoryCorpus as $, chatWorkerSeam as A, pairwiseSignificance as At, SandboxRunAbortError as B, createMcpEnvironment as Bt, withUntrackedArtifacts as C, loopDispatch as Ct, codeModeSupervisorTools as D, sentinelCompletion as Dt, runCoderChecks as E, deterministicCompletion as Et, selectChampion as F, auditIntent as Ft, equalKOnCost as G, resolveSecretEnv as Gt, printBenchmarkReport as H, envKeyProvider as Ht, assertStrategyContract as I, defaultAuditorInstruction as It, runPersonified as J, trajectoryReport as K, secretEnvOfMcpServer as Kt, authorStrategy as L, McpSpawnFault as Lt, discriminatingMeans as M, renderLeaderboardMarkdown as Mt, pickChampion as N, renderLeaderboardSvg as Nt, unsafeInProcessRunner as O, stopSentinel as Ot, runStrategyEvolution as P, renderPairwiseMarkdown as Pt, FileCorpus as Q, strategyAuthorContract as R, connectStdioMcp as Rt, copyUntrackedIntoClone as S, loopCampaignDispatch as St, patchDelivered as T, completionAuthorizes as Tt, runBenchmark as U, mcpSecretEnvMetadataKey as Ut, openSandboxRun as V, sanitizeMcpToolSchema as Vt, promotionGate as W, resolveMcpServerLaunch as Wt, createShapeRegistry as X, builtinShapes as Y, registerShape as Z, NOTE_MAX_CHARS as _, harvestCorpus as _t, localShell as a, pipeline as at, composeWorkerEvidence as b, localSandboxClient as bt, createVerifierEnvironment as c, widen as ct, harvestSurfaceDiffs as d, createScopeAnalyst as dt, renderCorpusToInstructions as et, analystsFromRegistry as f, registryScopeAnalyst as ft, EVIDENCE_MAX_CHARS as g, HarvestError as gt, worktreeFanout as h, inProcessSandboxClient as ht, jjWorkspace as i, panel as it, createChatSessionStore as j, renderLeaderboardHtml as jt, chatTransportExecutor as k, leaderboard as kt, boxSurfaceReader as l, assertTraceDerivedFindings as lt, superviseSurface as m, runIsolatedCheck as mt, makeFinding$1 as n, flatWidenGate as nt, runInWorkspace as o, selectValidWinner as ot, failuresAnalyst as p, observationFromRegistry as pt, definePersona as q, createTangleSandboxExactProcessProvider as qt, gitWorkspace as r, loopUntil as rt, createWaterfallCollector as s, verify as st, computeFindingId$1 as t, fanout as tt, fsSurfaceReader as u, buildSteerContext as ut, VERIFY_TAIL_CHARS as v, defineLeaderboard as vt, analyzeTrace as w, superviseDispatch as wt, settledWorkerOut as x, inlineSandboxClient as xt, closingWorkerNote as y, resolveSandboxClient as yt, strategyAuthorSystemPrompt as z, materializeLocalMcp as zt };
8287
+ export { definePersona as $, createTangleSandboxExactProcessProvider as $t, chatWorkerSeam as A, superviseDispatch as At, DEFAULT_SHARED_BOX_RESOURCES as B, renderPairwiseMarkdown as Bt, withUntrackedArtifacts as C, harvestCorpus as Ct, codeModeSupervisorTools as D, inlineSandboxClient as Dt, runCoderChecks as E, localSandboxClient as Et, selectChampion as F, leaderboard as Ft, sharedWorkerClientName as G, materializeLocalMcp as Gt, ROUTER_CLIENT_HEADER as H, defaultAuditorInstruction as Ht, assertStrategyContract as I, pairwiseSignificance as It, printBenchmarkReport as J, envKeyProvider as Jt, SandboxRunAbortError as K, createMcpEnvironment as Kt, authorStrategy as L, renderLeaderboardHtml as Lt, discriminatingMeans as M, deterministicCompletion as Mt, pickChampion as N, sentinelCompletion as Nt, unsafeInProcessRunner as O, loopCampaignDispatch as Ot, runStrategyEvolution as P, stopSentinel as Pt, trajectoryReport as Q, secretEnvOfMcpServer as Qt, strategyAuthorContract as R, renderLeaderboardMarkdown as Rt, copyUntrackedIntoClone as S, HarvestError as St, patchDelivered as T, resolveSandboxClient as Tt, sharedBoxPlacement as U, McpSpawnFault as Ut, DEFAULT_SHARED_BOX_WORKERS as V, auditIntent as Vt, sharedBoxRefusal as W, connectStdioMcp as Wt, promotionGate as X, resolveMcpServerLaunch as Xt, runBenchmark as Y, mcpSecretEnvMetadataKey as Yt, equalKOnCost as Z, resolveSecretEnv as Zt, NOTE_MAX_CHARS as _, createScopeAnalyst as _t, localShell as a, InMemoryCorpus as at, composeWorkerEvidence as b, runIsolatedCheck as bt, createVerifierEnvironment as c, flatWidenGate as ct, harvestSurfaceDiffs as d, pipeline as dt, runPersonified as et, analystsFromRegistry as f, selectValidWinner as ft, EVIDENCE_MAX_CHARS as g, buildSteerContext as gt, worktreeFanout as h, assertTraceDerivedFindings as ht, jjWorkspace as i, FileCorpus as it, createChatSessionStore as j, completionAuthorizes as jt, chatTransportExecutor as k, loopDispatch as kt, boxSurfaceReader as l, loopUntil as lt, superviseSurface as m, widen as mt, makeFinding$1 as n, createShapeRegistry as nt, runInWorkspace as o, renderCorpusToInstructions as ot, failuresAnalyst as p, verify as pt, openSandboxRun as q, sanitizeMcpToolSchema as qt, gitWorkspace as r, registerShape as rt, createWaterfallCollector as s, fanout as st, computeFindingId$1 as t, builtinShapes as tt, fsSurfaceReader as u, panel as ut, VERIFY_TAIL_CHARS as v, registryScopeAnalyst as vt, analyzeTrace as w, defineLeaderboard as wt, settledWorkerOut as x, inProcessSandboxClient as xt, closingWorkerNote as y, observationFromRegistry as yt, strategyAuthorSystemPrompt as z, renderLeaderboardSvg as zt };
7368
8288
 
7369
- //# sourceMappingURL=runtime-4NuCVO6X.js.map
8289
+ //# sourceMappingURL=runtime-hOLlAc1i.js.map