@tangle-network/agent-runtime 0.143.0 → 0.153.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/{activation-mi8TgSLM.js → activation-DKxQsHiO.js} +3 -3
- package/dist/{activation-mi8TgSLM.js.map → activation-DKxQsHiO.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{analyst-loop-CvkmfhUB.js → analyst-loop-B2kTHKNh.js} +2 -2
- package/dist/{analyst-loop-CvkmfhUB.js.map → analyst-loop-B2kTHKNh.js.map} +1 -1
- package/dist/analyst-loop.js +1 -1
- package/dist/{authoring-DuyShLdw.js → authoring-Tk2xFys0.js} +2 -2
- package/dist/{authoring-DuyShLdw.js.map → authoring-Tk2xFys0.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-CD5PoNmC.js → candidate-execution-CB9RJbbJ.js} +4 -4
- package/dist/{candidate-execution-CD5PoNmC.js.map → candidate-execution-CB9RJbbJ.js.map} +1 -1
- package/dist/{conversation-1hNtDeMM.js → conversation-D64WyWrK.js} +4 -4
- package/dist/{conversation-1hNtDeMM.js.map → conversation-D64WyWrK.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/durable.d.ts +102 -4
- package/dist/durable.js +259 -10
- package/dist/durable.js.map +1 -1
- package/dist/{environment-provider-B8eZ85Ga.d.ts → environment-provider-DJG0yIYl.d.ts} +2 -2
- package/dist/{environment-provider-DCBJ13VP.js → environment-provider-D_MXw3jK.js} +88 -9
- package/dist/environment-provider-D_MXw3jK.js.map +1 -0
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/executable-spec-BUcUcEPk.js +73 -0
- package/dist/executable-spec-BUcUcEPk.js.map +1 -0
- package/dist/{graph-De_XEsfH.js → graph-M0Qr4863.js} +4 -4
- package/dist/{graph-De_XEsfH.js.map → graph-M0Qr4863.js.map} +1 -1
- package/dist/{improvement-cycle-Bi-Tf4QF.js → improvement-cycle-CDxlGQGE.js} +7 -7
- package/dist/{improvement-cycle-Bi-Tf4QF.js.map → improvement-cycle-CDxlGQGE.js.map} +1 -1
- package/dist/{index-B8rKtH3U.d.ts → index-BihHgUAI.d.ts} +4 -4
- package/dist/{index-C2caGomG.d.ts → index-Dlz7ejRx.d.ts} +339 -503
- package/dist/{index-D4sLkOPY.d.ts → index-LQfgFJoX.d.ts} +2 -2
- package/dist/index.d.ts +7 -7
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +4 -4
- package/dist/intelligence.js +6 -6
- package/dist/kernel.d.ts +6 -6
- package/dist/kernel.js +13 -13
- package/dist/{knowledge-CVE6Wk1i.js → knowledge-DM-i40b9.js} +10 -7
- package/dist/{knowledge-CVE6Wk1i.js.map → knowledge-DM-i40b9.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-BoHdQqLm.d.ts → loop-runner-bin-D-BW51yr.d.ts} +3 -3
- package/dist/{loop-runner-bin-DdaI1nLL.js → loop-runner-bin-pD5WJuqJ.js} +4 -4
- package/dist/{loop-runner-bin-DdaI1nLL.js.map → loop-runner-bin-pD5WJuqJ.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/{materialization-P86EciBw.js → materialization-Bo6j3Hg9.js} +257 -61
- package/dist/materialization-Bo6j3Hg9.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +3 -3
- package/dist/mcp/index.js +6 -6
- package/dist/{model-policy-DgRJIJse.js → model-policy-Sw4ywhtL.js} +68 -6
- package/dist/model-policy-Sw4ywhtL.js.map +1 -0
- package/dist/{openai-tools-BiAWKjh6.js → openai-tools-CWBywy-e.js} +2 -2
- package/dist/{openai-tools-BiAWKjh6.js.map → openai-tools-CWBywy-e.js.map} +1 -1
- package/dist/{prepare-D3n7cA39.js → prepare-C3eFd3UA.js} +2 -2
- package/dist/{prepare-D3n7cA39.js.map → prepare-C3eFd3UA.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{protected-model-port-bq6bD9YX.js → protected-model-port-Dn2b6peS.js} +2 -2
- package/dist/{protected-model-port-bq6bD9YX.js.map → protected-model-port-Dn2b6peS.js.map} +1 -1
- package/dist/{redact-DexTuAiX.d.ts → redact-NAptmqKw.d.ts} +3 -3
- package/dist/{researcher-CiSY6Wzb.js → researcher-BMFFPwKb.js} +2 -2
- package/dist/{researcher-CiSY6Wzb.js.map → researcher-BMFFPwKb.js.map} +1 -1
- package/dist/{run-layout-Be_Z0dF8.js → run-layout-C2jgwsCq.js} +111 -6
- package/dist/run-layout-C2jgwsCq.js.map +1 -0
- package/dist/{runtime-J6Toky8K.d.ts → runtime-B-5dp5Iz.d.ts} +214 -14
- package/dist/{runtime-BnqjbOGX.js → runtime-RY_rvv7t.js} +85 -82
- package/dist/runtime-RY_rvv7t.js.map +1 -0
- package/dist/{sandbox-events-COwCWUVB.js → sandbox-events-DMijDq2p.js} +49 -2
- package/dist/sandbox-events-DMijDq2p.js.map +1 -0
- package/dist/{spawn-journal-D2HKUImC.js → spawn-journal-CLguaA2A.js} +8 -43
- package/dist/spawn-journal-CLguaA2A.js.map +1 -0
- package/dist/{stream-agent-turn-C1Vs_3B9.d.ts → stream-agent-turn-BGyszuPH.d.ts} +2 -2
- package/dist/{stream-agent-turn-CXRugSGO.js → stream-agent-turn-D6HoaRPV.js} +90 -14
- package/dist/stream-agent-turn-D6HoaRPV.js.map +1 -0
- package/dist/{structural-rollout-CJgj9YXH.js → structural-rollout-P1YxFRfl.js} +11 -8
- package/dist/structural-rollout-P1YxFRfl.js.map +1 -0
- package/dist/{supervise-hCgG6ROJ.js → supervise-BezbzKiJ.js} +1550 -1186
- package/dist/supervise-BezbzKiJ.js.map +1 -0
- package/dist/{supervisor-s8SfZYbW.js → supervisor-DBVlPONC.js} +597 -194
- package/dist/supervisor-DBVlPONC.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +12 -12
- package/dist/{top-app-BMOSKK06.js → top-app-tKo9OrON.js} +189 -86
- package/dist/top-app-tKo9OrON.js.map +1 -0
- package/dist/tui/bin.js +1 -1
- package/dist/tui/index.d.ts +32 -4
- package/dist/tui/index.js +1 -1
- package/dist/{types-Df9vulGc.d.ts → types-BPQhQRrC.d.ts} +507 -10
- package/dist/{util-C1bv6yog.js → util-Bncw0o_F.js} +41 -2
- package/dist/util-Bncw0o_F.js.map +1 -0
- package/dist/{workspace-archive-C52LjkeN.js → workspace-archive-Dm73lTfB.js} +2 -2
- package/dist/{workspace-archive-C52LjkeN.js.map → workspace-archive-Dm73lTfB.js.map} +1 -1
- package/package.json +4 -4
- package/dist/environment-provider-DCBJ13VP.js.map +0 -1
- package/dist/materialization-P86EciBw.js.map +0 -1
- package/dist/model-policy-DgRJIJse.js.map +0 -1
- package/dist/retained-run-binding-Dp2e8xne.js +0 -268
- package/dist/retained-run-binding-Dp2e8xne.js.map +0 -1
- package/dist/run-layout-Be_Z0dF8.js.map +0 -1
- package/dist/runtime-BnqjbOGX.js.map +0 -1
- package/dist/sandbox-events-COwCWUVB.js.map +0 -1
- package/dist/spawn-journal-D2HKUImC.js.map +0 -1
- package/dist/stream-agent-turn-CXRugSGO.js.map +0 -1
- package/dist/structural-rollout-CJgj9YXH.js.map +0 -1
- package/dist/supervise-hCgG6ROJ.js.map +0 -1
- package/dist/supervisor-s8SfZYbW.js.map +0 -1
- package/dist/top-app-BMOSKK06.js.map +0 -1
- package/dist/util-C1bv6yog.js.map +0 -1
|
@@ -120,6 +120,45 @@ function usdEstimatedOf(...spends) {
|
|
|
120
120
|
}
|
|
121
121
|
return priced ? { usdEstimated: total } : {};
|
|
122
122
|
}
|
|
123
|
+
/** A conserved spend with every channel at zero and no completeness claim on it. */
|
|
124
|
+
function zeroSpend() {
|
|
125
|
+
return {
|
|
126
|
+
iterations: 0,
|
|
127
|
+
tokens: zeroTokenUsage(),
|
|
128
|
+
usd: 0,
|
|
129
|
+
ms: 0
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */
|
|
133
|
+
function cloneSpend(spend) {
|
|
134
|
+
return {
|
|
135
|
+
iterations: spend.iterations,
|
|
136
|
+
tokens: cloneTokenUsage(spend.tokens),
|
|
137
|
+
...spend.tokensKnown === false ? { tokensKnown: false } : {},
|
|
138
|
+
usd: spend.usd,
|
|
139
|
+
...spend.usdKnown === false ? { usdKnown: false } : {},
|
|
140
|
+
...spend.usdEstimated !== void 0 ? { usdEstimated: spend.usdEstimated } : {},
|
|
141
|
+
ms: spend.ms
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Sum two conserved spends per channel. Tokens and dollars never fold into each other, an
|
|
146
|
+
* incomplete input keeps the sum incomplete on that channel, and the catalog-priced part of the
|
|
147
|
+
* dollar total is summed separately so `usd - usdEstimated` still names what a provider billed.
|
|
148
|
+
*/
|
|
149
|
+
function addSpend(a, b) {
|
|
150
|
+
const tokens = cloneTokenUsage(a.tokens);
|
|
151
|
+
addTokenUsage(tokens, b.tokens);
|
|
152
|
+
return {
|
|
153
|
+
iterations: a.iterations + b.iterations,
|
|
154
|
+
tokens,
|
|
155
|
+
...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
|
|
156
|
+
usd: a.usd + b.usd,
|
|
157
|
+
...a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {},
|
|
158
|
+
...usdEstimatedOf(a, b),
|
|
159
|
+
ms: a.ms + b.ms
|
|
160
|
+
};
|
|
161
|
+
}
|
|
123
162
|
/** Copy a token subtotal without dropping optional provider cache telemetry. */
|
|
124
163
|
function cloneTokenUsage(usage) {
|
|
125
164
|
const cacheBreakdownUnknown = usage.cacheBreakdownKnown === false || usage.input > 0 && !hasClassifiedCacheBreakdown(usage);
|
|
@@ -277,6 +316,6 @@ async function mapWithConcurrency(items, limit, fn) {
|
|
|
277
316
|
return results;
|
|
278
317
|
}
|
|
279
318
|
//#endregion
|
|
280
|
-
export {
|
|
319
|
+
export { withTimeout as _, cloneTokenUsage as a, isAbortError as c, randomSuffix as d, randomUuid as f, throwIfAborted as g, throwAbort as h, cloneSpend as i, mapWithConcurrency as l, stringifySafe as m, addTokenUsage as n, deleteBoxSafe as o, sleep as p, chargedTokens as r, hasCompleteCacheBreakdown as s, addSpend as t, promptCacheTokenClasses as u, zeroSpend as v, zeroTokenUsage as y };
|
|
281
320
|
|
|
282
|
-
//# sourceMappingURL=util-
|
|
321
|
+
//# sourceMappingURL=util-Bncw0o_F.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util-Bncw0o_F.js","names":[],"sources":["../src/runtime/util.ts"],"sourcesContent":["/**\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 type { Spend } from './supervise/types'\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): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\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 timer = setTimeout(() => resolve(undefined), ms)\n promise.then(\n (value) => {\n clearTimeout(timer)\n resolve(value)\n },\n () => {\n clearTimeout(timer)\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/** Copy a conserved spend without dropping a completeness marker or the catalog-priced part. */\nexport function cloneSpend(spend: Spend): Spend {\n return {\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 }\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 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 }\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/** 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: Readonly<Record<string, number | string>> | 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 bound = Math.max(1, Math.floor(limit))\n const results = new Array<R>(items.length)\n let next = 0\n let failed = false\n const worker = async (): Promise<void> => {\n while (!failed) {\n const i = next\n next += 1\n if (i >= items.length) return\n try {\n results[i] = await fn(items[i] as T, i)\n } catch (err) {\n failed = true\n throw err\n }\n }\n }\n const workerCount = Math.min(bound, items.length)\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n return results\n}\n"],"mappings":";;;;;;AAiBA,eAAsB,cAAc,KAAoD;CACtF,IAAI,CAAC,OAAO,OAAQ,IAA6B,WAAW,YAAY,OAAO;CAC/E,IAAI;EACF,MAAM,IAAI,OAAO;EACjB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAgB,aAAa,MAAM,GAAW;CAC5C,OAAO,KAAK,OAAO,CAAC,CACjB,SAAS,EAAE,CAAC,CACZ,MAAM,GAAG,IAAI,GAAG;AACrB;;AAGA,SA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KACrB,MAAM,cAAc,KAAA,KACpB,MAAM,eAAe,KAAA,KACrB,MAAM,aAAa,MAAM,YAAY,MAAM,eAAe;CAI5D,IAAI,MAAM,wBAAwB,SAAU,QAAQ,KAAK,CAAC,YACxD,IAAI,sBAAsB;AAE9B;;;;;;;;;;AAWA,eAAsB,mBACpB,OACA,OACA,IACc;CACd,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;CAC3C,MAAM,UAAU,IAAI,MAAS,MAAM,MAAM;CACzC,IAAI,OAAO;CACX,IAAI,SAAS;CACb,MAAM,SAAS,YAA2B;EACxC,OAAO,CAAC,QAAQ;GACd,MAAM,IAAI;GACV,QAAQ;GACR,IAAI,KAAK,MAAM,QAAQ;GACvB,IAAI;IACF,QAAQ,KAAK,MAAM,GAAG,MAAM,IAAS,CAAC;GACxC,SAAS,KAAK;IACZ,SAAS;IACT,MAAM;GACR;EACF;CACF;CACA,MAAM,cAAc,KAAK,IAAI,OAAO,MAAM,MAAM;CAChD,MAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,YAAY,SAAS,OAAO,CAAC,CAAC;CACrE,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as verifyMaterializedWorkspace, C as assertNoGitIndirection, D as captureMaterializedWorkspace, E as candidateWorkspaceManifest, T as runCandidateGit, a as persistCandidateOutputArtifact, at as deepFreezeCandidate, ct as omitTopLevelDigest, k as verifyBytes, lt as sha256Bytes, nt as canonicalCandidateBytes, ot as embeddedCandidateArtifact, rt as canonicalCandidateDigest$1, st as immutableCandidateValue, w as readCandidateGitTreeFiles } from "./prepare-
|
|
1
|
+
import { A as verifyMaterializedWorkspace, C as assertNoGitIndirection, D as captureMaterializedWorkspace, E as candidateWorkspaceManifest, T as runCandidateGit, a as persistCandidateOutputArtifact, at as deepFreezeCandidate, ct as omitTopLevelDigest, k as verifyBytes, lt as sha256Bytes, nt as canonicalCandidateBytes, ot as embeddedCandidateArtifact, rt as canonicalCandidateDigest$1, st as immutableCandidateValue, w as readCandidateGitTreeFiles } from "./prepare-C3eFd3UA.js";
|
|
2
2
|
import { agentCandidateBundleSchema } from "@tangle-network/agent-interface";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
4
|
import { dirname, isAbsolute, join, resolve, sep, win32 } from "node:path";
|
|
@@ -572,4 +572,4 @@ const typedArrayByteLengthGetter = requireTypedArrayGetter("byteLength");
|
|
|
572
572
|
//#endregion
|
|
573
573
|
export { sealAgentCandidateBundle as i, captureAgentCandidateWorkspaceFiles as n, createAgentCandidateWorkspacePort as r, captureAgentCandidateWorkspace as t };
|
|
574
574
|
|
|
575
|
-
//# sourceMappingURL=workspace-archive-
|
|
575
|
+
//# sourceMappingURL=workspace-archive-Dm73lTfB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-archive-C52LjkeN.js","names":["canonicalCandidateDigest","canonicalCandidateDigest","fsConstants"],"sources":["../src/candidate-execution/bundle.ts","../src/candidate-execution/workspace-archive.ts"],"sourcesContent":["import type { AgentCandidateBundle } from '@tangle-network/agent-interface'\nimport { agentCandidateBundleSchema } from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue, omitTopLevelDigest } from './digest'\n\n/** Exact candidate wire shape before the runtime computes its canonical digest. */\nexport type AgentCandidateBundleInput = Omit<AgentCandidateBundle, 'digest'>\n\n/** Validate and content-address a candidate bundle before it crosses an approval boundary. */\nexport function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle {\n const digest = canonicalCandidateDigest(input)\n const parsed = agentCandidateBundleSchema.parse({ ...input, digest })\n const parsedDigest = canonicalCandidateDigest(omitTopLevelDigest(parsed))\n if (parsedDigest !== digest) {\n throw new Error('candidate bundle changed while validating its canonical wire shape')\n }\n return immutableCandidateValue(parsed)\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'\n\nimport type {\n AgentCandidateCapturedArtifact,\n AgentCandidateWorkspaceSnapshotEvidence,\n} from '@tangle-network/agent-interface'\nimport { type Entry, extract, type Pack, pack } from 'tar-stream'\n\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 {\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 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 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\nasync function captureRepository(\n root: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<{\n files: Array<{ path: string; mode: number; bytes: Uint8Array }>\n repository: WorkspaceArchiveRepository\n}> {\n const stats = await lstat(root)\n if (!stats.isDirectory() || stats.isSymbolicLink() || (await realpath(root)) !== root) {\n throw new Error('candidate repository root must be a real directory')\n }\n const topLevel = (await runCandidateGit(root, ['rev-parse', '--show-toplevel'])).stdout\n .toString('utf8')\n .trim()\n if (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 {\n name,\n mode,\n uid: 0,\n gid: 0,\n size: bytes.byteLength,\n mtime: fixedTarTime,\n type: 'file',\n uname: '',\n gname: '',\n },\n Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),\n (error) => (error ? rejectEntry(error) : resolveEntry()),\n )\n })\n}\n\nasync function readTarEntry(entry: Entry, 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<Uint8Array>,\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.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<Uint8Array>,\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.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\nasync function prepareEmptyDestination(destination: string): Promise<void> {\n await mkdir(destination, { recursive: true, mode: 0o700 })\n const stats = await lstat(destination)\n if (\n !stats.isDirectory() ||\n stats.isSymbolicLink() ||\n (await realpath(destination)) !== destination\n ) {\n throw new Error('candidate workspace destination must be 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\nfunction 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\nfunction 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\nfunction 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\nfunction 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\nfunction 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 typedArr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M,yBAAyB,KAAK,yBAAyB;CACpF,OAAO;AACT;AAEA,MAAM,yBAAyB,wBAAwB,QAAQ;AAC/D,MAAM,6BAA6B,wBAAwB,YAAY;AACvE,MAAM,6BAA6B,wBAAwB,YAAY"}
|
|
1
|
+
{"version":3,"file":"workspace-archive-Dm73lTfB.js","names":["canonicalCandidateDigest","canonicalCandidateDigest","fsConstants"],"sources":["../src/candidate-execution/bundle.ts","../src/candidate-execution/workspace-archive.ts"],"sourcesContent":["import type { AgentCandidateBundle } from '@tangle-network/agent-interface'\nimport { agentCandidateBundleSchema } from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue, omitTopLevelDigest } from './digest'\n\n/** Exact candidate wire shape before the runtime computes its canonical digest. */\nexport type AgentCandidateBundleInput = Omit<AgentCandidateBundle, 'digest'>\n\n/** Validate and content-address a candidate bundle before it crosses an approval boundary. */\nexport function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle {\n const digest = canonicalCandidateDigest(input)\n const parsed = agentCandidateBundleSchema.parse({ ...input, digest })\n const parsedDigest = canonicalCandidateDigest(omitTopLevelDigest(parsed))\n if (parsedDigest !== digest) {\n throw new Error('candidate bundle changed while validating its canonical wire shape')\n }\n return immutableCandidateValue(parsed)\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'\n\nimport type {\n AgentCandidateCapturedArtifact,\n AgentCandidateWorkspaceSnapshotEvidence,\n} from '@tangle-network/agent-interface'\nimport { type Entry, extract, type Pack, pack } from 'tar-stream'\n\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 {\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 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 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\nasync function captureRepository(\n root: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<{\n files: Array<{ path: string; mode: number; bytes: Uint8Array }>\n repository: WorkspaceArchiveRepository\n}> {\n const stats = await lstat(root)\n if (!stats.isDirectory() || stats.isSymbolicLink() || (await realpath(root)) !== root) {\n throw new Error('candidate repository root must be a real directory')\n }\n const topLevel = (await runCandidateGit(root, ['rev-parse', '--show-toplevel'])).stdout\n .toString('utf8')\n .trim()\n if (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 {\n name,\n mode,\n uid: 0,\n gid: 0,\n size: bytes.byteLength,\n mtime: fixedTarTime,\n type: 'file',\n uname: '',\n gname: '',\n },\n Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),\n (error) => (error ? rejectEntry(error) : resolveEntry()),\n )\n })\n}\n\nasync function readTarEntry(entry: Entry, 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<Uint8Array>,\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.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<Uint8Array>,\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.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\nasync function prepareEmptyDestination(destination: string): Promise<void> {\n await mkdir(destination, { recursive: true, mode: 0o700 })\n const stats = await lstat(destination)\n if (\n !stats.isDirectory() ||\n stats.isSymbolicLink() ||\n (await realpath(destination)) !== destination\n ) {\n throw new Error('candidate workspace destination must be 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\nfunction 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\nfunction 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\nfunction 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\nfunction 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\nfunction 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"],"mappings":";;;;;;;;;;;AASA,SAAgB,yBAAyB,OAAwD;CAC/F,MAAM,SAASA,2BAAyB,KAAK;CAC7C,MAAM,SAAS,2BAA2B,MAAM;EAAE,GAAG;EAAO;CAAO,CAAC;CAEpE,IADqBA,2BAAyB,mBAAmB,MAAM,CACxD,MAAM,QACnB,MAAM,IAAI,MAAM,oEAAoE;CAEtF,OAAO,wBAAwB,MAAM;AACvC;;;ACgCA,MAAM,cAAc;AACpB,MAAM,uBAAuB;AAC7B,MAAM,0BAA0B;AAChC,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AU,QAAQ,QAAS,OAAO;GAChD;EACF,OAAO,IAAI,QAAQ,SAAU,QAAQ,OACnC,OAAO;CAEX;CACA,OAAO;AACT;AAEA,SAAS,cAAc,MAAc,cAA8B;CACjE,MAAM,OAAO,QAAQ,MAAM,YAAY;CACvC,IAAI,CAAC,KAAK,WAAW,GAAG,OAAO,KAAK,GAClC,MAAM,IAAI,MAAM,6DAA6D,cAAc;CAE7F,OAAO;AACT;AAEA,SAAS,kBAAkB,OAAe,OAAqB;CAC7D,IAAI,CAAC,kCAAkC,KAAK,KAAK,GAC/C,MAAM,IAAI,MAAM,wBAAwB,MAAM,wBAAwB;AAE1E;AAEA,SAAS,oBAAoB,OAAwB;CACnD,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,QAAQ,SAAS;EACjD,MAAM,OAAO,MAAM,WAAW,KAAK;EACnC,IAAI,OAAO,MAAQ,SAAS,KAAM,OAAO;CAC3C;CACA,OAAO;AACT;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAIA,SAAS,wBAAwB,MAAgE;CAC/F,MAAM,sBAAsB,OAAO,eAAe,WAAW,SAAS;CACtE,MAAM,SAAS,OAAO,yBAAyB,qBAAqB,IAAI,CAAC,EAAE;CAC3E,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,yBAAyB,KAAK,yBAAyB;CACpF,OAAO;AACT;AAEA,MAAM,yBAAyB,wBAAwB,QAAQ;AAC/D,MAAM,6BAA6B,wBAAwB,YAAY;AACvE,MAAM,6BAA6B,wBAAwB,YAAY"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-runtime",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.153.1",
|
|
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": {
|
|
@@ -119,7 +119,7 @@
|
|
|
119
119
|
"@modelcontextprotocol/sdk": "1.30.0",
|
|
120
120
|
"@biomejs/biome": "^2.5.5",
|
|
121
121
|
"@tangle-network/agent-eval": ">=0.149.0 <0.150.0",
|
|
122
|
-
"@tangle-network/agent-interface": "^1.
|
|
122
|
+
"@tangle-network/agent-interface": "^1.4.0",
|
|
123
123
|
"@tangle-network/sandbox": ">=0.31.0 <0.32.0",
|
|
124
124
|
"@types/node": "26.1.1",
|
|
125
125
|
"@types/tar-stream": "3.1.4",
|
|
@@ -141,7 +141,7 @@
|
|
|
141
141
|
"license": "MIT",
|
|
142
142
|
"peerDependencies": {
|
|
143
143
|
"@tangle-network/agent-eval": ">=0.149.0 <0.150.0",
|
|
144
|
-
"@tangle-network/agent-interface": "^1.
|
|
144
|
+
"@tangle-network/agent-interface": "^1.4.0",
|
|
145
145
|
"@tangle-network/sandbox": ">=0.31.0 <0.32.0"
|
|
146
146
|
},
|
|
147
147
|
"peerDependenciesMeta": {
|
|
@@ -152,7 +152,7 @@
|
|
|
152
152
|
"dependencies": {
|
|
153
153
|
"@tangle-network/agent-core": ">=0.9.4 <0.10.0",
|
|
154
154
|
"@tangle-network/agent-knowledge": "^8.0.10",
|
|
155
|
-
"@tangle-network/agent-profile-materialize": ">=0.
|
|
155
|
+
"@tangle-network/agent-profile-materialize": ">=0.17.1 <0.18.0",
|
|
156
156
|
"@tangle-network/agent-trace-contract": "^1.0.2",
|
|
157
157
|
"tar-stream": "3.2.0"
|
|
158
158
|
},
|