@tangle-network/agent-runtime 0.314.2 → 0.317.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +6 -0
  2. package/dist/{activation-BpMnOlw5.d.ts → activation-BFDmjaKP.d.ts} +2 -2
  3. package/dist/{activation-Ci20OAsG.js → activation-CvdE2HIU.js} +3 -3
  4. package/dist/{activation-Ci20OAsG.js.map → activation-CvdE2HIU.js.map} +1 -1
  5. package/dist/agent.d.ts +2 -1
  6. package/dist/agent.js +2 -2
  7. package/dist/{bundle-BK3XBY6q.js → bundle-RgHpAFDY.js} +2 -2
  8. package/dist/{bundle-BK3XBY6q.js.map → bundle-RgHpAFDY.js.map} +1 -1
  9. package/dist/candidate-execution/index.js +5 -5
  10. package/dist/{coordination-driver-CyJF37L8.js → coordination-driver-DGhN8GO9.js} +3 -3
  11. package/dist/{coordination-driver-CyJF37L8.js.map → coordination-driver-DGhN8GO9.js.map} +1 -1
  12. package/dist/{delegate-CTezpiM2.js → delegate-B5pmSbQa.js} +2 -2
  13. package/dist/{delegate-CTezpiM2.js.map → delegate-B5pmSbQa.js.map} +1 -1
  14. package/dist/durable.d.ts +1 -1
  15. package/dist/durable.js +4 -4
  16. package/dist/{graph-DGDrO_ZW.js → graph-G0j1ysqe.js} +4 -4
  17. package/dist/{graph-DGDrO_ZW.js.map → graph-G0j1ysqe.js.map} +1 -1
  18. package/dist/{improvement-cycle-DReg-Qi4.js → improvement-cycle-D7yR6GC2.js} +6 -6
  19. package/dist/{improvement-cycle-DReg-Qi4.js.map → improvement-cycle-D7yR6GC2.js.map} +1 -1
  20. package/dist/{index-B89bMKhD.d.ts → index-CUh40yUJ.d.ts} +13 -90
  21. package/dist/index.d.ts +4 -4
  22. package/dist/index.js +9 -9
  23. package/dist/integrations-DopfCC2a.d.ts +190 -0
  24. package/dist/integrations-dFi-ALk7.js +132 -0
  25. package/dist/integrations-dFi-ALk7.js.map +1 -0
  26. package/dist/intelligence.d.ts +2 -2
  27. package/dist/intelligence.js +7 -7
  28. package/dist/kernel.d.ts +2 -2
  29. package/dist/kernel.js +9 -9
  30. package/dist/{loop-runner-bin-eoycPwY3.js → loop-runner-bin-CFVX4oi0.js} +3 -3
  31. package/dist/{loop-runner-bin-eoycPwY3.js.map → loop-runner-bin-CFVX4oi0.js.map} +1 -1
  32. package/dist/{loop-runner-bin-BM1in-RT.d.ts → loop-runner-bin-DQKLUt0l.d.ts} +2 -2
  33. package/dist/loop-runner-bin.d.ts +1 -1
  34. package/dist/loop-runner-bin.js +1 -1
  35. package/dist/mcp/bin.js +3 -3
  36. package/dist/mcp/index.d.ts +74 -33
  37. package/dist/mcp/index.js +129 -6
  38. package/dist/mcp/index.js.map +1 -1
  39. package/dist/{openai-tools-xPO6dzf4.d.ts → openai-tools-u3gWBi3x.d.ts} +2 -2
  40. package/dist/placement.d.ts +132 -0
  41. package/dist/placement.js +319 -0
  42. package/dist/placement.js.map +1 -0
  43. package/dist/platform.d.ts +1 -188
  44. package/dist/platform.js +1 -129
  45. package/dist/platform.js.map +1 -1
  46. package/dist/{prepare-8A1CAWG8.js → prepare-CD9kR0gS.js} +3 -3
  47. package/dist/{prepare-8A1CAWG8.js.map → prepare-CD9kR0gS.js.map} +1 -1
  48. package/dist/{profile-BhQShsM1.js → profile-CHXYmpGd.js} +2 -2
  49. package/dist/{profile-BhQShsM1.js.map → profile-CHXYmpGd.js.map} +1 -1
  50. package/dist/profile-materialization-Cca615eu.d.ts +90 -0
  51. package/dist/profiles.d.ts +1 -1
  52. package/dist/{protected-model-port-ug52OmvB.js → protected-model-port-B0pHd65J.js} +4 -4
  53. package/dist/{protected-model-port-ug52OmvB.js.map → protected-model-port-B0pHd65J.js.map} +1 -1
  54. package/dist/{provision-supervisor-B6D3XRbL.js → provision-supervisor-BQLLrUtn.js} +4 -4
  55. package/dist/{provision-supervisor-B6D3XRbL.js.map → provision-supervisor-BQLLrUtn.js.map} +1 -1
  56. package/dist/{runtime-NlIVxRXu.js → runtime-B9BOFyEp.js} +10 -9
  57. package/dist/runtime-B9BOFyEp.js.map +1 -0
  58. package/dist/{search-executor-DFs-79tK.js → search-executor-B5ZVFsDV.js} +3 -3
  59. package/dist/{search-executor-DFs-79tK.js.map → search-executor-B5ZVFsDV.js.map} +1 -1
  60. package/dist/{server-B8ubWXpW.js → server-TwpH9aik.js} +4 -4
  61. package/dist/{server-B8ubWXpW.js.map → server-TwpH9aik.js.map} +1 -1
  62. package/dist/{supervise-BE9ta8bl.js → supervise-CU6AuxWY.js} +119 -29
  63. package/dist/supervise-CU6AuxWY.js.map +1 -0
  64. package/dist/{supervisor-DmSuKksw.js → supervisor-CbFyf48U.js} +3 -3
  65. package/dist/{supervisor-DmSuKksw.js.map → supervisor-CbFyf48U.js.map} +1 -1
  66. package/dist/testing.d.ts +1 -1
  67. package/dist/testing.js +14 -14
  68. package/dist/tool-loop.d.ts +45 -6
  69. package/dist/tool-loop.js +49 -21
  70. package/dist/tool-loop.js.map +1 -1
  71. package/dist/tui/index.d.ts +1 -1
  72. package/dist/tui/index.js +1 -1
  73. package/dist/workspace-store/index.d.ts +206 -0
  74. package/dist/workspace-store/index.js +855 -0
  75. package/dist/workspace-store/index.js.map +1 -0
  76. package/dist/{workspace-streams-BEvSX97P.js → workspace-streams-DkijayqX.js} +16 -3
  77. package/dist/workspace-streams-DkijayqX.js.map +1 -0
  78. package/package.json +11 -1
  79. package/skills/profile-authoring/SKILL.md +114 -171
  80. package/dist/runtime-NlIVxRXu.js.map +0 -1
  81. package/dist/supervise-BE9ta8bl.js.map +0 -1
  82. package/dist/workspace-streams-BEvSX97P.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace-streams-DkijayqX.js","names":["sha256Bytes","canonicalCandidateDigest","canonicalCandidateBytes","sha256Bytes","canonicalCandidateBytes","fsConstants","canonicalCandidateBytes","hasControlCharacter","sha256Bytes","canonicalCandidateBytes","canonicalCandidateDigest","sha256Bytes","fsConstants","canonicalCandidateBytes","canonicalCandidateDigest"],"sources":["../src/runtime/supervise/deadline.ts","../src/runtime/supervise/resources.ts","../src/runtime/util.ts","../src/candidate-execution/digest.ts","../src/candidate-execution/artifact-streams.ts","../src/candidate-execution/artifacts.ts","../src/candidate-execution/exact-object.ts","../src/candidate-execution/git-materialize.ts","../src/candidate-execution/output-artifacts.ts","../src/candidate-execution/workspace-archive.ts","../src/candidate-execution/workspace-streams.ts"],"sourcesContent":["import { ValidationError } from '../../errors'\nimport type { Executor } from './types'\n\n// Node clamps larger delays to 1 ms instead of waiting, so long budgets must be armed in chunks.\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\nexport const DEFAULT_SUCCESSFUL_SHUTDOWN_MS = 5_000\n\n/** The abort reason a child's own deadline carries. */\nexport const CHILD_DEADLINE_REASON = 'child deadline exceeded'\n/** The abort reason the root's budget deadline cascades to every node. */\nexport const ROOT_DEADLINE_REASON = 'root budget deadline exceeded'\n\n/**\n * What a steerable child's own time box does: a check-in, not a kill. At the child's deadline its\n * lead's scope delivers {@link DEADLINE_CHECK_IN_MESSAGE} to the child's inbox and keeps it\n * running; the child is stopped (reason `child deadline exceeded`) only once it then makes no\n * progress for `idleMs`. The run's own deadline, the budgets and cancellation still stop it at once.\n * `false` restores the hard kill at the time box. A child that exposes no inbox cannot be told,\n * so it is stopped at its time box as before.\n *\n * Measured 2026-10-07 on Discovery run terraform-dc-tokens-20261007e-codex1: four of 42 directors\n * were killed at the 90-minute boxes their root set, three of them mid-turn, losing 27, 6 and 91\n * minutes since their last recorded page, and each successor spent 12 to 19 minutes re-reading\n * before its first page.\n */\nexport type DeadlineCheckIn = false | { readonly idleMs?: number }\n\n/** How long a checked-in child may go without progress before it is stopped: 30 min. */\nexport const DEFAULT_CHECK_IN_IDLE_MS = 30 * 60_000\n\n/** The check-in a child receives at its own time box. */\nexport const DEADLINE_CHECK_IN_MESSAGE =\n 'Check-in: your time box has ended. This is not a stop. Finish the step you are on and start ' +\n 'nothing new. Record your current state and every result you have not recorded yet, then call ' +\n 'submit_result with what you have now; if the work is not done, mark it incomplete and name ' +\n 'what remains. Your lead decides whether to continue you or hand the work on. You keep running ' +\n 'while you make progress.'\n\n/** The idle bound a check-in policy sets, or undefined when time boxes are hard kills. */\nexport function checkInIdleMs(policy: DeadlineCheckIn | undefined): number | undefined {\n if (policy === false) return undefined\n const idleMs = policy?.idleMs ?? DEFAULT_CHECK_IN_IDLE_MS\n if (!Number.isSafeInteger(idleMs) || idleMs <= 0) {\n throw new ValidationError(\n 'deadlineCheckIn.idleMs must be a positive safe integer of milliseconds',\n )\n }\n return idleMs\n}\n\n/**\n * How long an abort waits for a manager whose result was already accepted to end the turn that\n * submitted it. Acceptance asks the turn's harness to stop; what remains is the turn's final\n * session copy (a bounded native capture), metering its usage and committing its result. Its\n * workspace capture is not part of it: the manager's owner runs that after the result.\n */\nexport const ACCEPTED_RESULT_GRACE_MS = 5 * 60_000\n\n/** Whether an abort reason is a deadline: the child's own or the root budget's. */\nexport function isDeadlineAbortReason(reason: unknown): boolean {\n return reason === CHILD_DEADLINE_REASON || reason === ROOT_DEADLINE_REASON\n}\nconst TEARDOWN_ACKNOWLEDGEMENT_MS = 250\n\n/** Arm a finite wall-clock deadline in safe chunks. Resource deadlines unref by default;\n * a standalone wait opts into keeping the process alive until it settles or is cancelled. */\nexport function armDeadlineTimer(\n delayMs: number,\n onDeadline: () => void,\n keepAlive = false,\n): () => void {\n const deadlineAtMs = Date.now() + Math.max(0, delayMs)\n if (!Number.isFinite(delayMs) || !Number.isSafeInteger(Math.ceil(deadlineAtMs))) {\n throw new ValidationError('timer delay must produce a finite safe deadline')\n }\n let cleared = false\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const arm = (): void => {\n if (cleared) return\n const remainingMs = Math.max(0, deadlineAtMs - Date.now())\n timer = setTimeout(\n () => {\n if (cleared) return\n if (Date.now() >= deadlineAtMs) onDeadline()\n else arm()\n },\n Math.min(remainingMs, MAX_TIMER_DELAY_MS),\n )\n if (!keepAlive && typeof timer.unref === 'function') timer.unref()\n }\n\n arm()\n return () => {\n cleared = true\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\n/**\n * Resolve a spawned child's duration into one absolute cutoff. An omitted child deadline inherits\n * the parent cutoff; an explicit child duration may shorten, but never extend, that cutoff.\n */\nexport function boundedChildDeadlineAt(\n parentDeadlineAtMs: number,\n childDeadlineMs: number | undefined,\n nowMs: number,\n): number | undefined {\n const parent = parentDeadlineAtMs > 0 ? parentDeadlineAtMs : undefined\n const child = childDeadlineMs === undefined ? undefined : nowMs + childDeadlineMs\n if (parent === undefined) return child\n if (child === undefined) return parent\n return Math.min(parent, child)\n}\n\n/** One answer from `Executor.teardown`. */\nexport type TeardownAnswer = Awaited<ReturnType<Executor<unknown>['teardown']>>\n\n/** Invoke teardown once and bound how long the runtime waits for its acknowledgement. A hard\n * execution deadline always wins; without one, numeric grace gets a short acknowledgement\n * allowance and a brutal kill gets only that allowance. Explicit `infinity` remains unbounded\n * only when no execution deadline exists. The losing promise stays observed. `ask` issues the\n * request; a scope passes its per-child single-flight asker (see `singleFlightTeardown`). */\nexport async function teardownExecutor<Out>(\n executor: Executor<Out>,\n grace: number | 'brutalKill' | 'infinity',\n deadlineAtMs: number | undefined,\n now: () => number,\n ask: (grace: number | 'brutalKill' | 'infinity') => Promise<TeardownAnswer> = (requested) =>\n Promise.resolve(executor.teardown(requested)),\n): Promise<void> {\n const work = Promise.resolve(ask(grace))\n\n const requestedWaitMs =\n grace === 'infinity'\n ? undefined\n : grace === 'brutalKill'\n ? (executor.teardownTimeoutMs ?? TEARDOWN_ACKNOWLEDGEMENT_MS)\n : grace + TEARDOWN_ACKNOWLEDGEMENT_MS\n // The execution cutoff stops new work; cleanup still gets a small, bounded acknowledgement\n // window after that cutoff. Otherwise an already-resolved brutal kill invoked exactly at the\n // deadline would be mislabeled as a cleanup failure without receiving one microtask.\n const deadlineWaitMs =\n deadlineAtMs === undefined\n ? undefined\n : Math.max(0, deadlineAtMs - now()) + TEARDOWN_ACKNOWLEDGEMENT_MS\n const waitMs =\n requestedWaitMs === undefined\n ? deadlineWaitMs\n : deadlineWaitMs === undefined\n ? requestedWaitMs\n : Math.min(requestedWaitMs, deadlineWaitMs)\n\n let receipt: TeardownAnswer\n if (waitMs === undefined) {\n receipt = await work\n } else if (waitMs <= 0) {\n void work.catch(() => undefined)\n throw new ValidationError('executor teardown did not acknowledge before its deadline')\n } else {\n let clearTimer: (() => void) | undefined\n const timedOut = new Promise<never>((_resolve, reject) => {\n clearTimer = armDeadlineTimer(\n waitMs,\n () =>\n reject(new ValidationError(`executor teardown did not acknowledge within ${waitMs}ms`)),\n true,\n )\n })\n try {\n receipt = await Promise.race([work, timedOut])\n } finally {\n clearTimer?.()\n }\n }\n\n if (!receipt.destroyed) {\n throw new ValidationError(\n `executor teardown reported destroyed=false${receipt.detail ? `: ${receipt.detail}` : ''}`,\n )\n }\n}\n\n/**\n * The optional teardown surfaces a wrapping executor forwards, so wrapping never changes how a\n * child is released: the acknowledgement window a remote teardown needs, the release of a\n * retained execution at root settlement, and the environments an unconfirmed teardown names for\n * a sweeper. A wrapper that dropped `releaseRetained` left every retained child it wrapped\n * running after settlement. Each surface is present only when the inner executor implements it.\n */\nexport function teardownSurfaces(\n inner: Executor<unknown>,\n): Pick<Executor<unknown>, 'teardownTimeoutMs' | 'releaseRetained' | 'heldEnvironments'> {\n return {\n ...(inner.teardownTimeoutMs === undefined\n ? {}\n : { teardownTimeoutMs: inner.teardownTimeoutMs }),\n ...(inner.releaseRetained === undefined\n ? {}\n : { releaseRetained: (signal: AbortSignal) => inner.releaseRetained!(signal) }),\n ...(inner.heldEnvironments === undefined\n ? {}\n : { heldEnvironments: () => inner.heldEnvironments!() }),\n }\n}\n\n/**\n * An asker that sends an executor at most one teardown at a time. While a request is still\n * running, every later ask returns that same request instead of sending another beside it.\n *\n * A settlement's own teardown has a short acknowledgement window, and a request that misses it\n * keeps running. Without this, the first settlement retry sent a second teardown next to the\n * first. An executor that does not deduplicate internally, such as one that re-issues its\n * cancels, then ran two teardowns at once. `onRequest` runs once for each request actually sent.\n */\nexport function singleFlightTeardown<Out>(\n executor: Executor<Out>,\n onRequest: () => void,\n): (grace: number | 'brutalKill' | 'infinity') => Promise<TeardownAnswer> {\n let inFlight: Promise<TeardownAnswer> | undefined\n return (grace) => {\n if (inFlight !== undefined) return inFlight\n onRequest()\n let request: Promise<TeardownAnswer>\n try {\n request = Promise.resolve(executor.teardown(grace))\n } catch (error) {\n request = Promise.reject(error)\n }\n inFlight = request\n const settle = (): void => {\n if (inFlight === request) inFlight = undefined\n }\n request.then(settle, settle)\n return request\n }\n}\n","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 { 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. Downstream code pattern-matches on `err.name`. */\nexport function abortError(): Error {\n const err = new Error('aborted')\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 */\nexport function 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/**\n * The spend of work that HAPPENED and reported no usage receipt.\n *\n * Not the same value as {@link zeroSpend} even though both carry `{0,0}` tokens and `$0`. A bare\n * zero asserts a MEASUREMENT — \"this ran and cost nothing\" — and every consumer downstream reads it\n * that way: the pool keeps reporting `readout().tokensKnown === true`, the journal totals stay\n * clean, the OTEL span records a priced zero, and a caller's token-denominated ceiling can never\n * fire no matter how much the work really burned. A ceiling that cannot fire is worse than no\n * ceiling, because it reads as protection.\n *\n * `tokensKnown` is the marker the substrate already threads end to end for exactly this case\n * (`budget.ts`, `otel-spans.ts`, `spawn-journal.ts`, `supervisor.ts`): the work is recorded, the\n * zero is labelled a floor rather than a total, and every rollup that touches it reports its\n * balance as a ceiling rather than a measurement. Use this — never a bare zero — whenever a runtime\n * cannot see what its worker spent.\n *\n * The same rule applies to dollars. A dollar-capped run must refuse an executor whose billed spend\n * is unknowable; `budgetExempt` does not authorize Runtime to relabel unknown spend as a measured\n * zero. Callers that require dollar accounting must use a backend with a trusted billing receipt.\n */\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 }\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 }\n}\n\n/**\n * Fold the token-provenance channel across spends, as a field to spread.\n *\n * Returns nothing when no contributor stated one, because ABSENT already means \"the executor's own\n * live stream\", which is what every path reported before a harness store was readable. A\n * contributor that stated one and a contributor that did not therefore disagree, and the sum is\n * `'mixed'` — the honest answer for a tree whose spend came from two kinds of receipt.\n */\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/**\n * Fold the platform box-time channel across spends, as a field to spread.\n *\n * Returns nothing when no input carried the channel, so a fold over router or cli-bridge work —\n * which runs no box at all — never gains a `boxMinutesProvenance: 'uncaptured'` that would claim\n * a box ran and went unmetered.\n *\n * Three rules, one per field:\n * - `boxMinutes` sums the numbers that are present, and stays ABSENT when none is. A missing\n * measurement never enters the sum as a zero.\n * - `boxMinutesKnown` is sticky-false, like `tokensKnown`: one contributor that could not state\n * its box time makes the whole sum a floor.\n * - `boxMinutesProvenance` degrades. `'observed'` survives only when every contributor that\n * carried a number was observed; one derived number makes the sum `'estimated'`; no number at\n * all is `'uncaptured'`.\n */\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/**\n * The token charge for one observation: every token counted ONCE, at the moment it first enters\n * the context — `input − cacheRead + output`.\n *\n * `input` is a rolled-up prompt total that re-counts a cached prefix on every turn that reads it,\n * so charging `input` makes a 100K prefix read 40 times cost 4.1M for content authored once. A\n * cache read is content that was already charged when it was written, so it is the one class the\n * charge subtracts. Under a complete split the result is exactly `freshInput + cacheWrite`. No\n * price weight is involved: this counts work, and money is a separate channel.\n *\n * The subtraction form is what makes the charge ADDITIVE. `input` and `cacheRead` both accumulate\n * through `addTokenUsage`, so the charge on an aggregate equals the sum of the charges on the\n * records that built it — including an aggregate that mixes classified and unclassified turns,\n * where the unclassified remainder is charged in full and only the reported cache reads are\n * credited. A form that read `freshInput + cacheWrite` directly loses that: one unclassified turn\n * would drop the whole aggregate to `input + output` and over-charge every classified turn with it.\n *\n * The one arithmetic guarantee: a set of classes that does not FIT inside the prompt total it\n * partitions credits nothing, so the charge is never below `output` and a class that overflows its\n * own total buys no tokens. It is not a guarantee against a provider that reports a cache read it\n * never served — that provider can under-report `input` just as easily, and the token channel is an\n * accounting unit, not a trust boundary. Prompt tokens the provider left unclassified are charged\n * in full, so a spend with no readable split charges an upper bound on newly-presented work rather\n * than a measurement, and every caller that enforces a ceiling must report the difference\n * (`BudgetPool` does it through `readout().cacheBreakdownKnown`).\n */\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 */\nexport interface PromptCacheCounters {\n readonly readTokens?: unknown\n readonly writeTokens?: unknown\n}\n\n/** The prompt-cache token classes of one observation, as `LoopTokenUsage` members. */\nexport type PromptCacheTokenClasses = Pick<\n LoopTokenUsage,\n 'freshInput' | 'cacheRead' | 'cacheWrite' | 'cacheBreakdownKnown'\n>\n\n/**\n * Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds\n * and `chargedTokens` credits.\n *\n * The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`\n * vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the\n * three outcomes are different facts that must not collapse into one another:\n *\n * - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,\n * because a provider that says nothing about caching has not said the split is unknowable.\n * - **Read and write both reported, and fitting inside `input`** — a complete partition, so\n * `freshInput` is the remainder and the split is known.\n * - **One counter reported, or classes that overflow `input`** — the counters that ARE measured\n * pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports\n * no write) still credits the read it measured, while declaring the rest unclassified so the\n * charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a\n * partition of a total it exceeds.\n *\n * A counter the provider did not report stays absent. A zero would claim the provider measured no\n * cache, which is a different fact from a provider that did not report.\n */\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/**\n * Add the observed subtotal into `acc`; token and cache incompleteness are sticky.\n *\n * A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO\n * classes. Folding them in would hide the overflow: the accumulator's larger `input` can absorb a\n * class total that overflowed the one delta that reported it, and `chargedTokens` would then credit\n * at the aggregate a cache read it refuses at the record. That is the one way the charge could come\n * out below the sum of the charges on the records that built it.\n */\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/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. On the first `fn` rejection no NEW\n * items are picked up; already-in-flight calls are awaited, then the first\n * error is rethrown. `limit` is clamped to ≥ 1.\n *\n * Used where a burst of provisioning (e.g. forking N child boxes) must respect\n * the loop's concurrency bound instead of firing all N at once.\n */\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","import { createHash } from 'node:crypto'\nimport {\n type AgentCandidateEmbeddedArtifact,\n canonicalCandidateBytes,\n type Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport type { CanonicalCandidateDocument } from './types'\n\nexport { canonicalCandidateBytes }\n\n/** Use native hashing for workspace archives. */\nexport function sha256Bytes(bytes: Uint8Array): Sha256Digest {\n return `sha256:${createHash('sha256').update(bytes).digest('hex')}`\n}\n\nexport function canonicalCandidateDigest(value: unknown): Sha256Digest {\n return sha256Bytes(canonicalCandidateBytes(value))\n}\n\n/** Returns a detached, deeply frozen JSON value with canonical number normalization. */\nexport function immutableCandidateValue<T>(value: T): T {\n return deepFreezeCandidate(\n JSON.parse(Buffer.from(canonicalCandidateBytes(value)).toString('utf8')) as T,\n )\n}\n\nexport function canonicalCandidateDocument<T extends { digest: Sha256Digest }>(\n valueWithoutDigest: Omit<T, 'digest'>,\n): CanonicalCandidateDocument<T> {\n const bytes = canonicalCandidateBytes(valueWithoutDigest)\n const digest = sha256Bytes(bytes)\n const value = deepFreezeCandidate({\n ...JSON.parse(Buffer.from(bytes).toString('utf8')),\n digest,\n }) as T\n return Object.freeze({\n value,\n get bytes(): Uint8Array {\n return Uint8Array.from(bytes)\n },\n digest,\n })\n}\n\nexport function verifyCanonicalCandidateDocument<T extends { digest: Sha256Digest }>(\n value: T,\n label: string,\n): T {\n if (canonicalCandidateDigest(omitTopLevelDigest(value)) !== value.digest) {\n throw new Error(`${label} digest does not match`)\n }\n return immutableCandidateValue(value)\n}\n\nexport function embeddedCandidateArtifact(bytes: Uint8Array): AgentCandidateEmbeddedArtifact {\n return {\n encoding: 'base64',\n content: Buffer.from(bytes).toString('base64'),\n sha256: sha256Bytes(bytes),\n byteLength: bytes.byteLength,\n }\n}\n\nexport function omitTopLevelDigest<T extends { digest: Sha256Digest }>(\n value: T,\n): Omit<T, 'digest'> {\n const { digest: _digest, ...rest } = value\n return rest\n}\n\nexport function deepFreezeCandidate<T>(value: T, seen = new Set<object>()): T {\n if (\n value === null ||\n typeof value !== 'object' ||\n ArrayBuffer.isView(value) ||\n seen.has(value as object)\n ) {\n return value\n }\n seen.add(value as object)\n for (const child of Object.values(value as Record<string, unknown>)) {\n deepFreezeCandidate(child, seen)\n }\n return Object.freeze(value)\n}\n","import { createHash } from 'node:crypto'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateCapturedArtifact,\n agentCandidateArtifactRefSchema,\n} from '@tangle-network/agent-interface'\nimport { immutableCandidateValue } from './digest'\nimport type {\n AgentCandidateArtifactPort,\n AgentCandidateOutputArtifactPort,\n AgentCandidateOutputPurpose,\n} from './types'\n\n/** Verify the complete stream, including its final digest, before accepting its consumer's result. */\nexport async function* verifiedArtifactChunks(\n artifact: AgentCandidateCapturedArtifact,\n port: AgentCandidateArtifactPort,\n signal?: AbortSignal,\n): AsyncGenerator<Uint8Array> {\n signal?.throwIfAborted()\n if (!('content' in artifact) && !port.readStream) {\n throw new Error('streaming workspace artifacts require readStream')\n }\n const chunks =\n 'content' in artifact\n ? [Buffer.from(artifact.content, 'base64')]\n : port.readStream!(artifact, { signal })\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of chunks) {\n signal?.throwIfAborted()\n if (!(chunk instanceof Uint8Array))\n throw new Error('candidate artifact emitted a non-byte chunk')\n byteLength += chunk.byteLength\n if (byteLength > artifact.byteLength)\n throw new Error('candidate artifact exceeds its declared length')\n hash.update(chunk)\n yield chunk\n }\n signal?.throwIfAborted()\n if (byteLength !== artifact.byteLength || `sha256:${hash.digest('hex')}` !== artifact.sha256) {\n throw new Error('candidate artifact failed digest or length verification')\n }\n}\n\nconst selfVerifyingPuts = new WeakMap<object, object>()\n\n/**\n * Declare that this exact putStream resolves only after reading its stored object back from where\n * this exact readStream reads it, and matching its digest and length. The claim belongs to the\n * pair, so a wrapper that replaces either function never inherits it.\n */\nexport function markPutStreamVerified(putStream: object, readStream: object): void {\n selfVerifyingPuts.set(putStream, readStream)\n}\n\n/** Whether a port's putStream already read back what its readStream will return. */\nexport function putStreamVerifiedBy(port: AgentCandidateOutputArtifactPort): boolean {\n return (\n port.putStream !== undefined &&\n port.readStream !== undefined &&\n selfVerifyingPuts.get(port.putStream) === port.readStream\n )\n}\n\n/** Stream evaluator evidence into its existing store and verify durable readback before returning. */\nexport async function persistCandidateOutputArtifactStream(\n port: AgentCandidateOutputArtifactPort,\n input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n chunks: AsyncIterable<Uint8Array>\n maxBytes: number\n signal?: AbortSignal\n },\n): Promise<AgentCandidateArtifactRef> {\n if (!port.putStream || !port.readStream) {\n throw new Error('streaming workspace persistence requires putStream and readStream')\n }\n input.signal?.throwIfAborted()\n const hash = createHash('sha256')\n let byteLength = 0\n let consumed = false\n async function* checked(): AsyncGenerator<Uint8Array> {\n for await (const chunk of input.chunks) {\n input.signal?.throwIfAborted()\n if (!(chunk instanceof Uint8Array))\n throw new Error('candidate artifact emitted a non-byte chunk')\n byteLength += chunk.byteLength\n if (byteLength > input.maxBytes)\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n hash.update(chunk)\n yield chunk\n }\n consumed = true\n input.signal?.throwIfAborted()\n }\n const chunks = checked()\n try {\n const ref = agentCandidateArtifactRefSchema.parse(\n await port.putStream({\n executionId: input.executionId,\n purpose: input.purpose,\n chunks,\n ...(input.signal ? { signal: input.signal } : {}),\n }),\n )\n input.signal?.throwIfAborted()\n if (\n !consumed ||\n ref.sha256 !== `sha256:${hash.digest('hex')}` ||\n ref.byteLength !== byteLength\n ) {\n throw new Error('candidate output locator does not identify the submitted bytes')\n }\n // A port that already read its stored object back is not read a third time. Measured\n // 2026-10-11: a critics tribunal on /mnt/traces re-read 1.1 GB/min of just-written workspace\n // archives, each one written once and read back twice.\n if (!putStreamVerifiedBy(port)) {\n for await (const _chunk of verifiedArtifactChunks(ref, port, input.signal)) {\n // Verification consumes the durable object without retaining it.\n }\n }\n return immutableCandidateValue(ref)\n } finally {\n await chunks.return(undefined)\n }\n}\n","import { createHash } from 'node:crypto'\nimport { constants as fsConstants } from 'node:fs'\nimport { lstat, open, readdir, readlink, realpath } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve, sep } from 'node:path'\n\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateCapturedArtifact,\n AgentCandidateProfilePlanMaterial,\n AgentCandidateWorkspaceManifestMaterial,\n AgentCandidateWorkspaceSnapshotEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateBytes, sha256Bytes } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\n\nexport function artifactCacheKey(artifact: AgentCandidateCapturedArtifact): string {\n return `${artifact.sha256}:${artifact.byteLength}`\n}\n\nexport async function readVerifiedArtifact(\n artifact: AgentCandidateCapturedArtifact,\n port: AgentCandidateArtifactPort,\n): Promise<Uint8Array> {\n const bytes =\n 'content' in artifact\n ? Buffer.from(artifact.content, 'base64')\n : await port.read(artifact as AgentCandidateArtifactRef)\n verifyBytes(bytes, artifact.sha256, artifact.byteLength, 'candidate artifact')\n return Uint8Array.from(bytes)\n}\n\nexport function verifyBytes(\n bytes: Uint8Array,\n digest: string,\n byteLength: number,\n label: string,\n): void {\n if (bytes.byteLength !== byteLength) {\n throw new Error(`${label} byte length ${bytes.byteLength} does not match ${byteLength}`)\n }\n const actual = sha256Bytes(bytes)\n if (actual !== digest) {\n throw new Error(`${label} digest ${actual} does not match ${digest}`)\n }\n}\n\nexport async function verifyWorkspaceSnapshotArtifacts(\n snapshot: AgentCandidateWorkspaceSnapshotEvidence,\n port: AgentCandidateArtifactPort,\n): Promise<{ manifest: Uint8Array; archive: Uint8Array }> {\n const [manifest, archive] = await Promise.all([\n readVerifiedArtifact(snapshot.manifest, port),\n readVerifiedArtifact(snapshot.archive, port),\n ])\n const canonicalManifest = canonicalCandidateBytes(snapshot.material)\n if (!Buffer.from(manifest).equals(Buffer.from(canonicalManifest))) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n if (sha256Bytes(canonicalManifest) !== snapshot.digest) {\n throw new Error('workspace snapshot digest does not match its canonical manifest material')\n }\n return { manifest, archive }\n}\n\n/** The per-scan caps a bounded capture applies. */\nexport interface WorkspaceScanLimits {\n readonly maxFiles: number\n readonly maxFileBytes: number\n readonly maxTotalFileBytes: number\n}\n\n/** A configured file-count or byte limit stopped workspace capture. */\nexport class WorkspaceScanLimitError extends Error {}\n\n/** What a workspace scan reads and how it records a file's permission bits. */\nexport interface WorkspaceScanOptions {\n readonly signal?: AbortSignal\n readonly ignoredProtectedRootEntries?: readonly ('.git' | '.sidecar')[]\n readonly limits?: WorkspaceScanLimits\n /**\n * Record Git's two file modes instead of the filesystem's exact permission bits: `0o755` when\n * any execute bit is set, `0o644` otherwise. A checkout umask then cannot move a manifest\n * digest, while a real permission change still does.\n *\n * This is the normalization `readCandidateGitTreeFiles` already applies to a Git tree\n * (`100644`/`100755`), so one tree scanned from disk and the same tree read out of Git produce\n * the same manifest. Off by default: the flag changes the digest, so a capture and the verify\n * that checks it must agree on it.\n */\n readonly portableTree?: boolean\n}\n\n/**\n * Refuse a materialized workspace whose files, modes, or bytes are not the signed manifest.\n *\n * The scan streams, so the size of the largest file does not decide whether the check can run, and\n * the refusal names the one mismatch a caller can produce on its own: a capture and a verify that\n * disagree about `portableTree`.\n */\nexport async function verifyMaterializedWorkspace(\n root: string,\n expected: AgentCandidateWorkspaceManifestMaterial,\n options: Omit<WorkspaceScanOptions, 'limits'> = {},\n): Promise<void> {\n assertWorkspaceManifest(await scanMaterializedWorkspaceManifest(root, options), expected)\n}\n\n/**\n * The canonical manifest of one materialized workspace, read without holding any file.\n *\n * Every file is digested by streaming, so the size of the largest file does not decide whether the\n * workspace can be described. `FileHandle.readFile` refuses anything above 2 GiB with\n * `ERR_FS_FILE_TOO_LARGE`, which made a workspace holding one such artifact impossible to verify\n * against a manifest it already matched. The digest is sha-256 over the same bytes either way, so\n * a manifest a buffered read produced is reproduced exactly.\n */\nexport async function scanMaterializedWorkspaceManifest(\n root: string,\n options: WorkspaceScanOptions = {},\n): Promise<AgentCandidateWorkspaceManifestMaterial> {\n return workspaceManifestFromEntries(await walkWorkspace(root, options, false))\n}\n\n/**\n * Capture settings Runtime's own callers may add. `skipPythonBytecode` leaves out `__pycache__/`\n * directories and `*.pyc` files: the interpreter writes them beside the sources it runs, Git\n * ignores them, and each carries its source's modification time, so a digest that covered them\n * would change when a program was merely run and could not be reproduced from any checkout.\n */\nexport interface WorkspaceCaptureOptions extends WorkspaceScanOptions {\n readonly skipPythonBytecode?: boolean\n}\n\nexport async function captureMaterializedWorkspace(\n root: string,\n options: WorkspaceCaptureOptions = {},\n): Promise<{\n manifest: AgentCandidateWorkspaceManifestMaterial\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>\n}> {\n const entries = await walkWorkspace(root, options, true)\n return {\n manifest: workspaceManifestFromEntries(entries),\n files: entries.map((entry) => ({\n path: entry.path,\n mode: entry.mode,\n bytes: Uint8Array.from(capturedBytes(entry)),\n })),\n }\n}\n\n/** Capture exact verified regular-file bytes for fresh isolated materialization. */\nexport async function readMaterializedWorkspaceFiles(\n root: string,\n expected: AgentCandidateWorkspaceManifestMaterial,\n options: WorkspaceScanOptions = {},\n): Promise<ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>> {\n const observed = await captureMaterializedWorkspace(root, options)\n assertWorkspaceManifest(observed.manifest, expected)\n return observed.files.map((file) =>\n Object.freeze({ path: file.path, mode: file.mode, bytes: Uint8Array.from(file.bytes) }),\n )\n}\n\n/**\n * Build the canonical manifest for files a caller already holds — the shape a remote executor\n * returns. Pass `portableTree` to record Git's two file modes instead of exact permission bits, and\n * pass the same flag to every verify that reads the result.\n */\nexport function candidateWorkspaceManifest(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n options: { portableTree?: boolean } = {},\n): AgentCandidateWorkspaceManifestMaterial {\n return workspaceManifestFromEntries(\n files.map((file) => ({\n path: file.path,\n mode: options.portableTree === true ? portableFileMode(file.mode) : file.mode,\n sha256: sha256Bytes(file.bytes),\n byteLength: file.bytes.byteLength,\n })),\n )\n}\n\nfunction workspaceManifestFromEntries(\n entries: ReadonlyArray<{\n path: string\n mode: number\n sha256: Sha256Digest\n byteLength: number\n }>,\n): AgentCandidateWorkspaceManifestMaterial {\n return {\n kind: 'agent-candidate-workspace-manifest',\n files: entries\n .map((entry) => ({\n path: entry.path,\n mode: entry.mode,\n sha256: entry.sha256,\n byteLength: entry.byteLength,\n }))\n .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)),\n }\n}\n\n/** Git records exactly two file modes, and a portable-tree scan records the same two. */\nfunction portableFileMode(mode: number): number {\n return (mode & 0o111) !== 0 ? 0o755 : 0o644\n}\n\nfunction capturedBytes(entry: ScannedWorkspaceEntry): Buffer {\n if (!entry.bytes) throw new Error(`workspace file was digested without its bytes: ${entry.path}`)\n return entry.bytes\n}\n\nfunction assertWorkspaceManifest(\n observed: AgentCandidateWorkspaceManifestMaterial,\n expected: AgentCandidateWorkspaceManifestMaterial,\n): void {\n if (Buffer.from(canonicalCandidateBytes(observed)).equals(canonicalCandidateBytes(expected))) {\n return\n }\n // The one mismatch a caller can produce by passing `portableTree` on one side of a\n // capture/verify pair and not the other. Named, because the general refusal below reads as\n // changed bytes and would send a reader looking for a file that never changed. Comparing the\n // two manifests already in hand costs no second walk.\n if (\n Buffer.from(canonicalCandidateBytes(withPortableModes(observed))).equals(\n canonicalCandidateBytes(withPortableModes(expected)),\n )\n ) {\n throw new Error(\n 'materialized workspace files do not match the signed manifest: only the file modes differ, ' +\n 'so the capture and this verify disagree about portableTree',\n )\n }\n throw new Error('materialized workspace files, modes, or bytes do not match the signed manifest')\n}\n\nfunction withPortableModes(\n material: AgentCandidateWorkspaceManifestMaterial,\n): AgentCandidateWorkspaceManifestMaterial {\n return {\n ...material,\n files: material.files.map((file) => ({ ...file, mode: portableFileMode(file.mode) })),\n }\n}\n\nexport async function verifyMaterializedProfileWorkspace(\n root: string,\n expected: AgentCandidateProfilePlanMaterial,\n fileRoot: 'workspace' | 'agent' = 'workspace',\n): Promise<void> {\n const observed = await scanMaterializedWorkspaceManifest(root)\n const observedProfile = observed.files.map(({ path, mode, sha256 }) => ({\n relPath: path,\n mode,\n contentSha256: sha256,\n }))\n const expectedFiles = expected.files\n .filter((file) => (file.root ?? 'workspace') === fileRoot)\n .map(({ root: _root, ...file }) => file)\n if (\n !Buffer.from(canonicalCandidateBytes(observedProfile)).equals(\n canonicalCandidateBytes(expectedFiles),\n )\n ) {\n throw new Error(\n `profile ${fileRoot} staging files, modes, or bytes do not match the signed profile plan`,\n )\n }\n}\n\ninterface ScannedWorkspaceEntry {\n readonly path: string\n readonly mode: number\n readonly sha256: Sha256Digest\n readonly byteLength: number\n /** Present only when the walk was asked to keep bytes. */\n readonly bytes?: Buffer\n}\n\nasync function walkWorkspace(\n root: string,\n options: WorkspaceCaptureOptions,\n keepBytes: boolean,\n): Promise<ScannedWorkspaceEntry[]> {\n const ignoredProtectedRootEntries = new Set<string>(options.ignoredProtectedRootEntries ?? [])\n const limits = options.limits\n // Scan the RESOLVED root. The property this guards is that every captured path lies under\n // one real directory with no aliasing, which resolving satisfies directly — rejecting a\n // symlinked prefix outright does not, and makes the scan impossible on macOS, where the\n // OS itself hands out temp paths under /var, a symlink to /private/var. Symlinks INSIDE\n // the workspace are still refused entry by entry below, with O_NOFOLLOW on every open.\n const requestedRoot = resolve(root)\n const rootStats = await lstat(requestedRoot)\n if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) {\n throw new Error('workspace root must be a real directory')\n }\n const absoluteRoot = await realpath(requestedRoot)\n const resolvedStats = await lstat(absoluteRoot)\n if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) {\n throw new Error('workspace root must resolve to a real directory')\n }\n const scanned: ScannedWorkspaceEntry[] = []\n let totalBytes = 0\n\n async function visit(directory: string): Promise<void> {\n options.signal?.throwIfAborted()\n const entries = await readdir(directory, { withFileTypes: true })\n entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n for (const entry of entries) {\n options.signal?.throwIfAborted()\n if (directory === absoluteRoot && ignoredProtectedRootEntries.has(entry.name)) {\n continue\n }\n if (\n options.skipPythonBytecode === true &&\n ((entry.isDirectory() && entry.name === '__pycache__') ||\n (entry.isFile() && entry.name.endsWith('.pyc')))\n ) {\n continue\n }\n const absolute = resolve(directory, entry.name)\n const relPath = relative(absoluteRoot, absolute).split(sep).join('/')\n if (!relPath || relPath.startsWith('../') || relPath.includes('/../')) {\n throw new Error(`workspace entry escapes root: ${relPath}`)\n }\n const stats = await lstat(absolute)\n if (stats.isSymbolicLink()) {\n throw new Error(await symlinkRefusal(absolute, relPath, absoluteRoot))\n }\n if (stats.isDirectory()) {\n await visit(absolute)\n continue\n }\n if (!stats.isFile()) {\n throw new Error(`workspace contains a non-regular entry: ${relPath}`)\n }\n if (limits && scanned.length >= limits.maxFiles) {\n throw new WorkspaceScanLimitError('workspace exceeds maxFiles')\n }\n const descriptor = await open(\n absolute,\n fsConstants.O_RDONLY |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n )\n try {\n const openedStats = await descriptor.stat()\n if (!openedStats.isFile()) {\n throw new Error(`workspace contains a non-regular entry: ${relPath}`)\n }\n if (openedStats.nlink !== 1) {\n throw new Error(`workspace contains a hard-linked file: ${relPath}`)\n }\n const mode =\n options.portableTree === true\n ? portableFileMode(openedStats.mode)\n : openedStats.mode & 0o777\n if (limits && openedStats.size > limits.maxFileBytes) {\n throw new WorkspaceScanLimitError(`workspace file exceeds maxFileBytes: ${relPath}`)\n }\n const remainingBytes = limits ? limits.maxTotalFileBytes - totalBytes : undefined\n if (remainingBytes !== undefined && openedStats.size > remainingBytes) {\n throw new WorkspaceScanLimitError('workspace exceeds maxTotalFileBytes')\n }\n const read = await readWorkspaceFile(\n descriptor,\n limits ? Math.min(limits.maxFileBytes, remainingBytes ?? limits.maxFileBytes) : undefined,\n keepBytes,\n relPath,\n options.signal,\n )\n totalBytes += read.byteLength\n scanned.push({\n path: relPath,\n mode,\n sha256: read.sha256,\n byteLength: read.byteLength,\n ...(read.bytes === undefined ? {} : { bytes: read.bytes }),\n })\n } finally {\n await descriptor.close()\n }\n }\n }\n\n await visit(absoluteRoot)\n return scanned\n}\n\n/**\n * Why one symbolic link is refused, in the terms that separate a portable link from a link that\n * reaches outside the tree.\n *\n * Every link is refused, in both mode policies. `AgentCandidateWorkspaceManifestMaterial` has no\n * representation for one — `mode`, `sha256` and `byteLength` describe a regular file — so a link\n * recorded as a file would let two different trees share one digest. The reason says which kind of\n * link it was, so a caller can tell a link it can rewrite from one it cannot.\n */\nasync function symlinkRefusal(\n absolute: string,\n relPath: string,\n absoluteRoot: string,\n): Promise<string> {\n const target = await readlink(absolute)\n if (isAbsolute(target)) {\n return `workspace contains an absolute symlink: ${relPath} -> ${target}`\n }\n if (!isWithin(absoluteRoot, resolve(dirname(absolute), target))) {\n return `workspace contains a symlink that escapes its tree: ${relPath} -> ${target}`\n }\n let physical: string\n try {\n physical = await realpath(absolute)\n } catch {\n return `workspace contains an unresolved symlink: ${relPath} -> ${target}`\n }\n if (!isWithin(absoluteRoot, physical)) {\n return `workspace contains a symlink that resolves outside its tree: ${relPath} -> ${target}`\n }\n return `workspace contains a symlink: ${relPath} -> ${target}`\n}\n\nfunction isWithin(root: string, path: string): boolean {\n return path === root || path.startsWith(`${root}${sep}`)\n}\n\n/**\n * Read one open regular file into its digest, keeping the bytes only when the caller needs them.\n *\n * The content reaches the hash in 1 MiB chunks and is never held whole for a digest-only walk, so\n * the size of the largest file does not decide whether a workspace can be described.\n * `FileHandle.readFile` refuses anything above 2 GiB with `ERR_FS_FILE_TOO_LARGE`. Hashing the\n * chunks in order equals hashing the whole buffer, so a manifest a buffered read produced is\n * reproduced byte for byte.\n */\nasync function readWorkspaceFile(\n descriptor: Awaited<ReturnType<typeof open>>,\n maxBytes: number | undefined,\n keepBytes: boolean,\n path: string,\n signal?: AbortSignal,\n): Promise<{ sha256: Sha256Digest; byteLength: number; bytes?: Buffer }> {\n const hash = createHash('sha256')\n const buffer = Buffer.allocUnsafe(1024 * 1024)\n const chunks: Buffer[] = []\n let total = 0\n while (true) {\n signal?.throwIfAborted()\n const { bytesRead } = await descriptor.read(buffer, 0, buffer.byteLength, null)\n if (bytesRead === 0) break\n total += bytesRead\n if (maxBytes !== undefined && total > maxBytes) {\n throw new WorkspaceScanLimitError(`workspace file exceeds its capture limit: ${path}`)\n }\n const chunk = buffer.subarray(0, bytesRead)\n hash.update(chunk)\n // The read buffer is reused, so a kept chunk has to be copied out of it.\n if (keepBytes) chunks.push(Buffer.from(chunk))\n }\n const sha256 = `sha256:${hash.digest('hex')}` as Sha256Digest\n return keepBytes\n ? { sha256, byteLength: total, bytes: Buffer.concat(chunks, total) }\n : { sha256, byteLength: total }\n}\n","/** Reject unknown fields while requiring every declared non-optional field. */\nexport function assertExactObjectKeys(\n value: unknown,\n required: readonly string[],\n label: string,\n optional: readonly string[] = [],\n): void {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const allowed = new Set([...required, ...optional])\n if (allowed.size !== required.length + optional.length) {\n throw new Error(`${label} exact-key contract contains duplicate fields`)\n }\n for (const key of Object.keys(value)) {\n if (!allowed.has(key)) throw new Error(`${label} contains unknown field ${key}`)\n }\n for (const key of required) {\n if (!(key in value)) throw new Error(`${label} is missing field ${key}`)\n }\n}\n\n/**\n * Reject a string carrying a lone surrogate. A well-formed UTF-16 string round-trips through UTF-8\n * unchanged; a lone surrogate does not, so a value that passes here is safe to persist and re-read\n * as the same bytes.\n */\nexport function isWellFormedUnicode(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1)\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false\n index++\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return false\n }\n }\n return true\n}\n","import { spawn } from 'node:child_process'\nimport { mkdir, mkdtemp, readFile, realpath, rm, stat } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\nimport type {\n AgentCandidateCode,\n AgentCandidateGitHubRepository,\n AgentCandidateGitHubResource,\n AgentCandidateWorkspaceManifestMaterial,\n} from '@tangle-network/agent-interface'\n\nimport { candidateWorkspaceManifest, verifyBytes } from './artifacts'\nimport { canonicalCandidateBytes } from './digest'\nimport type { AgentCandidateRepositoryPort } from './types'\n\ninterface GitResult {\n stdout: Buffer\n stderr: Buffer\n}\n\nexport async function verifyCandidateCode(\n code: AgentCandidateCode,\n repositories: AgentCandidateRepositoryPort,\n patchBytes?: Uint8Array,\n): Promise<string | undefined> {\n if (code.kind === 'disabled') return undefined\n const repositoryRoot = await verifiedRepositoryRoot(code.repository, repositories)\n await assertCommitAndBaseTree(repositoryRoot, code.baseCommit, code.baseTree)\n\n if (code.kind === 'no-op') {\n await assertSafeTree(repositoryRoot, code.baseTree)\n return code.baseTree\n }\n if (!patchBytes) throw new Error('git-patch candidate is missing verified patch bytes')\n\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-git-'))\n try {\n const indexFile = join(temporary, 'index')\n await runCandidateGit(repositoryRoot, ['read-tree', code.baseTree], undefined, {\n GIT_INDEX_FILE: indexFile,\n })\n await runCandidateGit(\n repositoryRoot,\n ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'],\n patchBytes,\n { GIT_INDEX_FILE: indexFile },\n )\n const candidateTree = (\n await runCandidateGit(repositoryRoot, ['write-tree'], undefined, {\n GIT_INDEX_FILE: indexFile,\n })\n ).stdout\n .toString('utf8')\n .trim()\n if (candidateTree !== code.candidateTree) {\n throw new Error(\n `git patch materialized tree ${candidateTree} does not match ${code.candidateTree}`,\n )\n }\n await assertSafeTree(repositoryRoot, candidateTree)\n return candidateTree\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nexport async function readCandidateGitHubResource(\n resource: AgentCandidateGitHubResource,\n repositories: AgentCandidateRepositoryPort,\n): Promise<Uint8Array> {\n const repositoryRoot = await verifiedRepositoryRoot(resource.repository, repositories)\n const commitType = (\n await runCandidateGit(repositoryRoot, ['cat-file', '-t', resource.commit])\n ).stdout\n .toString('utf8')\n .trim()\n if (commitType !== 'commit') {\n throw new Error(`GitHub resource commit is not a commit object: ${resource.commit}`)\n }\n const listing = (\n await runCandidateGit(repositoryRoot, ['ls-tree', '-z', resource.commit, '--', resource.path])\n ).stdout\n const entries = parseTreeEntries(listing)\n if (entries.length !== 1 || entries[0]?.path !== resource.path) {\n throw new Error(`GitHub resource path is not one exact file: ${resource.path}`)\n }\n const entry = entries[0]\n if (entry?.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(`GitHub resource path is not a regular Git blob: ${resource.path}`)\n }\n const bytes = (await runCandidateGit(repositoryRoot, ['cat-file', 'blob', entry.object])).stdout\n verifyBytes(bytes, resource.sha256, resource.byteLength, `GitHub resource ${resource.path}`)\n return Uint8Array.from(bytes)\n}\n\nexport async function verifyTaskCheckout(\n taskRoot: string,\n expected: { baseCommit: string; baseTree: string },\n): Promise<void> {\n const root = resolve(taskRoot)\n const head = (await runCandidateGit(root, ['rev-parse', 'HEAD'])).stdout.toString('utf8').trim()\n if (head !== expected.baseCommit) {\n throw new Error(`task checkout HEAD ${head} does not match ${expected.baseCommit}`)\n }\n const tree = (await runCandidateGit(root, ['rev-parse', 'HEAD^{tree}'])).stdout\n .toString('utf8')\n .trim()\n if (tree !== expected.baseTree) {\n throw new Error(`task checkout base tree ${tree} does not match ${expected.baseTree}`)\n }\n}\n\n/**\n * Apply an evaluator-captured binary diff in a detached object database and\n * prove its result tree exactly matches the captured after-state manifest.\n */\nexport async function verifyTaskOutcomePatch(input: {\n repositoryRoot: string\n baseCommit: string\n baseTree: string\n resultTree: string\n patch: Uint8Array\n afterState: AgentCandidateWorkspaceManifestMaterial\n}): Promise<{ resultTree: string; resultCommit: string }> {\n const repositoryRoot = resolve(input.repositoryRoot)\n await verifyTaskCheckout(repositoryRoot, input)\n const gitDir = resolve(\n (await runCandidateGit(repositoryRoot, ['rev-parse', '--absolute-git-dir'])).stdout\n .toString('utf8')\n .trim(),\n )\n if ((await realpath(gitDir)) !== gitDir || gitDir.includes(':')) {\n throw new Error('task Git object store has an unsupported path')\n }\n await assertNoGitIndirection(repositoryRoot, gitDir, 'task repository')\n\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-task-outcome-'))\n try {\n const objectDirectory = join(temporary, 'objects')\n const indexFile = join(temporary, 'index')\n await mkdir(objectDirectory)\n const gitEnvironment = {\n GIT_INDEX_FILE: indexFile,\n GIT_OBJECT_DIRECTORY: objectDirectory,\n GIT_ALTERNATE_OBJECT_DIRECTORIES: join(gitDir, 'objects'),\n }\n await runCandidateGit(repositoryRoot, ['read-tree', input.baseTree], undefined, gitEnvironment)\n if (input.patch.byteLength > 0) {\n await runCandidateGit(\n repositoryRoot,\n ['apply', '--cached', '--binary', '--whitespace=nowarn', '-'],\n input.patch,\n gitEnvironment,\n )\n }\n const resultTree = (\n await runCandidateGit(repositoryRoot, ['write-tree'], undefined, gitEnvironment)\n ).stdout\n .toString('utf8')\n .trim()\n if (resultTree !== input.resultTree) {\n throw new Error(\n `task outcome patch materialized tree ${resultTree} does not match ${input.resultTree}`,\n )\n }\n await assertSafeTree(repositoryRoot, resultTree, gitEnvironment)\n const observed = await workspaceManifestFromGitTree(repositoryRoot, resultTree, gitEnvironment)\n if (\n !Buffer.from(canonicalCandidateBytes(observed)).equals(\n Buffer.from(canonicalCandidateBytes(input.afterState)),\n )\n ) {\n throw new Error('task outcome after-state does not match the materialized result tree')\n }\n const resultCommit = (\n await runCandidateGit(\n repositoryRoot,\n ['commit-tree', resultTree, '-p', input.baseCommit],\n Buffer.from('candidate task outcome\\n', 'utf8'),\n {\n ...gitEnvironment,\n GIT_AUTHOR_NAME: 'Tangle Evaluator',\n GIT_AUTHOR_EMAIL: 'evaluator@tangle.tools',\n GIT_AUTHOR_DATE: '2000-01-01T00:00:00Z',\n GIT_COMMITTER_NAME: 'Tangle Evaluator',\n GIT_COMMITTER_EMAIL: 'evaluator@tangle.tools',\n GIT_COMMITTER_DATE: '2000-01-01T00:00:00Z',\n },\n )\n ).stdout\n .toString('utf8')\n .trim()\n const committedTree = (\n await runCandidateGit(\n repositoryRoot,\n ['rev-parse', `${resultCommit}^{tree}`],\n undefined,\n gitEnvironment,\n )\n ).stdout\n .toString('utf8')\n .trim()\n if (committedTree !== resultTree) {\n throw new Error('task outcome evaluator commit does not bind the verified result tree')\n }\n return { resultTree, resultCommit }\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nasync function verifiedRepositoryRoot(\n repository: AgentCandidateGitHubRepository,\n repositories: AgentCandidateRepositoryPort,\n): Promise<string> {\n const repositoryRoot = resolve(await repositories.resolve(repository))\n const rootStats = await stat(repositoryRoot)\n if (!rootStats.isDirectory()) throw new Error('candidate repository path is not a directory')\n\n const origin = (await runCandidateGit(repositoryRoot, ['remote', 'get-url', 'origin'])).stdout\n .toString('utf8')\n .trim()\n const actual = parseGitHubRemote(origin)\n if (!actual || actual.owner !== repository.owner || actual.repo !== repository.repo) {\n throw new Error(\n `local repository origin ${origin || '<missing>'} does not match github.com/${repository.owner}/${repository.repo}`,\n )\n }\n\n const gitDirText = (\n await runCandidateGit(repositoryRoot, ['rev-parse', '--absolute-git-dir'])\n ).stdout\n .toString('utf8')\n .trim()\n const gitDir = resolve(gitDirText)\n await assertNoGitIndirection(repositoryRoot, gitDir, 'candidate repository')\n return repositoryRoot\n}\n\nexport async function assertNoGitIndirection(\n repositoryRoot: string,\n gitDir: string,\n label: string,\n): Promise<void> {\n const replacements = (\n await runCandidateGit(repositoryRoot, ['for-each-ref', '--format=%(refname)', 'refs/replace'])\n ).stdout\n .toString('utf8')\n .trim()\n if (replacements) throw new Error(`${label} contains Git replace refs`)\n // `--git-common-dir` answers relative to the worktree for an ordinary repository, so the\n // path is resolved against a root the caller supplied and carries whatever symlinks that\n // root carries. Read the object store through its RESOLVED path: the alternates below must\n // be read at the real location, and a symlinked prefix is the OS's own doing on macOS,\n // where a temp root lives under /var, a symlink to /private/var.\n const commonDir = await realpath(\n resolve(\n repositoryRoot,\n (await runCandidateGit(repositoryRoot, ['rev-parse', '--git-common-dir'])).stdout\n .toString('utf8')\n .trim(),\n ),\n )\n if (commonDir.includes(':')) {\n throw new Error(`${label} Git common directory has an unsupported path`)\n }\n for (const objectRoot of new Set([gitDir, commonDir])) {\n for (const name of ['alternates', 'http-alternates']) {\n const path = join(objectRoot, 'objects', 'info', name)\n try {\n const contents = await readFile(path, 'utf8')\n if (contents.trim()) throw new Error(`${label} uses forbidden Git ${name}`)\n } catch (error) {\n if (!isNoEntry(error)) throw error\n }\n }\n }\n}\n\nasync function assertCommitAndBaseTree(\n repositoryRoot: string,\n commit: string,\n expectedTree: string,\n): Promise<void> {\n const type = (await runCandidateGit(repositoryRoot, ['cat-file', '-t', commit])).stdout\n .toString('utf8')\n .trim()\n if (type !== 'commit') throw new Error(`candidate base object is not a commit: ${commit}`)\n const actualTree = (\n await runCandidateGit(repositoryRoot, ['rev-parse', `${commit}^{tree}`])\n ).stdout\n .toString('utf8')\n .trim()\n if (actualTree !== expectedTree) {\n throw new Error(`candidate base commit tree ${actualTree} does not match ${expectedTree}`)\n }\n}\n\nasync function assertSafeTree(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string> = {},\n): Promise<void> {\n const listing = (\n await runCandidateGit(\n repositoryRoot,\n ['ls-tree', '-rz', '--full-tree', tree],\n undefined,\n environment,\n )\n ).stdout\n const entries = parseTreeEntries(listing)\n if (entries.length === 0) throw new Error('candidate Git tree cannot be empty')\n for (const entry of entries) {\n if (entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(\n `candidate Git tree contains a symlink, submodule, or non-blob: ${entry.path}`,\n )\n }\n assertSafeGitPath(entry.path)\n }\n}\n\nasync function workspaceManifestFromGitTree(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string>,\n): Promise<AgentCandidateWorkspaceManifestMaterial> {\n return candidateWorkspaceManifest(\n await readCandidateGitTreeFiles(repositoryRoot, tree, environment),\n )\n}\n\nexport async function readCandidateGitTreeFiles(\n repositoryRoot: string,\n tree: string,\n environment: Record<string, string> = {},\n limits?: { maxFiles: number; maxFileBytes: number; maxTotalFileBytes: number },\n): Promise<Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>> {\n const listing = (\n await runCandidateGit(\n repositoryRoot,\n ['ls-tree', '-rzl', '--full-tree', tree],\n undefined,\n environment,\n )\n ).stdout\n const files: Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }> = []\n const entries = parseTreeEntries(listing)\n if (limits && entries.length > limits.maxFiles) {\n throw new Error('candidate Git tree exceeds maxFiles')\n }\n let totalBytes = 0\n for (const entry of entries) {\n if (entry.type !== 'blob' || (entry.mode !== '100644' && entry.mode !== '100755')) {\n throw new Error(`candidate Git tree contains a non-regular file: ${entry.path}`)\n }\n assertSafeGitPath(entry.path)\n if (entry.size === undefined) {\n throw new Error(`candidate Git tree is missing blob size: ${entry.path}`)\n }\n if (limits && entry.size > limits.maxFileBytes) {\n throw new Error(`candidate Git tree file exceeds maxFileBytes: ${entry.path}`)\n }\n totalBytes += entry.size\n if (limits && totalBytes > limits.maxTotalFileBytes) {\n throw new Error('candidate Git tree exceeds maxTotalFileBytes')\n }\n const bytes = (\n await runCandidateGit(\n repositoryRoot,\n ['cat-file', 'blob', entry.object],\n undefined,\n environment,\n )\n ).stdout\n if (bytes.byteLength !== entry.size) {\n throw new Error(`candidate Git blob size changed: ${entry.path}`)\n }\n files.push({\n path: entry.path,\n mode: entry.mode === '100755' ? 0o755 : 0o644,\n bytes: Uint8Array.from(bytes),\n })\n }\n return files.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n}\n\nfunction parseTreeEntries(bytes: Uint8Array): Array<{\n mode: string\n type: string\n object: string\n size?: number\n path: string\n}> {\n const raw = Buffer.from(bytes)\n const decoded = raw.toString('utf8')\n if (!Buffer.from(decoded, 'utf8').equals(raw)) {\n throw new Error('candidate Git tree contains a non-UTF-8 path')\n }\n const rows = decoded.split('\\0').filter(Boolean)\n return rows.map((row) => {\n const tab = row.indexOf('\\t')\n const header = row.slice(0, tab).split(' ').filter(Boolean)\n const path = row.slice(tab + 1)\n const [mode, type, object, sizeText] = header\n if (tab < 1 || !mode || !type || !object || !path) {\n throw new Error('malformed Git tree entry')\n }\n const size = sizeText && /^\\d+$/.test(sizeText) ? Number(sizeText) : undefined\n if (size !== undefined && !Number.isSafeInteger(size)) {\n throw new Error('candidate Git tree entry size exceeds the safe integer range')\n }\n return { mode, type, object, ...(size === undefined ? {} : { size }), path }\n })\n}\n\nfunction assertSafeGitPath(path: string): void {\n if (\n !path ||\n path.startsWith('/') ||\n path.includes('\\\\') ||\n path.includes('\\0') ||\n hasControlCharacter(path) ||\n path.split('/').some((part) => !part || part === '.' || part === '..') ||\n path.split('/')[0]?.toLowerCase() === '.git'\n ) {\n throw new Error(`candidate Git tree contains an unsafe path: ${path}`)\n }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\nfunction parseGitHubRemote(value: string): { owner: string; repo: string } | undefined {\n const match = value.match(\n /^(?:https?:\\/\\/github\\.com\\/|ssh:\\/\\/git@github\\.com\\/|git@github\\.com:)([^/]+)\\/([^/]+?)(?:\\.git)?$/,\n )\n if (!match?.[1] || !match[2]) return undefined\n return { owner: match[1], repo: match[2] }\n}\n\nexport async function runCandidateGit(\n repositoryRoot: string,\n args: string[],\n input?: Uint8Array,\n extraEnv: Record<string, string> = {},\n): Promise<GitResult> {\n const env = Object.fromEntries(\n Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_')),\n ) as Record<string, string>\n Object.assign(env, {\n GIT_CONFIG_NOSYSTEM: '1',\n GIT_CONFIG_GLOBAL: '/dev/null',\n GIT_CONFIG_SYSTEM: '/dev/null',\n GIT_TERMINAL_PROMPT: '0',\n GIT_NO_REPLACE_OBJECTS: '1',\n LC_ALL: 'C',\n ...extraEnv,\n })\n const fullArgs = [\n '-c',\n 'core.hooksPath=/dev/null',\n '-c',\n 'core.fsmonitor=false',\n '-c',\n 'core.untrackedCache=false',\n '-c',\n 'protocol.file.allow=never',\n '-C',\n repositoryRoot,\n ...args,\n ]\n return await new Promise((resolveResult, reject) => {\n const child = spawn('git', fullArgs, { env, stdio: ['pipe', 'pipe', 'pipe'] })\n const stdout: Buffer[] = []\n const stderr: Buffer[] = []\n child.stdout.on('data', (chunk: Buffer) => stdout.push(chunk))\n child.stderr.on('data', (chunk: Buffer) => stderr.push(chunk))\n child.on('error', reject)\n child.on('close', (code, signal) => {\n const out = Buffer.concat(stdout)\n const err = Buffer.concat(stderr)\n if (code !== 0) {\n reject(\n new Error(\n `git ${args[0] ?? '<command>'} failed (${signal ?? code}): ${err.toString('utf8').trim()}`,\n ),\n )\n return\n }\n resolveResult({ stdout: out, stderr: err })\n })\n if (input) child.stdin.end(input)\n else child.stdin.end()\n })\n}\n\nfunction isNoEntry(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: string }).code === 'ENOENT'\n )\n}\n","import {\n type AgentCandidateArtifactRef,\n agentCandidateArtifactRefSchema,\n} from '@tangle-network/agent-interface'\n\nimport { verifyBytes } from './artifacts'\nimport { immutableCandidateValue, sha256Bytes } from './digest'\nimport type { AgentCandidateOutputArtifactPort, AgentCandidateOutputPurpose } from './types'\n\n/** Persist evaluator evidence, read it back, and bind the returned locator to the exact bytes. */\nexport async function persistCandidateOutputArtifact(\n port: AgentCandidateOutputArtifactPort,\n input: {\n executionId: string\n purpose: AgentCandidateOutputPurpose\n bytes: Uint8Array\n signal?: AbortSignal\n },\n): Promise<AgentCandidateArtifactRef> {\n input.signal?.throwIfAborted()\n const bytes = Uint8Array.from(input.bytes)\n const expectedDigest = sha256Bytes(bytes)\n const ref = agentCandidateArtifactRefSchema.parse(\n await port.put({\n executionId: input.executionId,\n purpose: input.purpose,\n bytes: Uint8Array.from(bytes),\n ...(input.signal ? { signal: input.signal } : {}),\n }),\n )\n input.signal?.throwIfAborted()\n if (ref.sha256 !== expectedDigest || ref.byteLength !== bytes.byteLength) {\n throw new Error('candidate output locator does not identify the submitted bytes')\n }\n const stored = await port.read(ref)\n input.signal?.throwIfAborted()\n verifyBytes(stored, expectedDigest, bytes.byteLength, 'persisted candidate output')\n return immutableCandidateValue(ref)\n}\n","import { randomUUID } from 'node:crypto'\nimport { constants as fsConstants } from 'node:fs'\nimport {\n lstat,\n mkdir,\n mkdtemp,\n open,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, resolve, sep, win32 } from 'node:path'\nimport { isAnyArrayBuffer, isSharedArrayBuffer } from 'node:util/types'\nimport type {\n AgentCandidateCapturedArtifact,\n AgentCandidateWorkspaceSnapshotEvidence,\n} from '@tangle-network/agent-interface'\nimport { extract, type Pack, pack, type Extract as TarExtract } from 'tar-stream'\nimport {\n candidateWorkspaceManifest,\n captureMaterializedWorkspace,\n verifyBytes,\n verifyMaterializedWorkspace,\n} from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n deepFreezeCandidate,\n embeddedCandidateArtifact,\n sha256Bytes,\n} from './digest'\nimport { isWellFormedUnicode } from './exact-object'\nimport {\n assertNoGitIndirection,\n readCandidateGitTreeFiles,\n runCandidateGit,\n} from './git-materialize'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport type {\n AgentCandidateExecutorWorkspaceFile,\n AgentCandidateOutputArtifactPort,\n AgentCandidateWorkspacePort,\n} from './types'\n\nconst archiveKind = 'agent-candidate-workspace-archive' as const\nconst workspaceEntryPrefix = 'workspace/'\nconst repositoryMetadataEntry = 'metadata/repository.json'\nconst repositoryBundleEntry = 'metadata/repository.bundle'\nconst fixedTarTime = new Date(0)\n\nexport interface AgentCandidateWorkspaceArchiveLimits {\n maxArchiveBytes: number\n maxEmbeddedArtifactBytes: number\n maxFiles: number\n maxFileBytes: number\n maxTotalFileBytes: number\n maxPathBytes: number\n maxRepositoryBundleBytes: number\n}\n\nconst defaultLimits: AgentCandidateWorkspaceArchiveLimits = Object.freeze({\n maxArchiveBytes: 512 * 1024 * 1024,\n maxEmbeddedArtifactBytes: 1024 * 1024,\n maxFiles: 50_000,\n maxFileBytes: 128 * 1024 * 1024,\n maxTotalFileBytes: 256 * 1024 * 1024,\n maxPathBytes: 4_096,\n maxRepositoryBundleBytes: 128 * 1024 * 1024,\n})\n\ninterface WorkspaceArchiveRepository {\n headCommit: string\n headTree: string\n bundle: {\n sha256: `sha256:${string}`\n byteLength: number\n bytes: Uint8Array\n }\n}\n\ninterface WorkspaceArchiveRepositoryMetadata {\n kind: typeof archiveKind\n headCommit: string\n headTree: string\n bundle: {\n sha256: `sha256:${string}`\n byteLength: number\n }\n}\n\ninterface DecodedWorkspaceArchive {\n files: Array<{ path: string; mode: number; bytes: Uint8Array }>\n repository?: WorkspaceArchiveRepository\n}\n\nexport interface CaptureAgentCandidateWorkspaceOptions {\n /** Include Git HEAD so task preparation can prove its exact commit and tree. */\n includeRepository?: boolean\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n /** Use the evaluator-owned artifact store when manifest or archive bytes should not be embedded. */\n artifactPersistence?: {\n executionId: string\n outputArtifacts: AgentCandidateOutputArtifactPort\n signal?: AbortSignal\n }\n}\n\nexport interface CreateAgentCandidateWorkspacePortOptions {\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n}\n\nexport interface CapturedAgentCandidateWorkspace {\n readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence\n /** Caller-owned bytes accepted by createAgentCandidateWorkspacePort. */\n readonly archive: Uint8Array\n}\n\n/** Capture one exact regular-file workspace for immutable candidate execution. */\nexport async function captureAgentCandidateWorkspace(\n rootInput: string,\n options: CaptureAgentCandidateWorkspaceOptions = {},\n): Promise<CapturedAgentCandidateWorkspace> {\n const root = resolve(rootInput)\n const limits = workspaceLimits(options.limits)\n const captured = options.includeRepository\n ? await captureRepository(root, limits)\n : await captureMaterializedWorkspace(root, {\n limits: {\n maxFiles: limits.maxFiles,\n maxFileBytes: limits.maxFileBytes,\n maxTotalFileBytes: limits.maxTotalFileBytes,\n },\n })\n assertWorkspaceFilesWithinLimits(captured.files, limits)\n const repository = 'repository' in captured ? captured.repository : undefined\n return captureWorkspaceFiles(captured.files, repository, limits, options.artifactPersistence)\n}\n\n/** Capture detached files returned by a remote executor into the standard archive. */\nexport async function captureAgentCandidateWorkspaceFiles(\n input: readonly AgentCandidateExecutorWorkspaceFile[],\n options: Omit<CaptureAgentCandidateWorkspaceOptions, 'includeRepository'> = {},\n): Promise<CapturedAgentCandidateWorkspace> {\n const limits = workspaceLimits(options.limits)\n return captureWorkspaceFiles(\n normalizeWorkspaceFiles(input, limits),\n undefined,\n limits,\n options.artifactPersistence,\n )\n}\n\nasync function captureWorkspaceFiles(\n files: readonly AgentCandidateExecutorWorkspaceFile[],\n repository: WorkspaceArchiveRepository | undefined,\n limits: AgentCandidateWorkspaceArchiveLimits,\n artifactPersistence: CaptureAgentCandidateWorkspaceOptions['artifactPersistence'],\n): Promise<CapturedAgentCandidateWorkspace> {\n const material = candidateWorkspaceManifest(files)\n const manifest = canonicalCandidateBytes(material)\n const archive = await encodeWorkspaceArchive(files, repository, limits.maxArchiveBytes)\n if (\n !artifactPersistence &&\n (manifest.byteLength > limits.maxEmbeddedArtifactBytes ||\n archive.byteLength > limits.maxEmbeddedArtifactBytes)\n ) {\n throw new Error(\n 'candidate workspace artifacts exceed maxEmbeddedArtifactBytes; artifactPersistence is required',\n )\n }\n const manifestArtifact = await captureWorkspaceArtifact('manifest', manifest, artifactPersistence)\n const archiveArtifact = await captureWorkspaceArtifact('archive', archive, artifactPersistence)\n const snapshot = deepFreezeCandidate({\n kind: 'agent-candidate-workspace-snapshot',\n digest: canonicalCandidateDigest(material),\n material,\n manifest: manifestArtifact,\n archive: archiveArtifact,\n } satisfies AgentCandidateWorkspaceSnapshotEvidence)\n return Object.freeze({ snapshot, archive })\n}\n\nasync function captureWorkspaceArtifact(\n kind: 'manifest' | 'archive',\n bytes: Uint8Array,\n persistence: CaptureAgentCandidateWorkspaceOptions['artifactPersistence'],\n): Promise<AgentCandidateCapturedArtifact> {\n if (!persistence) return embeddedCandidateArtifact(bytes)\n if (!persistence.executionId.trim()) {\n throw new Error('candidate workspace artifact persistence requires an executionId')\n }\n return persistCandidateOutputArtifact(persistence.outputArtifacts, {\n executionId: persistence.executionId,\n purpose: kind === 'manifest' ? 'candidate-workspace-manifest' : 'candidate-workspace-archive',\n bytes,\n ...(persistence.signal ? { signal: persistence.signal } : {}),\n })\n}\n\n/** Create the standard bounded materializer for candidate execution ports. */\nexport function createAgentCandidateWorkspacePort(\n options: CreateAgentCandidateWorkspacePortOptions = {},\n): AgentCandidateWorkspacePort {\n const limits = workspaceLimits(options.limits)\n const port: AgentCandidateWorkspacePort = {\n materialize: async ({ role, snapshot, archive, destination }) => {\n await materializeAgentCandidateWorkspace({\n role,\n snapshot,\n archive,\n destination,\n limits,\n })\n },\n }\n return Object.freeze(port)\n}\n\nasync function materializeAgentCandidateWorkspace(input: {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n destination: string\n limits: AgentCandidateWorkspaceArchiveLimits\n}): Promise<void> {\n const decoded = await decodeVerifiedWorkspaceArchive(input)\n const destination = resolve(input.destination)\n await prepareEmptyDestination(destination)\n const staging = await mkdtemp(`${destination}.materializing-`)\n try {\n await writeWorkspaceFiles(staging, decoded.files)\n if (decoded.repository) {\n await materializeRepository(decoded.repository, staging)\n }\n await verifyMaterializedWorkspace(staging, input.snapshot.material, {\n ignoredProtectedRootEntries: decoded.repository ? ['.git'] : [],\n })\n await rename(staging, destination)\n } catch (error) {\n await rm(staging, { recursive: true, force: true })\n await rm(destination, { recursive: true, force: true })\n throw error\n }\n}\n\n/** Verify a portable archive before its source environment may be discarded. */\nexport async function verifyAgentCandidateWorkspaceArchive(input: {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n}): Promise<void> {\n await decodeVerifiedWorkspaceArchive({ ...input, limits: workspaceLimits(input.limits) })\n}\n\nasync function decodeVerifiedWorkspaceArchive(input: {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n limits: AgentCandidateWorkspaceArchiveLimits\n}): Promise<DecodedWorkspaceArchive> {\n verifyBytes(\n input.archive,\n input.snapshot.archive.sha256,\n input.snapshot.archive.byteLength,\n 'candidate workspace archive',\n )\n const decoded = await parseWorkspaceArchive(input.archive, input.limits)\n if (decoded.repository && input.role !== 'task') {\n throw new Error('only task workspaces may carry a Git repository')\n }\n assertArchiveMatchesSnapshot(decoded.files, input.snapshot)\n return decoded\n}\n\nasync function captureRepository(\n requestedRoot: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<{\n files: Array<{ path: string; mode: number; bytes: Uint8Array }>\n repository: WorkspaceArchiveRepository\n}> {\n const requestedStats = await lstat(requestedRoot)\n if (!requestedStats.isDirectory() || requestedStats.isSymbolicLink()) {\n throw new Error('candidate repository root must be a real directory')\n }\n // Capture the RESOLVED root. The property this guards is that capture starts at one real\n // worktree root with no aliasing, which resolving satisfies directly — rejecting a symlinked\n // prefix outright does not, and makes capture impossible on macOS, where the OS itself hands\n // out temp paths under /var, a symlink to /private/var. Git reports a resolved path, so the\n // worktree-root comparison below needs the resolved form on both sides.\n const root = await realpath(requestedRoot)\n const resolvedStats = await lstat(root)\n if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) {\n throw new Error('candidate repository root must resolve to a real directory')\n }\n const topLevel = (await runCandidateGit(root, ['rev-parse', '--show-toplevel'])).stdout\n .toString('utf8')\n .trim()\n if ((await realpath(resolve(topLevel))) !== root) {\n throw new Error('candidate repository capture must start at the Git worktree root')\n }\n const gitDir = resolve(\n (await runCandidateGit(root, ['rev-parse', '--absolute-git-dir'])).stdout\n .toString('utf8')\n .trim(),\n )\n if ((await realpath(gitDir)) !== gitDir || gitDir.includes(':')) {\n throw new Error('candidate repository Git object store has an unsupported path')\n }\n await assertNoGitIndirection(root, gitDir, 'candidate repository')\n const headCommit = (await runCandidateGit(root, ['rev-parse', 'HEAD'])).stdout\n .toString('utf8')\n .trim()\n const headTree = (await runCandidateGit(root, ['rev-parse', 'HEAD^{tree}'])).stdout\n .toString('utf8')\n .trim()\n assertGitObjectId(headCommit, 'HEAD')\n assertGitObjectId(headTree, 'HEAD tree')\n if (headCommit.length !== headTree.length) {\n throw new Error('candidate repository HEAD and tree use different object formats')\n }\n const files = await readCandidateGitTreeFiles(root, headTree, {}, limits)\n assertWorkspaceFilesWithinLimits(files, limits)\n const reachableBytesText = (\n await runCandidateGit(root, ['rev-list', '--disk-usage', '--objects', 'HEAD'])\n ).stdout\n .toString('utf8')\n .trim()\n const reachableBytes = Number(reachableBytesText)\n if (!Number.isSafeInteger(reachableBytes) || reachableBytes < 0) {\n throw new Error('candidate repository reachable size is invalid')\n }\n if (reachableBytes > limits.maxRepositoryBundleBytes) {\n throw new Error('candidate repository exceeds maxRepositoryBundleBytes')\n }\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-workspace-bundle-'))\n const bundlePath = join(temporary, `${randomUUID()}.bundle`)\n try {\n await runCandidateGit(root, ['bundle', 'create', bundlePath, 'HEAD'])\n const bundle = Uint8Array.from(await readFile(bundlePath))\n if (bundle.byteLength > limits.maxRepositoryBundleBytes) {\n throw new Error('candidate repository bundle exceeds maxRepositoryBundleBytes')\n }\n return {\n files,\n repository: {\n headCommit,\n headTree,\n bundle: {\n sha256: sha256Bytes(bundle),\n byteLength: bundle.byteLength,\n bytes: bundle,\n },\n },\n }\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nasync function encodeWorkspaceArchive(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepository | undefined,\n maxArchiveBytes: number,\n): Promise<Uint8Array> {\n const archive = pack()\n const output = collectStream(archive, maxArchiveBytes, 'candidate workspace archive')\n try {\n await writeWorkspaceArchiveEntries(archive, files, repository)\n archive.finalize()\n return await output\n } catch (error) {\n archive.destroy(error instanceof Error ? error : new Error(String(error)))\n await output.catch(() => undefined)\n throw error\n }\n}\n\nasync function verifyCanonicalWorkspaceArchive(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepository | undefined,\n expected: Uint8Array,\n maxArchiveBytes: number,\n): Promise<void> {\n const archive = pack()\n const comparison = streamEqualsBytes(\n archive,\n expected,\n maxArchiveBytes,\n 'candidate workspace archive',\n )\n try {\n await writeWorkspaceArchiveEntries(archive, files, repository)\n archive.finalize()\n if (!(await comparison)) throw new Error('candidate workspace tar is not canonical')\n } catch (error) {\n archive.destroy(error instanceof Error ? error : new Error(String(error)))\n await comparison.catch(() => undefined)\n throw error\n }\n}\n\nasync function writeWorkspaceArchiveEntries(\n archive: Pack,\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepository | undefined,\n): Promise<void> {\n for (const file of files) {\n await writeTarEntry(archive, `${workspaceEntryPrefix}${file.path}`, file.mode, file.bytes)\n }\n if (!repository) return\n const metadata = canonicalCandidateBytes({\n kind: archiveKind,\n headCommit: repository.headCommit,\n headTree: repository.headTree,\n bundle: {\n sha256: repository.bundle.sha256,\n byteLength: repository.bundle.byteLength,\n },\n } satisfies WorkspaceArchiveRepositoryMetadata)\n await writeTarEntry(archive, repositoryMetadataEntry, 0o600, metadata)\n await writeTarEntry(archive, repositoryBundleEntry, 0o600, repository.bundle.bytes)\n}\n\nasync function parseWorkspaceArchive(\n bytes: Uint8Array,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<DecodedWorkspaceArchive> {\n if (bytes.byteLength > limits.maxArchiveBytes) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n }\n const parser = extract()\n const files: DecodedWorkspaceArchive['files'] = []\n const observedEntryNames = new Set<string>()\n const observedPaths = new Set<string>()\n let totalBytes = 0\n let retainedEntryBytes = 0\n let previousPath: string | undefined\n let repositoryMetadata: WorkspaceArchiveRepositoryMetadata | undefined\n let repositoryBundle: Uint8Array | undefined\n const decoded = (async () => {\n for await (const entry of parser) {\n const name = entry.header.name\n if (\n entry.header.type !== 'file' ||\n typeof name !== 'string' ||\n observedEntryNames.has(name)\n ) {\n throw new Error('candidate workspace tar contains an invalid entry')\n }\n observedEntryNames.add(name)\n if (name.startsWith(workspaceEntryPrefix)) {\n if (files.length >= limits.maxFiles) {\n throw new Error('candidate workspace archive has an invalid file count')\n }\n const path = safeArchivePath(name.slice(workspaceEntryPrefix.length), limits.maxPathBytes)\n if (!isWorkspaceFileMode(entry.header.mode)) {\n throw new Error(`candidate workspace archive has an unsupported mode: ${path}`)\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `workspace file ${path}`)\n retainedEntryBytes += fileBytes.byteLength\n assertWorkspacePathOrder(\n path,\n previousPath,\n observedPaths,\n 'candidate workspace archive paths must be unique and sorted',\n )\n previousPath = path\n if (fileBytes.byteLength > limits.maxTotalFileBytes - totalBytes) {\n throw new Error('candidate workspace archive exceeds maxTotalFileBytes')\n }\n totalBytes += fileBytes.byteLength\n files.push({ path, mode: entry.header.mode, bytes: fileBytes })\n } else if (name === repositoryMetadataEntry) {\n if (entry.header.mode !== 0o600 || repositoryMetadata) {\n throw new Error('candidate workspace archive repository metadata is invalid')\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n const metadataBytes = await readTarEntry(\n entry,\n limits.maxPathBytes,\n 'candidate repository metadata',\n )\n retainedEntryBytes += metadataBytes.byteLength\n repositoryMetadata = parseRepositoryMetadata(metadataBytes, limits.maxRepositoryBundleBytes)\n } else if (name === repositoryBundleEntry) {\n if (entry.header.mode !== 0o600 || repositoryBundle) {\n throw new Error('candidate workspace archive repository bundle is invalid')\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n repositoryBundle = await readTarEntry(\n entry,\n limits.maxRepositoryBundleBytes,\n 'candidate Git bundle',\n )\n retainedEntryBytes += repositoryBundle.byteLength\n } else {\n throw new Error(`candidate workspace tar contains an unsupported entry: ${name}`)\n }\n }\n if (Boolean(repositoryMetadata) !== Boolean(repositoryBundle)) {\n throw new Error('candidate workspace archive repository evidence is incomplete')\n }\n const repository =\n repositoryMetadata && repositoryBundle\n ? repositoryFromTar(repositoryMetadata, repositoryBundle)\n : undefined\n return { files, ...(repository ? { repository } : {}) }\n })()\n parser.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))\n const result = await decoded\n await verifyCanonicalWorkspaceArchive(\n result.files,\n result.repository,\n bytes,\n limits.maxArchiveBytes,\n )\n return result\n}\n\nfunction assertRetainedArchiveSize(\n archiveBytes: number,\n retainedEntryBytes: number,\n entryBytes: number | undefined,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): void {\n if (\n !Number.isSafeInteger(entryBytes) ||\n entryBytes === undefined ||\n entryBytes < 0 ||\n entryBytes > limits.maxArchiveBytes - archiveBytes - retainedEntryBytes\n ) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes while decoding')\n }\n}\n\nfunction parseRepositoryMetadata(\n bytes: Uint8Array,\n maxBundleBytes: number,\n): WorkspaceArchiveRepositoryMetadata {\n let value: unknown\n try {\n value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n } catch (error) {\n throw new Error('candidate workspace archive repository metadata is invalid', { cause: error })\n }\n if (\n !isRecord(value) ||\n Object.keys(value).sort().join(',') !== 'bundle,headCommit,headTree,kind' ||\n value.kind !== archiveKind ||\n typeof value.headCommit !== 'string' ||\n typeof value.headTree !== 'string' ||\n !isRecord(value.bundle) ||\n Object.keys(value.bundle).sort().join(',') !== 'byteLength,sha256' ||\n typeof value.bundle.sha256 !== 'string' ||\n !/^sha256:[a-f0-9]{64}$/.test(value.bundle.sha256) ||\n !Number.isSafeInteger(value.bundle.byteLength) ||\n (value.bundle.byteLength as number) <= 0 ||\n (value.bundle.byteLength as number) > maxBundleBytes\n ) {\n throw new Error('candidate workspace archive repository is invalid')\n }\n if (!Buffer.from(canonicalCandidateBytes(value)).equals(Buffer.from(bytes))) {\n throw new Error('candidate workspace archive repository metadata is not canonical')\n }\n assertGitObjectId(value.headCommit, 'repository HEAD')\n assertGitObjectId(value.headTree, 'repository HEAD tree')\n if (value.headCommit.length !== value.headTree.length) {\n throw new Error('candidate repository HEAD and tree use different object formats')\n }\n return {\n kind: archiveKind,\n headCommit: value.headCommit,\n headTree: value.headTree,\n bundle: {\n sha256: value.bundle.sha256 as `sha256:${string}`,\n byteLength: value.bundle.byteLength as number,\n },\n }\n}\n\nfunction repositoryFromTar(\n metadata: WorkspaceArchiveRepositoryMetadata,\n bundle: Uint8Array,\n): WorkspaceArchiveRepository {\n verifyBytes(bundle, metadata.bundle.sha256, metadata.bundle.byteLength, 'candidate Git bundle')\n return {\n headCommit: metadata.headCommit,\n headTree: metadata.headTree,\n bundle: { ...metadata.bundle, bytes: bundle },\n }\n}\n\nasync function writeTarEntry(\n archive: Pack,\n name: string,\n mode: number,\n bytes: Uint8Array,\n): Promise<void> {\n await new Promise<void>((resolveEntry, rejectEntry) => {\n archive.entry(\n workspaceTarHeader(name, mode, bytes.byteLength),\n Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),\n (error) => (error ? rejectEntry(error) : resolveEntry()),\n )\n })\n}\n\ntype TarEntry = TarExtract extends AsyncIterable<infer Entry> ? Entry : never\n\nasync function readTarEntry(entry: TarEntry, maxBytes: number, label: string): Promise<Uint8Array> {\n const size = entry.header.size\n if (!Number.isSafeInteger(size) || size === undefined || size < 0 || size > maxBytes) {\n throw new Error(`${label} has an invalid tar size`)\n }\n const bytes = await collectStream(entry, maxBytes, label)\n if (bytes.byteLength !== size) throw new Error(`${label} differs from its tar size`)\n return bytes\n}\n\nasync function collectStream(\n stream: AsyncIterable<unknown>,\n maxBytes: number,\n label: string,\n): Promise<Uint8Array> {\n const chunks: Buffer[] = []\n let totalBytes = 0\n for await (const chunk of stream) {\n if (!(chunk instanceof Uint8Array)) {\n throw new Error(`${label} emitted a non-byte chunk`)\n }\n if (chunk.byteLength > maxBytes - totalBytes) {\n const error = new Error(`${label} exceeds its size limit`)\n if ('destroy' in stream && typeof stream.destroy === 'function') stream.destroy(error)\n throw error\n }\n const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n chunks.push(bytes)\n totalBytes += bytes.byteLength\n }\n return Buffer.concat(chunks, totalBytes)\n}\n\nasync function streamEqualsBytes(\n stream: AsyncIterable<unknown>,\n expected: Uint8Array,\n maxBytes: number,\n label: string,\n): Promise<boolean> {\n const expectedBuffer = Buffer.from(expected.buffer, expected.byteOffset, expected.byteLength)\n let equal = true\n let offset = 0\n for await (const chunk of stream) {\n if (!(chunk instanceof Uint8Array)) {\n throw new Error(`${label} emitted a non-byte chunk`)\n }\n if (chunk.byteLength > maxBytes - offset) {\n const error = new Error(`${label} exceeds its size limit`)\n if ('destroy' in stream && typeof stream.destroy === 'function') stream.destroy(error)\n throw error\n }\n const observed = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n if (\n offset + observed.byteLength > expectedBuffer.byteLength ||\n !observed.equals(expectedBuffer.subarray(offset, offset + observed.byteLength))\n ) {\n equal = false\n }\n offset += observed.byteLength\n }\n return equal && offset === expectedBuffer.byteLength\n}\n\nexport async function prepareEmptyDestination(destination: string): Promise<void> {\n await mkdir(destination, { recursive: true, mode: 0o700 })\n const stats = await lstat(destination)\n if (!stats.isDirectory() || stats.isSymbolicLink()) {\n throw new Error('candidate workspace destination must be a real directory')\n }\n // A symlinked PREFIX is the OS's own doing on macOS, where temp paths live under /var, a\n // symlink to /private/var. What must hold is that the destination itself is a real\n // directory, which both this check and the lstat above require.\n const resolvedDestination = await realpath(destination)\n const resolvedStats = await lstat(resolvedDestination)\n if (!resolvedStats.isDirectory() || resolvedStats.isSymbolicLink()) {\n throw new Error('candidate workspace destination must resolve to a real directory')\n }\n if ((await readdir(destination)).length > 0) {\n throw new Error('candidate workspace destination must be empty')\n }\n}\n\nasync function writeWorkspaceFiles(\n destination: string,\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n): Promise<void> {\n for (const file of files) {\n const path = workspacePath(destination, file.path)\n await mkdir(dirname(path), { recursive: true, mode: 0o700 })\n const descriptor = await open(\n path,\n fsConstants.O_WRONLY |\n fsConstants.O_CREAT |\n fsConstants.O_EXCL |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n 0o600,\n )\n try {\n await descriptor.writeFile(file.bytes)\n const stats = await descriptor.stat()\n if (!stats.isFile() || stats.nlink !== 1) {\n throw new Error(`candidate workspace file identity changed while writing: ${file.path}`)\n }\n await descriptor.chmod(file.mode)\n } finally {\n await descriptor.close()\n }\n }\n}\n\nasync function materializeRepository(\n repository: WorkspaceArchiveRepository,\n destination: string,\n): Promise<void> {\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-workspace-bundle-'))\n const bundlePath = join(temporary, `${randomUUID()}.bundle`)\n try {\n await writeFile(bundlePath, repository.bundle.bytes, { flag: 'wx', mode: 0o600 })\n await runCandidateGit(destination, [\n 'init',\n '--quiet',\n '--initial-branch=candidate',\n `--object-format=${repository.headCommit.length === 64 ? 'sha256' : 'sha1'}`,\n ])\n await runCandidateGit(destination, ['bundle', 'verify', bundlePath])\n await runCandidateGit(destination, ['bundle', 'unbundle', bundlePath])\n const objectType = (\n await runCandidateGit(destination, ['cat-file', '-t', repository.headCommit])\n ).stdout\n .toString('utf8')\n .trim()\n if (objectType !== 'commit') throw new Error('candidate repository HEAD is not a commit')\n const observedTree = (\n await runCandidateGit(destination, ['rev-parse', `${repository.headCommit}^{tree}`])\n ).stdout\n .toString('utf8')\n .trim()\n if (observedTree !== repository.headTree) {\n throw new Error('candidate repository bundle HEAD tree changed')\n }\n await runCandidateGit(destination, ['update-ref', '--no-deref', 'HEAD', repository.headCommit])\n await runCandidateGit(destination, ['read-tree', repository.headTree])\n const status = (\n await runCandidateGit(destination, ['status', '--porcelain=v1', '--untracked-files=all'])\n ).stdout\n .toString('utf8')\n .trim()\n if (status) throw new Error('candidate repository files do not exactly match HEAD')\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nfunction assertArchiveMatchesSnapshot(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n snapshot: AgentCandidateWorkspaceSnapshotEvidence,\n): void {\n const material = candidateWorkspaceManifest(files)\n const materialBytes = canonicalCandidateBytes(material)\n verifyBytes(\n materialBytes,\n snapshot.manifest.sha256,\n snapshot.manifest.byteLength,\n 'candidate workspace manifest',\n )\n if (\n canonicalCandidateDigest(material) !== snapshot.digest ||\n !Buffer.from(materialBytes).equals(Buffer.from(canonicalCandidateBytes(snapshot.material)))\n ) {\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n }\n}\n\nfunction assertWorkspaceFilesWithinLimits(\n files: ReadonlyArray<{ path: string; mode: number; bytes: Uint8Array }>,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): void {\n if (files.length > limits.maxFiles) {\n throw new Error('candidate workspace exceeds maxFiles')\n }\n let totalBytes = 0\n let previousPath: string | undefined\n const observedPaths = new Set<string>()\n for (const file of files) {\n const path = safeArchivePath(file.path, limits.maxPathBytes)\n assertWorkspacePathOrder(\n path,\n previousPath,\n observedPaths,\n 'candidate workspace paths must be unique and sorted',\n )\n previousPath = path\n if (!isWorkspaceFileMode(file.mode)) {\n throw new Error(`candidate workspace file has unsupported mode: ${path}`)\n }\n if (file.bytes.byteLength > limits.maxFileBytes) {\n throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`)\n }\n totalBytes += file.bytes.byteLength\n if (totalBytes > limits.maxTotalFileBytes) {\n throw new Error('candidate workspace exceeds maxTotalFileBytes')\n }\n }\n}\n\nfunction normalizeWorkspaceFiles(\n input: readonly AgentCandidateExecutorWorkspaceFile[],\n limits: AgentCandidateWorkspaceArchiveLimits,\n): AgentCandidateExecutorWorkspaceFile[] {\n if (!Array.isArray(input)) {\n throw new Error('candidate workspace files must be an array')\n }\n const fileCount = input.length\n if (fileCount > limits.maxFiles) {\n throw new Error('candidate workspace exceeds maxFiles')\n }\n let totalBytes = 0\n const files: AgentCandidateExecutorWorkspaceFile[] = []\n for (let index = 0; index < fileCount; index++) {\n const inputFile = input[index]\n if (!isRecord(inputFile) || Object.keys(inputFile).sort().join(',') !== 'bytes,mode,path') {\n throw new Error(`candidate workspace file ${index} is invalid`)\n }\n const descriptors = Object.getOwnPropertyDescriptors(inputFile)\n if (\n !('value' in (descriptors.path ?? {})) ||\n !('value' in (descriptors.mode ?? {})) ||\n !('value' in (descriptors.bytes ?? {}))\n ) {\n throw new Error(`candidate workspace file ${index} must use fixed values`)\n }\n const path = safeArchivePath(descriptors.path?.value, limits.maxPathBytes)\n const mode = descriptors.mode?.value\n const inputBytes = descriptors.bytes?.value\n if (!isWorkspaceFileMode(mode)) {\n throw new Error(`candidate workspace file has unsupported mode: ${path}`)\n }\n const view = inspectWorkspaceBytes(inputBytes, path)\n if (view.byteLength > limits.maxFileBytes) {\n throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`)\n }\n if (view.byteLength > limits.maxTotalFileBytes - totalBytes) {\n throw new Error('candidate workspace exceeds maxTotalFileBytes')\n }\n if (view.byteLength > Math.max(0, limits.maxArchiveBytes - 1024)) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n }\n totalBytes += view.byteLength\n files.push({ path, mode, bytes: detachWorkspaceBytes(view) })\n }\n files.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n assertWorkspaceFilesWithinLimits(files, limits)\n return files\n}\n\nfunction isWorkspaceFileMode(value: unknown): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= 0o777\n}\n\nexport function workspaceLimits(\n overrides: Partial<AgentCandidateWorkspaceArchiveLimits> | undefined,\n): AgentCandidateWorkspaceArchiveLimits {\n const limits = { ...defaultLimits, ...overrides }\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`candidate workspace ${name} must be a positive safe integer`)\n }\n }\n return Object.freeze(limits)\n}\n\nexport function safeArchivePath(value: unknown, maxPathBytes: number): string {\n if (\n typeof value !== 'string' ||\n !value ||\n !isWellFormedUnicode(value) ||\n Buffer.byteLength(value, 'utf8') > maxPathBytes ||\n isAbsolute(value) ||\n win32.isAbsolute(value) ||\n value.includes('\\\\') ||\n value.includes('\\0') ||\n hasControlCharacter(value) ||\n value.split('/').some((part) => !part || part === '.' || part === '..') ||\n ['.git', '.sidecar'].includes(value.split('/')[0]?.toLowerCase() ?? '')\n ) {\n throw new Error(`candidate workspace archive contains an unsafe path: ${String(value)}`)\n }\n return value\n}\n\nexport function assertWorkspacePathOrder(\n path: string,\n previousPath: string | undefined,\n observedPaths: Set<string>,\n errorMessage: string,\n): void {\n if (previousPath !== undefined && previousPath >= path) throw new Error(errorMessage)\n for (let slash = path.indexOf('/'); slash !== -1; slash = path.indexOf('/', slash + 1)) {\n if (observedPaths.has(path.slice(0, slash))) throw new Error(errorMessage)\n }\n observedPaths.add(path)\n}\n\nfunction inspectWorkspaceBytes(\n input: unknown,\n path: string,\n): { buffer: ArrayBuffer; byteOffset: number; byteLength: number } {\n let buffer: ArrayBufferLike\n let byteOffset: number\n let byteLength: number\n try {\n buffer = typedArrayBufferGetter.call(input as Uint8Array) as ArrayBufferLike\n byteOffset = typedArrayByteOffsetGetter.call(input as Uint8Array) as number\n byteLength = typedArrayByteLengthGetter.call(input as Uint8Array) as number\n } catch {\n throw new Error(`candidate workspace file bytes are invalid: ${path}`)\n }\n if (isSharedArrayBuffer(buffer)) {\n throw new Error(`candidate workspace file uses shared bytes: ${path}`)\n }\n if (!isAnyArrayBuffer(buffer)) {\n throw new Error(`candidate workspace file bytes are invalid: ${path}`)\n }\n return { buffer, byteOffset, byteLength }\n}\n\nfunction detachWorkspaceBytes(input: {\n buffer: ArrayBuffer\n byteOffset: number\n byteLength: number\n}): Uint8Array {\n const { buffer, byteOffset, byteLength } = input\n const copy = new Uint8Array(byteLength)\n Uint8Array.prototype.set.call(copy, new Uint8Array(buffer, byteOffset, byteLength))\n return copy\n}\n\nexport function workspacePath(root: string, relativePath: string): string {\n const path = resolve(root, relativePath)\n if (!path.startsWith(`${root}${sep}`)) {\n throw new Error(`candidate workspace archive path escapes its destination: ${relativePath}`)\n }\n return path\n}\n\nfunction assertGitObjectId(value: string, label: string): void {\n if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value)) {\n throw new Error(`candidate repository ${label} is not a Git object id`)\n }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\ntype TypedArrayGetter = (this: Uint8Array) => unknown\n\nfunction requireTypedArrayGetter(name: 'buffer' | 'byteOffset' | 'byteLength'): TypedArrayGetter {\n const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype) as object\n const getter = Object.getOwnPropertyDescriptor(typedArrayPrototype, name)?.get\n if (!getter) throw new Error(`typed array intrinsic ${name} accessor is unavailable`)\n return getter\n}\n\nconst typedArrayBufferGetter = requireTypedArrayGetter('buffer')\nconst typedArrayByteOffsetGetter = requireTypedArrayGetter('byteOffset')\nconst typedArrayByteLengthGetter = requireTypedArrayGetter('byteLength')\n\n/** Shared canonical header for both archive encoders. */\nexport function workspaceTarHeader(name: string, mode: number, size: number) {\n return {\n name,\n mode,\n uid: 0,\n gid: 0,\n size,\n mtime: fixedTarTime,\n type: 'file' as const,\n uname: '',\n gname: '',\n }\n}\n","import { createHash } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport { mkdir, mkdtemp, open, realpath, rename, rm } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport { Readable } from 'node:stream'\nimport { pipeline } from 'node:stream/promises'\nimport type {\n AgentCandidateArtifactRef,\n AgentCandidateWorkspaceManifestMaterial,\n AgentCandidateWorkspaceSnapshotEvidence,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { extract, type Pack, pack } from 'tar-stream'\nimport { persistCandidateOutputArtifactStream, verifiedArtifactChunks } from './artifact-streams'\nimport { scanMaterializedWorkspaceManifest, verifyBytes } from './artifacts'\nimport { canonicalCandidateBytes, canonicalCandidateDigest, deepFreezeCandidate } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\nimport {\n type AgentCandidateWorkspaceArchiveLimits,\n assertWorkspacePathOrder,\n type CaptureAgentCandidateWorkspaceOptions,\n prepareEmptyDestination,\n safeArchivePath,\n workspaceLimits,\n workspacePath,\n workspaceTarHeader,\n} from './workspace-archive'\n\ntype WorkspaceFile = AgentCandidateWorkspaceManifestMaterial['files'][number]\n\nexport interface CaptureAgentCandidateWorkspaceToArtifactsOptions {\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n artifactPersistence: NonNullable<CaptureAgentCandidateWorkspaceOptions['artifactPersistence']>\n}\n\n/** Capture regular files to durable artifacts with memory bounded by the manifest and stream buffers. */\nexport async function captureAgentCandidateWorkspaceToArtifacts(\n rootInput: string,\n options: CaptureAgentCandidateWorkspaceToArtifactsOptions,\n): Promise<{ readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence }> {\n const { outputArtifacts, executionId, signal } = options.artifactPersistence\n if (!outputArtifacts.putStream || !outputArtifacts.readStream) {\n throw new Error('streaming workspace persistence requires putStream and readStream')\n }\n if (!executionId.trim())\n throw new Error('candidate workspace artifact persistence requires an executionId')\n signal?.throwIfAborted()\n const limits = workspaceLimits(options.limits)\n const material = await scanMaterializedWorkspaceManifest(rootInput, { limits, signal })\n validateManifest(material, limits)\n const root = await realpath(resolve(rootInput))\n const manifest = canonicalCandidateBytes(material)\n const manifestArtifact = await persistCandidateOutputArtifactStream(outputArtifacts, {\n executionId,\n purpose: 'candidate-workspace-manifest',\n chunks: oneChunk(manifest),\n maxBytes: manifest.byteLength,\n signal,\n })\n const archiveArtifact = await persistCandidateOutputArtifactStream(outputArtifacts, {\n executionId,\n purpose: 'candidate-workspace-archive',\n chunks: workspaceArchiveChunks(root, material, signal),\n maxBytes: limits.maxArchiveBytes,\n signal,\n })\n return Object.freeze({\n snapshot: deepFreezeCandidate({\n kind: 'agent-candidate-workspace-snapshot' as const,\n digest: canonicalCandidateDigest(material),\n material,\n manifest: manifestArtifact,\n archive: archiveArtifact,\n }),\n })\n}\n\n/**\n * A workspace stored as one content-addressed object per file plus the manifest that names them.\n *\n * Its digest is the manifest's, the same identity an archived capture of the same files has. Two\n * trees share every file they have in common, so storing one costs only the files no earlier\n * capture in the store holds: on Discovery Lab run terraform-dc-tokens-20261006d, the files a\n * director changed between two captures one to two minutes apart were 5.5 to 8.2 MB of a\n * 60 to 70 MB workspace.\n */\nexport interface AgentCandidateWorkspaceTree {\n readonly kind: 'agent-candidate-workspace-tree'\n /** The manifest's digest; the manifest is the object of this digest. */\n readonly digest: Sha256Digest\n readonly manifest: AgentCandidateArtifactRef\n readonly files: number\n /** The bytes of every file in the workspace. */\n readonly bytes: number\n /** The bytes this capture added to the store; every other file was already there. */\n readonly storedBytes: number\n}\n\n/**\n * Store a workspace as a tree: each regular file the store does not already hold, then the\n * manifest. The store must find objects by content (`locate`) and stream them.\n */\nexport async function captureAgentCandidateWorkspaceTreeToArtifacts(\n rootInput: string,\n options: CaptureAgentCandidateWorkspaceToArtifactsOptions,\n): Promise<AgentCandidateWorkspaceTree> {\n const { outputArtifacts, executionId, signal } = options.artifactPersistence\n if (!outputArtifacts.putStream || !outputArtifacts.readStream || !outputArtifacts.locate) {\n throw new Error('workspace tree persistence requires putStream, readStream and locate')\n }\n if (!executionId.trim())\n throw new Error('candidate workspace artifact persistence requires an executionId')\n signal?.throwIfAborted()\n const limits = workspaceLimits(options.limits)\n const material = await scanMaterializedWorkspaceManifest(rootInput, { limits, signal })\n validateManifest(material, limits)\n const root = await realpath(resolve(rootInput))\n let bytes = 0\n let storedBytes = 0\n for (const file of material.files) {\n signal?.throwIfAborted()\n bytes += file.byteLength\n const held = await outputArtifacts.locate(\n { sha256: file.sha256, byteLength: file.byteLength },\n signal === undefined ? undefined : { signal },\n )\n if (held !== undefined) continue\n const stored = await persistCandidateOutputArtifactStream(outputArtifacts, {\n executionId,\n purpose: 'candidate-workspace-file',\n chunks: workspaceFileChunks(root, file, signal),\n maxBytes: file.byteLength,\n signal,\n })\n if (stored.sha256 !== file.sha256 || stored.byteLength !== file.byteLength)\n throw new Error(`workspace file changed during capture: ${file.path}`)\n storedBytes += file.byteLength\n }\n const manifestBytes = canonicalCandidateBytes(material)\n const manifest = await persistCandidateOutputArtifactStream(outputArtifacts, {\n executionId,\n purpose: 'candidate-workspace-manifest',\n chunks: oneChunk(manifestBytes),\n maxBytes: manifestBytes.byteLength,\n signal,\n })\n const digest = canonicalCandidateDigest(material)\n if (manifest.sha256 !== digest)\n throw new Error('candidate workspace manifest digest does not name its stored bytes')\n return deepFreezeCandidate({\n kind: 'agent-candidate-workspace-tree' as const,\n digest,\n manifest,\n files: material.files.length,\n bytes,\n storedBytes,\n })\n}\n\n/**\n * Read a tree back by its digest and confirm the store holds every file it names. Returns the\n * manifest; reading a file is `artifacts.read` of what `locate` returns for its digest.\n */\nexport async function verifyAgentCandidateWorkspaceTree(\n tree: Pick<AgentCandidateWorkspaceTree, 'digest' | 'manifest'>,\n artifacts: AgentCandidateArtifactPort,\n options: { limits?: Partial<AgentCandidateWorkspaceArchiveLimits>; signal?: AbortSignal } = {},\n): Promise<AgentCandidateWorkspaceManifestMaterial> {\n const { signal } = options\n if (!artifacts.locate) throw new Error('workspace tree verification requires locate')\n if (tree.manifest.sha256 !== tree.digest)\n throw new Error('workspace tree digest does not name its manifest')\n signal?.throwIfAborted()\n // A durable store that holds evicted objects serves them as streams; its buffered read may refuse.\n let bytes: Uint8Array\n if (artifacts.readStream) {\n const chunks: Uint8Array[] = []\n for await (const chunk of verifiedArtifactChunks(tree.manifest, artifacts, signal))\n chunks.push(chunk)\n bytes = Buffer.concat(chunks)\n } else bytes = await artifacts.read(tree.manifest)\n verifyBytes(bytes, tree.manifest.sha256, tree.manifest.byteLength, 'workspace tree manifest')\n const material = JSON.parse(\n Buffer.from(bytes).toString('utf8'),\n ) as AgentCandidateWorkspaceManifestMaterial\n validateManifest(material, workspaceLimits(options.limits))\n if (canonicalCandidateDigest(material) !== tree.digest)\n throw new Error('workspace tree manifest is not canonical')\n for (const file of material.files) {\n signal?.throwIfAborted()\n const held = await artifacts.locate(\n { sha256: file.sha256, byteLength: file.byteLength },\n signal === undefined ? undefined : { signal },\n )\n if (held === undefined) throw new Error(`workspace tree file is not in the store: ${file.path}`)\n }\n return material\n}\n\nexport interface AgentCandidateWorkspaceArtifactsOptions {\n role: 'task' | 'candidate' | 'knowledge' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n artifacts: AgentCandidateArtifactPort\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n signal?: AbortSignal\n}\n\n/** Verify durable regular-file workspace evidence without retaining archive or file contents. */\nexport async function verifyAgentCandidateWorkspaceArtifacts(\n input: AgentCandidateWorkspaceArtifactsOptions,\n): Promise<void> {\n await consumeWorkspaceArtifacts(input)\n}\n\n/** Read selected files only after the existing verifier has accepted the entire archive. */\nexport async function readAgentCandidateWorkspaceArtifactFiles(\n input: AgentCandidateWorkspaceArtifactsOptions & {\n readonly paths: readonly string[]\n readonly maxReadBytes: number\n },\n): Promise<ReadonlyMap<string, Uint8Array>> {\n if (!Number.isSafeInteger(input.maxReadBytes) || input.maxReadBytes < 0)\n throw new Error('workspace selective read requires a non-negative safe maxReadBytes')\n const selected = new Map<string, Uint8Array[]>()\n const files = new Map(input.snapshot.material.files.map((file) => [file.path, file]))\n let bytes = 0\n for (const path of input.paths) {\n if (selected.has(path)) throw new Error('workspace selective read repeats a path')\n const file = files.get(path)\n if (!file) throw new Error(`workspace selective read names a missing file: ${path}`)\n bytes += file.byteLength\n if (!Number.isSafeInteger(bytes) || bytes > input.maxReadBytes)\n throw new Error('workspace selective read exceeds maxReadBytes')\n selected.set(path, [])\n }\n await consumeWorkspaceArtifacts(input, undefined, selected)\n return new Map([...selected].map(([path, chunks]) => [path, Buffer.concat(chunks)]))\n}\n\n/** Restore regular-file artifacts into an empty destination, publishing only after complete verification. */\nexport async function materializeAgentCandidateWorkspaceFromArtifacts(\n input: AgentCandidateWorkspaceArtifactsOptions & { destination: string },\n): Promise<void> {\n input.signal?.throwIfAborted()\n if (!input.artifacts.readStream)\n throw new Error('streaming workspace artifacts require readStream')\n const destination = resolve(input.destination)\n await prepareEmptyDestination(destination)\n const staging = await mkdtemp(`${destination}.materializing-`)\n try {\n await consumeWorkspaceArtifacts(input, staging)\n input.signal?.throwIfAborted()\n await rename(staging, destination)\n } catch (error) {\n await rm(staging, { recursive: true, force: true })\n throw error\n }\n}\n\nasync function consumeWorkspaceArtifacts(\n input: AgentCandidateWorkspaceArtifactsOptions,\n destination?: string,\n selected?: Map<string, Uint8Array[]>,\n): Promise<void> {\n const { artifacts, signal } = input\n const snapshot = deepFreezeCandidate(structuredClone(input.snapshot))\n signal?.throwIfAborted()\n if (!artifacts.readStream) throw new Error('streaming workspace artifacts require readStream')\n const limits = workspaceLimits(input.limits)\n validateManifest(snapshot.material, limits)\n if (snapshot.archive.byteLength > limits.maxArchiveBytes)\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n const manifest = canonicalCandidateBytes(snapshot.material)\n verifyBytes(\n manifest,\n snapshot.manifest.sha256,\n snapshot.manifest.byteLength,\n 'candidate workspace manifest',\n )\n if (canonicalCandidateDigest(snapshot.material) !== snapshot.digest)\n throw new Error('workspace snapshot digest does not match its canonical manifest material')\n let offset = 0\n for await (const chunk of verifiedArtifactChunks(snapshot.manifest, artifacts, signal)) {\n if (\n !Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength).equals(\n manifest.subarray(offset, offset + chunk.byteLength),\n )\n ) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n offset += chunk.byteLength\n }\n\n const parser = extract()\n const canonical = pack()\n const canonicalResult = digestChunks(canonical, limits.maxArchiveBytes, signal)\n // Both drains start before writing, so tar-stream's backpressure bounds every queue.\n const reading = pipeline(\n Readable.from(verifiedArtifactChunks(snapshot.archive, artifacts, signal)),\n parser as unknown as NodeJS.WritableStream,\n { signal },\n )\n reading.catch(() => undefined)\n canonicalResult.catch(() => undefined)\n try {\n let index = 0\n for await (const entry of parser) {\n signal?.throwIfAborted()\n const expected = snapshot.material.files[index++]\n if (\n !expected ||\n entry.header.type !== 'file' ||\n entry.header.name !== `workspace/${expected.path}` ||\n entry.header.mode !== expected.mode ||\n entry.header.size !== expected.byteLength\n ) {\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n }\n const file = destination ? await openDestination(destination, expected.path) : undefined\n try {\n async function* checked(): AsyncGenerator<Uint8Array> {\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of entry) {\n if (!(chunk instanceof Uint8Array))\n throw new Error('workspace entry emitted a non-byte chunk')\n signal?.throwIfAborted()\n byteLength += chunk.byteLength\n if (byteLength > expected!.byteLength)\n throw new Error('workspace entry exceeds its manifest length')\n hash.update(chunk)\n if (file) await file.writeFile(chunk)\n selected?.get(expected!.path)?.push(Uint8Array.from(chunk))\n yield chunk\n }\n if (\n byteLength !== expected!.byteLength ||\n `sha256:${hash.digest('hex')}` !== expected!.sha256\n ) {\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n }\n }\n await appendTarFile(canonical, expected, checked(), signal)\n if (file) await file.chmod(expected.mode)\n } finally {\n await file?.close()\n }\n }\n if (index !== snapshot.material.files.length)\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n await reading\n canonical.finalize()\n const observed = await canonicalResult\n if (\n observed.byteLength !== snapshot.archive.byteLength ||\n observed.sha256 !== snapshot.archive.sha256\n ) {\n throw new Error('candidate workspace tar is not canonical')\n }\n } catch (error) {\n parser.destroy(asError(error))\n canonical.destroy(asError(error))\n await Promise.allSettled([reading, canonicalResult])\n throw error\n }\n}\n\nasync function openDestination(destination: string, relativePath: string) {\n const path = workspacePath(destination, relativePath)\n await mkdir(dirname(path), { recursive: true, mode: 0o700 })\n return open(\n path,\n constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,\n 0o600,\n )\n}\n\nasync function* workspaceArchiveChunks(\n root: string,\n material: AgentCandidateWorkspaceManifestMaterial,\n signal?: AbortSignal,\n): AsyncGenerator<Uint8Array> {\n const archive = pack()\n const writing = (async () => {\n try {\n for (const file of material.files) {\n signal?.throwIfAborted()\n await appendTarFile(archive, file, workspaceFileChunks(root, file, signal), signal)\n }\n archive.finalize()\n } catch (error) {\n archive.destroy(asError(error))\n throw error\n }\n })()\n writing.catch(() => undefined)\n try {\n for await (const chunk of archive) {\n if (!(chunk instanceof Uint8Array))\n throw new Error('workspace archive emitted a non-byte chunk')\n signal?.throwIfAborted()\n yield chunk\n }\n await writing\n } finally {\n archive.destroy()\n await writing.catch(() => undefined)\n }\n}\n\nasync function* workspaceFileChunks(\n root: string,\n expected: WorkspaceFile,\n signal?: AbortSignal,\n): AsyncGenerator<Uint8Array> {\n const path = workspacePath(root, expected.path)\n if ((await realpath(path)) !== path)\n throw new Error(`workspace file path changed during capture: ${expected.path}`)\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n const stats = await file.stat()\n if (\n !stats.isFile() ||\n stats.nlink !== 1 ||\n stats.size !== expected.byteLength ||\n (stats.mode & 0o777) !== expected.mode\n ) {\n throw new Error(`workspace file changed during capture: ${expected.path}`)\n }\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of file.createReadStream({\n autoClose: false,\n highWaterMark: 64 * 1024,\n })) {\n signal?.throwIfAborted()\n byteLength += chunk.byteLength\n if (byteLength > expected.byteLength)\n throw new Error(`workspace file changed during capture: ${expected.path}`)\n hash.update(chunk)\n yield chunk\n }\n if (byteLength !== expected.byteLength || `sha256:${hash.digest('hex')}` !== expected.sha256) {\n throw new Error(`workspace file changed during capture: ${expected.path}`)\n }\n } finally {\n await file.close()\n }\n}\n\nasync function appendTarFile(\n archive: Pack,\n file: WorkspaceFile,\n chunks: AsyncIterable<Uint8Array>,\n signal?: AbortSignal,\n): Promise<void> {\n const entry = archive.entry(\n workspaceTarHeader(`workspace/${file.path}`, file.mode, file.byteLength),\n )\n await pipeline(Readable.from(chunks), entry as unknown as NodeJS.WritableStream, { signal })\n}\n\nasync function digestChunks(\n chunks: AsyncIterable<unknown>,\n maxBytes: number,\n signal?: AbortSignal,\n) {\n const hash = createHash('sha256')\n let byteLength = 0\n for await (const chunk of chunks) {\n if (!(chunk instanceof Uint8Array))\n throw new Error('workspace archive emitted a non-byte chunk')\n signal?.throwIfAborted()\n byteLength += chunk.byteLength\n if (byteLength > maxBytes)\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n hash.update(chunk)\n }\n return { sha256: `sha256:${hash.digest('hex')}`, byteLength }\n}\n\nfunction validateManifest(\n material: AgentCandidateWorkspaceManifestMaterial,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): void {\n if (\n material.kind !== 'agent-candidate-workspace-manifest' ||\n material.files.length > limits.maxFiles\n )\n throw new Error('candidate workspace exceeds maxFiles')\n let total = 0\n let previous: string | undefined\n const paths = new Set<string>()\n for (const file of material.files) {\n safeArchivePath(file.path, limits.maxPathBytes)\n assertWorkspacePathOrder(\n file.path,\n previous,\n paths,\n 'candidate workspace paths must be unique and sorted',\n )\n previous = file.path\n if (!Number.isSafeInteger(file.mode) || file.mode < 0 || file.mode > 0o777)\n throw new Error('candidate workspace file has unsupported mode')\n if (\n !Number.isSafeInteger(file.byteLength) ||\n file.byteLength < 0 ||\n file.byteLength > limits.maxFileBytes\n )\n throw new Error('candidate workspace file exceeds maxFileBytes')\n total += file.byteLength\n if (total > limits.maxTotalFileBytes)\n throw new Error('candidate workspace exceeds maxTotalFileBytes')\n }\n}\n\nasync function* oneChunk(bytes: Uint8Array): AsyncGenerator<Uint8Array> {\n yield bytes\n}\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error(String(error))\n}\n"],"mappings":";;;;;;;;;;;;;;AAIA,MAAM,qBAAqB;AAE3B,MAAa,iCAAiC;;AAG9C,MAAa,wBAAwB;;AAErC,MAAa,uBAAuB;;AAkBpC,MAAa,2BAA2B,KAAK;;AAG7C,MAAa,4BACX;;AAOF,SAAgB,cAAc,QAAyD;CACrF,IAAI,WAAW,OAAO,OAAO,KAAA;CAC7B,MAAM,SAAS,QAAQ,UAAA;CACvB,IAAI,CAAC,OAAO,cAAc,MAAM,KAAK,UAAU,GAC7C,MAAM,IAAI,gBACR,wEACF;CAEF,OAAO;AACT;;;;;;;AAQA,MAAa,2BAA2B,IAAI;;AAG5C,SAAgB,sBAAsB,QAA0B;CAC9D,OAAO,WAAA,6BAAoC,WAAA;AAC7C;AACA,MAAM,8BAA8B;;;AAIpC,SAAgB,iBACd,SACA,YACA,YAAY,OACA;CACZ,MAAM,eAAe,KAAK,IAAI,IAAI,KAAK,IAAI,GAAG,OAAO;CACrD,IAAI,CAAC,OAAO,SAAS,OAAO,KAAK,CAAC,OAAO,cAAc,KAAK,KAAK,YAAY,CAAC,GAC5E,MAAM,IAAI,gBAAgB,iDAAiD;CAE7E,IAAI,UAAU;CACd,IAAI;CAEJ,MAAM,YAAkB;EACtB,IAAI,SAAS;EACb,MAAM,cAAc,KAAK,IAAI,GAAG,eAAe,KAAK,IAAI,CAAC;EACzD,QAAQ,iBACA;GACJ,IAAI,SAAS;GACb,IAAI,KAAK,IAAI,KAAK,cAAc,WAAW;QACtC,IAAI;EACX,GACA,KAAK,IAAI,aAAa,kBAAkB,CAC1C;EACA,IAAI,CAAC,aAAa,OAAO,MAAM,UAAU,YAAY,M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F;AAEA,gBAAgB,SAAS,OAA+C;CACtE,MAAM;AACR;AACA,SAAS,QAAQ,OAAuB;CACtC,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-runtime",
