@tangle-network/agent-runtime 9.0.9 → 9.0.11

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 (101) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/{activation-CjS7d4_x.js → activation-B_10QJ3D.js} +4 -4
  3. package/dist/{activation-CjS7d4_x.js.map → activation-B_10QJ3D.js.map} +1 -1
  4. package/dist/{activation-OSYxeVWi.d.ts → activation-emYXDX7T.d.ts} +2 -2
  5. package/dist/agent.d.ts +1 -1
  6. package/dist/agent.js +4 -4
  7. package/dist/{bundle-CcpL2lfr.js → bundle-9NLb1WO3.js} +2 -2
  8. package/dist/{bundle-CcpL2lfr.js.map → bundle-9NLb1WO3.js.map} +1 -1
  9. package/dist/candidate-execution/index.js +5 -4
  10. package/dist/candidate-execution/index.js.map +1 -1
  11. package/dist/{continuation-DDPfLw2w.js → continuation-CZaeHEzQ.js} +2 -2
  12. package/dist/{continuation-DDPfLw2w.js.map → continuation-CZaeHEzQ.js.map} +1 -1
  13. package/dist/{coordination-manager-C0OJ1T9V.js → coordination-manager-BUct8qFe.js} +6 -6
  14. package/dist/{coordination-manager-C0OJ1T9V.js.map → coordination-manager-BUct8qFe.js.map} +1 -1
  15. package/dist/deadline-CySmJ_0S.js +134 -0
  16. package/dist/deadline-CySmJ_0S.js.map +1 -0
  17. package/dist/{delegate-Ct_KCtwW.js → delegate-DHtsLCyr.js} +2 -2
  18. package/dist/{delegate-Ct_KCtwW.js.map → delegate-DHtsLCyr.js.map} +1 -1
  19. package/dist/durable.d.ts +1 -1
  20. package/dist/durable.js +13 -13
  21. package/dist/{failure-cause-W0o778qO.js → failure-cause-WifbY42M.js} +2 -2
  22. package/dist/{failure-cause-W0o778qO.js.map → failure-cause-WifbY42M.js.map} +1 -1
  23. package/dist/{graph-DHvP4C1q.js → graph-D6KJ6wxN.js} +239 -306
  24. package/dist/graph-D6KJ6wxN.js.map +1 -0
  25. package/dist/{graph-registry-Dbm8QhbA.js → graph-registry-B_1C7qye.js} +1 -1
  26. package/dist/{graph-registry-D0FE9VpR.js → graph-registry-BbZN5deo.js} +282 -6
  27. package/dist/graph-registry-BbZN5deo.js.map +1 -0
  28. package/dist/{improve-DIsur006.js → improve-CUqmH45C.js} +8 -9
  29. package/dist/{improve-DIsur006.js.map → improve-CUqmH45C.js.map} +1 -1
  30. package/dist/index.d.ts +3 -3
  31. package/dist/index.js +15 -102
  32. package/dist/index.js.map +1 -1
  33. package/dist/intelligence.d.ts +2 -2
  34. package/dist/intelligence.js +7 -7
  35. package/dist/{jsonl-file-DsxVI0E_.js → jsonl-file-BhuxeejY.js} +114 -2
  36. package/dist/jsonl-file-BhuxeejY.js.map +1 -0
  37. package/dist/kernel.d.ts +2 -2
  38. package/dist/kernel.js +17 -16
  39. package/dist/{loop-runner-ku4_lGxf.js → loop-runner-CCeBurqG.js} +2 -2
  40. package/dist/{loop-runner-ku4_lGxf.js.map → loop-runner-CCeBurqG.js.map} +1 -1
  41. package/dist/{loop-runner-CCdQ1pmE.d.ts → loop-runner-Q9nlHcEH.d.ts} +2 -2
  42. package/dist/loop-runner-bin.d.ts +1 -1
  43. package/dist/loop-runner-bin.js +1 -1
  44. package/dist/mcp/bin.js +3 -3
  45. package/dist/mcp/index.d.ts +1 -1
  46. package/dist/mcp/index.js +7 -7
  47. package/dist/mcp/memory-bin.js +1 -1
  48. package/dist/output-artifacts-AqkZ8lO2.js +331 -0
  49. package/dist/output-artifacts-AqkZ8lO2.js.map +1 -0
  50. package/dist/{prepare-D7WwIddG.js → prepare-Cw4ZaN01.js} +5 -4
  51. package/dist/{prepare-D7WwIddG.js.map → prepare-Cw4ZaN01.js.map} +1 -1
  52. package/dist/{profile-BT0X-dm5.js → profile-Cxl_Ajl2.js} +2 -2
  53. package/dist/{profile-BT0X-dm5.js.map → profile-Cxl_Ajl2.js.map} +1 -1
  54. package/dist/profiles.d.ts +1 -1
  55. package/dist/{provision-supervisor-la7aXbs3.js → provision-supervisor-CNTBbuDV.js} +8 -6
  56. package/dist/{provision-supervisor-la7aXbs3.js.map → provision-supervisor-CNTBbuDV.js.map} +1 -1
  57. package/dist/{run-cancellation-CfwQmkeG.js → run-cancellation-Cy9ie5cQ.js} +3 -3
  58. package/dist/{run-cancellation-CfwQmkeG.js.map → run-cancellation-Cy9ie5cQ.js.map} +1 -1
  59. package/dist/{run-state-BCfmjm6a.js → run-state-C0nr4O7P.js} +6 -6
  60. package/dist/{run-state-BCfmjm6a.js.map → run-state-C0nr4O7P.js.map} +1 -1
  61. package/dist/{runtime-DXkdY7VT.js → runtime-C5yB7Vkk.js} +50 -25
  62. package/dist/{runtime-DXkdY7VT.js.map → runtime-C5yB7Vkk.js.map} +1 -1
  63. package/dist/{search-executor-DQH_PWxu.js → search-executor-BgEY5MKQ.js} +6 -6
  64. package/dist/{search-executor-DQH_PWxu.js.map → search-executor-BgEY5MKQ.js.map} +1 -1
  65. package/dist/{server-D4nCyP5N.js → server-X67SS4r8.js} +5 -5
  66. package/dist/{server-D4nCyP5N.js.map → server-X67SS4r8.js.map} +1 -1
  67. package/dist/{settle-record-soq9tzaX.js → settle-record-tgpwk6QF.js} +3 -3
  68. package/dist/{settle-record-soq9tzaX.js.map → settle-record-tgpwk6QF.js.map} +1 -1
  69. package/dist/{structural-rollout-D5rtwNgB.js → structural-rollout-BSzN8a0T.js} +7 -6
  70. package/dist/{structural-rollout-D5rtwNgB.js.map → structural-rollout-BSzN8a0T.js.map} +1 -1
  71. package/dist/{supervise-G9tWVS7d.js → supervise-RJG2ruTF.js} +189 -210
  72. package/dist/supervise-RJG2ruTF.js.map +1 -0
  73. package/dist/{supervision-discovery-DgkhVixZ.js → supervision-discovery-Hekh50FG.js} +5 -5
  74. package/dist/{supervision-discovery-DgkhVixZ.js.map → supervision-discovery-Hekh50FG.js.map} +1 -1
  75. package/dist/{supervisor-ByKjr-4D.js → supervisor-DbtgkJyr.js} +24 -12
  76. package/dist/supervisor-DbtgkJyr.js.map +1 -0
  77. package/dist/{supervisor-accounting-CvpkFhZU.js → supervisor-accounting-us4w7tG6.js} +8 -118
  78. package/dist/supervisor-accounting-us4w7tG6.js.map +1 -0
  79. package/dist/testing.d.ts +1 -1
  80. package/dist/testing.js +13 -13
  81. package/dist/{tool-server-Df-Uy99W.js → tool-server-CirrqFlr.js} +2 -2
  82. package/dist/{tool-server-Df-Uy99W.js.map → tool-server-CirrqFlr.js.map} +1 -1
  83. package/dist/{top-web-Cg5nyWlg.js → top-web-xSGEh02D.js} +7 -7
  84. package/dist/{top-web-Cg5nyWlg.js.map → top-web-xSGEh02D.js.map} +1 -1
  85. package/dist/tui/bin.js +3 -3
  86. package/dist/tui/index.d.ts +1 -1
  87. package/dist/tui/index.js +2 -2
  88. package/dist/{types-KQkbyDmn.d.ts → types-DMqr8Tmx.d.ts} +204 -165
  89. package/dist/{util-fcckrkKp.js → util-qsH5cC9S.js} +3 -132
  90. package/dist/util-qsH5cC9S.js.map +1 -0
  91. package/dist/{workspace-streams-DA9R3j-p.js → workspace-streams-BakRr-Pl.js} +9 -330
  92. package/dist/workspace-streams-BakRr-Pl.js.map +1 -0
  93. package/package.json +1 -1
  94. package/dist/graph-DHvP4C1q.js.map +0 -1
  95. package/dist/graph-registry-D0FE9VpR.js.map +0 -1
  96. package/dist/jsonl-file-DsxVI0E_.js.map +0 -1
  97. package/dist/supervise-G9tWVS7d.js.map +0 -1
  98. package/dist/supervisor-ByKjr-4D.js.map +0 -1
  99. package/dist/supervisor-accounting-CvpkFhZU.js.map +0 -1
  100. package/dist/util-fcckrkKp.js.map +0 -1
  101. package/dist/workspace-streams-DA9R3j-p.js.map +0 -1
