@tangle-network/agent-runtime 0.134.2 → 0.134.4
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/dist/{activation-CY_v6Ia7.js → activation-q9Zo4NRy.js} +3 -3
- package/dist/{activation-CY_v6Ia7.js.map → activation-q9Zo4NRy.js.map} +1 -1
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +3 -3
- package/dist/{analyst-loop-BKWqQhVI.js → analyst-loop-Dk6_xfhI.js} +2 -2
- package/dist/{analyst-loop-BKWqQhVI.js.map → analyst-loop-Dk6_xfhI.js.map} +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/analyst-loop.js +1 -1
- package/dist/{authoring-BDICoQby.js → authoring-CmzMOTKX.js} +2 -2
- package/dist/{authoring-BDICoQby.js.map → authoring-CmzMOTKX.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-CWMkOz7g.js → candidate-execution-CyCLYLfK.js} +4 -4
- package/dist/{candidate-execution-CWMkOz7g.js.map → candidate-execution-CyCLYLfK.js.map} +1 -1
- package/dist/{conversation-CrWcNPQg.js → conversation-DYVSghi8.js} +2 -2
- package/dist/{conversation-CrWcNPQg.js.map → conversation-DYVSghi8.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/{environment-provider-CPHwqLLm.js → environment-provider-CLNVqp6H.js} +2 -2
- package/dist/{environment-provider-CPHwqLLm.js.map → environment-provider-CLNVqp6H.js.map} +1 -1
- package/dist/{environment-provider-qDOhdE9M.d.ts → environment-provider-DIRm41xB.d.ts} +3 -3
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-D5TKFG8R.js → graph-B0wXX8Pr.js} +3 -3
- package/dist/{graph-D5TKFG8R.js.map → graph-B0wXX8Pr.js.map} +1 -1
- package/dist/{improvement-cycle-XLPktFtP.js → improvement-cycle-4dO93TTE.js} +6 -6
- package/dist/{improvement-cycle-XLPktFtP.js.map → improvement-cycle-4dO93TTE.js.map} +1 -1
- package/dist/{index-DBZTN4ci.d.ts → index-7VFw3_z0.d.ts} +4 -4
- package/dist/{index-CgBJtAzI.d.ts → index-BbdLlSh6.d.ts} +3 -3
- package/dist/{index-DiUDbnk-.d.ts → index-SWNlB0Hv.d.ts} +29 -23
- package/dist/index.d.ts +9 -9
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +5 -5
- package/dist/intelligence.js +6 -6
- package/dist/kernel.d.ts +7 -7
- package/dist/kernel.js +10 -10
- package/dist/{knowledge-Dv2HMnE6.js → knowledge-EDOC3wEs.js} +5 -5
- package/dist/{knowledge-Dv2HMnE6.js.map → knowledge-EDOC3wEs.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-Bieu4QO4.js → loop-runner-bin-CoBcsxpe.js} +4 -4
- package/dist/{loop-runner-bin-Bieu4QO4.js.map → loop-runner-bin-CoBcsxpe.js.map} +1 -1
- package/dist/{loop-runner-bin-D5JXvb_l.d.ts → loop-runner-bin-DXqzpr4i.d.ts} +3 -3
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +5 -5
- package/dist/mcp/index.js +5 -5
- package/dist/{openai-tools-D4Rf0Ciu.js → openai-tools-BQHlv-Ex.js} +2 -2
- package/dist/{openai-tools-D4Rf0Ciu.js.map → openai-tools-BQHlv-Ex.js.map} +1 -1
- package/dist/{openai-tools-CzEiSbPW.d.ts → openai-tools-BulrPqjW.d.ts} +2 -2
- package/dist/{prepare-BxP7Hq1l.js → prepare-Czki1LBy.js} +4 -2
- package/dist/{prepare-BxP7Hq1l.js.map → prepare-Czki1LBy.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{protected-model-port-B82zDDu5.js → protected-model-port-OhS0l_6m.js} +2 -2
- package/dist/{protected-model-port-B82zDDu5.js.map → protected-model-port-OhS0l_6m.js.map} +1 -1
- package/dist/{redact-6UE6pdNi.d.ts → redact-DTVIFTeR.d.ts} +3 -3
- package/dist/{runtime-DlxoqEj2.d.ts → runtime-C60zv0Q4.d.ts} +4 -4
- package/dist/{runtime-Ox-uvtni.js → runtime-DJMlvPY7.js} +14 -11
- package/dist/runtime-DJMlvPY7.js.map +1 -0
- package/dist/{sandbox-events-vIwmuPdl.js → sandbox-events-CA2amHoA.js} +98 -3
- package/dist/sandbox-events-CA2amHoA.js.map +1 -0
- package/dist/{spawn-journal-TJSlDa2J.js → spawn-journal-ZKEKel8N.js} +10 -4
- package/dist/spawn-journal-ZKEKel8N.js.map +1 -0
- package/dist/{stream-agent-turn-CJog3ebs.d.ts → stream-agent-turn-BLuTjcvw.d.ts} +3 -3
- package/dist/{stream-agent-turn-CdIcf-bn.js → stream-agent-turn-DYBpzMmq.js} +2 -2
- package/dist/{stream-agent-turn-CdIcf-bn.js.map → stream-agent-turn-DYBpzMmq.js.map} +1 -1
- package/dist/{structural-rollout-CnHKUCVM.js → structural-rollout-GX7EzxeM.js} +4 -4
- package/dist/{structural-rollout-CnHKUCVM.js.map → structural-rollout-GX7EzxeM.js.map} +1 -1
- package/dist/{supervise-BNOccEtp.js → supervise-7JtBc_eW.js} +6 -6
- package/dist/{supervise-BNOccEtp.js.map → supervise-7JtBc_eW.js.map} +1 -1
- package/dist/{supervisor-4r4BYSti.js → supervisor-Bfh5Gq_P.js} +147 -33
- package/dist/supervisor-Bfh5Gq_P.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +108 -96
- package/dist/testing.js.map +1 -1
- package/dist/{types-D4BfurNs.d.ts → types-CfQbuWgo.d.ts} +26 -5
- package/dist/{types-6zHo67jn.d.ts → types-DzZCZcwI.d.ts} +14 -14
- package/dist/{util-CG3ghHfb.js → util-C1bv6yog.js} +60 -2
- package/dist/util-C1bv6yog.js.map +1 -0
- package/dist/{workspace-archive-BwJQSvGi.js → workspace-archive-B_JDld25.js} +2 -2
- package/dist/{workspace-archive-BwJQSvGi.js.map → workspace-archive-B_JDld25.js.map} +1 -1
- package/package.json +10 -10
- package/dist/runtime-Ox-uvtni.js.map +0 -1
- package/dist/sandbox-events-vIwmuPdl.js.map +0 -1
- package/dist/spawn-journal-TJSlDa2J.js.map +0 -1
- package/dist/supervisor-4r4BYSti.js.map +0 -1
- package/dist/util-CG3ghHfb.js.map +0 -1
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","names":["canonicalAgentImprovementProposalFixture","canonicalAgentProfileImprovementProposalFixture","canonicalAgentProfileImprovementStateFixture","canonicalCandidateDigest"],"sources":["../src/testing/fixtures/agent-improvement-proposal.json","../src/testing/fixtures/agent-profile-improvement-proposal.json","../src/testing/fixtures/agent-profile-improvement-state.json","../src/testing/index.ts"],"sourcesContent":["","","","import {\n type AgentImprovementProposal,\n type AgentProfile,\n type AgentProfileImprovementMeasuredComparison,\n SANDBOX_SIZE_PRESET_NAMES,\n type SandboxSizePreset,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { applyExactAgentProfileDiff, parseExactAgentProfile } from '../candidate-execution/profile'\nimport { verifyAgentImprovementProposal } from '../intelligence/improvement-cycle'\nimport canonicalAgentImprovementProposalFixture from './fixtures/agent-improvement-proposal.json'\nimport canonicalAgentProfileImprovementProposalFixture from './fixtures/agent-profile-improvement-proposal.json'\nimport canonicalAgentProfileImprovementStateFixture from './fixtures/agent-profile-improvement-state.json'\n\nexport {\n type DriverAgentOptions,\n driverAgent,\n} from '../runtime/supervise/coordination-driver'\nexport {\n type RunGraphTestOptions,\n runGraphWithTestBrain,\n} from '../runtime/supervise/graph'\nexport {\n type SuperviseTestOptions,\n superviseWithTestBrain,\n} from '../runtime/supervise/supervise'\nexport {\n type SupervisorAgentTestDeps,\n supervisorAgentWithTestBrain,\n} from '../runtime/supervise/supervisor-agent'\nexport type { ToolLoopCallContext, ToolLoopChat } from '../runtime/tool-loop'\n\nconst serializedAgentImprovementProposalFixture = JSON.stringify(\n canonicalAgentImprovementProposalFixture,\n)\nconst serializedAgentProfileImprovementProposalFixture = JSON.stringify(\n canonicalAgentProfileImprovementProposalFixture,\n)\nconst serializedAgentProfileImprovementStateFixture = JSON.stringify(\n canonicalAgentProfileImprovementStateFixture,\n)\n\n/** A proposal produced by Runtime's opaque profile-improvement path. */\nexport type AgentProfileImprovementProposalFixture = Omit<\n AgentImprovementProposal,\n 'evaluation'\n> & {\n evaluation: AgentProfileImprovementMeasuredComparison\n}\n\n/** Complete private state for exercising profile activation and restore in consumer tests. */\nexport interface AgentProfileImprovementFixture {\n proposal: AgentProfileImprovementProposalFixture\n baselineProfile: AgentProfile\n candidateProfile: AgentProfile\n recommendedSize: SandboxSizePreset\n}\n\n/** Load an isolated, production-validated Runtime proposal for consumer tests. */\nexport function loadAgentImprovementProposalFixture(): AgentImprovementProposal {\n return verifyAgentImprovementProposal(JSON.parse(serializedAgentImprovementProposalFixture))\n}\n\n/** Load an isolated profile proposal and its private activation state for consumer tests. */\nexport function loadAgentProfileImprovementFixture(): AgentProfileImprovementFixture {\n const proposal = loadAgentProfileImprovementProposal()\n const state = parseAgentProfileImprovementState(\n JSON.parse(serializedAgentProfileImprovementStateFixture),\n )\n const experiment = proposal.evaluation.experiment\n const baselineStateDigest = profileStateDigest(state.baselineProfile, state.recommendedSize)\n const candidateStateDigest = profileStateDigest(state.candidateProfile, state.recommendedSize)\n if (\n baselineStateDigest !== experiment.baseline.stateDigest ||\n candidateStateDigest !== experiment.candidate.stateDigest\n ) {\n throw new Error('profile improvement fixture state does not match its proposal')\n }\n const appliedCandidate = experiment.change.reduce(\n (profile, change, index) =>\n applyExactAgentProfileDiff(profile, change, `profile improvement fixture change ${index}`),\n state.baselineProfile,\n )\n if (\n canonicalCandidateDigest(appliedCandidate) !== canonicalCandidateDigest(state.candidateProfile)\n ) {\n throw new Error('profile improvement fixture candidate does not match its proposal changes')\n }\n return immutableCandidateValue({ proposal, ...state })\n}\n\nfunction loadAgentProfileImprovementProposal(): AgentProfileImprovementProposalFixture {\n const proposal = verifyAgentImprovementProposal(\n JSON.parse(serializedAgentProfileImprovementProposalFixture),\n )\n if (proposal.evaluation.kind !== 'agent-profile-improvement-measured-comparison') {\n throw new Error('profile improvement fixture contains a sealed candidate comparison')\n }\n return { ...proposal, evaluation: proposal.evaluation }\n}\n\nfunction parseAgentProfileImprovementState(\n input: unknown,\n): Omit<AgentProfileImprovementFixture, 'proposal'> {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new Error('profile improvement fixture state must be an object')\n }\n const record = input as Record<string, unknown>\n const fields = Object.keys(record).sort()\n const expectedFields = ['baselineProfile', 'candidateProfile', 'recommendedSize']\n if (\n fields.length !== expectedFields.length ||\n fields.some((field, i) => field !== expectedFields[i])\n ) {\n throw new Error('profile improvement fixture state contains unsupported fields')\n }\n const recommendedSize = SANDBOX_SIZE_PRESET_NAMES.find((size) => size === record.recommendedSize)\n if (!recommendedSize) {\n throw new Error('profile improvement fixture has an invalid recommended size')\n }\n return {\n baselineProfile: parseExactAgentProfile(\n record.baselineProfile,\n 'profile improvement fixture baseline',\n ),\n candidateProfile: parseExactAgentProfile(\n record.candidateProfile,\n 'profile improvement fixture candidate',\n ),\n recommendedSize,\n }\n}\n\nfunction profileStateDigest(\n profile: AgentProfile,\n recommendedSize: SandboxSizePreset,\n): ReturnType<typeof canonicalCandidateDigest> {\n return canonicalCandidateDigest({ definition: profile, recommendedSize })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ACkD;CAClD,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,qDAAqD;CAEvE,MAAM,SAAS;CACf,MAAM,SAAS,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK;CACxC,MAAM,iBAAiB;EAAC;EAAmB;EAAoB;CAAiB;CAChF,IACE,OAAO,WAAW,eAAe,UACjC,OAAO,MAAM,OAAO,MAAM,UAAU,eAAe,EAAE,GAErD,MAAM,IAAI,MAAM,+DAA+D;CAEjF,MAAM,kBAAkB,0BAA0B,MAAM,SAAS,SAAS,OAAO,eAAe;CAChG,IAAI,CAAC,iBACH,MAAM,IAAI,MAAM,6DAA6D;CAE/E,OAAO;EACL,iBAAiB,uBACf,OAAO,iBACP,sCACF;EACA,kBAAkB,uBAChB,OAAO,kBACP,uCACF;EACA;CACF;AACF;AAEA,SAAS,mBACP,SACA,iBAC6C;CAC7C,OAAOA,2BAAyB;EAAE,YAAY;EAAS;CAAgB,CAAC;AAC1E"}
|
|
1
|
+
{"version":3,"file":"testing.js","names":["canonicalAgentImprovementProposalFixture","canonicalAgentProfileImprovementProposalFixture","canonicalAgentProfileImprovementStateFixture","canonicalCandidateDigest"],"sources":["../src/testing/fixtures/agent-improvement-proposal.json","../src/testing/fixtures/agent-profile-improvement-proposal.json","../src/testing/fixtures/agent-profile-improvement-state.json","../src/testing/index.ts"],"sourcesContent":["","","","import {\n type AgentImprovementProposal,\n type AgentProfile,\n type AgentProfileImprovementMeasuredComparison,\n SANDBOX_SIZE_PRESET_NAMES,\n type SandboxSizePreset,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { applyExactAgentProfileDiff, parseExactAgentProfile } from '../candidate-execution/profile'\nimport { verifyAgentImprovementProposal } from '../intelligence/improvement-cycle'\nimport canonicalAgentImprovementProposalFixture from './fixtures/agent-improvement-proposal.json'\nimport canonicalAgentProfileImprovementProposalFixture from './fixtures/agent-profile-improvement-proposal.json'\nimport canonicalAgentProfileImprovementStateFixture from './fixtures/agent-profile-improvement-state.json'\n\nexport {\n type DriverAgentOptions,\n driverAgent,\n} from '../runtime/supervise/coordination-driver'\nexport {\n type RunGraphTestOptions,\n runGraphWithTestBrain,\n} from '../runtime/supervise/graph'\nexport {\n type SuperviseTestOptions,\n superviseWithTestBrain,\n} from '../runtime/supervise/supervise'\nexport {\n type SupervisorAgentTestDeps,\n supervisorAgentWithTestBrain,\n} from '../runtime/supervise/supervisor-agent'\nexport type { ToolLoopCallContext, ToolLoopChat } from '../runtime/tool-loop'\n\nconst serializedAgentImprovementProposalFixture = JSON.stringify(\n canonicalAgentImprovementProposalFixture,\n)\nconst serializedAgentProfileImprovementProposalFixture = JSON.stringify(\n canonicalAgentProfileImprovementProposalFixture,\n)\nconst serializedAgentProfileImprovementStateFixture = JSON.stringify(\n canonicalAgentProfileImprovementStateFixture,\n)\n\n/** A proposal produced by Runtime's opaque profile-improvement path. */\nexport type AgentProfileImprovementProposalFixture = Omit<\n AgentImprovementProposal,\n 'evaluation'\n> & {\n evaluation: AgentProfileImprovementMeasuredComparison\n}\n\n/** Complete private state for exercising profile activation and restore in consumer tests. */\nexport interface AgentProfileImprovementFixture {\n proposal: AgentProfileImprovementProposalFixture\n baselineProfile: AgentProfile\n candidateProfile: AgentProfile\n recommendedSize: SandboxSizePreset\n}\n\n/** Load an isolated, production-validated Runtime proposal for consumer tests. */\nexport function loadAgentImprovementProposalFixture(): AgentImprovementProposal {\n return verifyAgentImprovementProposal(JSON.parse(serializedAgentImprovementProposalFixture))\n}\n\n/** Load an isolated profile proposal and its private activation state for consumer tests. */\nexport function loadAgentProfileImprovementFixture(): AgentProfileImprovementFixture {\n const proposal = loadAgentProfileImprovementProposal()\n const state = parseAgentProfileImprovementState(\n JSON.parse(serializedAgentProfileImprovementStateFixture),\n )\n const experiment = proposal.evaluation.experiment\n const baselineStateDigest = profileStateDigest(state.baselineProfile, state.recommendedSize)\n const candidateStateDigest = profileStateDigest(state.candidateProfile, state.recommendedSize)\n if (\n baselineStateDigest !== experiment.baseline.stateDigest ||\n candidateStateDigest !== experiment.candidate.stateDigest\n ) {\n throw new Error('profile improvement fixture state does not match its proposal')\n }\n const appliedCandidate = experiment.change.reduce(\n (profile, change, index) =>\n applyExactAgentProfileDiff(profile, change, `profile improvement fixture change ${index}`),\n state.baselineProfile,\n )\n if (\n canonicalCandidateDigest(appliedCandidate) !== canonicalCandidateDigest(state.candidateProfile)\n ) {\n throw new Error('profile improvement fixture candidate does not match its proposal changes')\n }\n return immutableCandidateValue({ proposal, ...state })\n}\n\nfunction loadAgentProfileImprovementProposal(): AgentProfileImprovementProposalFixture {\n const proposal = verifyAgentImprovementProposal(\n JSON.parse(serializedAgentProfileImprovementProposalFixture),\n )\n if (proposal.evaluation.kind !== 'agent-profile-improvement-measured-comparison') {\n throw new Error('profile improvement fixture contains a sealed candidate comparison')\n }\n return { ...proposal, evaluation: proposal.evaluation }\n}\n\nfunction parseAgentProfileImprovementState(\n input: unknown,\n): Omit<AgentProfileImprovementFixture, 'proposal'> {\n if (typeof input !== 'object' || input === null || Array.isArray(input)) {\n throw new Error('profile improvement fixture state must be an object')\n }\n const record = input as Record<string, unknown>\n const fields = Object.keys(record).sort()\n const expectedFields = ['baselineProfile', 'candidateProfile', 'recommendedSize']\n if (\n fields.length !== expectedFields.length ||\n fields.some((field, i) => field !== expectedFields[i])\n ) {\n throw new Error('profile improvement fixture state contains unsupported fields')\n }\n const recommendedSize = SANDBOX_SIZE_PRESET_NAMES.find((size) => size === record.recommendedSize)\n if (!recommendedSize) {\n throw new Error('profile improvement fixture has an invalid recommended size')\n }\n return {\n baselineProfile: parseExactAgentProfile(\n record.baselineProfile,\n 'profile improvement fixture baseline',\n ),\n candidateProfile: parseExactAgentProfile(\n record.candidateProfile,\n 'profile improvement fixture candidate',\n ),\n recommendedSize,\n }\n}\n\nfunction profileStateDigest(\n profile: AgentProfile,\n recommendedSize: SandboxS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,2EAA2E;CAE7F,OAAO,wBAAwB;EAAE;EAAU,GAAG;CAAM,CAAC;AACvD;AAEA,SAAS,sCAA8E;CACrF,MAAM,WAAW,+BACf,KAAK,MAAM,gDAAgD,CAC7D;CACA,IAAI,SAAS,WAAW,SAAS,iDAC/B,MAAM,IAAI,MAAM,oEAAoE;CAEtF,OAAO;EAAE,GAAG;EAAU,YAAY,SAAS;CAAW;AACxD;AAEA,SAAS,kCACP,OACkD;CAClD,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,qDAAqD;CAEvE,MAAM,SAAS;CACf,MAAM,SAAS,OAAO,KAAK,MAAM,CAAC,CAAC,KAAK;CACxC,MAAM,iBAAiB;EAAC;EAAmB;EAAoB;CAAiB;CAChF,IACE,OAAO,WAAW,eAAe,UACjC,OAAO,MAAM,OAAO,MAAM,UAAU,eAAe,EAAE,GAErD,MAAM,IAAI,MAAM,+DAA+D;CAEjF,MAAM,kBAAkB,0BAA0B,MAAM,SAAS,SAAS,OAAO,eAAe;CAChG,IAAI,CAAC,iBACH,MAAM,IAAI,MAAM,6DAA6D;CAE/E,OAAO;EACL,iBAAiB,uBACf,OAAO,iBACP,sCACF;EACA,kBAAkB,uBAChB,OAAO,kBACP,uCACF;EACA;CACF;AACF;AAEA,SAAS,mBACP,SACA,iBAC6C;CAC7C,OAAOA,2BAAyB;EAAE,YAAY;EAAS;CAAgB,CAAC;AAC1E"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { J as AgentTaskStatus, U as AgentRuntimeEvent, it as RuntimeStreamEvent, v as LoopTokenUsage, y as LoopTraceEmitter } from "./types-
|
|
1
|
+
import { J as AgentTaskStatus, U as AgentRuntimeEvent, it as RuntimeStreamEvent, v as LoopTokenUsage, y as LoopTraceEmitter } from "./types-DzZCZcwI.js";
|
|
2
2
|
import { l as RuntimeHooks } from "./runtime-hooks-sbRpjStq.js";
|
|
3
3
|
import { ControlEvalResult, DefaultVerdict, KnowledgeReadinessReport, KnowledgeRequirement, ToolSpan } from "@tangle-network/agent-eval";
|
|
4
4
|
import { AgentProfile as AgentProfile$1, Sha256Digest } from "@tangle-network/agent-interface";
|
|
@@ -896,17 +896,31 @@ type UsageEvent = {
|
|
|
896
896
|
output: number;
|
|
897
897
|
/** Newly processed prompt tokens. Present only with a complete cache split. */
|
|
898
898
|
freshInput?: number;
|
|
899
|
-
/** Prompt tokens
|
|
899
|
+
/** Prompt tokens the provider reported reading from cache. */
|
|
900
900
|
cacheRead?: number;
|
|
901
|
-
/** Prompt tokens
|
|
901
|
+
/** Prompt tokens the provider reported writing to cache. */
|
|
902
902
|
cacheWrite?: number;
|
|
903
|
-
/**
|
|
903
|
+
/**
|
|
904
|
+
* False when this observation cannot classify all positive prompt tokens — including a
|
|
905
|
+
* provider that reports a read with no write counter. The measured counters are still
|
|
906
|
+
* carried; the marker says the remaining prompt tokens are unclassified, so a charge over
|
|
907
|
+
* them is an upper bound. A counter the provider did not report is absent, never zero.
|
|
908
|
+
*/
|
|
904
909
|
cacheBreakdownKnown?: false;
|
|
905
910
|
} | {
|
|
906
911
|
kind: 'cost';
|
|
907
912
|
/** Known dollar subtotal. When false, `usd` must not be treated as total cost. */
|
|
908
913
|
usdKnown?: false;
|
|
909
914
|
usd: number;
|
|
915
|
+
/**
|
|
916
|
+
* The part of `usd` this runtime priced from a model catalog because no provider receipt
|
|
917
|
+
* covered the work. Requires `usdKnown: false` — a catalog price approximates what a
|
|
918
|
+
* provider would bill and never measures what it did.
|
|
919
|
+
*
|
|
920
|
+
* Absence means this runtime priced nothing here, NOT that `usd` is a receipt. `usdKnown`
|
|
921
|
+
* is what says whether a dollar figure is measured.
|
|
922
|
+
*/
|
|
923
|
+
usdEstimated?: number;
|
|
910
924
|
} | {
|
|
911
925
|
kind: 'iteration';
|
|
912
926
|
};
|
|
@@ -1113,6 +1127,11 @@ interface Spend {
|
|
|
1113
1127
|
* when enforcing a dollar-denominated comparison or limit. */
|
|
1114
1128
|
usdKnown?: boolean;
|
|
1115
1129
|
usd: number;
|
|
1130
|
+
/** The part of `usd` priced from a model catalog because no provider receipt covered the work.
|
|
1131
|
+
* `usd - usdEstimated` is what a provider is known to have billed. Present only with
|
|
1132
|
+
* `usdKnown: false`; absence means nothing here was catalog-priced, not that `usd` is
|
|
1133
|
+
* measured. */
|
|
1134
|
+
usdEstimated?: number;
|
|
1116
1135
|
ms: number;
|
|
1117
1136
|
}
|
|
1118
1137
|
/** OTP child-spec restart class. */
|
|
@@ -1560,6 +1579,8 @@ type SpawnEvent = {
|
|
|
1560
1579
|
kind: 'metered';
|
|
1561
1580
|
id: NodeId;
|
|
1562
1581
|
spend: Spend;
|
|
1582
|
+
/** Runtime bookkeeping only; this record carries no provider inference attempt. */
|
|
1583
|
+
accountingOnly?: true;
|
|
1563
1584
|
/** Runtime-owned provider attempt evidence for this driver's own inference turn. */
|
|
1564
1585
|
providerModel?: ProviderModelExecutionEvidence;
|
|
1565
1586
|
seq: number;
|
|
@@ -1905,4 +1926,4 @@ interface WidenGate<Out> {
|
|
|
1905
1926
|
}
|
|
1906
1927
|
//#endregion
|
|
1907
1928
|
export { WaitOpts as $, WaitSpec as $t, ResumedWork as A, exportEvalRuns as At, SpawnOpts as B, RuntimeTelemetryOptions as Bt, NodeStatus as C, OtelSpan as Ct, Restart as D, buildRuntimeEventOtelSpans as Dt, ProviderModelExecutionEvidence as E, buildLoopSpanNodes as Et, Runtime as F, toOtelAttributes as Ft, SpendGap as G, sanitizeAgentRuntimeEvent as Gt, SpawnRejection as H, SanitizedKnowledgeRequirement as Ht, Scope as I, RuntimeEventCollector as It, Supervisor as J, PendingWait as Jt, SteerableRootHandle as K, sanitizeKnowledgeReadinessReport as Kt, Settled as L, RuntimeStreamEventCollector as Lt, RootMaterialization as M, loopEventToOtelSpan as Mt, RootProviderModelEvidence as N, padSpanId as Nt, ResultBlobStore as O, createOpenInferenceFileExporter as Ot, RootSignal as P, padTraceId as Pt, UsageEvent as Q, WaitRejection as Qt, SpawnEvent as R, RuntimeStreamEventSink as Rt, NodeSnapshot as S, OtelExporter as St, ProviderModelAttemptEvidence as T, buildLoopOtelSpans as Tt, Spend as U, createRuntimeEventCollector as Ut, SpawnPrior as V, SanitizedKnowledgeReadinessReport as Vt, SpendChannel as W, createRuntimeStreamEventCollector as Wt, TreeView as X, WaitProbe as Xt, SupervisorOpts as Y, WaitOutcome as Yt, UnknownMaterializationReason as Z, WaitProbeRegistry as Zt, MaterializedExecutionIdentity as _, ScopeProgressInput as _n, EvalRunsExportResult as _t, DefaultVerdict as a, waitUntil as an, readWorkerTraceContext as at, NodeExecutionIdentity as b, readWorkerProgress as bn, OtelAttribute as bt, ExecutorAccounting as c, ToolStepInput as cn, workerTraceSeamKey as ct, ExecutorFactory as d, decodeToolPart as dn, mergeTraceEnv as dt, createWaitProbes as en, WidenGate as et, ExecutorMaterialization as f, sandboxSessionTraceSource as fn, readTraceContextFromEnv as ft, Handle as g, ExecutorProgress as gn, EvalRunsExportConfig as gt, ExecutorResult as h, DEFAULT_STALL_AFTER_MS as hn, EvalRunGeneration as ht, Budget as i, validateWaitSpec as in, WorkerTraceSeamCarrier as it, RootHandle as j, generateSpanId as jt, ResumedKeyState as k, createOtelExporter as kt, ExecutorContext as l, TraceSource as ln, TraceContext as lt, ExecutorRegistry as m, ActivityNote as mn, EvalRunEvent as mt, AgentExecutionRef as n, pollFor as nn, WorkerTraceUnavailableReason as nt, ExecutionBindingReceipt as o, SessionMessageLike as on, workerTraceEnv as ot, ExecutorNodeContext as p, ActivityLog as pn, traceContextToEnv as pt, SupervisedResult as q, sanitizeRuntimeStreamEvent as qt, AgentSpec as r, timerAt as rn, WorkerTraceResolver as rt, Executor as s, SessionTraceBox as sn, workerTraceHeaders as st, Agent as t, isWaitOutcome as tn, WorkerTraceEvidence as tt, ExecutorExecutionBinding as u, createPushTraceSource as un, createPropagatingTraceEmitter as ut, MaterializedModelIdentity as v, WorkerProgress as vn, INTELLIGENCE_WIRE_VERSION as vt, ProfileMaterializationReceipt as w, RuntimeEventOtelOptions as wt, NodeId as x, OtelExportConfig as xt, NoWinnerError as y, createActivityLog as yn, LoopSpanNode as yt, SpawnJournal as z, RuntimeStreamEventSummary as zt };
|
|
1908
|
-
//# sourceMappingURL=types-
|
|
1929
|
+
//# sourceMappingURL=types-CfQbuWgo.d.ts.map
|
|
@@ -714,9 +714,9 @@ interface LoopTokenUsage {
|
|
|
714
714
|
tokensKnown?: false;
|
|
715
715
|
/** Prompt tokens newly processed by the provider, when every prompt class is known. */
|
|
716
716
|
freshInput?: number;
|
|
717
|
-
/** Prompt tokens
|
|
717
|
+
/** Prompt tokens the provider reported serving from its cache. */
|
|
718
718
|
cacheRead?: number;
|
|
719
|
-
/** Prompt tokens
|
|
719
|
+
/** Prompt tokens the provider reported writing to its cache. */
|
|
720
720
|
cacheWrite?: number;
|
|
721
721
|
/**
|
|
722
722
|
* False when any positive-input observation omitted or contradicted the prompt-cache split.
|
|
@@ -917,11 +917,11 @@ interface SandboxClient {
|
|
|
917
917
|
create(options?: CreateSandboxOptions): Promise<SandboxInstance>;
|
|
918
918
|
describePlacement?(box: SandboxInstance): LoopSandboxPlacement;
|
|
919
919
|
/**
|
|
920
|
-
* Optional CRIU capability probe. When present and it resolves
|
|
921
|
-
* `{ available: true }`, the loop's `lineage.fork` seam may checkpoint
|
|
922
|
-
* parent box
|
|
923
|
-
*
|
|
924
|
-
*
|
|
920
|
+
* Optional legacy CRIU capability probe. When present and it resolves
|
|
921
|
+
* `{ available: true }`, the loop's `lineage.fork` seam may checkpoint and fork
|
|
922
|
+
* a parent box when live `branch(count)` is unavailable. Current Sandbox boxes
|
|
923
|
+
* expose live branching directly. The kernel reads this ONLY through the
|
|
924
|
+
* capability probe — it never branches on backend kind.
|
|
925
925
|
* The raw `Sandbox` SDK class satisfies it; the loop's test fakes omit it
|
|
926
926
|
* (⇒ `canFork = false`).
|
|
927
927
|
* @experimental
|
|
@@ -948,8 +948,8 @@ interface SandboxClient {
|
|
|
948
948
|
* When the driver authors its own branch point (`describePlan().parentIndex`),
|
|
949
949
|
* it may descend from any prior
|
|
950
950
|
* iteration, so no box is pruned and the live-box count rises to the total
|
|
951
|
-
* iterations across all rounds. Size `forkFanout` runs accordingly
|
|
952
|
-
*
|
|
951
|
+
* iterations across all rounds. Size `forkFanout` runs accordingly. Live branch
|
|
952
|
+
* children use copy-on-write, but each is still a live box until loop end.
|
|
953
953
|
*
|
|
954
954
|
* @experimental
|
|
955
955
|
*/
|
|
@@ -970,10 +970,10 @@ interface LoopLineageOptions {
|
|
|
970
970
|
*/
|
|
971
971
|
sessionContinuity?: boolean;
|
|
972
972
|
/**
|
|
973
|
-
* When true
|
|
974
|
-
*
|
|
975
|
-
*
|
|
976
|
-
*
|
|
973
|
+
* When true, a fanout round (N planned tasks) descending from a prior round
|
|
974
|
+
* branches the parent's live box so all N branches inherit its context prefix.
|
|
975
|
+
* If live branching is unavailable, the lineage uses legacy CRIU when its
|
|
976
|
+
* probe is positive. Otherwise it degrades to N fresh boxes with no prefix.
|
|
977
977
|
* Round 0 always starts fresh. NEVER set this for a `random@k` control arm —
|
|
978
978
|
* forking would couple the independent samples.
|
|
979
979
|
*
|
|
@@ -1215,4 +1215,4 @@ interface ExecCtx {
|
|
|
1215
1215
|
}
|
|
1216
1216
|
//#endregion
|
|
1217
1217
|
export { OpenAIChatToolChoice as $, RuntimeRunCompleteInput as A, AgentBackendInput as B, MountRecorder as C, SelectionReceipt as D, SandboxClient as E, RuntimeRunRow as F, AgentTaskContext as G, AgentKnowledgeProvider as H, RuntimeRunStatus as I, AgentTaskStatus as J, AgentTaskRunResult as K, startRuntimeRun as L, RuntimeRunHandle as M, RuntimeRunOptions as N, ValidationCtx as O, RuntimeRunPersistenceAdapter as P, OpenAIChatTool as Q, AgentAdapter as R, MountManifestEntry as S, RunProvenance as T, AgentRuntimeEvent as U, AgentExecutionBackend as V, AgentRuntimeEventSink as W, KnowledgeReadinessDecision as X, BackendErrorDetail as Y, OpenAIChatResponseFormat as Z, LoopTeardownFailedPayload as _, Iteration as a, LoopTraceEvent as b, LoopIterationDispatchPayload as c, LoopLineageOptions as d, RunAgentTaskOptions as et, LoopPlanDescription as f, LoopStartedPayload as g, LoopSandboxPlacement as h, ExecCtx as i, RuntimeStreamEvent as it, RuntimeRunCost as j, Validator as k, LoopIterationEndedPayload as l, LoopResult as m, DefaultVerdict as n, RuntimeSession as nt, LoopDecisionPayload as o, LoopPlanPayload as p, AgentTaskSpec as q, Driver as r, RuntimeSessionStore as rt, LoopEndedPayload as s, AgentRunSpec as t, RunAgentTaskStreamOptions as tt, LoopIterationStartedPayload as u, LoopTokenUsage as v, OutputAdapter as w, LoopWinner as x, LoopTraceEmitter as y, AgentBackendContext as z };
|
|
1218
|
-
//# sourceMappingURL=types-
|
|
1218
|
+
//# sourceMappingURL=types-DzZCZcwI.d.ts.map
|
|
@@ -103,6 +103,23 @@ function zeroTokenUsage() {
|
|
|
103
103
|
output: 0
|
|
104
104
|
};
|
|
105
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Sum the catalog-priced part of a dollar total across spends, as a field to spread.
|
|
108
|
+
*
|
|
109
|
+
* Returns nothing when no input carried one. A fold of pure provider receipts must not gain a
|
|
110
|
+
* `usdEstimated: 0`, which would read as "this runtime checked and priced none" on a path that
|
|
111
|
+
* never prices at all.
|
|
112
|
+
*/
|
|
113
|
+
function usdEstimatedOf(...spends) {
|
|
114
|
+
let total = 0;
|
|
115
|
+
let priced = false;
|
|
116
|
+
for (const spend of spends) {
|
|
117
|
+
if (spend.usdEstimated === void 0) continue;
|
|
118
|
+
priced = true;
|
|
119
|
+
total += spend.usdEstimated;
|
|
120
|
+
}
|
|
121
|
+
return priced ? { usdEstimated: total } : {};
|
|
122
|
+
}
|
|
106
123
|
/** Copy a token subtotal without dropping optional provider cache telemetry. */
|
|
107
124
|
function cloneTokenUsage(usage) {
|
|
108
125
|
const cacheBreakdownUnknown = usage.cacheBreakdownKnown === false || usage.input > 0 && !hasClassifiedCacheBreakdown(usage);
|
|
@@ -165,6 +182,47 @@ function classifiedTotal(usage, cacheRead) {
|
|
|
165
182
|
return (usage.freshInput ?? 0) + cacheRead + (usage.cacheWrite ?? 0);
|
|
166
183
|
}
|
|
167
184
|
/**
|
|
185
|
+
* Translate one provider prompt-cache report into the prompt token classes `addTokenUsage` folds
|
|
186
|
+
* and `chargedTokens` credits.
|
|
187
|
+
*
|
|
188
|
+
* The input is the open `promptCache` record an `llm_call` carries, keyed by the `PromptCacheUsage`
|
|
189
|
+
* vocabulary (`readTokens`, `writeTokens`). Providers report that vocabulary unevenly, and the
|
|
190
|
+
* three outcomes are different facts that must not collapse into one another:
|
|
191
|
+
*
|
|
192
|
+
* - **Nothing reported** — no classes and no marker. The caller's own unknown handling decides,
|
|
193
|
+
* because a provider that says nothing about caching has not said the split is unknowable.
|
|
194
|
+
* - **Read and write both reported, and fitting inside `input`** — a complete partition, so
|
|
195
|
+
* `freshInput` is the remainder and the split is known.
|
|
196
|
+
* - **One counter reported, or classes that overflow `input`** — the counters that ARE measured
|
|
197
|
+
* pass through and `cacheBreakdownKnown` is false. A read with no write counter (OpenAI reports
|
|
198
|
+
* no write) still credits the read it measured, while declaring the rest unclassified so the
|
|
199
|
+
* charge stays a declared upper bound. An overflowing claim buys nothing: it cannot be a
|
|
200
|
+
* partition of a total it exceeds.
|
|
201
|
+
*
|
|
202
|
+
* A counter the provider did not report stays absent. A zero would claim the provider measured no
|
|
203
|
+
* cache, which is a different fact from a provider that did not report.
|
|
204
|
+
*/
|
|
205
|
+
function promptCacheTokenClasses(input, promptCache) {
|
|
206
|
+
if (promptCache === void 0) return {};
|
|
207
|
+
const read = tokenCount(promptCache.readTokens);
|
|
208
|
+
const write = tokenCount(promptCache.writeTokens);
|
|
209
|
+
if (read === void 0 && write === void 0) return {};
|
|
210
|
+
if (input === void 0 || (read ?? 0) + (write ?? 0) > input) return { cacheBreakdownKnown: false };
|
|
211
|
+
if (read !== void 0 && write !== void 0) return {
|
|
212
|
+
freshInput: input - read - write,
|
|
213
|
+
cacheRead: read,
|
|
214
|
+
cacheWrite: write
|
|
215
|
+
};
|
|
216
|
+
return {
|
|
217
|
+
...read !== void 0 ? { cacheRead: read } : {},
|
|
218
|
+
...write !== void 0 ? { cacheWrite: write } : {},
|
|
219
|
+
cacheBreakdownKnown: false
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
function tokenCount(value) {
|
|
223
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
168
226
|
* Add the observed subtotal into `acc`; token and cache incompleteness are sticky.
|
|
169
227
|
*
|
|
170
228
|
* A delta whose classes do not FIT inside its own `input` contributes its prompt total and NO
|
|
@@ -219,6 +277,6 @@ async function mapWithConcurrency(items, limit, fn) {
|
|
|
219
277
|
return results;
|
|
220
278
|
}
|
|
221
279
|
//#endregion
|
|
222
|
-
export { hasCompleteCacheBreakdown as a,
|
|
280
|
+
export { zeroTokenUsage as _, hasCompleteCacheBreakdown as a, promptCacheTokenClasses as c, sleep as d, stringifySafe as f, withTimeout as g, usdEstimatedOf as h, deleteBoxSafe as i, randomSuffix as l, throwIfAborted as m, chargedTokens as n, isAbortError as o, throwAbort as p, cloneTokenUsage as r, mapWithConcurrency as s, addTokenUsage as t, randomUuid as u };
|
|
223
281
|
|
|
224
|
-
//# sourceMappingURL=util-
|
|
282
|
+
//# sourceMappingURL=util-C1bv6yog.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util-C1bv6yog.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 { 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/** 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":";;;;;;AAgBA,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,SAAgB,aAAqB;CACnC,OAAO,OAAO,WAAW;AAC3B;;AAGA,SAAgB,aAAoB;CAClC,MAAM,sBAAM,IAAI,MAAM,SAAS;CAC/B,IAAI,OAAO;CACX,OAAO;AACT;;AAGA,SAAgB,aAAoB;CAClC,MAAM,WAAW;AACnB;;AAGA,SAAgB,eAAe,QAAuC;CACpE,IAAI,QAAQ,SAAS,MAAM,WAAW;AACxC;;AAGA,SAAgB,aAAa,KAAuB;CAClD,OAAO,eAAe,SAAS,IAAI,SAAS;AAC9C;;;;;;AAOA,SAAgB,MAAM,IAAY,QAAqC;CACrE,OAAO,IAAI,SAAS,YAAY;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A,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-Czki1LBy.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-B_JDld25.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-archive-BwJQSvGi.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 = requireTypedArrayGet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;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-B_JDld25.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,MAAM,wBAAwB;AAC9B,MAAM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