@tangle-network/agent-runtime 0.349.0 → 0.352.1

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 (139) hide show
  1. package/dist/{activation-wBipBkCf.d.ts → activation-BidzGkUQ.d.ts} +2 -24
  2. package/dist/{activation-tNGW73Y9.js → activation-C6zNC2kx.js} +12 -14
  3. package/dist/{activation-tNGW73Y9.js.map → activation-C6zNC2kx.js.map} +1 -1
  4. package/dist/agent.d.ts +8 -12
  5. package/dist/agent.js +9 -12
  6. package/dist/agent.js.map +1 -1
  7. package/dist/{analyst-loop-DZw5QWT9.js → analyst-loop-BZvXCDKy.js} +2 -3
  8. package/dist/{analyst-loop-DZw5QWT9.js.map → analyst-loop-BZvXCDKy.js.map} +1 -1
  9. package/dist/analyst-loop.d.ts +3 -5
  10. package/dist/analyst-loop.js +1 -2
  11. package/dist/{bundle-1xaJEgjq.js → bundle-DeDkJbsr.js} +3 -4
  12. package/dist/{bundle-1xaJEgjq.js.map → bundle-DeDkJbsr.js.map} +1 -1
  13. package/dist/candidate-execution/index.d.ts +13 -33
  14. package/dist/candidate-execution/index.js +16 -18
  15. package/dist/candidate-execution/index.js.map +1 -1
  16. package/dist/chat-turn.d.ts +2 -0
  17. package/dist/chat-turn.js +1 -0
  18. package/dist/{coordination-manager-B2Z_MmL9.js → coordination-manager-B7QadgrI.js} +101 -132
  19. package/dist/{coordination-manager-B2Z_MmL9.js.map → coordination-manager-B7QadgrI.js.map} +1 -1
  20. package/dist/{delegate-Dr-63jFl.js → delegate-CoscoyEo.js} +19 -21
  21. package/dist/delegate-CoscoyEo.js.map +1 -0
  22. package/dist/durable.d.ts +16 -149
  23. package/dist/durable.js +57 -980
  24. package/dist/durable.js.map +1 -1
  25. package/dist/{errors-DodWX-cb.js → errors-AzSuGI23.js} +5 -3
  26. package/dist/errors-AzSuGI23.js.map +1 -0
  27. package/dist/execution-handle-Bd2_nUB6.js +167 -0
  28. package/dist/execution-handle-Bd2_nUB6.js.map +1 -0
  29. package/dist/execution-handle-CujvqgCn.d.ts +130 -0
  30. package/dist/{graph-DPejYB3C.js → graph-mojMML8e.js} +192 -14
  31. package/dist/graph-mojMML8e.js.map +1 -0
  32. package/dist/{improve-DwSahPi1.js → improve-Dm5ZE8mr.js} +36 -53
  33. package/dist/{improve-DwSahPi1.js.map → improve-Dm5ZE8mr.js.map} +1 -1
  34. package/dist/{improvement-adapter-sIthWkcN.d.ts → improvement-adapter-D5GRU1eY.d.ts} +2 -6
  35. package/dist/index.d.ts +41 -89
  36. package/dist/index.js +45 -61
  37. package/dist/index.js.map +1 -1
  38. package/dist/intelligence.d.ts +39 -59
  39. package/dist/intelligence.js +24 -33
  40. package/dist/intelligence.js.map +1 -1
  41. package/dist/journal-store-BJPMUydp.js +3925 -0
  42. package/dist/journal-store-BJPMUydp.js.map +1 -0
  43. package/dist/kernel.d.ts +5 -5
  44. package/dist/kernel.js +12 -11
  45. package/dist/{loop-runner-CP6MfO1b.js → loop-runner-5cL_vZi0.js} +5 -6
  46. package/dist/{loop-runner-CP6MfO1b.js.map → loop-runner-5cL_vZi0.js.map} +1 -1
  47. package/dist/{loop-runner-C6pGq-2l.d.ts → loop-runner-DyLD-aNb.d.ts} +3 -5
  48. package/dist/loop-runner-bin.d.ts +5 -8
  49. package/dist/loop-runner-bin.js +2 -3
  50. package/dist/mcp/bin.js +6 -8
  51. package/dist/mcp/bin.js.map +1 -1
  52. package/dist/mcp/index.d.ts +8 -18
  53. package/dist/mcp/index.js +17 -25
  54. package/dist/mcp/index.js.map +1 -1
  55. package/dist/mcp/memory-bin.js +4 -6
  56. package/dist/mcp/memory-bin.js.map +1 -1
  57. package/dist/{model-policy-CyCUwHed.js → model-policy-C-RGAUW4.js} +11 -13
  58. package/dist/{model-policy-CyCUwHed.js.map → model-policy-C-RGAUW4.js.map} +1 -1
  59. package/dist/placement.d.ts +12 -14
  60. package/dist/placement.js +1 -2
  61. package/dist/platform.d.ts +7 -13
  62. package/dist/platform.js +3 -6
  63. package/dist/platform.js.map +1 -1
  64. package/dist/{prepare-B9wWffjO.js → prepare-XWwsOh8O.js} +50 -69
  65. package/dist/{prepare-B9wWffjO.js.map → prepare-XWwsOh8O.js.map} +1 -1
  66. package/dist/{profile-JLJd2wFG.js → profile-C01SQZKa.js} +58 -92
  67. package/dist/profile-C01SQZKa.js.map +1 -0
  68. package/dist/{profile-materialization-bPm0gGLO.d.ts → profile-materialization-BRY22Oh8.d.ts} +1 -3
  69. package/dist/profiles.d.ts +25 -12
  70. package/dist/profiles.js +52 -11
  71. package/dist/profiles.js.map +1 -1
  72. package/dist/{protected-model-port-DVVh-hEk.d.ts → protected-model-port-IKqhTypD.d.ts} +2 -14
  73. package/dist/{protected-redaction-DFCeo4vg.js → protected-redaction-DilFZch5.js} +2 -3
  74. package/dist/{protected-redaction-DFCeo4vg.js.map → protected-redaction-DilFZch5.js.map} +1 -1
  75. package/dist/{provision-supervisor-C4v2vqDo.js → provision-supervisor-D9pO-iPl.js} +11 -15
  76. package/dist/{provision-supervisor-C4v2vqDo.js.map → provision-supervisor-D9pO-iPl.js.map} +1 -1
  77. package/dist/{run-cancellation-CzFhQGMa.js → run-cancellation-CoJRKvih.js} +6 -7
  78. package/dist/{run-cancellation-CzFhQGMa.js.map → run-cancellation-CoJRKvih.js.map} +1 -1
  79. package/dist/{runtime-CsvGCQpl.js → runtime-BJPXHWbc.js} +652 -215
  80. package/dist/runtime-BJPXHWbc.js.map +1 -0
  81. package/dist/{runtime-hooks-tXpAarhW.js → runtime-hooks-CsW2pfFk.js} +2 -3
  82. package/dist/{runtime-hooks-tXpAarhW.js.map → runtime-hooks-CsW2pfFk.js.map} +1 -1
  83. package/dist/{runtime-hooks-nsqxSUFL.d.ts → runtime-hooks-ZQqPw-0g.d.ts} +1 -3
  84. package/dist/{sandbox-profile-compat-DtuJWFrM.js → sandbox-profile-compat-CXjozdWL.js} +52 -653
  85. package/dist/sandbox-profile-compat-CXjozdWL.js.map +1 -0
  86. package/dist/{search-executor-CCb82Umc.js → search-executor-CQEHMXoT.js} +12 -15
  87. package/dist/{search-executor-CCb82Umc.js.map → search-executor-CQEHMXoT.js.map} +1 -1
  88. package/dist/{server-CKPwZU-I.js → server-U9NGgudQ.js} +19 -30
  89. package/dist/{server-CKPwZU-I.js.map → server-U9NGgudQ.js.map} +1 -1
  90. package/dist/{structural-rollout-DylC_fwU.js → structural-rollout-wMSxE7bn.js} +71 -70
  91. package/dist/structural-rollout-wMSxE7bn.js.map +1 -0
  92. package/dist/{substrate-CGDFTSRh.js → substrate-Db2pp6y3.js} +2 -3
  93. package/dist/{substrate-CGDFTSRh.js.map → substrate-Db2pp6y3.js.map} +1 -1
  94. package/dist/{supervise-BGfm2GlY.js → supervise-CNNhX0ab.js} +460 -195
  95. package/dist/supervise-CNNhX0ab.js.map +1 -0
  96. package/dist/supervision-discovery-CewADdEs.js +772 -0
  97. package/dist/supervision-discovery-CewADdEs.js.map +1 -0
  98. package/dist/{supervisor-wS9Ehz_x.js → supervisor-rK5Y8en6.js} +521 -4320
  99. package/dist/supervisor-rK5Y8en6.js.map +1 -0
  100. package/dist/{task-queue-0fKkoweu.d.ts → task-queue-kefGy79U.d.ts} +1 -3
  101. package/dist/task-queue.d.ts +1 -1
  102. package/dist/task-queue.js +1 -2
  103. package/dist/testing.d.ts +7 -15
  104. package/dist/testing.js +241 -244
  105. package/dist/testing.js.map +1 -1
  106. package/dist/tool-loop.d.ts +16 -19
  107. package/dist/tool-loop.js +2 -3
  108. package/dist/{tool-server-XV4aJwoQ.js → tool-server-CZWd_Opp.js} +3 -4
  109. package/dist/{tool-server-XV4aJwoQ.js.map → tool-server-CZWd_Opp.js.map} +1 -1
  110. package/dist/{top-snapshot-CflmaDgk.js → top-snapshot-DcV7VG4m.js} +179 -163
  111. package/dist/top-snapshot-DcV7VG4m.js.map +1 -0
  112. package/dist/tui/bin.js +50 -81
  113. package/dist/tui/bin.js.map +1 -1
  114. package/dist/tui/index.d.ts +27 -58
  115. package/dist/tui/index.js +2 -2
  116. package/dist/{types-C8BGOCBn.d.ts → types-0uzVKtFW.d.ts} +388 -484
  117. package/dist/{types-Cwrea-bU.d.ts → types-qsqfyQoY.d.ts} +1 -3
  118. package/dist/util-ebWMWzY0.js +624 -0
  119. package/dist/util-ebWMWzY0.js.map +1 -0
  120. package/dist/workspace-store/index.d.ts +12 -22
  121. package/dist/workspace-store/index.js +13 -10
  122. package/dist/workspace-store/index.js.map +1 -1
  123. package/dist/{workspace-streams-BiS4ABah.d.ts → workspace-streams-Dq2Fzk3c.d.ts} +1 -11
  124. package/package.json +31 -26
  125. package/skills/agent-graphs/SKILL.md +17 -4
  126. package/skills/be-ambitious/SKILL.md +46 -0
  127. package/skills/graph-designer/SKILL.md +9 -2
  128. package/dist/delegate-Dr-63jFl.js.map +0 -1
  129. package/dist/errors-DodWX-cb.js.map +0 -1
  130. package/dist/graph-DPejYB3C.js.map +0 -1
  131. package/dist/profile-JLJd2wFG.js.map +0 -1
  132. package/dist/record-events-D93DkpAx.js +0 -263
  133. package/dist/record-events-D93DkpAx.js.map +0 -1
  134. package/dist/runtime-CsvGCQpl.js.map +0 -1
  135. package/dist/sandbox-profile-compat-DtuJWFrM.js.map +0 -1
  136. package/dist/structural-rollout-DylC_fwU.js.map +0 -1
  137. package/dist/supervise-BGfm2GlY.js.map +0 -1
  138. package/dist/supervisor-wS9Ehz_x.js.map +0 -1
  139. package/dist/top-snapshot-CflmaDgk.js.map +0 -1