@@ -1,135 +1,6 @@
1
1
  import { m as ValidationError } from "./errors-DG8yufqX.js";
2
+ import { o as armDeadlineTimer } from "./deadline-CySmJ_0S.js";
2
3
  import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
3
- // src/runtime/supervise/deadline.ts
4
- const MAX_TIMER_DELAY_MS = 2147483647;
5
- const DEFAULT_SUCCESSFUL_SHUTDOWN_MS = 5e3;
6
- /** The abort reason a child's own deadline carries. */
7
- const CHILD_DEADLINE_REASON = "child deadline exceeded";
8
- /** The abort reason the root's budget deadline cascades to every node. */
9
- const ROOT_DEADLINE_REASON = "root budget deadline exceeded";
10
- /** The check-in a child receives at its own time box. */
11
- 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.";
12
- /** The idle bound a check-in policy sets, or undefined when time boxes are hard kills. */
13
- function checkInIdleMs(policy) {
14
- if (policy === false) return void 0;
15
- const idleMs = policy?.idleMs ?? 18e5;
16
- if (!Number.isSafeInteger(idleMs) || idleMs <= 0) throw new ValidationError("deadlineCheckIn.idleMs must be a positive safe integer of milliseconds");
17
- return idleMs;
18
- }
19
- /** How long a manager whose result was accepted has to end the turn that submitted it before an
20
- * abort, or Runtime's cancel of its retained run, stops its harness: the turn's end meters its
21
- * usage and commits its result; its workspace capture runs after, in the manager's owner. */
22
- const ACCEPTED_RESULT_GRACE_MS = 3e5;
23
- /** Whether an abort reason is a deadline: the child's own or the root budget's. */
24
- function isDeadlineAbortReason(reason) {
25
- return reason === "child deadline exceeded" || reason === "root budget deadline exceeded";
26
- }
27
- const TEARDOWN_ACKNOWLEDGEMENT_MS = 250;
28
- /** Arm a finite wall-clock deadline in safe chunks. Resource deadlines unref by default;
29
- * a standalone wait opts into keeping the process alive until it settles or is cancelled. */
30
- function armDeadlineTimer(delayMs, onDeadline, keepAlive = false) {
31
- const deadlineAtMs = Date.now() + Math.max(0, delayMs);
32
- if (!Number.isFinite(delayMs) || !Number.isSafeInteger(Math.ceil(deadlineAtMs))) throw new ValidationError("timer delay must produce a finite safe deadline");
33
- let cleared = false;
34
- let timer;
35
- const arm = () => {
36
- if (cleared) return;
37
- const remainingMs = Math.max(0, deadlineAtMs - Date.now());
38
- timer = setTimeout(() => {
39
- if (cleared) return;
40
- if (Date.now() >= deadlineAtMs) onDeadline();
41
- else arm();
42
- }, Math.min(remainingMs, MAX_TIMER_DELAY_MS));
43
- if (!keepAlive && typeof timer.unref === "function") timer.unref();
44
- };
45
- arm();
46
- return () => {
47
- cleared = true;
48
- if (timer !== void 0) clearTimeout(timer);
49
- };
50
- }
51
- /**
52
- * Resolve a spawned child's duration into one absolute cutoff. An omitted child deadline inherits
53
- * the parent cutoff; an explicit child duration may shorten, but never extend, that cutoff.
54
- */
55
- function boundedChildDeadlineAt(parentDeadlineAtMs, childDeadlineMs, nowMs) {
56
- const parent = parentDeadlineAtMs > 0 ? parentDeadlineAtMs : void 0;
57
- const child = childDeadlineMs === void 0 ? void 0 : nowMs + childDeadlineMs;
58
- if (parent === void 0) return child;
59
- if (child === void 0) return parent;
60
- return Math.min(parent, child);
61
- }
62
- /** Invoke teardown once and bound how long the runtime waits for its acknowledgement. A hard
63
- * execution deadline always wins; without one, numeric grace gets a short acknowledgement
64
- * allowance and a brutal kill gets only that allowance. Explicit `infinity` remains unbounded
65
- * only when no execution deadline exists. The losing promise stays observed. `ask` issues the
66
- * request; a scope passes its per-child single-flight asker (see `singleFlightTeardown`). */
67
- async function teardownExecutor(executor, grace, deadlineAtMs, now, ask = (requested) => Promise.resolve(executor.teardown(requested))) {
68
- const work = Promise.resolve(ask(grace));
69
- const requestedWaitMs = grace === "infinity" ? void 0 : grace === "brutalKill" ? executor.teardownTimeoutMs ?? TEARDOWN_ACKNOWLEDGEMENT_MS : grace + TEARDOWN_ACKNOWLEDGEMENT_MS;
70
- const deadlineWaitMs = deadlineAtMs === void 0 ? void 0 : Math.max(0, deadlineAtMs - now()) + TEARDOWN_ACKNOWLEDGEMENT_MS;
71
- const waitMs = requestedWaitMs === void 0 ? deadlineWaitMs : deadlineWaitMs === void 0 ? requestedWaitMs : Math.min(requestedWaitMs, deadlineWaitMs);
72
- let receipt;
73
- if (waitMs === void 0) receipt = await work;
74
- else if (waitMs <= 0) {
75
- work.catch(() => void 0);
76
- throw new ValidationError("executor teardown did not acknowledge before its deadline");
77
- } else {
78
- let clearTimer;
79
- const timedOut = new Promise((_resolve, reject) => {
80
- clearTimer = armDeadlineTimer(waitMs, () => reject(new ValidationError(`executor teardown did not acknowledge within ${waitMs}ms`)), true);
81
- });
82
- try {
83
- receipt = await Promise.race([work, timedOut]);
84
- } finally {
85
- clearTimer?.();
86
- }
87
- }
88
- if (!receipt.destroyed) throw new ValidationError(`executor teardown reported destroyed=false${receipt.detail ? `: ${receipt.detail}` : ""}`);
89
- }
90
- /**
91
- * The optional teardown surfaces a wrapping executor forwards, so wrapping never changes how a
92
- * child is released: the acknowledgement window a remote teardown needs, the release of a
93
- * retained execution at root settlement, and the environments an unconfirmed teardown names for
94
- * a sweeper. A wrapper that dropped `releaseRetained` left every retained child it wrapped
95
- * running after settlement. Each surface is present only when the inner executor implements it.
96
- */
97
- function teardownSurfaces(inner) {
98
- return {
99
- ...inner.teardownTimeoutMs === void 0 ? {} : { teardownTimeoutMs: inner.teardownTimeoutMs },
100
- ...inner.releaseRetained === void 0 ? {} : { releaseRetained: (signal) => inner.releaseRetained(signal) },
101
- ...inner.heldEnvironments === void 0 ? {} : { heldEnvironments: () => inner.heldEnvironments() },
102
- ...inner.heldForContinuation === void 0 ? {} : { heldForContinuation: () => inner.heldForContinuation() }
103
- };
104
- }
105
- /**
106
- * An asker that sends an executor at most one teardown at a time. While a request is still
107
- * running, every later ask returns that same request instead of sending another beside it.
108
- *
109
- * A settlement's own teardown has a short acknowledgement window, and a request that misses it
110
- * keeps running. Without this, the first settlement retry sent a second teardown next to the
111
- * first. An executor that does not deduplicate internally, such as one that re-issues its
112
- * cancels, then ran two teardowns at once. `onRequest` runs once for each request actually sent.
113
- */
114
- function singleFlightTeardown(executor, onRequest) {
115
- let inFlight;
116
- return (grace) => {
117
- if (inFlight !== void 0) return inFlight;
118
- onRequest();
119
- let request;
120
- try {
121
- request = Promise.resolve(executor.teardown(grace));
122
- } catch (error) {
123
- request = Promise.reject(error);
124
- }
125
- inFlight = request;
126
- const settle = () => {
127
- if (inFlight === request) inFlight = void 0;
128
- };
129
- request.then(settle, settle);
130
- return request;
131
- };
132
- }
133
4
  // src/runtime/supervise/resources.ts