3
- "version": "0.314.2",
3
+ "version": "0.317.0",
4
4
  "description": "Shared task-lifecycle skeleton for agents: a recursive loop kernel for chat turns, one-shot tasks, and multi-attempt loops, with trace capture and eval-gated self-improvement. Domain behavior lives in adapters; scoring and ship-gates in @tangle-network/agent-eval.",
5
5
  "homepage": "https://github.com/tangle-network/agent-runtime#readme",
6
6
  "repository": {
@@ -34,6 +34,11 @@
34
34
  "import": "./dist/tool-loop.js",
35
35
  "default": "./dist/tool-loop.js"
36
36
  },
37
+ "./placement": {
38
+ "types": "./dist/placement.d.ts",
39
+ "import": "./dist/placement.js",
40
+ "default": "./dist/placement.js"
41
+ },
37
42
  "./intelligence": {
38
43
  "types": "./dist/intelligence.d.ts",
39
44
  "import": "./dist/intelligence.js",
@@ -83,6 +88,11 @@
83
88
  "types": "./dist/task-queue.d.ts",
84
89
  "import": "./dist/task-queue.js",
85
90
  "default": "./dist/task-queue.js"
91
+ },
92
+ "./workspace-store": {
93
+ "types": "./dist/workspace-store/index.d.ts",
94
+ "import": "./dist/workspace-store/index.js",
95
+ "default": "./dist/workspace-store/index.js"
86
96
  }
87
97
  },
88
98
  "bin": {