@@ -1,10 +1,10 @@
1
- import { m as ValidationError } from "./errors-DodWX-cb.js";
2
- import { runTaskQueue } from "./task-queue.js";
1
+ import { m as ValidationError } from "./errors-AzSuGI23.js";
2
+ import { p as mapWithConcurrency } from "./util-ebWMWzY0.js";
3
3
  import { agentCandidateArtifactRefSchema, canonicalCandidateBytes as canonicalCandidateBytes$1 } from "@tangle-network/agent-interface";
4
4
  import { isRecord } from "@tangle-network/agent-core";
5
5
  import { createHash, randomUUID } from "node:crypto";
6
6
  import { constants } from "node:fs";
7
- import { dirname, isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
7
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
8
8
  import { spawn } from "node:child_process";
9
9
  import { lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
10
10
  import { homedir, tmpdir } from "node:os";
@@ -12,629 +12,36 @@ import { Readable } from "node:stream";
12
12
  import { isAnyArrayBuffer, isSharedArrayBuffer } from "node:util/types";
13
13
  import { extract, pack } from "tar-stream";
14
14
  import { pipeline } from "node:stream/promises";
15
- //#region src/runtime/supervise/deadline.ts
16
- const MAX_TIMER_DELAY_MS = 2147483647;
17
- const DEFAULT_SUCCESSFUL_SHUTDOWN_MS = 5e3;
18
- /** The abort reason a child's own deadline carries. */
19
- const CHILD_DEADLINE_REASON = "child deadline exceeded";
20
- /** The abort reason the root's budget deadline cascades to every node. */
21
- const ROOT_DEADLINE_REASON = "root budget deadline exceeded";
22
- /** The check-in a child receives at its own time box. */
23
- const DEADLINE_CHECK_IN_MESSAGE = "Check-in: your time box has ended. This is not a stop. Finish the step you are on and start nothing new. Record your current state and every result you have not recorded yet, then call submit_result with what you have now; if the work is not done, mark it incomplete and name what remains. Your lead decides whether to continue you or hand the work on. You keep running while you make progress.";
24
- /** The idle bound a check-in policy sets, or undefined when time boxes are hard kills. */
25
- function checkInIdleMs(policy) {
26
- if (policy === false) return void 0;
27
- const idleMs = policy?.idleMs ?? 18e5;
28
- if (!Number.isSafeInteger(idleMs) || idleMs <= 0) throw new ValidationError("deadlineCheckIn.idleMs must be a positive safe integer of milliseconds");
29
- return idleMs;
30
- }
31
- /**
32
- * How long an abort waits for a manager whose result was already accepted to end the turn that
33
- * submitted it. Acceptance asks the turn's harness to stop; what remains is the turn's final
34
- * session copy (a bounded native capture), metering its usage and committing its result. Its
35
- * workspace capture is not part of it: the manager's owner runs that after the result.
36
- */
37
- const ACCEPTED_RESULT_GRACE_MS = 5 * 6e4;
38
- /** Whether an abort reason is a deadline: the child's own or the root budget's. */
39
- function isDeadlineAbortReason(reason) {
40
- return reason === "child deadline exceeded" || reason === "root budget deadline exceeded";
41
- }
42
- const TEARDOWN_ACKNOWLEDGEMENT_MS = 250;
43
- /** Arm a finite wall-clock deadline in safe chunks. Resource deadlines unref by default;
44
- * a standalone wait opts into keeping the process alive until it settles or is cancelled. */
45
- function armDeadlineTimer(delayMs, onDeadline, keepAlive = false) {
46
- const deadlineAtMs = Date.now() + Math.max(0, delayMs);
47
- if (!Number.isFinite(delayMs) || !Number.isSafeInteger(Math.ceil(deadlineAtMs))) throw new ValidationError("timer delay must produce a finite safe deadline");
48
- let cleared = false;
49
- let timer;
50
- const arm = () => {
51
- if (cleared) return;
52
- const remainingMs = Math.max(0, deadlineAtMs - Date.now());
53
- timer = setTimeout(() => {
54
- if (cleared) return;
55
- if (Date.now() >= deadlineAtMs) onDeadline();
56
- else arm();
57
- }, Math.min(remainingMs, MAX_TIMER_DELAY_MS));
58
- if (!keepAlive && typeof timer.unref === "function") timer.unref();
59
- };
60
- arm();
61
- return () => {
62
- cleared = true;
63
- if (timer !== void 0) clearTimeout(timer);
64
- };
65
- }
66
- /**
67
- * Resolve a spawned child's duration into one absolute cutoff. An omitted child deadline inherits
68
- * the parent cutoff; an explicit child duration may shorten, but never extend, that cutoff.
69
- */
70
- function boundedChildDeadlineAt(parentDeadlineAtMs, childDeadlineMs, nowMs) {
71
- const parent = parentDeadlineAtMs > 0 ? parentDeadlineAtMs : void 0;
72
- const child = childDeadlineMs === void 0 ? void 0 : nowMs + childDeadlineMs;
73
- if (parent === void 0) return child;
74
- if (child === void 0) return parent;
75
- return Math.min(parent, child);
76
- }
77
- /** Invoke teardown once and bound how long the runtime waits for its acknowledgement. A hard
78
- * execution deadline always wins; without one, numeric grace gets a short acknowledgement
79
- * allowance and a brutal kill gets only that allowance. Explicit `infinity` remains unbounded
80
- * only when no execution deadline exists. The losing promise stays observed. `ask` issues the
81
- * request; a scope passes its per-child single-flight asker (see `singleFlightTeardown`). */
82
- async function teardownExecutor(executor, grace, deadlineAtMs, now, ask = (requested) => Promise.resolve(executor.teardown(requested))) {
83
- const work = Promise.resolve(ask(grace));
84
- const requestedWaitMs = grace === "infinity" ? void 0 : grace === "brutalKill" ? executor.teardownTimeoutMs ?? TEARDOWN_ACKNOWLEDGEMENT_MS : grace + TEARDOWN_ACKNOWLEDGEMENT_MS;
85
- const deadlineWaitMs = deadlineAtMs === void 0 ? void 0 : Math.max(0, deadlineAtMs - now()) + TEARDOWN_ACKNOWLEDGEMENT_MS;
86
- const waitMs = requestedWaitMs === void 0 ? deadlineWaitMs : deadlineWaitMs === void 0 ? requestedWaitMs : Math.min(requestedWaitMs, deadlineWaitMs);
87
- let receipt;
88
- if (waitMs === void 0) receipt = await work;
89
- else if (waitMs <= 0) {
90
- work.catch(() => void 0);
91
- throw new ValidationError("executor teardown did not acknowledge before its deadline");
92
- } else {
93
- let clearTimer;
94
- const timedOut = new Promise((_resolve, reject) => {
95
- clearTimer = armDeadlineTimer(waitMs, () => reject(new ValidationError(`executor teardown did not acknowledge within ${waitMs}ms`)), true);
96
- });
97
- try {
98
- receipt = await Promise.race([work, timedOut]);
99
- } finally {
100
- clearTimer?.();
101
- }
102
- }
103
- if (!receipt.destroyed) throw new ValidationError(`executor teardown reported destroyed=false${receipt.detail ? `: ${receipt.detail}` : ""}`);
104
- }
105
- /**
106
- * The optional teardown surfaces a wrapping executor forwards, so wrapping never changes how a
107
- * child is released: the acknowledgement window a remote teardown needs, the release of a
108
- * retained execution at root settlement, and the environments an unconfirmed teardown names for
109
- * a sweeper. A wrapper that dropped `releaseRetained` left every retained child it wrapped
110
- * running after settlement. Each surface is present only when the inner executor implements it.
111
- */
112
- function teardownSurfaces(inner) {
113
- return {
114
- ...inner.teardownTimeoutMs === void 0 ? {} : { teardownTimeoutMs: inner.teardownTimeoutMs },
115
- ...inner.releaseRetained === void 0 ? {} : { releaseRetained: (signal) => inner.releaseRetained(signal) },
116
- ...inner.heldEnvironments === void 0 ? {} : { heldEnvironments: () => inner.heldEnvironments() },
117
- ...inner.heldForContinuation === void 0 ? {} : { heldForContinuation: () => inner.heldForContinuation() }
118
- };
119
- }
120
- /**
121
- * An asker that sends an executor at most one teardown at a time. While a request is still
122
- * running, every later ask returns that same request instead of sending another beside it.
123
- *
124
- * A settlement's own teardown has a short acknowledgement window, and a request that misses it
125
- * keeps running. Without this, the first settlement retry sent a second teardown next to the
126
- * first. An executor that does not deduplicate internally, such as one that re-issues its
127
- * cancels, then ran two teardowns at once. `onRequest` runs once for each request actually sent.
128
- */
129
- function singleFlightTeardown(executor, onRequest) {
130
- let inFlight;
131
- return (grace) => {
132
- if (inFlight !== void 0) return inFlight;
133
- onRequest();
134
- let request;
135
- try {
136
- request = Promise.resolve(executor.teardown(grace));
137
- } catch (error) {
138
- request = Promise.reject(error);
139
- }
140
- inFlight = request;
141
- const settle = () => {
142
- if (inFlight === request) inFlight = void 0;
143
- };
144
- request.then(settle, settle);
145
- return request;
146
- };
147
- }
148
- //#endregion
149
- //#region src/runtime/supervise/resources.ts
150
- /** Validate caller-owned names and units without assigning domain meaning to them. */
151
- function assertResources(resources, kind, label) {
152
- if (resources === void 0) return;
153
- if (resources === null || typeof resources !== "object" || Array.isArray(resources)) throw new Error(`${label} must be a resource map`);
154
- for (const [name, resource] of Object.entries(resources)) {
155
- if (!name.trim() || !resource || typeof resource !== "object" || typeof resource.unit !== "string" || !resource.unit.trim()) throw new Error(`${label}: resource names and units must be non-empty strings`);
156
- const value = kind === "limit" ? "limit" in resource ? resource.limit : void 0 : "amount" in resource ? resource.amount : void 0;
157
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${label}.${name}.${kind} must be a non-negative safe integer`);
158
- if (kind === "amount" && (!("known" in resource) || typeof resource.known !== "boolean")) throw new Error(`${label}.${name}.known must be a boolean`);
159
- }
160
- }
161
- /** Missing contributors are not usage claims; enforced omissions are marked before aggregation.
162
- * Overflow retains a safe lower bound and marks it unknown, preserving readable component receipts. */
163
- function addResourceSpend(...maps) {
164
- const totals = /* @__PURE__ */ new Map();
165
- for (const resources of maps) {
166
- assertResources(resources, "amount", "resource spend");
167
- for (const [name, resource] of Object.entries(resources ?? {})) {
168
- const prior = totals.get(name);
169
- if (prior && prior.unit !== resource.unit) throw new Error(`resource ${name}: unit mismatch`);
170
- const amount = (prior?.amount ?? 0) + resource.amount;
171
- totals.set(name, {
172
- unit: resource.unit,
173
- amount: Math.min(amount, Number.MAX_SAFE_INTEGER),
174
- known: (prior?.known ?? true) && resource.known && Number.isSafeInteger(amount)
175
- });
15
+ // src/agent/native-system-prompt.ts
16
+ /** Native replace and append controls shared by local and sealed candidate execution. */
17
+ function nativeSystemPrompt(harness, prompt, systemPath = ".tangle/system-prompt.md") {
18
+ const files = [];
19
+ const flags = [];
20
+ for (const intent of ["systemPrompt", "appendSystemPrompt"]) {
21
+ const text = prompt?.[intent];
22
+ if (text === void 0) continue;
23
+ if (typeof text !== "string" || intent === "appendSystemPrompt" && !text.trim()) throw new Error(`profile.prompt.${intent} must be ${intent === "systemPrompt" ? "a string" : "non-empty text"}`);
24
+ const append = intent === "appendSystemPrompt";
25
+ const path = append ? posix.join(posix.dirname(systemPath), "append-system-prompt.md") : systemPath;
26
+ if (harness === "codex" && append) {
27
+ flags.push("-c", `developer_instructions=${JSON.stringify(text)}`);
28
+ continue;
176
29
  }
177
- }
178
- return totals.size ? { resources: Object.fromEntries(totals) } : {};
179
- }
180
- /** A terminal omission under an enforced ceiling is unknown, never measured zero. */
181
- function withBudgetResources(spend, budget, notStarted = false) {
182
- const resources = new Map(Object.entries(addResourceSpend(spend.resources).resources ?? {}));
183
- for (const [name, limit] of Object.entries(budget.resources ?? {})) {
184
- const observed = resources.get(name);
185
- if (observed && observed.unit !== limit.unit) throw new Error(`resource ${name}: unit mismatch`);
186
- if (!observed) resources.set(name, {
187
- unit: limit.unit,
188
- amount: 0,
189
- known: notStarted
190
- });
191
- }
192
- return resources.size ? {
193
- ...spend,
194
- resources: Object.fromEntries(resources)
195
- } : spend;
196
- }
197
- /** Stream increments and a terminal total describe the same work; never sum them twice. */
198
- function resourceTelemetry(streamed, terminal) {
199
- const resources = new Map(Object.entries(addResourceSpend(terminal.resources).resources ?? {}));
200
- for (const [name, value] of Object.entries(streamed.resources ?? {})) {
201
- const other = resources.get(name);
202
- if (other && other.unit !== value.unit) throw new Error(`resource ${name}: unit mismatch`);
203
- resources.set(name, {
204
- ...value,
205
- amount: Math.max(value.amount, other?.amount ?? 0),
206
- known: value.known && (other?.known ?? true) && (other === void 0 || other.amount === value.amount)
207
- });
208
- }
209
- return addResourceSpend(Object.fromEntries(resources));
210
- }
211
- //#endregion
212
- //#region src/runtime/util.ts
213
- /**
214
- * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);
215
- * swallows errors (the platform reaps on expiry). Returns `false` when delete
216
- * threw, `true` otherwise, so callers can surface a leak if they choose.
217
- */
218
- async function deleteBoxSafe(box) {
219
- if (!box || typeof box.delete !== "function") return true;
220
- try {
221
- await box.delete();
222
- return true;
223
- } catch {
224
- return false;
225
- }
226
- }
227
- /** Short base36 id for trace correlation. Not cryptographic, not collision-free. */
228
- function randomSuffix(len = 8) {
229
- return Math.random().toString(36).slice(2, 2 + len);
230
- }
231
- /** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */
232
- function randomUuid() {
233
- return crypto.randomUUID();
234
- }
235
- /** Construct an AbortError carrying the abort reason's message. Downstream code pattern-matches on `err.name`. */
236
- function abortError(reason) {
237
- const err = new Error(reason instanceof Error ? reason.message : reason === void 0 ? "aborted" : String(reason));
238
- err.name = "AbortError";
239
- return err;
240
- }
241
- /** Throw an AbortError. */
242
- function throwAbort() {
243
- throw abortError();
244
- }
245
- /** Throw if the signal is already aborted; otherwise no-op. */
246
- function throwIfAborted(signal) {
247
- if (signal?.aborted) throw abortError();
248
- }
249
- /** True for any error whose `name` is `AbortError` (the cross-kernel abort contract). */
250
- function isAbortError(err) {
251
- return err instanceof Error && err.name === "AbortError";
252
- }
253
- /**
254
- * Sleep that resolves early on abort and always clears its timer so it never
255
- * keeps the event loop alive. Resolves (does not reject) on abort — callers
256
- * re-check the signal explicitly after the sleep.
257
- */
258
- function sleep(ms, signal, keepAlive = true) {
259
- if (signal?.aborted) return Promise.resolve();
260
- return new Promise((resolve) => {
261
- const done = () => {
262
- clearTimer();
263
- signal?.removeEventListener("abort", done);
264
- resolve();
265
- };
266
- const clearTimer = armDeadlineTimer(ms, done, keepAlive);
267
- signal?.addEventListener("abort", done, { once: true });
268
- });
269
- }
270
- /**
271
- * Race a promise against a timeout. Resolves with the value if it settles in
272
- * time, otherwise resolves with `undefined`. Always clears the timer.
273
- */
274
- function withTimeout(promise, ms) {
275
- return new Promise((resolve) => {
276
- const clearTimer = armDeadlineTimer(ms, () => resolve(void 0), true);
277
- promise.then((value) => {
278
- clearTimer();
279
- resolve(value);
280
- }, () => {
281
- clearTimer();
282
- resolve(void 0);
30
+ const flag = harness === "claude-code" ? append ? "--append-system-prompt-file" : "--system-prompt-file" : harness === "pi" || harness === "prime" ? append ? "--append-system-prompt" : "--system-prompt" : harness === "codex" ? "-c" : void 0;
31
+ if (!flag) throw new Error(`${harness} has no native ${intent} launch projection`);
32
+ files.push({
33
+ relPath: append ? ".tangle/append-system-prompt.md" : ".tangle/system-prompt.md",
34
+ content: text,
35
+ source: "generated"
283
36
  });
284
- });
285
- }
286
- /**
287
- * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).
288
- * Strings pass through unstringified so a preview of a string output is the
289
- * string itself, not a quoted re-encoding.
290
- */
291
- function stringifySafe(value, opts = {}) {
292
- let s;
293
- try {
294
- if (typeof value === "string") s = value;
295
- else s = (opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)) ?? String(value);
296
- } catch {
297
- s = String(value);
37
+ flags.push(flag, harness === "codex" ? `model_instructions_file=${JSON.stringify(path)}` : path);
298
38
  }
299
- if (opts.max !== void 0 && s.length > opts.max) return `${s.slice(0, opts.max)}…`;
300
- return s;
301
- }
302
- /** A fresh zero token-usage accumulator. */
303
- function zeroTokenUsage() {
304
39
  return {
305
- input: 0,
306
- output: 0
40
+ files,
41
+ flags
307
42
  };
308
43
  }
309
- /**
310
- * Sum the catalog-priced part of a dollar total across spends, as a field to spread.
311
- *
312
- * Returns nothing when no input carried one. A fold of pure provider receipts must not gain a
313
- * `usdEstimated: 0`, which would read as "this runtime checked and priced none" on a path that
314
- * never prices at all.
315
- */
316
- function usdEstimatedOf(...spends) {
317
- let total = 0;
318
- let priced = false;
319
- for (const spend of spends) {
320
- if (spend.usdEstimated === void 0) continue;
321
- priced = true;
322
- total += spend.usdEstimated;
323
- }
324
- return priced ? { usdEstimated: total } : {};
325
- }
326
- /** A conserved spend with every channel at zero and no completeness claim on it. */
327
- function zeroSpend() {
328
- return {
329
- iterations: 0,
330
- tokens: zeroTokenUsage(),
331
- usd: 0,
332
- ms: 0
333
- };
334
- }
335
- /**
336
- * The spend of work that HAPPENED and reported no usage receipt.
337
- *
338
- * Not the same value as {@link zeroSpend} even though both carry `{0,0}` tokens and `$0`. A bare
339
- * zero asserts a MEASUREMENT — "this ran and cost nothing" — and every consumer downstream reads it
340
- * that way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay
341
- * clean, the OTEL span records a priced zero, and a caller's token-denominated ceiling can never
342
- * fire no matter how much the work really burned. A ceiling that cannot fire is worse than no
343
- * ceiling, because it reads as protection.
344
- *
345
- * `tokensKnown` is the marker the substrate already threads end to end for exactly this case
346
- * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the
347
- * zero is labelled a floor rather than a total, and every rollup that touches it reports its
348
- * balance as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime
349
- * cannot see what its worker spent.
350
- *
351
- * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend
352
- * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured
353
- * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.
354
- */
355
- function unmeteredSpend(ms) {
356
- return {
357
- iterations: 0,
358
- tokens: zeroTokenUsage(),
359
- tokensKnown: false,
360
- usd: 0,
361
- usdKnown: false,
362
- ms
363
- };
364
- }
365
- /** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */
366
- function cloneSpend(spend) {
367
- return {
368
- ...addResourceSpend(spend.resources),
369
- iterations: spend.iterations,
370
- tokens: cloneTokenUsage(spend.tokens),
371
- ...spend.tokensKnown === false ? { tokensKnown: false } : {},
372
- usd: spend.usd,
373
- ...spend.usdKnown === false ? { usdKnown: false } : {},
374
- ...spend.usdEstimated !== void 0 ? { usdEstimated: spend.usdEstimated } : {},
375
- ms: spend.ms,
376
- ...boxMinutesOf(spend),
377
- ...spend.tokensProvenance === void 0 ? {} : { tokensProvenance: spend.tokensProvenance }
378
- };
379
- }
380
- /**
381
- * Sum two conserved spends per channel. Tokens and dollars never fold into each other, an
382
- * incomplete input keeps the sum incomplete on that channel, and the catalog-priced part of the
383
- * dollar total is summed separately so `usd - usdEstimated` still names what a provider billed.
384
- */
385
- function addSpend(a, b) {
386
- const tokens = cloneTokenUsage(a.tokens);
387
- addTokenUsage(tokens, b.tokens);
388
- return {
389
- ...addResourceSpend(a.resources, b.resources),
390
- iterations: a.iterations + b.iterations,
391
- tokens,
392
- ...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
393
- usd: a.usd + b.usd,
394
- ...a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {},
395
- ...usdEstimatedOf(a, b),
396
- ms: a.ms + b.ms,
397
- ...boxMinutesOf(a, b),
398
- ...tokensProvenanceOf(a, b)
399
- };
400
- }
401
- /**
402
- * Fold the token-provenance channel across spends, as a field to spread.
403
- *
404
- * Returns nothing when no contributor stated one, because ABSENT already means "the executor's own
405
- * live stream", which is what every path reported before a harness store was readable. A
406
- * contributor that stated one and a contributor that did not therefore disagree, and the sum is
407
- * `'mixed'` — the honest answer for a tree whose spend came from two kinds of receipt.
408
- */
409
- function tokensProvenanceOf(...spends) {
410
- let folded;
411
- let sawStated = false;
412
- for (const spend of spends) {
413
- const stated = spend.tokensProvenance ?? "stream-receipt";
414
- if (spend.tokensProvenance !== void 0) sawStated = true;
415
- folded = folded === void 0 || folded === stated ? stated : "mixed";
416
- }
417
- return !sawStated || folded === void 0 || folded === "stream-receipt" ? {} : { tokensProvenance: folded };
418
- }
419
- /**
420
- * Fold the platform box-time channel across spends, as a field to spread.
421
- *
422
- * Returns nothing when no input carried the channel, so a fold over router or cli-bridge work —
423
- * which runs no box at all — never gains a `boxMinutesProvenance: 'uncaptured'` that would claim
424
- * a box ran and went unmetered.
425
- *
426
- * Three rules, one per field:
427
- * - `boxMinutes` sums the numbers that are present, and stays ABSENT when none is. A missing
428
- * measurement never enters the sum as a zero.
429
- * - `boxMinutesKnown` is sticky-false, like `tokensKnown`: one contributor that could not state
430
- * its box time makes the whole sum a floor.
431
- * - `boxMinutesProvenance` degrades. `'observed'` survives only when every contributor that
432
- * carried a number was observed; one derived number makes the sum `'estimated'`; no number at
433
- * all is `'uncaptured'`.
434
- */
435
- function boxMinutesOf(...spends) {
436
- const present = spends.filter((spend) => spend.boxMinutesProvenance !== void 0);
437
- if (present.length === 0) return {};
438
- let minutes = 0;
439
- let sawNumber = false;
440
- let known = true;
441
- let observedOnly = true;
442
- for (const spend of present) {
443
- if (typeof spend.boxMinutes === "number" && Number.isFinite(spend.boxMinutes)) {
444
- minutes += spend.boxMinutes;
445
- sawNumber = true;
446
- if (spend.boxMinutesProvenance !== "observed") observedOnly = false;
447
- }
448
- if (spend.boxMinutesKnown !== true) known = false;
449
- }
450
- return {
451
- ...sawNumber ? { boxMinutes: roundBoxMinutes(minutes) } : {},
452
- boxMinutesKnown: known,
453
- boxMinutesProvenance: sawNumber ? observedOnly ? "observed" : "estimated" : "uncaptured"
454
- };
455
- }
456
- /**
457
- * Box minutes at four decimals — a tenth of a second.
458
- *
459
- * Fine enough that a box alive for two seconds reports `0.0333` instead of a zero that would read
460
- * as a measured free box, and coarse enough that summing floats does not print
461
- * `1.5000000000000002`.
462
- */
463
- function roundBoxMinutes(minutes) {
464
- return Number(minutes.toFixed(4));
465
- }
466
- /** Copy a token subtotal without dropping optional provider cache telemetry. */
467
- function cloneTokenUsage(usage) {
468
- const cacheBreakdownUnknown = usage.cacheBreakdownKnown === false || usage.input > 0 && !hasClassifiedCacheBreakdown(usage);
469
- return {
470
- input: usage.input,
471
- output: usage.output,
472
- ...usage.tokensKnown === false ? { tokensKnown: false } : {},
473
- ...usage.freshInput !== void 0 ? { freshInput: usage.freshInput } : {},
474
- ...usage.cacheRead !== void 0 ? { cacheRead: usage.cacheRead } : {},
475
- ...usage.cacheWrite !== void 0 ? { cacheWrite: usage.cacheWrite } : {},
476
- ...cacheBreakdownUnknown ? { cacheBreakdownKnown: false } : {}
477
- };
478
- }
479
- /** True only when every positive prompt token has a consistent cache classification. */
480
- function hasCompleteCacheBreakdown(usage) {
481
- if (usage.cacheBreakdownKnown === false) return false;
482
- return hasClassifiedCacheBreakdown(usage);
483
- }
484
- function hasClassifiedCacheBreakdown(usage) {
485
- if (usage.input === 0) return true;
486
- if (usage.freshInput === void 0 || usage.cacheRead === void 0 || usage.cacheWrite === void 0) return false;
487
- return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input;
488
- }
489
- /**
490
- * The token charge for one observation: every token counted ONCE, at the moment it first enters
491
- * the context — `input − cacheRead + output`.
492
- *
493
- * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,
494
- * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A
495
- * cache read is content that was already charged when it was written, so it is the one class the
496
- * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No
497
- * price weight is involved: this counts work, and money is a separate channel.
498
- *
499
- * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate
500
- * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the
501
- * records that built it — including an aggregate that mixes classified and unclassified turns,
502
- * where the unclassified remainder is charged in full and only the reported cache reads are
503
- * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn
504
- * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.
505
- *
506
- * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it
507
- * partitions credits nothing, so the charge is never below `output` and a class that overflows its
508
- * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it
509
- * never served — that provider can under-report `input` just as easily, and the token channel is an
510
- * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged
511
- * in full, so a spend with no readable split charges an upper bound on newly-presented work rather
512
- * than a measurement, and every caller that enforces a ceiling must report the difference
513
- * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).
514
- */
515
- function chargedTokens(usage) {
516
- return usage.input - creditedCacheRead(usage) + usage.output;
517
- }
518
- /** `cacheRead` if the reported classes fit inside `input`, else nothing. */
519
- function creditedCacheRead(usage) {
520
- const { cacheRead } = usage;
521
- if (cacheRead === void 0) return 0;
522
- return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead;
523
- }
524
- function classifiedTotal(usage, cacheRead) {
525
- return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0);
526
- }
527
- /**
528
- * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds
529
- * and `chargedTokens` credits.
530
- *
531
- * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`
532
- * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the
533
- * three outcomes are different facts that must not collapse into one another:
534
- *
535
- * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,
536
- * because a provider that says nothing about caching has not said the split is unknowable.
537
- * - **Read and write both reported, and fitting inside `input`** — a complete partition, so
538
- * `freshInput` is the remainder and the split is known.
539
- * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured
540
- * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports
541
- * no write) still credits the read it measured, while declaring the rest unclassified so the
542
- * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a
543
- * partition of a total it exceeds.
544
- *
545
- * A counter the provider did not report stays absent. A zero would claim the provider measured no
546
- * cache, which is a different fact from a provider that did not report.
547
- */
548
- function promptCacheTokenClasses(input, promptCache) {
549
- if (promptCache === void 0) return {};
550
- const read = tokenCount(promptCache.readTokens);
551
- const write = tokenCount(promptCache.writeTokens);
552
- if (read === void 0 && write === void 0) return {};
553
- if (input === void 0 || (read ?? 0) + (write ?? 0) > input) return { cacheBreakdownKnown: false };
554
- if (read !== void 0 && write !== void 0) return {
555
- freshInput: input - read - write,
556
- cacheRead: read,
557
- cacheWrite: write
558
- };
559
- return {
560
- ...read !== void 0 ? { cacheRead: read } : {},
561
- ...write !== void 0 ? { cacheWrite: write } : {},
562
- cacheBreakdownKnown: false
563
- };
564
- }
565
- function tokenCount(value) {
566
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
567
- }
568
- /**
569
- * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.
570
- *
571
- * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO
572
- * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a
573
- * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit
574
- * at the aggregate a cache read it refuses at the record. That is the one way the charge could come
575
- * out below the sum of the charges on the records that built it.
576
- */
577
- function addTokenUsage(acc, delta) {
578
- acc.input += delta.input ?? 0;
579
- acc.output += delta.output ?? 0;
580
- if (delta.tokensKnown === false) acc.tokensKnown = false;
581
- const input = delta.input ?? 0;
582
- const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input;
583
- if (fits) {
584
- if (delta.freshInput !== void 0) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput;
585
- if (delta.cacheRead !== void 0) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead;
586
- if (delta.cacheWrite !== void 0) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite;
587
- }
588
- const classified = fits && delta.freshInput !== void 0 && delta.cacheRead !== void 0 && delta.cacheWrite !== void 0 && delta.freshInput + delta.cacheRead + delta.cacheWrite === input;
589
- if (delta.cacheBreakdownKnown === false || input > 0 && !classified) acc.cacheBreakdownKnown = false;
590
- }
591
- /**
592
- * Map `items` through `fn` with at most `limit` calls in flight at once,
593
- * preserving input order in the result. On the first `fn` rejection no NEW
594
- * items are picked up; already-in-flight calls are awaited, then the first
595
- * error is rethrown. `limit` is clamped to ≥ 1.
596
- *
597
- * Used where a burst of provisioning (e.g. forking N child boxes) must respect
598
- * the loop's concurrency bound instead of firing all N at once.
599
- */
600
- async function mapWithConcurrency(items, limit, fn) {
601
- const results = new Array(items.length);
602
- let next = 0;
603
- for await (const settled of runTaskQueue({
604
- concurrency: Math.max(1, Math.min(Math.floor(limit), items.length)),
605
- take: () => {
606
- const index = next++;
607
- return index < items.length ? {
608
- id: String(index),
609
- value: index
610
- } : void 0;
611
- },
612
- execute: ({ value: index }) => fn(items[index], index)
613
- })) {
614
- if (settled.status === "rejected") throw settled.reason;
615
- results[settled.task.value] = settled.value;
616
- }
617
- return results;
618
- }
619
- /** The message of a thrown value: an `Error`'s own message, anything else stringified. */
620
- function errorMessage(error) {
621
- return error instanceof Error ? error.message : String(error);
622
- }
623
- /** True for an object whose `Symbol.asyncIterator` is callable, so `for await` can consume it. */
624
- function isAsyncIterable(value) {
625
- return value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
626
- }
627
- /** 32-bit FNV-1a over a string's UTF-16 code units, as eight lowercase hex digits. */
628
- function fnv1a32Hex(text) {
629
- let h = 2166136261;
630
- for (let i = 0; i < text.length; i += 1) {
631
- h ^= text.charCodeAt(i);
632
- h = Math.imul(h, 16777619);
633
- }
634
- return (h >>> 0).toString(16).padStart(8, "0");
635
- }
636
- //#endregion
637
- //#region src/path-control-characters.ts
44
+ // src/path-control-characters.ts
638
45
  /** Whether a serialized field contains an ASCII control or delete character. */
639
46
  function hasControlCharacter(value) {
640
47
  for (let index = 0; index < value.length; index++) {
@@ -643,8 +50,7 @@ function hasControlCharacter(value) {
643
50
  }
644
51
  return false;
645
52
  }
646
- //#endregion
647
- //#region src/candidate-execution/digest.ts
53
+ // src/candidate-execution/digest.ts
648
54
  /** Use native hashing for workspace archives. */
649
55
  function sha256Bytes$1(bytes) {
650
56
  return `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
@@ -693,8 +99,7 @@ function deepFreezeCandidate(value, seen = /* @__PURE__ */ new Set()) {
693
99
  for (const child of Object.values(value)) deepFreezeCandidate(child, seen);
694
100
  return Object.freeze(value);
695
101
  }
696
- //#endregion
697
- //#region src/candidate-execution/artifacts.ts
102
+ // src/candidate-execution/artifacts.ts
698
103
  function artifactCacheKey(artifact) {
699
104
  return `${artifact.sha256}:${artifact.byteLength}`;
700
105
  }
@@ -926,7 +331,7 @@ function isWithin(root, path) {
926
331
  */
927
332
  async function readWorkspaceFile(descriptor, maxBytes, keepBytes, path, signal) {
928
333
  const hash = createHash("sha256");
929
- const buffer = Buffer.allocUnsafe(1024 * 1024);
334
+ const buffer = Buffer.allocUnsafe(1048576);
930
335
  const chunks = [];
931
336
  let total = 0;
932
337
  while (true) {
@@ -949,8 +354,7 @@ async function readWorkspaceFile(descriptor, maxBytes, keepBytes, path, signal)
949
354
  byteLength: total
950
355
  };
951
356
  }
952
- //#endregion
953
- //#region src/candidate-execution/exact-object.ts
357
+ // src/candidate-execution/exact-object.ts
954
358
  /** Reject unknown fields while requiring every declared non-optional field. */
955
359
  function assertExactObjectKeys(value, required, label, optional = []) {
956
360
  if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object`);
@@ -975,8 +379,7 @@ function isWellFormedUnicode(value) {
975
379
  }
976
380
  return true;
977
381
  }
978
- //#endregion
979
- //#region src/candidate-execution/output-artifacts.ts
382
+ // src/candidate-execution/output-artifacts.ts
980
383
  /** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */
981
384
  async function persistCandidateOutputArtifact(port, input) {
982
385
  input.signal?.throwIfAborted();
@@ -995,8 +398,7 @@ async function persistCandidateOutputArtifact(port, input) {
995
398
  verifyBytes(stored, expectedDigest, bytes.byteLength, "persisted candidate output");
996
399
  return immutableCandidateValue(ref);
997
400
  }
998
- //#endregion
999
- //#region src/candidate-execution/workspace-archive.ts
401
+ // src/candidate-execution/workspace-archive.ts
1000
402
  const archiveKind = "agent-candidate-workspace-archive";
1001
403
  const workspaceEntryPrefix = "workspace/";
1002
404
  const repositoryMetadataEntry = "metadata/repository.json";
@@ -1005,13 +407,13 @@ const repositoryIndexEntry = "metadata/repository.index.json";
1005
407
  const repositoryIndexPrefix = "index/";
1006
408
  const fixedTarTime = /* @__PURE__ */ new Date(0);
1007
409
  const defaultLimits = Object.freeze({
1008
- maxArchiveBytes: 512 * 1024 * 1024,
1009
- maxEmbeddedArtifactBytes: 1024 * 1024,
410
+ maxArchiveBytes: 536870912,
411
+ maxEmbeddedArtifactBytes: 1048576,
1010
412
  maxFiles: 5e4,
1011
- maxFileBytes: 128 * 1024 * 1024,
1012
- maxTotalFileBytes: 256 * 1024 * 1024,
413
+ maxFileBytes: 134217728,
414
+ maxTotalFileBytes: 268435456,
1013
415
  maxPathBytes: 4096,
1014
- maxRepositoryBundleBytes: 128 * 1024 * 1024
416
+ maxRepositoryBundleBytes: 134217728
1015
417
  });
1016
418
  /** Capture detached files returned by a remote executor into the standard archive. */
1017
419
  async function captureAgentCandidateWorkspaceFiles(input, options = {}) {
@@ -1414,8 +816,7 @@ function workspaceTarHeader(name, mode, size) {
1414
816
  gname: ""
1415
817
  };
1416
818
  }
1417
- //#endregion
1418
- //#region src/candidate-execution/artifact-streams.ts
819
+ // src/candidate-execution/artifact-streams.ts
1419
820
  /** Verify the complete stream, including its final digest, before accepting its consumer's result. */
1420
821
  async function* verifiedArtifactChunks(artifact, port, signal) {
1421
822
  signal?.throwIfAborted();
@@ -1482,8 +883,7 @@ async function persistCandidateOutputArtifactStream(port, input) {
1482
883
  await chunks.return(void 0);
1483
884
  }
1484
885
  }
1485
- //#endregion
1486
- //#region src/candidate-execution/git-materialize.ts
886
+ // src/candidate-execution/git-materialize.ts
1487
887
  async function verifyCandidateCode(code, repositories, patchBytes) {
1488
888
  if (code.kind === "disabled") return void 0;
1489
889
  const repositoryRoot = await verifiedRepositoryRoot(code.repository, repositories);
@@ -1617,7 +1017,8 @@ async function verifiedRepositoryRoot(repository, repositories) {
1617
1017
  ])).stdout.toString("utf8").trim();
1618
1018
  const actual = parseGitHubRemote(origin);
1619
1019
  if (!actual || actual.owner !== repository.owner || actual.repo !== repository.repo) throw new Error(`local repository origin ${origin || "<missing>"} does not match github.com/${repository.owner}/${repository.repo}`);
1620
- await assertNoGitIndirection(repositoryRoot, resolve((await runCandidateGit(repositoryRoot, ["rev-parse", "--absolute-git-dir"])).stdout.toString("utf8").trim()), "candidate repository");
1020
+ const gitDirText = (await runCandidateGit(repositoryRoot, ["rev-parse", "--absolute-git-dir"])).stdout.toString("utf8").trim();
1021
+ await assertNoGitIndirection(repositoryRoot, resolve(gitDirText), "candidate repository");
1621
1022
  return repositoryRoot;
1622
1023
  }
1623
1024
  async function assertNoGitIndirection(repositoryRoot, gitDir, label) {
@@ -1811,8 +1212,7 @@ async function runCandidateGit(repositoryRoot, args, input, extraEnv = {}, optio
1811
1212
  function isNoEntry(error) {
1812
1213
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
1813
1214
  }
1814
- //#endregion
1815
- //#region src/candidate-execution/workspace-archive-local.ts
1215
+ // src/candidate-execution/workspace-archive-local.ts
1816
1216
  /** Capture one exact regular-file workspace for immutable candidate execution. */
1817
1217
  async function captureAgentCandidateWorkspace(rootInput, options = {}) {
1818
1218
  const root = resolve(rootInput);
@@ -1872,7 +1272,8 @@ async function captureRepository(requestedRoot, limits, workingTree) {
1872
1272
  const root = await realpath(requestedRoot);
1873
1273
  const resolvedStats = await lstat(root);
1874
1274
  if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) throw new Error("candidate repository root must resolve to a real directory");
1875
- if (await realpath(resolve((await runCandidateGit(root, ["rev-parse", "--show-toplevel"])).stdout.toString("utf8").trim())) !== root) throw new Error("candidate repository capture must start at the Git worktree root");
1275
+ const topLevel = (await runCandidateGit(root, ["rev-parse", "--show-toplevel"])).stdout.toString("utf8").trim();
1276
+ if (await realpath(resolve(topLevel)) !== root) throw new Error("candidate repository capture must start at the Git worktree root");
1876
1277
  const gitDir = resolve((await runCandidateGit(root, ["rev-parse", "--absolute-git-dir"])).stdout.toString("utf8").trim());
1877
1278
  if (await realpath(gitDir) !== gitDir || gitDir.includes(":")) throw new Error("candidate repository Git object store has an unsupported path");
1878
1279
  await assertNoGitIndirection(root, gitDir, "candidate repository");
@@ -2054,7 +1455,8 @@ async function prepareEmptyDestination(destination, options = {}) {
2054
1455
  throw error;
2055
1456
  }
2056
1457
  if (!stats.isDirectory() || stats.isSymbolicLink()) throw new Error("candidate workspace destination must be a real directory");
2057
- const resolvedStats = await lstat(await realpath(destination));
1458
+ const resolvedDestination = await realpath(destination);
1459
+ const resolvedStats = await lstat(resolvedDestination);
2058
1460
  if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) throw new Error("candidate workspace destination must resolve to a real directory");
2059
1461
  if ((await readdir(destination)).length > 0) throw new Error("candidate workspace destination must be empty");
2060
1462
  }
@@ -2164,8 +1566,7 @@ function workspacePath(root, relativePath) {
2164
1566
  if (!path.startsWith(`${root}${sep}`)) throw new Error(`candidate workspace archive path escapes its destination: ${relativePath}`);
2165
1567
  return path;
2166
1568
  }
2167
- //#endregion
2168
- //#region src/candidate-execution/workspace-streams.ts
1569
+ // src/candidate-execution/workspace-streams.ts
2169
1570
  /**
2170
1571
  * Files a tree capture stores at once; each waits on a durable-store round trip of its own and on
2171
1572
  * four fsyncs. On drew-gtr-pro, with three 180 ms store requests per file, 64 at once
@@ -2443,7 +1844,7 @@ async function* workspaceFileChunks(root, expected, signal) {
2443
1844
  let byteLength = 0;
2444
1845
  for await (const chunk of file.createReadStream({
2445
1846
  autoClose: false,
2446
- highWaterMark: 64 * 1024
1847
+ highWaterMark: 65536
2447
1848
  })) {
2448
1849
  signal?.throwIfAborted();
2449
1850
  byteLength += chunk.byteLength;
@@ -2496,8 +1897,7 @@ async function* oneChunk(bytes) {
2496
1897
  function asError(error) {
2497
1898
  return error instanceof Error ? error : new Error(String(error));
2498
1899
  }
2499
- //#endregion
2500
- //#region src/runtime/sandbox-profile-compat.ts
1900
+ // src/runtime/sandbox-profile-compat.ts
2501
1901
  /**
2502
1902
  * Interface 5.3 admits proxy secrets and private config values, but the current Sandbox SDK
2503
1903
  * carries Interface 4.0. Refuse these fields before either candidate conversion or a direct
@@ -2527,7 +1927,6 @@ function refuseNonPublicConfigValues(values, path, context) {
2527
1927
  function refuseSandboxProfileField(field, context = "candidate profile") {
2528
1928
  throw new ValidationError(`${context} field ${field} is refused: Sandbox's Interface 4.0.0 cannot carry it yet, and Runtime does not drop it`);
2529
1929
  }
2530
- //#endregion
2531
- export { isAbortError as $, verifyMaterializedProfileWorkspace as A, sha256Bytes$1 as B, WorkspaceScanLimitError as C, armDeadlineTimer as Ct, readMaterializedWorkspaceFiles as D, singleFlightTeardown as Dt, captureMaterializedWorkspace as E, isDeadlineAbortReason as Et, canonicalCandidateDocument as F, addTokenUsage as G, hasControlCharacter as H, deepFreezeCandidate as I, cloneTokenUsage as J, chargedTokens as K, embeddedCandidateArtifact as L, verifyWorkspaceSnapshotArtifacts as M, canonicalCandidateBytes$1 as N, readVerifiedArtifact as O, teardownExecutor as Ot, canonicalCandidateDigest$1 as P, hasCompleteCacheBreakdown as Q, immutableCandidateValue as R, isWellFormedUnicode as S, ROOT_DEADLINE_REASON as St, candidateWorkspaceManifest as T, checkInIdleMs as Tt, abortError as U, verifyCanonicalCandidateDocument as V, addSpend as W, errorMessage as X, deleteBoxSafe as Y, fnv1a32Hex as Z, captureAgentCandidateWorkspaceFiles as _, withBudgetResources as _t, materializeAgentCandidateWorkspaceFromArtifacts as a, roundBoxMinutes as at, persistCandidateOutputArtifact as b, DEADLINE_CHECK_IN_MESSAGE as bt, verifyAgentCandidateWorkspaceTree as c, throwAbort as ct, readCandidateGitHubResource as d, withTimeout as dt, isAsyncIterable as et, verifyCandidateCode as f, zeroSpend as ft, verifiedArtifactChunks as g, resourceTelemetry as gt, markPutStreamVerified as h, assertResources as ht, captureAgentCandidateWorkspaceTreeToArtifacts as i, randomUuid as it, verifyMaterializedWorkspace as j, verifyBytes as k, teardownSurfaces as kt, captureAgentCandidateWorkspace as l, throwIfAborted as lt, verifyTaskOutcomePatch as m, addResourceSpend as mt, refuseSandboxProfileField as n, promptCacheTokenClasses as nt, readAgentCandidateWorkspaceArtifactFiles as o, sleep as ot, verifyTaskCheckout as p, zeroTokenUsage as pt, cloneSpend as q, captureAgentCandidateWorkspaceToArtifacts as r, randomSuffix as rt, verifyAgentCandidateWorkspaceArtifacts as s, stringifySafe as st, assertSandboxProfileCompatibility as t, mapWithConcurrency as tt, createAgentCandidateWorkspacePort as u, unmeteredSpend as ut, verifyAgentCandidateWorkspaceArchive as v, ACCEPTED_RESULT_GRACE_MS as vt, artifactCacheKey as w, boundedChildDeadlineAt as wt, assertExactObjectKeys as x, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as xt, workspaceLimits as y, CHILD_DEADLINE_REASON as yt, omitTopLevelDigest as z };
1930
+ export { verifyMaterializedProfileWorkspace as A, sha256Bytes$1 as B, WorkspaceScanLimitError as C, readMaterializedWorkspaceFiles as D, captureMaterializedWorkspace as E, canonicalCandidateDocument as F, hasControlCharacter as H, deepFreezeCandidate as I, embeddedCandidateArtifact as L, verifyWorkspaceSnapshotArtifacts as M, canonicalCandidateBytes$1 as N, readVerifiedArtifact as O, canonicalCandidateDigest$1 as P, immutableCandidateValue as R, isWellFormedUnicode as S, candidateWorkspaceManifest as T, nativeSystemPrompt as U, verifyCanonicalCandidateDocument as V, captureAgentCandidateWorkspaceFiles as _, materializeAgentCandidateWorkspaceFromArtifacts as a, persistCandidateOutputArtifact as b, verifyAgentCandidateWorkspaceTree as c, readCandidateGitHubResource as d, verifyCandidateCode as f, verifiedArtifactChunks as g, markPutStreamVerified as h, captureAgentCandidateWorkspaceTreeToArtifacts as i, verifyMaterializedWorkspace as j, verifyBytes as k, captureAgentCandidateWorkspace as l, verifyTaskOutcomePatch as m, refuseSandboxProfileField as n, readAgentCandidateWorkspaceArtifactFiles as o, verifyTaskCheckout as p, captureAgentCandidateWorkspaceToArtifacts as r, verifyAgentCandidateWorkspaceArtifacts as s, assertSandboxProfileCompatibility as t, createAgentCandidateWorkspacePort as u, verifyAgentCandidateWorkspaceArchive as v, artifactCacheKey as w, assertExactObjectKeys as x, workspaceLimits as y, omitTopLevelDigest as z };
2532
1931
 
2533
- //# sourceMappingURL=sandbox-profile-compat-DtuJWFrM.js.map
1932
+ //# sourceMappingURL=sandbox-profile-compat-CXjozdWL.js.map