134
5
  /** Validate caller-owned names and units without assigning domain meaning to them. */
135
6
  function assertResources(resources, kind, label) {
@@ -574,6 +445,6 @@ function unreportedSpend(total, prior) {
574
445
  ...total.boxMinutes === void 0 ? {} : { boxMinutes: Math.max(0, total.boxMinutes - (prior.boxMinutes ?? 0)) }
575
446
  };
576
447
  }
577
- export { withBudgetResources as A, singleFlightTeardown as B, unreportedSpend as C, addResourceSpend as D, zeroTokenUsage as E, ROOT_DEADLINE_REASON as F, teardownSurfaces as H, armDeadlineTimer as I, boundedChildDeadlineAt as L, CHILD_DEADLINE_REASON as M, DEADLINE_CHECK_IN_MESSAGE as N, assertResources as O, DEFAULT_SUCCESSFUL_SHUTDOWN_MS as P, checkInIdleMs as R, unmeteredSpend as S, zeroSpend as T, teardownExecutor as V, roundBoxMinutes as _, cloneSpend as a, throwAbort as b, errorMessage as c, isAbortError as d, isAsyncIterable as f, randomUuid as g, randomSuffix as h, chargedTokens as i, ACCEPTED_RESULT_GRACE_MS as j, resourceTelemetry as k, fnv1a32Hex as l, promptCacheTokenClasses as m, addSpend as n, cloneTokenUsage as o, mapWithConcurrency as p, addTokenUsage as r, deleteBoxSafe as s, abortError as t, hasCompleteCacheBreakdown as u, sleep as v, withTimeout as w, throwIfAborted as x, stringifySafe as y, isDeadlineAbortReason as z };
448
+ export { withBudgetResources as A, unreportedSpend as C, addResourceSpend as D, zeroTokenUsage as E, assertResources as O, unmeteredSpend as S, zeroSpend as T, roundBoxMinutes as _, cloneSpend as a, throwAbort as b, errorMessage as c, isAbortError as d, isAsyncIterable as f, randomUuid as g, randomSuffix as h, chargedTokens as i, resourceTelemetry as k, fnv1a32Hex as l, promptCacheTokenClasses as m, addSpend as n, cloneTokenUsage as o, mapWithConcurrency as p, addTokenUsage as r, deleteBoxSafe as s, abortError as t, hasCompleteCacheBreakdown as u, sleep as v, withTimeout as w, throwIfAborted as x, stringifySafe as y };
578
449
 
579
- //# sourceMappingURL=util-fcckrkKp.js.map
450
+ //# sourceMappingURL=util-qsH5cC9S.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util-qsH5cC9S.js","names":[],"sources":["../src/runtime/supervise/resources.ts","../src/runtime/util.ts"],"sourcesContent":["import type { Budget, ResourceSpend, Spend } from './types'\n\n/** Validate caller-owned names and units without assigning domain meaning to them. */\nexport function assertResources(\n resources: Budget['resources'] | Spend['resources'],\n kind: 'limit' | 'amount',\n label: string,\n): void {\n if (resources === undefined) return\n if (resources === null || typeof resources !== 'object' || Array.isArray(resources)) {\n throw new Error(`${label} must be a resource map`)\n }\n for (const [name, resource] of Object.entries(resources)) {\n if (\n !name.trim() ||\n !resource ||\n typeof resource !== 'object' ||\n typeof resource.unit !== 'string' ||\n !resource.unit.trim()\n ) {\n throw new Error(`${label}: resource names and units must be non-empty strings`)\n }\n const value =\n kind === 'limit'\n ? 'limit' in resource\n ? resource.limit\n : undefined\n : 'amount' in resource\n ? resource.amount\n : undefined\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n throw new Error(`${label}.${name}.${kind} must be a non-negative safe integer`)\n }\n if (kind === 'amount' && (!('known' in resource) || typeof resource.known !== 'boolean')) {\n throw new Error(`${label}.${name}.known must be a boolean`)\n }\n }\n}\n\n/** Missing contributors are not usage claims; enforced omissions are marked before aggregation.\n * Overflow retains a safe lower bound and marks it unknown, preserving readable component receipts. */\nexport function addResourceSpend(...maps: ReadonlyArray<Spend['resources']>): {\n resources?: Record<string, ResourceSpend>\n} {\n const totals = new Map<string, ResourceSpend>()\n for (const resources of maps) {\n assertResources(resources, 'amount', 'resource spend')\n for (const [name, resource] of Object.entries(resources ?? {})) {\n const prior = totals.get(name)\n if (prior && prior.unit !== resource.unit) throw new Error(`resource ${name}: unit mismatch`)\n const amount = (prior?.amount ?? 0) + resource.amount\n totals.set(name, {\n unit: resource.unit,\n amount: Math.min(amount, Number.MAX_SAFE_INTEGER),\n known: (prior?.known ?? true) && resource.known && Number.isSafeInteger(amount),\n })\n }\n }\n return totals.size ? { resources: Object.fromEntries(totals) } : {}\n}\n\n/** A terminal omission under an enforced ceiling is unknown, never measured zero. */\nexport function withBudgetResources(\n spend: Spend,\n budget: Pick<Budget, 'resources'>,\n notStarted = false,\n): Spend {\n const resources = new Map(Object.entries(addResourceSpend(spend.resources).resources ?? {}))\n for (const [name, limit] of Object.entries(budget.resources ?? {})) {\n const observed = resources.get(name)\n if (observed && observed.unit !== limit.unit) throw new Error(`resource ${name}: unit mismatch`)\n if (!observed) resources.set(name, { unit: limit.unit, amount: 0, known: notStarted })\n }\n return resources.size ? { ...spend, resources: Object.fromEntries(resources) } : spend\n}\n\n/** Stream increments and a terminal total describe the same work; never sum them twice. */\nexport function resourceTelemetry(streamed: Spend, terminal: Spend): Pick<Spend, 'resources'> {\n const resources = new Map(Object.entries(addResourceSpend(terminal.resources).resources ?? {}))\n for (const [name, value] of Object.entries(streamed.resources ?? {})) {\n const other = resources.get(name)\n if (other && other.unit !== value.unit) throw new Error(`resource ${name}: unit mismatch`)\n resources.set(name, {\n ...value,\n amount: Math.max(value.amount, other?.amount ?? 0),\n known:\n value.known &&\n (other?.known ?? true) &&\n (other === undefined || other.amount === value.amount),\n })\n }\n return addResourceSpend(Object.fromEntries(resources))\n}\n","/**\n *\n * Internal loop-kernel utilities shared across the kernel, drivers, and the\n * sandbox-acquire layer. Not part of the public barrel surface.\n *\n * @experimental\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport { armDeadlineTimer } from './supervise/deadline'\nimport { addResourceSpend } from './supervise/resources'\nimport type { Spend, TokenUsageProvenance } from './supervise/types'\nimport { runTaskQueue } from './task-queue'\nimport type { LoopTokenUsage } from './types'\n\n/**\n * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);\n * swallows errors (the platform reaps on expiry). Returns `false` when delete\n * threw, `true` otherwise, so callers can surface a leak if they choose.\n */\nexport async function deleteBoxSafe(box: SandboxInstance | undefined): Promise<boolean> {\n if (!box || typeof (box as { delete?: unknown }).delete !== 'function') return true\n try {\n await box.delete()\n return true\n } catch {\n return false\n }\n}\n\n/** Short base36 id for trace correlation. Not cryptographic, not collision-free. */\nexport function randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n\n/** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */\nexport function randomUuid(): string {\n return crypto.randomUUID()\n}\n\n/** Construct an AbortError carrying the abort reason's message. Downstream code pattern-matches on `err.name`. */\nexport function abortError(reason?: unknown): Error {\n const err = new Error(\n reason instanceof Error ? reason.message : reason === undefined ? 'aborted' : String(reason),\n )\n err.name = 'AbortError'\n return err\n}\n\n/** Throw an AbortError. */\nexport function throwAbort(): never {\n throw abortError()\n}\n\n/** Throw if the signal is already aborted; otherwise no-op. */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortError()\n}\n\n/** True for any error whose `name` is `AbortError` (the cross-kernel abort contract). */\nexport function isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\n/**\n * Sleep that resolves early on abort and always clears its timer so it never\n * keeps the event loop alive. Resolves (does not reject) on abort — callers\n * re-check the signal explicitly after the sleep.\n */\nexport function sleep(ms: number, signal?: AbortSignal, keepAlive = true): Promise<void> {\n if (signal?.aborted) return Promise.resolve()\n return new Promise((resolve) => {\n const done = () => {\n clearTimer()\n signal?.removeEventListener('abort', done)\n resolve()\n }\n const clearTimer = armDeadlineTimer(ms, done, keepAlive)\n signal?.addEventListener('abort', done, { once: true })\n })\n}\n\n/**\n * Race a promise against a timeout. Resolves with the value if it settles in\n * time, otherwise resolves with `undefined`. Always clears the timer.\n */\nexport function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n return new Promise<T | undefined>((resolve) => {\n const clearTimer = armDeadlineTimer(ms, () => resolve(undefined), true)\n promise.then(\n (value) => {\n clearTimer()\n resolve(value)\n },\n () => {\n clearTimer()\n resolve(undefined)\n },\n )\n })\n}\n\ninterface StringifyOptions {\n /** Pretty-print with 2-space indent. Default false (compact). */\n pretty?: boolean\n /** Truncate to this many chars, appending `…`. Default unbounded. */\n max?: number\n}\n\n/**\n * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).\n * Strings pass through unstringified so a preview of a string output is the\n * string itself, not a quoted re-encoding.\n */\nexport function stringifySafe(value: unknown, opts: StringifyOptions = {}): string {\n let s: string\n try {\n if (typeof value === 'string') {\n s = value\n } else {\n const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)\n s = json ?? String(value)\n }\n } catch {\n s = String(value)\n }\n if (opts.max !== undefined && s.length > opts.max) return `${s.slice(0, opts.max)}…`\n return s\n}\n\n/** A fresh zero token-usage accumulator. */\nexport function zeroTokenUsage(): LoopTokenUsage {\n return { input: 0, output: 0 }\n}\n\n/**\n * Sum the catalog-priced part of a dollar total across spends, as a field to spread.\n *\n * Returns nothing when no input carried one. A fold of pure provider receipts must not gain a\n * `usdEstimated: 0`, which would read as \"this runtime checked and priced none\" on a path that\n * never prices at all.\n */\nfunction usdEstimatedOf(...spends: ReadonlyArray<{ usdEstimated?: number }>): {\n usdEstimated?: number\n} {\n let total = 0\n let priced = false\n for (const spend of spends) {\n if (spend.usdEstimated === undefined) continue\n priced = true\n total += spend.usdEstimated\n }\n return priced ? { usdEstimated: total } : {}\n}\n\n/** A conserved spend with every channel at zero and no completeness claim on it. */\nexport function zeroSpend(): Spend {\n return { iterations: 0, tokens: zeroTokenUsage(), usd: 0, ms: 0 }\n}\n\n/** Work that happened and reported no receipt. Unlike {@link zeroSpend}, `tokensKnown: false` makes\n * the zero a floor, so a token or dollar ceiling still fires. Never relabel that as a measurement. */\nexport function unmeteredSpend(ms: number): Spend {\n return {\n iterations: 0,\n tokens: zeroTokenUsage(),\n tokensKnown: false,\n usd: 0,\n usdKnown: false,\n ms,\n }\n}\n\n/** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */\nexport function cloneSpend(spend: Spend): Spend {\n return {\n ...addResourceSpend(spend.resources),\n iterations: spend.iterations,\n tokens: cloneTokenUsage(spend.tokens),\n ...(spend.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: spend.usd,\n ...(spend.usdKnown === false ? { usdKnown: false } : {}),\n ...(spend.usdEstimated !== undefined ? { usdEstimated: spend.usdEstimated } : {}),\n ms: spend.ms,\n ...boxMinutesOf(spend),\n ...(spend.tokensProvenance === undefined ? {} : { tokensProvenance: spend.tokensProvenance }),\n ...streamBreakOf(spend),\n }\n}\n\n/**\n * Sum two conserved spends per channel. Tokens and dollars never fold into each other, an\n * incomplete input keeps the sum incomplete on that channel, and the catalog-priced part of the\n * dollar total is summed separately so `usd - usdEstimated` still names what a provider billed.\n */\nexport function addSpend(a: Spend, b: Spend): Spend {\n const tokens = cloneTokenUsage(a.tokens)\n addTokenUsage(tokens, b.tokens)\n return {\n ...addResourceSpend(a.resources, b.resources),\n iterations: a.iterations + b.iterations,\n tokens,\n ...(a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {}),\n usd: a.usd + b.usd,\n ...(a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {}),\n ...usdEstimatedOf(a, b),\n ms: a.ms + b.ms,\n ...boxMinutesOf(a, b),\n ...tokensProvenanceOf(a, b),\n ...streamBreakOf(a, b),\n }\n}\n\n/** Absent provenance is the live stream. A stated source beside an absent one folds to `mixed`. */\nfunction tokensProvenanceOf(...spends: ReadonlyArray<Spend>): {\n tokensProvenance?: TokenUsageProvenance\n} {\n let folded: TokenUsageProvenance | undefined\n let sawStated = false\n for (const spend of spends) {\n const stated = spend.tokensProvenance ?? 'stream-receipt'\n if (spend.tokensProvenance !== undefined) sawStated = true\n folded = folded === undefined || folded === stated ? stated : 'mixed'\n }\n return !sawStated || folded === undefined || folded === 'stream-receipt'\n ? {}\n : { tokensProvenance: folded }\n}\n\n/** Fold a broken stream's split. A spend that never broke contributes nothing, not a zero. */\nfunction streamBreakOf(\n ...spends: ReadonlyArray<Spend>\n): Pick<Spend, 'streamedTokens' | 'unobservedTokens' | 'iterationsKnown'> {\n const streamedTokens = foldTokenSplit(spends.map((spend) => spend.streamedTokens))\n const unobservedTokens = foldTokenSplit(spends.map((spend) => spend.unobservedTokens))\n const iterationsKnown = spends.some((spend) => spend.iterationsKnown === false)\n ? (false as const)\n : undefined\n return {\n ...(streamedTokens === undefined ? {} : { streamedTokens }),\n ...(unobservedTokens === undefined ? {} : { unobservedTokens }),\n ...(iterationsKnown === undefined ? {} : { iterationsKnown }),\n }\n}\n\nfunction foldTokenSplit(\n parts: ReadonlyArray<LoopTokenUsage | undefined>,\n): LoopTokenUsage | undefined {\n const present = parts.filter((part): part is LoopTokenUsage => part !== undefined)\n const first = present[0]\n if (first === undefined) return undefined\n const total = cloneTokenUsage(first)\n for (const part of present.slice(1)) addTokenUsage(total, part)\n return total\n}\n\n/** Sum present box minutes. Absence is not zero, so a path with no box stays unmarked.\n * `boxMinutesKnown` is sticky-false. Provenance degrades from observed to estimated to uncaptured. */\nfunction boxMinutesOf(...spends: ReadonlyArray<Spend>): {\n boxMinutes?: number\n boxMinutesKnown?: boolean\n boxMinutesProvenance?: 'observed' | 'estimated' | 'uncaptured'\n} {\n const present = spends.filter((spend) => spend.boxMinutesProvenance !== undefined)\n if (present.length === 0) return {}\n let minutes = 0\n let sawNumber = false\n let known = true\n let observedOnly = true\n for (const spend of present) {\n if (typeof spend.boxMinutes === 'number' && Number.isFinite(spend.boxMinutes)) {\n minutes += spend.boxMinutes\n sawNumber = true\n if (spend.boxMinutesProvenance !== 'observed') observedOnly = false\n }\n if (spend.boxMinutesKnown !== true) known = false\n }\n return {\n ...(sawNumber ? { boxMinutes: roundBoxMinutes(minutes) } : {}),\n boxMinutesKnown: known,\n boxMinutesProvenance: sawNumber ? (observedOnly ? 'observed' : 'estimated') : 'uncaptured',\n }\n}\n\n/**\n * Box minutes at four decimals — a tenth of a second.\n *\n * Fine enough that a box alive for two seconds reports `0.0333` instead of a zero that would read\n * as a measured free box, and coarse enough that summing floats does not print\n * `1.5000000000000002`.\n */\nexport function roundBoxMinutes(minutes: number): number {\n return Number(minutes.toFixed(4))\n}\n\n/** Copy a token subtotal without dropping optional provider cache telemetry. */\nexport function cloneTokenUsage(usage: LoopTokenUsage): LoopTokenUsage {\n const cacheBreakdownUnknown =\n usage.cacheBreakdownKnown === false || (usage.input > 0 && !hasClassifiedCacheBreakdown(usage))\n return {\n input: usage.input,\n output: usage.output,\n ...(usage.tokensKnown === false ? { tokensKnown: false as const } : {}),\n ...(usage.freshInput !== undefined ? { freshInput: usage.freshInput } : {}),\n ...(usage.cacheRead !== undefined ? { cacheRead: usage.cacheRead } : {}),\n ...(usage.cacheWrite !== undefined ? { cacheWrite: usage.cacheWrite } : {}),\n ...(cacheBreakdownUnknown ? { cacheBreakdownKnown: false as const } : {}),\n }\n}\n\n/** True only when every positive prompt token has a consistent cache classification. */\nexport function hasCompleteCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.cacheBreakdownKnown === false) return false\n return hasClassifiedCacheBreakdown(usage)\n}\n\nfunction hasClassifiedCacheBreakdown(usage: LoopTokenUsage): boolean {\n if (usage.input === 0) return true\n if (\n usage.freshInput === undefined ||\n usage.cacheRead === undefined ||\n usage.cacheWrite === undefined\n ) {\n return false\n }\n return usage.freshInput + usage.cacheRead + usage.cacheWrite === usage.input\n}\n\n/** Charge `input - cacheRead + output`. A cache read was charged when written. Classes that do not\n * fit `input` credit nothing. Unclassified prompt tokens charge in full. Do not charge\n * `freshInput + cacheWrite`: one unclassified turn would then over-charge the classified ones. */\nexport function chargedTokens(usage: LoopTokenUsage): number {\n return usage.input - creditedCacheRead(usage) + usage.output\n}\n\n/** `cacheRead` if the reported classes fit inside `input`, else nothing. */\nfunction creditedCacheRead(usage: LoopTokenUsage): number {\n const { cacheRead } = usage\n if (cacheRead === undefined) return 0\n return classifiedTotal(usage, cacheRead) > usage.input ? 0 : cacheRead\n}\n\nfunction classifiedTotal(usage: Partial<LoopTokenUsage>, cacheRead: number): number {\n return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0)\n}\n\n/**\n * The only two members this reads out of a provider prompt-cache report, named rather than taken as\n * an open record: both the typed `PromptCacheUsage` and the open `promptCache` an `llm_call` carries\n * satisfy it, and each value is validated before it is credited.\n */\ninterface PromptCacheCounters {\n readonly readTokens?: unknown\n readonly writeTokens?: unknown\n}\n\n/** The prompt-cache token classes of one observation, as `LoopTokenUsage` members. */\ntype PromptCacheTokenClasses = Pick<\n LoopTokenUsage,\n 'freshInput' | 'cacheRead' | 'cacheWrite' | 'cacheBreakdownKnown'\n>\n\n/** Nothing reported stays unmarked. A read and a write that fit `input` are a complete split.\n * One counter, or classes past `input`, pass through with `cacheBreakdownKnown: false`.\n * An unreported counter stays absent, never zero. */\nexport function promptCacheTokenClasses(\n input: number | undefined,\n promptCache: PromptCacheCounters | undefined,\n): PromptCacheTokenClasses {\n if (promptCache === undefined) return {}\n const read = tokenCount(promptCache.readTokens)\n const write = tokenCount(promptCache.writeTokens)\n if (read === undefined && write === undefined) return {}\n if (input === undefined || (read ?? 0) + (write ?? 0) > input) {\n return { cacheBreakdownKnown: false }\n }\n if (read !== undefined && write !== undefined) {\n return { freshInput: input - read - write, cacheRead: read, cacheWrite: write }\n }\n return {\n ...(read !== undefined ? { cacheRead: read } : {}),\n ...(write !== undefined ? { cacheWrite: write } : {}),\n cacheBreakdownKnown: false,\n }\n}\n\nfunction tokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\n/** Add a subtotal. Classes that overflow their own `input` are dropped, so a later fold cannot\n * credit a cache read this record refused. An unclassified positive input makes the sum unknown. */\nexport function addTokenUsage(acc: LoopTokenUsage, delta: Partial<LoopTokenUsage>): void {\n acc.input += delta.input ?? 0\n acc.output += delta.output ?? 0\n if (delta.tokensKnown === false) acc.tokensKnown = false\n\n const input = delta.input ?? 0\n const fits = classifiedTotal(delta, delta.cacheRead ?? 0) <= input\n if (fits) {\n if (delta.freshInput !== undefined) acc.freshInput = (acc.freshInput ?? 0) + delta.freshInput\n if (delta.cacheRead !== undefined) acc.cacheRead = (acc.cacheRead ?? 0) + delta.cacheRead\n if (delta.cacheWrite !== undefined) acc.cacheWrite = (acc.cacheWrite ?? 0) + delta.cacheWrite\n }\n\n const classified =\n fits &&\n delta.freshInput !== undefined &&\n delta.cacheRead !== undefined &&\n delta.cacheWrite !== undefined &&\n delta.freshInput + delta.cacheRead + delta.cacheWrite === input\n // A provider that reports prompt input without all three classes leaves the\n // split unknown. Do not let an earlier complete turn make the aggregate look\n // complete after a later unclassified positive-input turn.\n if (delta.cacheBreakdownKnown === false || (input > 0 && !classified)) {\n acc.cacheBreakdownKnown = false\n }\n}\n\n/** Run `fn` with at most `limit` calls in flight, preserving input order. The first rejection wins. */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length)\n let next = 0\n for await (const settled of runTaskQueue({\n concurrency: Math.max(1, Math.min(Math.floor(limit), items.length)),\n take: () => {\n const index = next++\n return index < items.length ? { id: String(index), value: index } : undefined\n },\n execute: ({ value: index }) => fn(items[index] as T, index),\n })) {\n if (settled.status === 'rejected') throw settled.reason\n results[settled.task.value] = settled.value\n }\n return results\n}\n\n/** The message of a thrown value: an `Error`'s own message, anything else stringified. */\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** True for an object whose `Symbol.asyncIterator` is callable, so `for await` can consume it. */\nexport function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'\n )\n}\n\n/** 32-bit FNV-1a over a string's UTF-16 code units, as eight lowercase hex digits. */\nexport function fnv1a32Hex(text: string): string {\n let h = 0x811c9dc5\n for (let i = 0; i < text.length; i += 1) {\n h ^= text.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return (h >>> 0).toString(16).padStart(8, '0')\n}\n\n/** Parent journals may already contain an interrupted driver's inference prefix. */\nexport function unreportedSpend(total: Spend, prior: Spend): Spend {\n const tokens = { ...total.tokens }\n for (const key of ['input', 'output', 'freshInput', 'cacheRead', 'cacheWrite'] as const) {\n const value = total.tokens[key]\n if (value !== undefined) tokens[key] = Math.max(0, value - (prior.tokens[key] ?? 0))\n }\n return {\n ...total,\n ...addResourceSpend(\n total.resources === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(total.resources).map(([name, value]) => {\n const previous = prior.resources?.[name]\n if (previous && previous.unit !== value.unit)\n throw new ValidationError(`resource ${name}: unit mismatch`)\n return [\n name,\n {\n ...value,\n amount: Math.max(0, value.amount - (previous?.amount ?? 0)),\n known: value.known && (previous?.known ?? true),\n },\n ]\n }),\n ),\n ),\n iterations: Math.max(0, total.iterations - prior.iterations),\n tokens,\n usd: Math.max(0, total.usd - prior.usd),\n ms: Math.max(0, total.ms - prior.ms),\n ...(total.usdEstimated === undefined\n ? {}\n : { usdEstimated: Math.max(0, total.usdEstimated - (prior.usdEstimated ?? 0)) }),\n ...(total.boxMinutes === undefined\n ? {}\n : { boxMinutes: Math.max(0, total.boxMinutes - (prior.boxMinutes ?? 0)) }),\n }\n}\n"],"mappings":";;;;;AAGA,SAAgB,gBACd,WACA,MACA,OACM;CACN,IAAI,cAAc,KAAA,GAAW;CAC7B,IAAI,cAAc,QAAQ,OAAO,cAAc,YAAY,MAAM,QAAQ,SAAS,GAChF,MAAM,IAAI,MAAM,GAAG,MAAM,wBAAwB;CAEnD,KAAK,MAAM,CAAC,MAAM,aAAa,OAAO,QAAQ,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ACnC,IAAI,YAAY,SAAS,SAAS,MAAM,MACtC,MAAM,IAAI,gBAAgB,YAAY,KAAK,gBAAgB;GAC7D,OAAO,CACL,MACA;IACE,GAAG;IACH,QAAQ,KAAK,IAAI,GAAG,MAAM,UAAU,UAAU,UAAU,EAAE;IAC1D,OAAO,MAAM,UAAU,UAAU,SAAS;GAC5C,CACF;EACF,CAAC,CACH,CACN;EACA,YAAY,KAAK,IAAI,GAAG,MAAM,aAAa,MAAM,UAAU;EAC3D;EACA,KAAK,KAAK,IAAI,GAAG,MAAM,MAAM,MAAM,GAAG;EACtC,IAAI,KAAK,IAAI,GAAG,MAAM,KAAK,MAAM,EAAE;EACnC,GAAI,MAAM,iBAAiB,KAAA,IACvB,CAAC,IACD,EAAE,cAAc,KAAK,IAAI,GAAG,MAAM,gBAAgB,MAAM,gBAAgB,EAAE,EAAE;EAChF,GAAI,MAAM,eAAe,KAAA,IACrB,CAAC,IACD,EAAE,YAAY,KAAK,IAAI,GAAG,MAAM,cAAc,MAAM,cAAc,EAAE,EAAE;CAC5E;AACF"}
@@ -1,11 +1,12 @@
1
- import { p as mapWithConcurrency } from "./util-fcckrkKp.js";
2
- import { agentCandidateArtifactRefSchema, canonicalCandidateBytes as canonicalCandidateBytes$1 } from "@tangle-network/agent-interface";
1
+ import { p as mapWithConcurrency } from "./util-qsH5cC9S.js";
2
+ import { _ as embeddedCandidateArtifact, a as captureMaterializedWorkspace, b as sha256Bytes$1, c as scanMaterializedWorkspaceManifest, d as verifyMaterializedWorkspace, g as deepFreezeCandidate, i as candidateWorkspaceManifest, l as verifyBytes, m as canonicalCandidateDigest$1, p as canonicalCandidateBytes$1, t as persistCandidateOutputArtifact, v as immutableCandidateValue } from "./output-artifacts-AqkZ8lO2.js";
3
+ import { agentCandidateArtifactRefSchema } from "@tangle-network/agent-interface";
3
4
  import { isRecord } from "@tangle-network/agent-core";
4
5
  import { createHash, randomUUID } from "node:crypto";
5
6
  import { constants } from "node:fs";
6
- import { dirname, isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
7
+ import { dirname, isAbsolute, join, resolve, sep, win32 } from "node:path";
7
8
  import { spawn } from "node:child_process";
8
- import { lstat, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
9
+ import { lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
9
10
  import { homedir, tmpdir } from "node:os";
10
11
  import { Readable } from "node:stream";
11
12
  import { isAnyArrayBuffer, isSharedArrayBuffer } from "node:util/types";
@@ -20,55 +21,6 @@ function hasControlCharacter(value) {
20
21
  }
21
22
  return false;
22
23
  }
23
- // src/candidate-execution/digest.ts
24
- /** Use native hashing for workspace archives. */
25
- function sha256Bytes$1(bytes) {
26
- return `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
27
- }
28
- function canonicalCandidateDigest$1(value) {
29
- return sha256Bytes$1(canonicalCandidateBytes$1(value));
30
- }
31
- /** Returns a detached, deeply frozen JSON value with canonical number normalization. */
32
- function immutableCandidateValue(value) {
33
- return deepFreezeCandidate(JSON.parse(Buffer.from(canonicalCandidateBytes$1(value)).toString("utf8")));
34
- }
35
- function canonicalCandidateDocument(valueWithoutDigest) {
36
- const bytes = canonicalCandidateBytes$1(valueWithoutDigest);
37
- const digest = sha256Bytes$1(bytes);
38
- const value = deepFreezeCandidate({
39
- ...JSON.parse(Buffer.from(bytes).toString("utf8")),
40
- digest
41
- });
42
- return Object.freeze({
43
- value,
44
- get bytes() {
45
- return Uint8Array.from(bytes);
46
- },
47
- digest
48
- });
49
- }
50
- function verifyCanonicalCandidateDocument(value, label) {
51
- if (canonicalCandidateDigest$1(omitTopLevelDigest(value)) !== value.digest) throw new Error(`${label} digest does not match`);
52
- return immutableCandidateValue(value);
53
- }
54
- function embeddedCandidateArtifact(bytes) {
55
- return {
56
- encoding: "base64",
57
- content: Buffer.from(bytes).toString("base64"),
58
- sha256: sha256Bytes$1(bytes),
59
- byteLength: bytes.byteLength
60
- };
61
- }
62
- function omitTopLevelDigest(value) {
63
- const { digest: _digest, ...rest } = value;
64
- return rest;
65
- }
66
- function deepFreezeCandidate(value, seen = /* @__PURE__ */ new Set()) {
67
- if (value === null || typeof value !== "object" || ArrayBuffer.isView(value) || seen.has(value)) return value;
68
- seen.add(value);
69
- for (const child of Object.values(value)) deepFreezeCandidate(child, seen);
70
- return Object.freeze(value);
71
- }
72
24
  // src/candidate-execution/artifact-streams.ts
73
25
  /** Verify the complete stream, including its final digest, before accepting its consumer's result. */
74
26
  async function* verifiedArtifactChunks(artifact, port, signal) {
@@ -136,261 +88,6 @@ async function persistCandidateOutputArtifactStream(port, input) {
136
88
  await chunks.return(void 0);
137
89
  }
138
90
  }
139
- // src/candidate-execution/artifacts.ts
140
- function artifactCacheKey(artifact) {
141
- return `${artifact.sha256}:${artifact.byteLength}`;
142
- }
143
- async function readVerifiedArtifact(artifact, port) {
144
- const bytes = "content" in artifact ? Buffer.from(artifact.content, "base64") : await port.read(artifact);
145
- verifyBytes(bytes, artifact.sha256, artifact.byteLength, "candidate artifact");
146
- return Uint8Array.from(bytes);
147
- }
148
- function verifyBytes(bytes, digest, byteLength, label) {
149
- if (bytes.byteLength !== byteLength) throw new Error(`${label} byte length ${bytes.byteLength} does not match ${byteLength}`);
150
- const actual = sha256Bytes$1(bytes);
151
- if (actual !== digest) throw new Error(`${label} digest ${actual} does not match ${digest}`);
152
- }
153
- async function verifyWorkspaceSnapshotArtifacts(snapshot, port) {
154
- const [manifest, archive] = await Promise.all([readVerifiedArtifact(snapshot.manifest, port), readVerifiedArtifact(snapshot.archive, port)]);
155
- const canonicalManifest = canonicalCandidateBytes$1(snapshot.material);
156
- if (!Buffer.from(manifest).equals(Buffer.from(canonicalManifest))) throw new Error("workspace manifest artifact is not the exact canonical manifest material");
157
- if (sha256Bytes$1(canonicalManifest) !== snapshot.digest) throw new Error("workspace snapshot digest does not match its canonical manifest material");
158
- return {
159
- manifest,
160
- archive
161
- };
162
- }
163
- /** A configured file-count or byte limit stopped workspace capture. */
164
- var WorkspaceScanLimitError = class extends Error {};
165
- /**
166
- * Refuse a materialized workspace whose files, modes, or bytes are not the signed manifest.
167
- *
168
- * The scan streams, so the size of the largest file does not decide whether the check can run, and
169
- * the refusal names the one mismatch a caller can produce on its own: a capture and a verify that
170
- * disagree about `portableTree`.
171
- */
172
- async function verifyMaterializedWorkspace(root, expected, options = {}) {
173
- assertWorkspaceManifest(await scanMaterializedWorkspaceManifest(root, options), expected);
174
- }
175
- /**
176
- * The canonical manifest of one materialized workspace, read without holding any file.
177
- *
178
- * Every file is digested by streaming, so the size of the largest file does not decide whether the
179
- * workspace can be described. `FileHandle.readFile` refuses anything above 2 GiB with
180
- * `ERR_FS_FILE_TOO_LARGE`, which made a workspace holding one such artifact impossible to verify
181
- * against a manifest it already matched. The digest is sha-256 over the same bytes either way, so
182
- * a manifest a buffered read produced is reproduced exactly.
183
- */
184
- async function scanMaterializedWorkspaceManifest(root, options = {}) {
185
- return workspaceManifestFromEntries(await walkWorkspace(root, options, false));
186
- }
187
- async function captureMaterializedWorkspace(root, options = {}) {
188
- const entries = await walkWorkspace(root, options, true);
189
- return {
190
- manifest: workspaceManifestFromEntries(entries),
191
- files: entries.map((entry) => ({
192
- path: entry.path,
193
- mode: entry.mode,
194
- bytes: Uint8Array.from(capturedBytes(entry))
195
- }))
196
- };
197
- }
198
- /** Capture exact verified regular-file bytes for fresh isolated materialization. */
199
- async function readMaterializedWorkspaceFiles(root, expected, options = {}) {
200
- const observed = await captureMaterializedWorkspace(root, options);
201
- assertWorkspaceManifest(observed.manifest, expected);
202
- return observed.files.map((file) => Object.freeze({
203
- path: file.path,
204
- mode: file.mode,
205
- bytes: Uint8Array.from(file.bytes)
206
- }));
207
- }
208
- /**
209
- * Build the canonical manifest for files a caller already holds — the shape a remote executor
210
- * returns. Pass `portableTree` to record Git's two file modes instead of exact permission bits, and
211
- * pass the same flag to every verify that reads the result.
212
- */
213
- function candidateWorkspaceManifest(files, options = {}) {
214
- return workspaceManifestFromEntries(files.map((file) => ({
215
- path: file.path,
216
- mode: options.portableTree === true ? portableFileMode(file.mode) : file.mode,
217
- sha256: sha256Bytes$1(file.bytes),
218
- byteLength: file.bytes.byteLength
219
- })));
220
- }
221
- function workspaceManifestFromEntries(entries) {
222
- return {
223
- kind: "agent-candidate-workspace-manifest",
224
- files: entries.map((entry) => ({
225
- path: entry.path,
226
- mode: entry.mode,
227
- sha256: entry.sha256,
228
- byteLength: entry.byteLength
229
- })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
230
- };
231
- }
232
- /** Git records exactly two file modes, and a portable-tree scan records the same two. */
233
- function portableFileMode(mode) {
234
- return (mode & 73) !== 0 ? 493 : 420;
235
- }
236
- function capturedBytes(entry) {
237
- if (!entry.bytes) throw new Error(`workspace file was digested without its bytes: ${entry.path}`);
238
- return entry.bytes;
239
- }
240
- function assertWorkspaceManifest(observed, expected) {
241
- if (Buffer.from(canonicalCandidateBytes$1(observed)).equals(canonicalCandidateBytes$1(expected))) return;
242
- if (Buffer.from(canonicalCandidateBytes$1(withPortableModes(observed))).equals(canonicalCandidateBytes$1(withPortableModes(expected)))) throw new Error("materialized workspace files do not match the signed manifest: only the file modes differ, so the capture and this verify disagree about portableTree");
243
- throw new Error("materialized workspace files, modes, or bytes do not match the signed manifest");
244
- }
245
- function withPortableModes(material) {
246
- return {
247
- ...material,
248
- files: material.files.map((file) => ({
249
- ...file,
250
- mode: portableFileMode(file.mode)
251
- }))
252
- };
253
- }
254
- async function verifyMaterializedProfileWorkspace(root, expected, fileRoot = "workspace") {
255
- const observedProfile = (await scanMaterializedWorkspaceManifest(root)).files.map(({ path, mode, sha256 }) => ({
256
- relPath: path,
257
- mode,
258
- contentSha256: sha256
259
- }));
260
- const expectedFiles = expected.files.filter((file) => (file.root ?? "workspace") === fileRoot).map(({ root: _root, ...file }) => file);
261
- if (!Buffer.from(canonicalCandidateBytes$1(observedProfile)).equals(canonicalCandidateBytes$1(expectedFiles))) throw new Error(`profile ${fileRoot} staging files, modes, or bytes do not match the signed profile plan`);
262
- }
263
- async function walkWorkspace(root, options, keepBytes) {
264
- const ignoredProtectedRootEntries = new Set(options.ignoredProtectedRootEntries ?? []);
265
- const excluded = new Set(options.excludedPaths ?? []);
266
- for (const path of excluded) if (!path || path.includes("\\") || path.includes("\0") || isAbsolute(path) || path.split("/").some((part) => !part || part === "." || part === "..")) throw new Error("workspace excluded path must be a safe relative path");
267
- const limits = options.limits;
268
- const selected = options.selectedPaths ? new Set(options.selectedPaths) : void 0;
269
- const selectedDirectories = /* @__PURE__ */ new Set();
270
- for (const path of selected ?? []) {
271
- if (!path || path.includes("\\") || path.includes("\0") || isAbsolute(path) || path.split("/").some((part) => !part || part === "." || part === "..")) throw new Error("workspace selected path must be a safe relative file path");
272
- let parent = dirname(path);
273
- while (parent !== ".") {
274
- selectedDirectories.add(parent);
275
- parent = dirname(parent);
276
- }
277
- }
278
- const requestedRoot = resolve(root);
279
- const rootStats = await lstat(requestedRoot);
280
- if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) throw new Error("workspace root must be a real directory");
281
- const absoluteRoot = await realpath(requestedRoot);
282
- const resolvedStats = await lstat(absoluteRoot);
283
- if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) throw new Error("workspace root must resolve to a real directory");
284
- const scanned = [];
285
- let totalBytes = 0;
286
- async function visit(directory) {
287
- options.signal?.throwIfAborted();
288
- const entries = await readdir(directory, { withFileTypes: true });
289
- entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
290
- for (const entry of entries) {
291
- options.signal?.throwIfAborted();
292
- if (directory === absoluteRoot && ignoredProtectedRootEntries.has(entry.name)) continue;
293
- if (options.skipPythonBytecode === true && (entry.isDirectory() && entry.name === "__pycache__" || entry.isFile() && entry.name.endsWith(".pyc"))) continue;
294
- const absolute = resolve(directory, entry.name);
295
- const relPath = relative(absoluteRoot, absolute).split(sep).join("/");
296
- if (!relPath || relPath.startsWith("../") || relPath.includes("/../")) throw new Error(`workspace entry escapes root: ${relPath}`);
297
- if (excluded.has(relPath)) continue;
298
- if (selected && !selected.has(relPath) && !selectedDirectories.has(relPath)) continue;
299
- const stats = await lstat(absolute);
300
- if (stats.isSymbolicLink()) throw new Error(await symlinkRefusal(absolute, relPath, absoluteRoot));
301
- if (stats.isDirectory()) {
302
- if (selected?.has(relPath)) throw new Error(`workspace selected file is a directory: ${relPath}`);
303
- await visit(absolute);
304
- continue;
305
- }
306
- if (!stats.isFile()) throw new Error(`workspace contains a non-regular entry: ${relPath}`);
307
- if (limits && scanned.length >= limits.maxFiles) throw new WorkspaceScanLimitError("workspace exceeds maxFiles");
308
- const descriptor = await open(absolute, constants.O_RDONLY | (typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0));
309
- try {
310
- const openedStats = await descriptor.stat();
311
- if (!openedStats.isFile()) throw new Error(`workspace contains a non-regular entry: ${relPath}`);
312
- if (openedStats.nlink !== 1) throw new Error(`workspace contains a hard-linked file: ${relPath}`);
313
- const mode = options.portableTree === true ? portableFileMode(openedStats.mode) : openedStats.mode & 511;
314
- if (limits && openedStats.size > limits.maxFileBytes) throw new WorkspaceScanLimitError(`workspace file exceeds maxFileBytes: ${relPath}`);
315
- const remainingBytes = limits ? limits.maxTotalFileBytes - totalBytes : void 0;
316
- if (remainingBytes !== void 0 && openedStats.size > remainingBytes) throw new WorkspaceScanLimitError("workspace exceeds maxTotalFileBytes");
317
- const read = await readWorkspaceFile(descriptor, limits ? Math.min(limits.maxFileBytes, remainingBytes ?? limits.maxFileBytes) : void 0, keepBytes, relPath, options.signal);
318
- totalBytes += read.byteLength;
319
- scanned.push({
320
- path: relPath,
321
- mode,
322
- sha256: read.sha256,
323
- byteLength: read.byteLength,
324
- ...read.bytes === void 0 ? {} : { bytes: read.bytes }
325
- });
326
- } finally {
327
- await descriptor.close();
328
- }
329
- }
330
- }
331
- await visit(absoluteRoot);
332
- if (selected && scanned.length !== selected.size) throw new Error("workspace selected files changed during capture");
333
- return scanned;
334
- }
335
- /**
336
- * Why one symbolic link is refused, in the terms that separate a portable link from a link that
337
- * reaches outside the tree.
338
- *
339
- * Every link is refused, in both mode policies. `AgentCandidateWorkspaceManifestMaterial` has no
340
- * representation for one — `mode`, `sha256` and `byteLength` describe a regular file — so a link
341
- * recorded as a file would let two different trees share one digest. The reason says which kind of
342
- * link it was, so a caller can tell a link it can rewrite from one it cannot.
343
- */
344
- async function symlinkRefusal(absolute, relPath, absoluteRoot) {
345
- const target = await readlink(absolute);
346
- if (isAbsolute(target)) return `workspace contains an absolute symlink: ${relPath} -> ${target}`;
347
- if (!isWithin(absoluteRoot, resolve(dirname(absolute), target))) return `workspace contains a symlink that escapes its tree: ${relPath} -> ${target}`;
348
- let physical;
349
- try {
350
- physical = await realpath(absolute);
351
- } catch {
352
- return `workspace contains an unresolved symlink: ${relPath} -> ${target}`;
353
- }
354
- if (!isWithin(absoluteRoot, physical)) return `workspace contains a symlink that resolves outside its tree: ${relPath} -> ${target}`;
355
- return `workspace contains a symlink: ${relPath} -> ${target}`;
356
- }
357
- function isWithin(root, path) {
358
- return path === root || path.startsWith(`${root}${sep}`);
359
- }
360
- /**
361
- * Read one open regular file into its digest, keeping the bytes only when the caller needs them.
362
- *
363
- * The content reaches the hash in 1 MiB chunks and is never held whole for a digest-only walk, so
364
- * the size of the largest file does not decide whether a workspace can be described.
365
- * `FileHandle.readFile` refuses anything above 2 GiB with `ERR_FS_FILE_TOO_LARGE`. Hashing the
366
- * chunks in order equals hashing the whole buffer, so a manifest a buffered read produced is
367
- * reproduced byte for byte.
368
- */
369
- async function readWorkspaceFile(descriptor, maxBytes, keepBytes, path, signal) {
370
- const hash = createHash("sha256");
371
- const buffer = Buffer.allocUnsafe(1048576);
372
- const chunks = [];
373
- let total = 0;
374
- while (true) {
375
- signal?.throwIfAborted();
376
- const { bytesRead } = await descriptor.read(buffer, 0, buffer.byteLength, null);
377
- if (bytesRead === 0) break;
378
- total += bytesRead;
379
- if (maxBytes !== void 0 && total > maxBytes) throw new WorkspaceScanLimitError(`workspace file exceeds its capture limit: ${path}`);
380
- const chunk = buffer.subarray(0, bytesRead);
381
- hash.update(chunk);
382
- if (keepBytes) chunks.push(Buffer.from(chunk));
383
- }
384
- const sha256 = `sha256:${hash.digest("hex")}`;
385
- return keepBytes ? {
386
- sha256,
387
- byteLength: total,
388
- bytes: Buffer.concat(chunks, total)
389
- } : {
390
- sha256,
391
- byteLength: total
392
- };
393
- }
394
91
  // src/candidate-execution/exact-object.ts
395
92
  /** Reject unknown fields while requiring every declared non-optional field. */
396
93
  function assertExactObjectKeys(value, required, label, optional = []) {
@@ -416,25 +113,6 @@ function isWellFormedUnicode(value) {
416
113
  }
417
114
  return true;
418
115
  }
419
- // src/candidate-execution/output-artifacts.ts
420
- /** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */
421
- async function persistCandidateOutputArtifact(port, input) {
422
- input.signal?.throwIfAborted();
423
- const bytes = Uint8Array.from(input.bytes);
424
- const expectedDigest = sha256Bytes$1(bytes);
425
- const ref = agentCandidateArtifactRefSchema.parse(await port.put({
426
- executionId: input.executionId,
427
- purpose: input.purpose,
428
- bytes: Uint8Array.from(bytes),
429
- ...input.signal ? { signal: input.signal } : {}
430
- }));
431
- input.signal?.throwIfAborted();
432
- if (ref.sha256 !== expectedDigest || ref.byteLength !== bytes.byteLength) throw new Error("candidate output locator does not identify the submitted bytes");
433
- const stored = await port.read(ref);
434
- input.signal?.throwIfAborted();
435
- verifyBytes(stored, expectedDigest, bytes.byteLength, "persisted candidate output");
436
- return immutableCandidateValue(ref);
437
- }
438
116
  // src/candidate-execution/workspace-archive.ts
439
117
  const archiveKind = "agent-candidate-workspace-archive";
440
118
  const workspaceEntryPrefix = "workspace/";
@@ -1383,11 +1061,12 @@ async function readRepositoryWorkingState(root, limits) {
1383
1061
  }
1384
1062
  async function captureRepositoryWorkingTree(root, limits) {
1385
1063
  const state = await readRepositoryWorkingState(root, limits);
1064
+ const selectedPaths = await existingRepositoryPaths(root, state.paths, limits);
1386
1065
  return {
1387
1066
  state,
1388
1067
  files: [...(await captureMaterializedWorkspace(root, {
1389
1068
  ignoredProtectedRootEntries: [".git"],
1390
- selectedPaths: await existingRepositoryPaths(root, state.paths, limits),
1069
+ selectedPaths,
1391
1070
  limits
1392
1071
  })).files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
1393
1072
  };
@@ -1857,6 +1536,6 @@ async function* oneChunk(bytes) {
1857
1536
  function asError(error) {
1858
1537
  return error instanceof Error ? error : new Error(String(error));
1859
1538
  }
1860
- export { markPutStreamVerified as A, verifyCanonicalCandidateDocument as B, readMaterializedWorkspaceFiles as C, verifyMaterializedProfileWorkspace as D, verifyBytes as E, deepFreezeCandidate as F, embeddedCandidateArtifact as I, immutableCandidateValue as L, canonicalCandidateBytes$1 as M, canonicalCandidateDigest$1 as N, verifyMaterializedWorkspace as O, canonicalCandidateDocument as P, omitTopLevelDigest as R, captureMaterializedWorkspace as S, scanMaterializedWorkspaceManifest as T, hasControlCharacter as V, assertExactObjectKeys as _, verifyAgentCandidateWorkspaceArtifacts as a, artifactCacheKey as b, createAgentCandidateWorkspacePort as c, verifyTaskCheckout as d, verifyTaskOutcomePatch as f, persistCandidateOutputArtifact as g, workspaceLimits as h, readAgentCandidateWorkspaceArtifactFiles as i, verifiedArtifactChunks as j, verifyWorkspaceSnapshotArtifacts as k, readCandidateGitHubResource as l, safeArchivePath as m, captureAgentCandidateWorkspaceTreeToArtifacts as n, verifyAgentCandidateWorkspaceTree as o, captureAgentCandidateWorkspaceFiles as p, materializeAgentCandidateWorkspaceFromArtifacts as r, captureAgentCandidateWorkspace as s, captureAgentCandidateWorkspaceToArtifacts as t, verifyCandidateCode as u, isWellFormedUnicode as v, readVerifiedArtifact as w, candidateWorkspaceManifest as x, WorkspaceScanLimitError as y, sha256Bytes$1 as z };
1539
+ export { isWellFormedUnicode as _, verifyAgentCandidateWorkspaceArtifacts as a, hasControlCharacter as b, createAgentCandidateWorkspacePort as c, verifyTaskCheckout as d, verifyTaskOutcomePatch as f, assertExactObjectKeys as g, workspaceLimits as h, readAgentCandidateWorkspaceArtifactFiles as i, readCandidateGitHubResource as l, safeArchivePath as m, captureAgentCandidateWorkspaceTreeToArtifacts as n, verifyAgentCandidateWorkspaceTree as o, captureAgentCandidateWorkspaceFiles as p, materializeAgentCandidateWorkspaceFromArtifacts as r, captureAgentCandidateWorkspace as s, captureAgentCandidateWorkspaceToArtifacts as t, verifyCandidateCode as u, markPutStreamVerified as v, verifiedArtifactChunks as y };
1861
1540
 
1862
- //# sourceMappingURL=workspace-streams-DA9R3j-p.js.map
1541
+ //# sourceMappingURL=workspace-streams-BakRr-Pl.js.map