@tangle-network/agent-runtime 0.349.0 → 0.350.2
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-tNGW73Y9.js → activation-CfJMyzEs.js} +12 -14
- package/dist/{activation-tNGW73Y9.js.map → activation-CfJMyzEs.js.map} +1 -1
- package/dist/{activation-wBipBkCf.d.ts → activation-DyiHrTlS.d.ts} +2 -24
- package/dist/agent.d.ts +8 -12
- package/dist/agent.js +9 -12
- package/dist/agent.js.map +1 -1
- package/dist/{analyst-loop-DZw5QWT9.js → analyst-loop-BZvXCDKy.js} +2 -3
- package/dist/{analyst-loop-DZw5QWT9.js.map → analyst-loop-BZvXCDKy.js.map} +1 -1
- package/dist/analyst-loop.d.ts +3 -5
- package/dist/analyst-loop.js +1 -2
- package/dist/{bundle-1xaJEgjq.js → bundle-Ze8pd07a.js} +3 -4
- package/dist/{bundle-1xaJEgjq.js.map → bundle-Ze8pd07a.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +13 -33
- package/dist/candidate-execution/index.js +16 -18
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/{coordination-manager-B2Z_MmL9.js → coordination-manager-BkVfWlMz.js} +101 -132
- package/dist/{coordination-manager-B2Z_MmL9.js.map → coordination-manager-BkVfWlMz.js.map} +1 -1
- package/dist/{delegate-Dr-63jFl.js → delegate-DgEie4ad.js} +19 -21
- package/dist/delegate-DgEie4ad.js.map +1 -0
- package/dist/durable.d.ts +13 -23
- package/dist/durable.js +48 -43
- package/dist/durable.js.map +1 -1
- package/dist/{errors-DodWX-cb.js → errors-wuhGvpE3.js} +2 -3
- package/dist/{errors-DodWX-cb.js.map → errors-wuhGvpE3.js.map} +1 -1
- package/dist/{graph-DPejYB3C.js → graph-Cx0FhKSE.js} +191 -14
- package/dist/graph-Cx0FhKSE.js.map +1 -0
- package/dist/{improve-DwSahPi1.js → improve-i0HU1-aa.js} +35 -53
- package/dist/{improve-DwSahPi1.js.map → improve-i0HU1-aa.js.map} +1 -1
- package/dist/{improvement-adapter-sIthWkcN.d.ts → improvement-adapter-D5GRU1eY.d.ts} +2 -6
- package/dist/index.d.ts +41 -89
- package/dist/index.js +43 -61
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +39 -59
- package/dist/intelligence.js +23 -33
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +5 -5
- package/dist/kernel.js +11 -11
- package/dist/{loop-runner-CP6MfO1b.js → loop-runner-BwN9MhdP.js} +5 -6
- package/dist/{loop-runner-CP6MfO1b.js.map → loop-runner-BwN9MhdP.js.map} +1 -1
- package/dist/{loop-runner-C6pGq-2l.d.ts → loop-runner-DvfOXVx9.d.ts} +3 -5
- package/dist/loop-runner-bin.d.ts +5 -8
- package/dist/loop-runner-bin.js +2 -3
- package/dist/mcp/bin.js +6 -8
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +8 -18
- package/dist/mcp/index.js +17 -25
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp/memory-bin.js +4 -6
- package/dist/mcp/memory-bin.js.map +1 -1
- package/dist/{model-policy-CyCUwHed.js → model-policy-GSxWwP-b.js} +11 -13
- package/dist/{model-policy-CyCUwHed.js.map → model-policy-GSxWwP-b.js.map} +1 -1
- package/dist/placement.d.ts +12 -14
- package/dist/placement.js +1 -2
- package/dist/platform.d.ts +7 -13
- package/dist/platform.js +3 -6
- package/dist/platform.js.map +1 -1
- package/dist/{prepare-B9wWffjO.js → prepare-DE8TQnLu.js} +49 -69
- package/dist/{prepare-B9wWffjO.js.map → prepare-DE8TQnLu.js.map} +1 -1
- package/dist/{profile-JLJd2wFG.js → profile-CAhZDW2T.js} +58 -92
- package/dist/profile-CAhZDW2T.js.map +1 -0
- package/dist/{profile-materialization-bPm0gGLO.d.ts → profile-materialization-BRY22Oh8.d.ts} +1 -3
- package/dist/profiles.d.ts +25 -12
- package/dist/profiles.js +52 -11
- package/dist/profiles.js.map +1 -1
- package/dist/{protected-model-port-DVVh-hEk.d.ts → protected-model-port-IKqhTypD.d.ts} +2 -14
- package/dist/{protected-redaction-DFCeo4vg.js → protected-redaction-DilFZch5.js} +2 -3
- package/dist/{protected-redaction-DFCeo4vg.js.map → protected-redaction-DilFZch5.js.map} +1 -1
- package/dist/{provision-supervisor-C4v2vqDo.js → provision-supervisor-Bde_FF0R.js} +11 -15
- package/dist/{provision-supervisor-C4v2vqDo.js.map → provision-supervisor-Bde_FF0R.js.map} +1 -1
- package/dist/{record-events-D93DkpAx.js → record-events-B2GUgYdz.js} +12 -14
- package/dist/{record-events-D93DkpAx.js.map → record-events-B2GUgYdz.js.map} +1 -1
- package/dist/{run-cancellation-CzFhQGMa.js → run-cancellation-BLy_Zz-w.js} +6 -7
- package/dist/{run-cancellation-CzFhQGMa.js.map → run-cancellation-BLy_Zz-w.js.map} +1 -1
- package/dist/{runtime-CsvGCQpl.js → runtime-6Ec9sHRe.js} +648 -215
- package/dist/runtime-6Ec9sHRe.js.map +1 -0
- package/dist/{runtime-hooks-tXpAarhW.js → runtime-hooks-CsW2pfFk.js} +2 -3
- package/dist/{runtime-hooks-tXpAarhW.js.map → runtime-hooks-CsW2pfFk.js.map} +1 -1
- package/dist/{runtime-hooks-nsqxSUFL.d.ts → runtime-hooks-ZQqPw-0g.d.ts} +1 -3
- package/dist/{sandbox-profile-compat-DtuJWFrM.js → sandbox-profile-compat-BxMQ1VXv.js} +61 -43
- package/dist/sandbox-profile-compat-BxMQ1VXv.js.map +1 -0
- package/dist/{search-executor-CCb82Umc.js → search-executor-B7g_5Wjl.js} +10 -15
- package/dist/{search-executor-CCb82Umc.js.map → search-executor-B7g_5Wjl.js.map} +1 -1
- package/dist/{server-CKPwZU-I.js → server-fvEMwGMQ.js} +19 -30
- package/dist/{server-CKPwZU-I.js.map → server-fvEMwGMQ.js.map} +1 -1
- package/dist/{structural-rollout-DylC_fwU.js → structural-rollout-B86bSixU.js} +69 -70
- package/dist/structural-rollout-B86bSixU.js.map +1 -0
- package/dist/{substrate-CGDFTSRh.js → substrate-Db2pp6y3.js} +2 -3
- package/dist/{substrate-CGDFTSRh.js.map → substrate-Db2pp6y3.js.map} +1 -1
- package/dist/{supervise-BGfm2GlY.js → supervise-CaeZcgAW.js} +460 -195
- package/dist/supervise-CaeZcgAW.js.map +1 -0
- package/dist/{supervisor-wS9Ehz_x.js → supervisor-C1OePYE-.js} +511 -626
- package/dist/supervisor-C1OePYE-.js.map +1 -0
- package/dist/{task-queue-0fKkoweu.d.ts → task-queue-kefGy79U.d.ts} +1 -3
- package/dist/task-queue.d.ts +1 -1
- package/dist/task-queue.js +1 -2
- package/dist/testing.d.ts +7 -15
- package/dist/testing.js +241 -244
- package/dist/testing.js.map +1 -1
- package/dist/tool-loop.d.ts +16 -19
- package/dist/tool-loop.js +2 -3
- package/dist/{tool-server-XV4aJwoQ.js → tool-server-CwuYeW_Z.js} +3 -4
- package/dist/{tool-server-XV4aJwoQ.js.map → tool-server-CwuYeW_Z.js.map} +1 -1
- package/dist/{top-snapshot-CflmaDgk.js → top-snapshot-ChwpTr7A.js} +4 -5
- package/dist/{top-snapshot-CflmaDgk.js.map → top-snapshot-ChwpTr7A.js.map} +1 -1
- package/dist/tui/bin.js +7 -9
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +3 -5
- package/dist/tui/index.js +2 -2
- package/dist/{types-C8BGOCBn.d.ts → types-Fowuwdz2.d.ts} +364 -483
- package/dist/{types-Cwrea-bU.d.ts → types-qsqfyQoY.d.ts} +1 -3
- package/dist/workspace-store/index.d.ts +12 -22
- package/dist/workspace-store/index.js +4 -7
- package/dist/workspace-store/index.js.map +1 -1
- package/dist/{workspace-streams-BiS4ABah.d.ts → workspace-streams-Dq2Fzk3c.d.ts} +1 -11
- package/package.json +25 -25
- package/skills/agent-graphs/SKILL.md +17 -4
- package/skills/be-ambitious/SKILL.md +46 -0
- package/skills/graph-designer/SKILL.md +9 -2
- package/dist/delegate-Dr-63jFl.js.map +0 -1
- package/dist/graph-DPejYB3C.js.map +0 -1
- package/dist/profile-JLJd2wFG.js.map +0 -1
- package/dist/runtime-CsvGCQpl.js.map +0 -1
- package/dist/sandbox-profile-compat-DtuJWFrM.js.map +0 -1
- package/dist/structural-rollout-DylC_fwU.js.map +0 -1
- package/dist/supervise-BGfm2GlY.js.map +0 -1
- package/dist/supervisor-wS9Ehz_x.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle-
|
|
1
|
+
{"version":3,"file":"bundle-Ze8pd07a.js","names":["canonicalCandidateDigest"],"sources":["../src/candidate-execution/bundle.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"],"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"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { $ as VerifiedAgentCandidate, A as AgentCandidateMemoryResetResult, B as AgentCandidateRepositoryPort, C as AgentCandidateExecutorProfileFile, D as AgentCandidateExecutorWorkspaceFile, E as AgentCandidateExecutorTaskOutcomeCapture, F as AgentCandidateProtectedModelActivation, G as CanonicalCandidateDocument, H as AgentCandidateTaskExecution, I as AgentCandidateProtectedModelReservation, J as PreparedAgentCandidateInstruction, K as PersistedTaskOutcomeEvidence, L as AgentCandidateProtectedModelSettlement, M as AgentCandidateModelPort, N as AgentCandidateOutputArtifactPort, O as AgentCandidateExecutorWorkspaceInput, P as AgentCandidateOutputPurpose, Q as ResolvedAgentCandidateContainer, R as AgentCandidateProtectedModelSettlementCall, S as AgentCandidateExecutorPort, T as AgentCandidateExecutorStopRequest, U as AgentCandidateVerificationPorts, V as AgentCandidateRunFinalization, W as AgentCandidateWorkspacePort, X as PreparedAgentCandidateLaunch, Y as PreparedAgentCandidateKnowledge, Z as PreparedAgentCandidateTrace, _ as AgentCandidateBenchmarkGraderPort, a as captureAgentCandidateWorkspaceTreeToArtifacts, b as AgentCandidateExecutorFinalCapture, c as verifyAgentCandidateWorkspaceTree, d as captureAgentCandidateWorkspaceFiles, et as VerifiedAgentCandidateTaskOutcome, f as CaptureAgentCandidateWorkspaceOptions, g as AgentCandidateArtifactPort, h as createAgentCandidateWorkspacePort, i as captureAgentCandidateWorkspaceToArtifacts, j as AgentCandidateModelLimits, k as AgentCandidateMemoryPort, l as AgentCandidateWorkspaceArchiveLimits, m as captureAgentCandidateWorkspace, n as AgentCandidateWorkspaceTree, o as materializeAgentCandidateWorkspaceFromArtifacts, p as CreateAgentCandidateWorkspacePortOptions, q as PreparedAgentCandidateExecution, r as CaptureAgentCandidateWorkspaceToArtifactsOptions, s as verifyAgentCandidateWorkspaceArtifacts, t as AgentCandidateWorkspaceArtifactsOptions, tt as AgentCandidateExecutionRoots, u as CapturedAgentCandidateWorkspace, v as AgentCandidateContainerPort, w as AgentCandidateExecutorRequest, x as AgentCandidateExecutorMemoryCapture, y as AgentCandidateExecutionPorts, z as AgentCandidateProtectedRunCapture } from "../workspace-streams-
|
|
2
|
-
import { A as AgentCandidateExecutionTerminalResult, C as AgentCandidateExecutionFinishResult, D as AgentCandidateExecutionRecoveryEvidence, E as AgentCandidateExecutionPhaseResult, M as AgentCandidatePreparationEvidence, O as AgentCandidateExecutionStageResult, S as AgentCandidateExecutionFailureClass, T as AgentCandidateExecutionPhase, _ as AgentCandidateExecutionAttemptRef, a as createProtectedAgentCandidateModelPort, b as AgentCandidateExecutionClaimStore, c as assertCandidateProfileBinding, d as parseExactAgentProfileDiff, g as AgentCandidateExecutionAttemptRecord, h as executePreparedAgentCandidate, i as CreateProtectedAgentCandidateModelPortOptions, j as AgentCandidateRetryRejection, k as AgentCandidateExecutionTerminalRecord, l as freezeGenericAgentCandidateProfile, m as ExecutePreparedAgentCandidateOptions, n as AgentCandidateModelGrantClient, o as agentCandidateProfileAsAgentProfile, p as prepareAgentCandidateExecution, r as AgentCandidateModelGrantReserveInput, s as applyExactAgentProfileDiff, t as AgentCandidateModelGrantActivateInput, v as AgentCandidateExecutionClaim, w as AgentCandidateExecutionLease, x as AgentCandidateExecutionCleanupHandles, y as AgentCandidateExecutionClaimResult } from "../protected-model-port-
|
|
1
|
+
import { $ as VerifiedAgentCandidate, A as AgentCandidateMemoryResetResult, B as AgentCandidateRepositoryPort, C as AgentCandidateExecutorProfileFile, D as AgentCandidateExecutorWorkspaceFile, E as AgentCandidateExecutorTaskOutcomeCapture, F as AgentCandidateProtectedModelActivation, G as CanonicalCandidateDocument, H as AgentCandidateTaskExecution, I as AgentCandidateProtectedModelReservation, J as PreparedAgentCandidateInstruction, K as PersistedTaskOutcomeEvidence, L as AgentCandidateProtectedModelSettlement, M as AgentCandidateModelPort, N as AgentCandidateOutputArtifactPort, O as AgentCandidateExecutorWorkspaceInput, P as AgentCandidateOutputPurpose, Q as ResolvedAgentCandidateContainer, R as AgentCandidateProtectedModelSettlementCall, S as AgentCandidateExecutorPort, T as AgentCandidateExecutorStopRequest, U as AgentCandidateVerificationPorts, V as AgentCandidateRunFinalization, W as AgentCandidateWorkspacePort, X as PreparedAgentCandidateLaunch, Y as PreparedAgentCandidateKnowledge, Z as PreparedAgentCandidateTrace, _ as AgentCandidateBenchmarkGraderPort, a as captureAgentCandidateWorkspaceTreeToArtifacts, b as AgentCandidateExecutorFinalCapture, c as verifyAgentCandidateWorkspaceTree, d as captureAgentCandidateWorkspaceFiles, et as VerifiedAgentCandidateTaskOutcome, f as CaptureAgentCandidateWorkspaceOptions, g as AgentCandidateArtifactPort, h as createAgentCandidateWorkspacePort, i as captureAgentCandidateWorkspaceToArtifacts, j as AgentCandidateModelLimits, k as AgentCandidateMemoryPort, l as AgentCandidateWorkspaceArchiveLimits, m as captureAgentCandidateWorkspace, n as AgentCandidateWorkspaceTree, o as materializeAgentCandidateWorkspaceFromArtifacts, p as CreateAgentCandidateWorkspacePortOptions, q as PreparedAgentCandidateExecution, r as CaptureAgentCandidateWorkspaceToArtifactsOptions, s as verifyAgentCandidateWorkspaceArtifacts, t as AgentCandidateWorkspaceArtifactsOptions, tt as AgentCandidateExecutionRoots, u as CapturedAgentCandidateWorkspace, v as AgentCandidateContainerPort, w as AgentCandidateExecutorRequest, x as AgentCandidateExecutorMemoryCapture, y as AgentCandidateExecutionPorts, z as AgentCandidateProtectedRunCapture } from "../workspace-streams-Dq2Fzk3c.js";
|
|
2
|
+
import { A as AgentCandidateExecutionTerminalResult, C as AgentCandidateExecutionFinishResult, D as AgentCandidateExecutionRecoveryEvidence, E as AgentCandidateExecutionPhaseResult, M as AgentCandidatePreparationEvidence, O as AgentCandidateExecutionStageResult, S as AgentCandidateExecutionFailureClass, T as AgentCandidateExecutionPhase, _ as AgentCandidateExecutionAttemptRef, a as createProtectedAgentCandidateModelPort, b as AgentCandidateExecutionClaimStore, c as assertCandidateProfileBinding, d as parseExactAgentProfileDiff, g as AgentCandidateExecutionAttemptRecord, h as executePreparedAgentCandidate, i as CreateProtectedAgentCandidateModelPortOptions, j as AgentCandidateRetryRejection, k as AgentCandidateExecutionTerminalRecord, l as freezeGenericAgentCandidateProfile, m as ExecutePreparedAgentCandidateOptions, n as AgentCandidateModelGrantClient, o as agentCandidateProfileAsAgentProfile, p as prepareAgentCandidateExecution, r as AgentCandidateModelGrantReserveInput, s as applyExactAgentProfileDiff, t as AgentCandidateModelGrantActivateInput, v as AgentCandidateExecutionClaim, w as AgentCandidateExecutionLease, x as AgentCandidateExecutionCleanupHandles, y as AgentCandidateExecutionClaimResult } from "../protected-model-port-IKqhTypD.js";
|
|
3
3
|
import { AgentCandidateArtifactRef, AgentCandidateBundle, AgentCandidateCapturedArtifact, AgentCandidateCodeDisabled, AgentCandidateCodeNoOp, AgentCandidateExecution, AgentCandidateGitHubRepository, AgentCandidateKnowledge, AgentCandidateMemoryPolicy, AgentCandidateProfile, AgentCandidateResolvedModel, AgentCandidateWorkspaceManifestMaterial, AgentCandidateWorkspaceSnapshotEvidence, AgentProfile, AgentProfileDiff, Sha256Digest } from "@tangle-network/agent-interface";
|
|
4
4
|
import { CodeSurface } from "@tangle-network/agent-eval/campaign";
|
|
5
5
|
import { AgentEnvironmentProvider, AgentExactProcessResources } from "@tangle-network/agent-interface/environment-provider";
|
|
6
|
-
//#region src/candidate-execution/artifacts.d.ts
|
|
7
6
|
/** The per-scan caps a bounded capture applies. */
|
|
8
7
|
interface WorkspaceScanLimits {
|
|
9
8
|
readonly maxFiles: number;
|
|
@@ -39,21 +38,17 @@ interface WorkspaceScanOptions {
|
|
|
39
38
|
* returns. Pass `portableTree` to record Git's two file modes instead of exact permission bits, and
|
|
40
39
|
* pass the same flag to every verify that reads the result.
|
|
41
40
|
*/
|
|
42
|
-
declare function candidateWorkspaceManifest(files: ReadonlyArray<{
|
|
41
|
+
export declare function candidateWorkspaceManifest(files: ReadonlyArray<{
|
|
43
42
|
path: string;
|
|
44
43
|
mode: number;
|
|
45
44
|
bytes: Uint8Array;
|
|
46
45
|
}>, options?: {
|
|
47
46
|
portableTree?: boolean;
|
|
48
47
|
}): AgentCandidateWorkspaceManifestMaterial;
|
|
49
|
-
//#endregion
|
|
50
|
-
//#region src/candidate-execution/bundle.d.ts
|
|
51
48
|
/** Exact candidate wire shape before the runtime computes its canonical digest. */
|
|
52
49
|
type AgentCandidateBundleInput = Omit<AgentCandidateBundle, 'digest'>;
|
|
53
50
|
/** Validate and content-address a candidate bundle before it crosses an approval boundary. */
|
|
54
|
-
declare function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle;
|
|
55
|
-
//#endregion
|
|
56
|
-
//#region src/candidate-execution/builder.d.ts
|
|
51
|
+
export declare function sealAgentCandidateBundle(input: AgentCandidateBundleInput): AgentCandidateBundle;
|
|
57
52
|
/** A complete profile that can be frozen without losing behavior. */
|
|
58
53
|
type AgentCandidateProfileSource = {
|
|
59
54
|
kind: 'profile';
|
|
@@ -93,9 +88,7 @@ interface BuildAgentCandidateBundleInput {
|
|
|
93
88
|
* deeply immutable; call `verifyAgentCandidateBundle` at the execution boundary
|
|
94
89
|
* to re-read external memory, repository, and workspace artifacts.
|
|
95
90
|
*/
|
|
96
|
-
declare function buildAgentCandidateBundle(input: BuildAgentCandidateBundleInput): ReturnType<typeof sealAgentCandidateBundle>;
|
|
97
|
-
//#endregion
|
|
98
|
-
//#region src/candidate-execution/claim-file-store.d.ts
|
|
91
|
+
export declare function buildAgentCandidateBundle(input: BuildAgentCandidateBundleInput): ReturnType<typeof sealAgentCandidateBundle>;
|
|
99
92
|
interface FileAgentCandidateExecutionClaimStoreOptions {
|
|
100
93
|
/** Evaluator-owned directory shared by every process allowed to execute candidates. */
|
|
101
94
|
directory: string;
|
|
@@ -103,7 +96,7 @@ interface FileAgentCandidateExecutionClaimStoreOptions {
|
|
|
103
96
|
now?: () => number;
|
|
104
97
|
}
|
|
105
98
|
/** Cross-process lifecycle implemented as fsynced, create-if-absent records. */
|
|
106
|
-
declare class FileAgentCandidateExecutionClaimStore implements AgentCandidateExecutionClaimStore {
|
|
99
|
+
export declare class FileAgentCandidateExecutionClaimStore implements AgentCandidateExecutionClaimStore {
|
|
107
100
|
private readonly directory;
|
|
108
101
|
private readonly now;
|
|
109
102
|
constructor(options: FileAgentCandidateExecutionClaimStoreOptions);
|
|
@@ -121,17 +114,13 @@ declare class FileAgentCandidateExecutionClaimStore implements AgentCandidateExe
|
|
|
121
114
|
private terminalPath;
|
|
122
115
|
private transitionPath;
|
|
123
116
|
}
|
|
124
|
-
//#endregion
|
|
125
|
-
//#region src/candidate-execution/dispose.d.ts
|
|
126
117
|
interface DisposePreparedAgentCandidateOptions {
|
|
127
118
|
cleanupTimeoutMs?: number;
|
|
128
119
|
}
|
|
129
120
|
/** Revoke reservations held by a prepared candidate that will not be executed. */
|
|
130
|
-
declare function disposePreparedAgentCandidateExecution(prepared: PreparedAgentCandidateExecution, options?: DisposePreparedAgentCandidateOptions): Promise<{
|
|
121
|
+
export declare function disposePreparedAgentCandidateExecution(prepared: PreparedAgentCandidateExecution, options?: DisposePreparedAgentCandidateOptions): Promise<{
|
|
131
122
|
disposed: true;
|
|
132
123
|
}>;
|
|
133
|
-
//#endregion
|
|
134
|
-
//#region src/candidate-execution/exact-process-executor.d.ts
|
|
135
124
|
interface ExactProcessCandidateExecutorOptions {
|
|
136
125
|
provider: AgentEnvironmentProvider;
|
|
137
126
|
resources: AgentExactProcessResources;
|
|
@@ -140,9 +129,7 @@ interface ExactProcessCandidateExecutorOptions {
|
|
|
140
129
|
providerOptions?: Record<string, unknown>;
|
|
141
130
|
}
|
|
142
131
|
/** Adapt one neutral exact-process provider to Runtime's trusted candidate boundary. */
|
|
143
|
-
declare function exactProcessProviderAsCandidateExecutor(options: ExactProcessCandidateExecutorOptions): AgentCandidateExecutorPort;
|
|
144
|
-
//#endregion
|
|
145
|
-
//#region src/candidate-execution/protected-model-grant.d.ts
|
|
132
|
+
export declare function exactProcessProviderAsCandidateExecutor(options: ExactProcessCandidateExecutorOptions): AgentCandidateExecutorPort;
|
|
146
133
|
/** Reservation fields supplied by a caller before Runtime resolves the model. */
|
|
147
134
|
type AgentCandidateModelGrantRunReservationInput = Omit<AgentCandidateModelGrantReserveInput, 'resolved'>;
|
|
148
135
|
/** Values available only while one protected model grant is active. */
|
|
@@ -179,13 +166,9 @@ interface RunProtectedAgentCandidateModelGrantResult<TResult> {
|
|
|
179
166
|
* after activation failure or callback failure, and the callback error is
|
|
180
167
|
* preserved when settlement also fails.
|
|
181
168
|
*/
|
|
182
|
-
declare function runProtectedAgentCandidateModelGrant<TResult>(options: RunProtectedAgentCandidateModelGrantOptions<TResult>): Promise<RunProtectedAgentCandidateModelGrantResult<TResult>>;
|
|
183
|
-
//#endregion
|
|
184
|
-
//#region src/candidate-execution/verify.d.ts
|
|
169
|
+
export declare function runProtectedAgentCandidateModelGrant<TResult>(options: RunProtectedAgentCandidateModelGrantOptions<TResult>): Promise<RunProtectedAgentCandidateModelGrantResult<TResult>>;
|
|
185
170
|
/** Verifies every digest, resource, workspace, and Git object in a candidate bundle. */
|
|
186
|
-
declare function verifyAgentCandidateBundle(input: unknown, ports: AgentCandidateVerificationPorts): Promise<VerifiedAgentCandidate>;
|
|
187
|
-
//#endregion
|
|
188
|
-
//#region src/candidate-execution/workspace-transfer.d.ts
|
|
171
|
+
export declare function verifyAgentCandidateBundle(input: unknown, ports: AgentCandidateVerificationPorts): Promise<VerifiedAgentCandidate>;
|
|
189
172
|
/** The canonical workspace evidence without manifest material or embedded file bytes. */
|
|
190
173
|
type AgentCandidateWorkspaceSnapshotReferences = Pick<AgentCandidateWorkspaceSnapshotEvidence, 'kind' | 'digest'> & {
|
|
191
174
|
readonly manifest: AgentCandidateArtifactRef;
|
|
@@ -200,7 +183,7 @@ type CaptureAgentWorkspaceSnapshotOptions = Omit<CaptureAgentCandidateWorkspaceO
|
|
|
200
183
|
* its public source provenance at the SDK boundary. Choose includeRepository and working-tree
|
|
201
184
|
* explicitly when staged, dirty, deleted and unignored untracked Git files must travel.
|
|
202
185
|
*/
|
|
203
|
-
declare function captureAgentWorkspaceSnapshot(root: string, options: CaptureAgentWorkspaceSnapshotOptions): Promise<AgentCandidateWorkspaceSnapshotReferences>;
|
|
186
|
+
export declare function captureAgentWorkspaceSnapshot(root: string, options: CaptureAgentWorkspaceSnapshotOptions): Promise<AgentCandidateWorkspaceSnapshotReferences>;
|
|
204
187
|
interface MaterializeAgentWorkspaceSnapshotOptions {
|
|
205
188
|
snapshot: AgentCandidateWorkspaceSnapshotReferences;
|
|
206
189
|
/** Authorizes each immutable reference for the accepted transfer owner; must stream reads. */
|
|
@@ -218,9 +201,7 @@ interface MaterializeAgentWorkspaceSnapshotOptions {
|
|
|
218
201
|
* staging. Destinations present before or during artifact reads are refused. The caller owns
|
|
219
202
|
* the allocation scope against other writers; Node directory rename is not atomic no-replace.
|
|
220
203
|
*/
|
|
221
|
-
declare function materializeAgentWorkspaceSnapshot(input: MaterializeAgentWorkspaceSnapshotOptions): Promise<void>;
|
|
222
|
-
//#endregion
|
|
223
|
-
//#region src/candidate-execution/workspace-tree.d.ts
|
|
204
|
+
export declare function materializeAgentWorkspaceSnapshot(input: MaterializeAgentWorkspaceSnapshotOptions): Promise<void>;
|
|
224
205
|
/**
|
|
225
206
|
* `'tree-v1'` records a file's exact permission bits. `'portable-tree-v1'` records the two modes
|
|
226
207
|
* Git stores — `755` when any execute bit is set, `644` otherwise, and `755` for a directory — so a
|
|
@@ -277,6 +258,5 @@ interface SeedWorkspaceTreeInput {
|
|
|
277
258
|
/** Default `'tree-v1'`; decides only the digest this returns, never the bytes it writes. */
|
|
278
259
|
readonly algorithm?: WorkspaceTreeAlgorithm;
|
|
279
260
|
}
|
|
280
|
-
|
|
281
|
-
export { type AgentCandidateArtifactPort, type AgentCandidateBenchmarkGraderPort, type AgentCandidateBundleInput, type AgentCandidateCodeSource, type AgentCandidateCodeSurfaceSource, type AgentCandidateContainerPort, type AgentCandidateExecutionAttemptRecord, type AgentCandidateExecutionAttemptRef, type AgentCandidateExecutionClaim, type AgentCandidateExecutionClaimResult, type AgentCandidateExecutionClaimStore, type AgentCandidateExecutionCleanupHandles, type AgentCandidateExecutionFailureClass, type AgentCandidateExecutionFinishResult, type AgentCandidateExecutionLease, type AgentCandidateExecutionPhase, type AgentCandidateExecutionPhaseResult, type AgentCandidateExecutionPorts, type AgentCandidateExecutionRecoveryEvidence, type AgentCandidateExecutionRoots, type AgentCandidateExecutionStageResult, type AgentCandidateExecutionTerminalRecord, type AgentCandidateExecutionTerminalResult, type AgentCandidateExecutorFinalCapture, type AgentCandidateExecutorMemoryCapture, type AgentCandidateExecutorPort, type AgentCandidateExecutorProfileFile, type AgentCandidateExecutorRequest, type AgentCandidateExecutorStopRequest, type AgentCandidateExecutorTaskOutcomeCapture, type AgentCandidateExecutorWorkspaceFile, type AgentCandidateExecutorWorkspaceInput, type AgentCandidateMemoryPort, type AgentCandidateMemoryResetResult, type AgentCandidateModelGrantClient, type AgentCandidateModelGrantReserveInput, type AgentCandidateModelGrantRunReservationInput, type AgentCandidateModelLimits, type AgentCandidateModelPort, type AgentCandidateOutputArtifactPort, type AgentCandidateOutputPurpose, type AgentCandidatePreparationEvidence, type AgentCandidateProfileSource, type AgentCandidateProtectedModelActivation, type AgentCandidateProtectedModelReservation, type AgentCandidateProtectedModelSettlement, type AgentCandidateProtectedModelSettlementCall, type AgentCandidateProtectedRunCapture, type AgentCandidateRepositoryPort, type AgentCandidateRetryRejection, type AgentCandidateRunFinalization, type AgentCandidateTaskExecution, type AgentCandidateVerificationPorts, type AgentCandidateWorkspaceArtifactsOptions, type AgentCandidateWorkspacePort, type AgentCandidateWorkspaceSnapshotReferences, type AgentCandidateWorkspaceTree, type BuildAgentCandidateBundleInput, type CanonicalCandidateDocument, type CaptureAgentCandidateWorkspaceOptions, type CaptureAgentCandidateWorkspaceToArtifactsOptions, type CaptureAgentWorkspaceSnapshotOptions, type CapturedAgentCandidateWorkspace, type CreateAgentCandidateWorkspacePortOptions, type CreateProtectedAgentCandidateModelPortOptions, type DescribeWorkspaceTreeOptions, type DisposePreparedAgentCandidateOptions, type ExactProcessCandidateExecutorOptions, type ExecutePreparedAgentCandidateOptions, FileAgentCandidateExecutionClaimStore, type FileAgentCandidateExecutionClaimStoreOptions, type MaterializeAgentWorkspaceSnapshotOptions, type PersistedTaskOutcomeEvidence, type PreparedAgentCandidateExecution, type PreparedAgentCandidateInstruction, type PreparedAgentCandidateKnowledge, type PreparedAgentCandidateLaunch, type PreparedAgentCandidateTrace, type ProtectedAgentCandidateModelGrantContext, type ResolvedAgentCandidateContainer, type RunProtectedAgentCandidateModelGrantOptions, type RunProtectedAgentCandidateModelGrantResult, type SeedWorkspaceTreeInput, type VerifiedAgentCandidate, type VerifiedAgentCandidateTaskOutcome, type WorkspaceScanLimits, type WorkspaceScanOptions, type WorkspaceTreeAlgorithm, type WorkspaceTreeDescriptor, type WorkspaceTreeEntryPolicy, type WorkspaceTreeExclusion, type WorkspaceTreeExclusionReason, agentCandidateProfileAsAgentProfile, applyExactAgentProfileDiff, assertCandidateProfileBinding, buildAgentCandidateBundle, candidateWorkspaceManifest, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, captureAgentCandidateWorkspaceToArtifacts, captureAgentCandidateWorkspaceTreeToArtifacts, captureAgentWorkspaceSnapshot, createAgentCandidateWorkspacePort, createProtectedAgentCandidateModelPort, disposePreparedAgentCandidateExecution, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, freezeGenericAgentCandidateProfile, materializeAgentCandidateWorkspaceFromArtifacts, materializeAgentWorkspaceSnapshot, parseExactAgentProfileDiff, prepareAgentCandidateExecution, runProtectedAgentCandidateModelGrant, sealAgentCandidateBundle, verifyAgentCandidateBundle, verifyAgentCandidateWorkspaceArtifacts, verifyAgentCandidateWorkspaceTree };
|
|
261
|
+
export { type AgentCandidateArtifactPort, type AgentCandidateBenchmarkGraderPort, type AgentCandidateBundleInput, type AgentCandidateCodeSource, type AgentCandidateCodeSurfaceSource, type AgentCandidateContainerPort, type AgentCandidateExecutionAttemptRecord, type AgentCandidateExecutionAttemptRef, type AgentCandidateExecutionClaim, type AgentCandidateExecutionClaimResult, type AgentCandidateExecutionClaimStore, type AgentCandidateExecutionCleanupHandles, type AgentCandidateExecutionFailureClass, type AgentCandidateExecutionFinishResult, type AgentCandidateExecutionLease, type AgentCandidateExecutionPhase, type AgentCandidateExecutionPhaseResult, type AgentCandidateExecutionPorts, type AgentCandidateExecutionRecoveryEvidence, type AgentCandidateExecutionRoots, type AgentCandidateExecutionStageResult, type AgentCandidateExecutionTerminalRecord, type AgentCandidateExecutionTerminalResult, type AgentCandidateExecutorFinalCapture, type AgentCandidateExecutorMemoryCapture, type AgentCandidateExecutorPort, type AgentCandidateExecutorProfileFile, type AgentCandidateExecutorRequest, type AgentCandidateExecutorStopRequest, type AgentCandidateExecutorTaskOutcomeCapture, type AgentCandidateExecutorWorkspaceFile, type AgentCandidateExecutorWorkspaceInput, type AgentCandidateMemoryPort, type AgentCandidateMemoryResetResult, type AgentCandidateModelGrantClient, type AgentCandidateModelGrantReserveInput, type AgentCandidateModelGrantRunReservationInput, type AgentCandidateModelLimits, type AgentCandidateModelPort, type AgentCandidateOutputArtifactPort, type AgentCandidateOutputPurpose, type AgentCandidatePreparationEvidence, type AgentCandidateProfileSource, type AgentCandidateProtectedModelActivation, type AgentCandidateProtectedModelReservation, type AgentCandidateProtectedModelSettlement, type AgentCandidateProtectedModelSettlementCall, type AgentCandidateProtectedRunCapture, type AgentCandidateRepositoryPort, type AgentCandidateRetryRejection, type AgentCandidateRunFinalization, type AgentCandidateTaskExecution, type AgentCandidateVerificationPorts, type AgentCandidateWorkspaceArtifactsOptions, type AgentCandidateWorkspacePort, type AgentCandidateWorkspaceSnapshotReferences, type AgentCandidateWorkspaceTree, type BuildAgentCandidateBundleInput, type CanonicalCandidateDocument, type CaptureAgentCandidateWorkspaceOptions, type CaptureAgentCandidateWorkspaceToArtifactsOptions, type CaptureAgentWorkspaceSnapshotOptions, type CapturedAgentCandidateWorkspace, type CreateAgentCandidateWorkspacePortOptions, type CreateProtectedAgentCandidateModelPortOptions, type DescribeWorkspaceTreeOptions, type DisposePreparedAgentCandidateOptions, type ExactProcessCandidateExecutorOptions, type ExecutePreparedAgentCandidateOptions, type FileAgentCandidateExecutionClaimStoreOptions, type MaterializeAgentWorkspaceSnapshotOptions, type PersistedTaskOutcomeEvidence, type PreparedAgentCandidateExecution, type PreparedAgentCandidateInstruction, type PreparedAgentCandidateKnowledge, type PreparedAgentCandidateLaunch, type PreparedAgentCandidateTrace, type ProtectedAgentCandidateModelGrantContext, type ResolvedAgentCandidateContainer, type RunProtectedAgentCandidateModelGrantOptions, type RunProtectedAgentCandidateModelGrantResult, type SeedWorkspaceTreeInput, type VerifiedAgentCandidate, type VerifiedAgentCandidateTaskOutcome, type WorkspaceScanLimits, type WorkspaceScanOptions, type WorkspaceTreeAlgorithm, type WorkspaceTreeDescriptor, type WorkspaceTreeEntryPolicy, type WorkspaceTreeExclusion, type WorkspaceTreeExclusionReason, agentCandidateProfileAsAgentProfile, applyExactAgentProfileDiff, assertCandidateProfileBinding, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, captureAgentCandidateWorkspaceToArtifacts, captureAgentCandidateWorkspaceTreeToArtifacts, createAgentCandidateWorkspacePort, createProtectedAgentCandidateModelPort, executePreparedAgentCandidate, freezeGenericAgentCandidateProfile, materializeAgentCandidateWorkspaceFromArtifacts, parseExactAgentProfileDiff, prepareAgentCandidateExecution, verifyAgentCandidateWorkspaceArtifacts, verifyAgentCandidateWorkspaceTree };
|
|
282
262
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { I as deepFreezeCandidate, L as embeddedCandidateArtifact, N as canonicalCandidateBytes$1, T as candidateWorkspaceManifest, _ as captureAgentCandidateWorkspaceFiles, a as materializeAgentCandidateWorkspaceFromArtifacts, c as verifyAgentCandidateWorkspaceTree, g as verifiedArtifactChunks, i as captureAgentCandidateWorkspaceTreeToArtifacts, l as captureAgentCandidateWorkspace, r as captureAgentCandidateWorkspaceToArtifacts, s as verifyAgentCandidateWorkspaceArtifacts, u as createAgentCandidateWorkspacePort, y as workspaceLimits } from "../sandbox-profile-compat-
|
|
2
|
-
import { a as applyExactAgentProfileDiff, b as parseExactCandidateProfile, i as agentCandidateProfileAsAgentProfile, o as assertCandidateProfileBinding, p as freezeGenericAgentCandidateProfile, v as parseExactAgentProfile, y as parseExactAgentProfileDiff } from "../profile-
|
|
3
|
-
import { t as sealAgentCandidateBundle } from "../bundle-
|
|
4
|
-
import { _ as sealTerminalDigest, a as consumePreparedCandidateExecution, b as sealAgentCandidateModelSettlement, c as withinCandidateCleanupDeadline, d as assertTerminalMatchesClaim, f as assertTerminalMatchesStaged, g as requireStagedTerminal, h as rejectedStage, i as beginPreparedCandidateDisposal, l as assertRecoveryMatchesStaged, m as rejectedFinish, n as executePreparedAgentCandidate, o as candidateClaimFileInternals, p as recoveredTerminalRecord, r as assertPreparedCandidateIntegrity, s as candidateCleanupDeadline, t as prepareAgentCandidateExecution, u as assertTerminalAllowedInPhase, v as terminalRecord, w as verifyAgentCandidateBundle, x as exactProcessProviderAsCandidateExecutor, y as createProtectedAgentCandidateModelPort } from "../prepare-
|
|
1
|
+
import { I as deepFreezeCandidate, L as embeddedCandidateArtifact, N as canonicalCandidateBytes$1, T as candidateWorkspaceManifest, _ as captureAgentCandidateWorkspaceFiles, a as materializeAgentCandidateWorkspaceFromArtifacts, c as verifyAgentCandidateWorkspaceTree, g as verifiedArtifactChunks, i as captureAgentCandidateWorkspaceTreeToArtifacts, l as captureAgentCandidateWorkspace, r as captureAgentCandidateWorkspaceToArtifacts, s as verifyAgentCandidateWorkspaceArtifacts, u as createAgentCandidateWorkspacePort, y as workspaceLimits } from "../sandbox-profile-compat-BxMQ1VXv.js";
|
|
2
|
+
import { a as applyExactAgentProfileDiff, b as parseExactCandidateProfile, i as agentCandidateProfileAsAgentProfile, o as assertCandidateProfileBinding, p as freezeGenericAgentCandidateProfile, v as parseExactAgentProfile, y as parseExactAgentProfileDiff } from "../profile-CAhZDW2T.js";
|
|
3
|
+
import { t as sealAgentCandidateBundle } from "../bundle-Ze8pd07a.js";
|
|
4
|
+
import { _ as sealTerminalDigest, a as consumePreparedCandidateExecution, b as sealAgentCandidateModelSettlement, c as withinCandidateCleanupDeadline, d as assertTerminalMatchesClaim, f as assertTerminalMatchesStaged, g as requireStagedTerminal, h as rejectedStage, i as beginPreparedCandidateDisposal, l as assertRecoveryMatchesStaged, m as rejectedFinish, n as executePreparedAgentCandidate, o as candidateClaimFileInternals, p as recoveredTerminalRecord, r as assertPreparedCandidateIntegrity, s as candidateCleanupDeadline, t as prepareAgentCandidateExecution, u as assertTerminalAllowedInPhase, v as terminalRecord, w as verifyAgentCandidateBundle, x as exactProcessProviderAsCandidateExecutor, y as createProtectedAgentCandidateModelPort } from "../prepare-DE8TQnLu.js";
|
|
5
5
|
import { agentCandidateArtifactRefSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema } from "@tangle-network/agent-interface";
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
7
|
import { linkSync } from "node:fs";
|
|
8
8
|
import { isAbsolute, join, resolve } from "node:path";
|
|
9
9
|
import { lstat, mkdir, open, unlink } from "node:fs/promises";
|
|
10
10
|
import { verifyCodeSurface } from "@tangle-network/agent-eval/campaign";
|
|
11
|
-
|
|
11
|
+
// src/candidate-execution/builder.ts
|
|
12
12
|
/**
|
|
13
13
|
* Compile one measured profile/code candidate into the immutable execution
|
|
14
14
|
* contract. Code bytes are re-read and verified by agent-eval before they are
|
|
@@ -17,7 +17,7 @@ import { verifyCodeSurface } from "@tangle-network/agent-eval/campaign";
|
|
|
17
17
|
* to re-read external memory, repository, and workspace artifacts.
|
|
18
18
|
*/
|
|
19
19
|
function buildAgentCandidateBundle(input) {
|
|
20
|
-
|
|
20
|
+
const bundle = {
|
|
21
21
|
kind: "agent-candidate-bundle",
|
|
22
22
|
digestAlgorithm: "rfc8785-sha256",
|
|
23
23
|
profile: compileCandidateProfile(input.profile),
|
|
@@ -25,7 +25,8 @@ function buildAgentCandidateBundle(input) {
|
|
|
25
25
|
execution: input.execution,
|
|
26
26
|
...input.knowledge !== void 0 ? { knowledge: input.knowledge } : {},
|
|
27
27
|
memory: input.memory
|
|
28
|
-
}
|
|
28
|
+
};
|
|
29
|
+
return sealAgentCandidateBundle(bundle);
|
|
29
30
|
}
|
|
30
31
|
function compileCandidateProfile(source) {
|
|
31
32
|
if (source.kind === "candidate-profile") return parseExactCandidateProfile(source.profile);
|
|
@@ -42,7 +43,8 @@ function compileCandidateProfile(source) {
|
|
|
42
43
|
function compileCandidateCode(source) {
|
|
43
44
|
if (source.kind === "disabled" || source.kind === "no-op") return source;
|
|
44
45
|
if (source.kind !== "code-surface") throw new Error(`unsupported candidate code source: ${String(source.kind)}`);
|
|
45
|
-
const
|
|
46
|
+
const verified = verifyCodeSurface(source.surface, source.worktreeDir);
|
|
47
|
+
const patch = embeddedCandidateArtifact(verified.patchBytes);
|
|
46
48
|
if (patch.sha256 !== source.surface.patch.sha256 || patch.byteLength !== source.surface.patch.byteLength) throw new Error("verified CodeSurface patch bytes do not match its content identity");
|
|
47
49
|
return {
|
|
48
50
|
kind: "git-patch",
|
|
@@ -56,8 +58,7 @@ function compileCandidateCode(source) {
|
|
|
56
58
|
}
|
|
57
59
|
};
|
|
58
60
|
}
|
|
59
|
-
|
|
60
|
-
//#region src/candidate-execution/claim-file-store.ts
|
|
61
|
+
// src/candidate-execution/claim-file-store.ts
|
|
61
62
|
const { assertExpiredLease, assertLease, assertSameSlot, assertUnexpiredLease, attemptRecord, claimSlot, leaseDigest, newLease, readClaim, readClaimIfPresent, readTerminal, readTerminalIfPresent, readTransitionIfPresent, rejectedExistingClaim, rejectedRetry, retryRejection, sealAttemptRef, sealClaim, sealLease } = candidateClaimFileInternals;
|
|
62
63
|
/** Cross-process lifecycle implemented as fsynced, create-if-absent records. */
|
|
63
64
|
var FileAgentCandidateExecutionClaimStore = class {
|
|
@@ -156,7 +157,8 @@ var FileAgentCandidateExecutionClaimStore = class {
|
|
|
156
157
|
const stored = await readClaim(claimPath);
|
|
157
158
|
assertSameSlot(stored.claim, lease, claimPath);
|
|
158
159
|
assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease);
|
|
159
|
-
const
|
|
160
|
+
const state = await this.transitionState(stored.claim);
|
|
161
|
+
const staged = requireStagedTerminal(state.staged, terminalDigest);
|
|
160
162
|
const terminalPath = this.terminalPath(lease);
|
|
161
163
|
const existing = await readTerminalIfPresent(terminalPath);
|
|
162
164
|
if (existing) {
|
|
@@ -305,8 +307,7 @@ async function syncDirectory(directory) {
|
|
|
305
307
|
function isNodeError(error, code) {
|
|
306
308
|
return error !== null && typeof error === "object" && "code" in error && error.code === code;
|
|
307
309
|
}
|
|
308
|
-
|
|
309
|
-
//#region src/candidate-execution/dispose.ts
|
|
310
|
+
// src/candidate-execution/dispose.ts
|
|
310
311
|
/** Revoke reservations held by a prepared candidate that will not be executed. */
|
|
311
312
|
async function disposePreparedAgentCandidateExecution(prepared, options = {}) {
|
|
312
313
|
const initialState = assertPreparedCandidateIntegrity(prepared);
|
|
@@ -350,8 +351,7 @@ async function disposePreparedAgentCandidateExecution(prepared, options = {}) {
|
|
|
350
351
|
consumePreparedCandidateExecution(prepared, "disposed");
|
|
351
352
|
return Object.freeze({ disposed: true });
|
|
352
353
|
}
|
|
353
|
-
|
|
354
|
-
//#region src/candidate-execution/protected-model-grant.ts
|
|
354
|
+
// src/candidate-execution/protected-model-grant.ts
|
|
355
355
|
const SETTLEMENT_RETRY_INITIAL_DELAY_MS = 25;
|
|
356
356
|
const SETTLEMENT_RETRY_MAX_DELAY_MS = 1e3;
|
|
357
357
|
/**
|
|
@@ -438,8 +438,7 @@ function isCandidateGrantDrainingError(error) {
|
|
|
438
438
|
if (candidate.code === "candidate_grant_draining") return true;
|
|
439
439
|
return typeof candidate.message === "string" && /\bcandidate_grant_draining\b/u.test(candidate.message);
|
|
440
440
|
}
|
|
441
|
-
|
|
442
|
-
//#region src/candidate-execution/workspace-transfer.ts
|
|
441
|
+
// src/candidate-execution/workspace-transfer.ts
|
|
443
442
|
/**
|
|
444
443
|
* Capture through the canonical archive owner and return references only.
|
|
445
444
|
* The caller holds its existing private source workspace lease throughout capture, and binds
|
|
@@ -517,7 +516,6 @@ async function assertAbsentDestination(destination) {
|
|
|
517
516
|
}
|
|
518
517
|
throw new Error("portable workspace destination already exists");
|
|
519
518
|
}
|
|
520
|
-
//#endregion
|
|
521
519
|
export { FileAgentCandidateExecutionClaimStore, agentCandidateProfileAsAgentProfile, applyExactAgentProfileDiff, assertCandidateProfileBinding, buildAgentCandidateBundle, candidateWorkspaceManifest, captureAgentCandidateWorkspace, captureAgentCandidateWorkspaceFiles, captureAgentCandidateWorkspaceToArtifacts, captureAgentCandidateWorkspaceTreeToArtifacts, captureAgentWorkspaceSnapshot, createAgentCandidateWorkspacePort, createProtectedAgentCandidateModelPort, disposePreparedAgentCandidateExecution, exactProcessProviderAsCandidateExecutor, executePreparedAgentCandidate, freezeGenericAgentCandidateProfile, materializeAgentCandidateWorkspaceFromArtifacts, materializeAgentWorkspaceSnapshot, parseExactAgentProfileDiff, prepareAgentCandidateExecution, runProtectedAgentCandidateModelGrant, sealAgentCandidateBundle, verifyAgentCandidateBundle, verifyAgentCandidateWorkspaceArtifacts, verifyAgentCandidateWorkspaceTree };
|
|
522
520
|
|
|
523
521
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["canonicalCandidateBytes","canonicalCandidateBytes"],"sources":["../../src/candidate-execution/builder.ts","../../src/candidate-execution/claim-file-store.ts","../../src/candidate-execution/dispose.ts","../../src/candidate-execution/protected-model-grant.ts","../../src/candidate-execution/workspace-transfer.ts"],"sourcesContent":["import type { CodeSurface } from '@tangle-network/agent-eval/campaign'\nimport { verifyCodeSurface } from '@tangle-network/agent-eval/campaign'\nimport type {\n AgentCandidateCodeDisabled,\n AgentCandidateCodeNoOp,\n AgentCandidateExecution,\n AgentCandidateGitHubRepository,\n AgentCandidateKnowledge,\n AgentCandidateMemoryPolicy,\n AgentCandidateProfile,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { type AgentCandidateBundleInput, sealAgentCandidateBundle } from './bundle'\nimport { embeddedCandidateArtifact } from './digest'\nimport {\n applyExactAgentProfileDiff,\n freezeGenericAgentCandidateProfile,\n parseExactAgentProfile,\n parseExactAgentProfileDiff,\n parseExactCandidateProfile,\n} from './profile'\n\n/** A complete profile that can be frozen without losing behavior. */\nexport type AgentCandidateProfileSource =\n | {\n kind: 'profile'\n profile: AgentProfile\n }\n | {\n kind: 'profile-diffs'\n base: AgentProfile\n /** Applied in order before the resulting profile is frozen into the bundle. */\n diffs: readonly AgentProfileDiff[]\n }\n | {\n kind: 'candidate-profile'\n /** Already converted to the closed, secret-free candidate profile contract. */\n profile: AgentCandidateProfile\n }\n\n/** The only accepted path from an agent-eval code candidate to executable bytes. */\nexport interface AgentCandidateCodeSurfaceSource {\n kind: 'code-surface'\n surface: CodeSurface\n repository: AgentCandidateGitHubRepository\n /** Optional parent directory used to resolve a relative `surface.worktreeRef`. */\n worktreeDir?: string\n}\n\n/** Explicit control/no-op code or one finalized CodeSurface whose bytes must still verify. */\nexport type AgentCandidateCodeSource =\n | AgentCandidateCodeDisabled\n | AgentCandidateCodeNoOp\n | AgentCandidateCodeSurfaceSource\n\n/** Complete measured surfaces and execution policy compiled into one candidate bundle. */\nexport interface BuildAgentCandidateBundleInput {\n profile: AgentCandidateProfileSource\n code: AgentCandidateCodeSource\n execution: AgentCandidateExecution\n knowledge?: AgentCandidateKnowledge\n memory: AgentCandidateMemoryPolicy\n}\n\n/**\n * Compile one measured profile/code candidate into the immutable execution\n * contract. Code bytes are re-read and verified by agent-eval before they are\n * embedded. The returned bundle is schema-validated, canonically digested, and\n * deeply immutable; call `verifyAgentCandidateBundle` at the execution boundary\n * to re-read external memory, repository, and workspace artifacts.\n */\nexport function buildAgentCandidateBundle(\n input: BuildAgentCandidateBundleInput,\n): ReturnType<typeof sealAgentCandidateBundle> {\n const bundle: AgentCandidateBundleInput = {\n kind: 'agent-candidate-bundle',\n digestAlgorithm: 'rfc8785-sha256',\n profile: compileCandidateProfile(input.profile),\n code: compileCandidateCode(input.code),\n execution: input.execution,\n ...(input.knowledge !== undefined ? { knowledge: input.knowledge } : {}),\n memory: input.memory,\n }\n return sealAgentCandidateBundle(bundle)\n}\n\nfunction compileCandidateProfile(source: AgentCandidateProfileSource): AgentCandidateProfile {\n if (source.kind === 'candidate-profile') {\n return parseExactCandidateProfile(source.profile)\n }\n\n if (source.kind === 'profile') {\n return freezeGenericAgentCandidateProfile(source.profile)\n }\n\n if (source.kind !== 'profile-diffs') {\n throw new Error(\n `unsupported candidate profile source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n if (source.diffs.length === 0) {\n throw new Error('profile-diffs source requires at least one AgentProfileDiff')\n }\n let profile = parseExactAgentProfile(source.base, 'base profile')\n for (const [index, inputDiff] of source.diffs.entries()) {\n const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`)\n profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`)\n }\n return freezeGenericAgentCandidateProfile(profile)\n}\n\nfunction compileCandidateCode(source: AgentCandidateCodeSource): AgentCandidateBundleInput['code'] {\n if (source.kind === 'disabled' || source.kind === 'no-op') return source\n if (source.kind !== 'code-surface') {\n throw new Error(\n `unsupported candidate code source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n\n const verified = verifyCodeSurface(source.surface, source.worktreeDir)\n const patch = embeddedCandidateArtifact(verified.patchBytes)\n if (\n patch.sha256 !== source.surface.patch.sha256 ||\n patch.byteLength !== source.surface.patch.byteLength\n ) {\n throw new Error('verified CodeSurface patch bytes do not match its content identity')\n }\n return {\n kind: 'git-patch',\n repository: source.repository,\n baseCommit: source.surface.baseCommit,\n baseTree: source.surface.baseTree,\n candidateTree: source.surface.candidateTree,\n patch: { format: 'git-diff-binary', artifact: patch },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { linkSync } from 'node:fs'\nimport { mkdir, open, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport {\n type AgentCandidateExecutionAttemptRecord,\n type AgentCandidateExecutionAttemptRef,\n type AgentCandidateExecutionClaim,\n type AgentCandidateExecutionClaimResult,\n type AgentCandidateExecutionClaimStore,\n type AgentCandidateExecutionFinishResult,\n type AgentCandidateExecutionLease,\n type AgentCandidateExecutionPhase,\n type AgentCandidateExecutionPhaseResult,\n type AgentCandidateExecutionRecoveryEvidence,\n type AgentCandidateExecutionStageResult,\n type AgentCandidateExecutionTerminalRecord,\n type AgentCandidateExecutionTerminalResult,\n type AgentCandidateRetryRejection,\n candidateClaimFileInternals,\n} from './claim'\nimport {\n assertRecoveryMatchesStaged,\n assertTerminalAllowedInPhase,\n assertTerminalMatchesClaim,\n assertTerminalMatchesStaged,\n recoveredTerminalRecord,\n rejectedFinish,\n rejectedStage,\n requireStagedTerminal,\n sealTerminalDigest,\n terminalRecord,\n} from './claim-terminal'\nimport { canonicalCandidateBytes } from './digest'\n\nconst {\n assertExpiredLease,\n assertLease,\n assertSameSlot,\n assertUnexpiredLease,\n attemptRecord,\n claimSlot,\n leaseDigest,\n newLease,\n readClaim,\n readClaimIfPresent,\n readTerminal,\n readTerminalIfPresent,\n readTransitionIfPresent,\n rejectedExistingClaim,\n rejectedRetry,\n retryRejection,\n sealAttemptRef,\n sealClaim,\n sealLease,\n} = candidateClaimFileInternals\n\nexport interface FileAgentCandidateExecutionClaimStoreOptions {\n /** Evaluator-owned directory shared by every process allowed to execute candidates. */\n directory: string\n /** Testable evaluator clock; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** Cross-process lifecycle implemented as fsynced, create-if-absent records. */\nexport class FileAgentCandidateExecutionClaimStore implements AgentCandidateExecutionClaimStore {\n private readonly directory: string\n private readonly now: () => number\n\n constructor(options: FileAgentCandidateExecutionClaimStoreOptions) {\n if (options.directory.length === 0) {\n throw new Error('candidate execution claim directory must not be empty')\n }\n this.directory = options.directory\n this.now = options.now ?? Date.now\n }\n\n async tryClaim(\n requested: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateExecutionClaimResult> {\n const claim = sealClaim(requested)\n await mkdir(this.directory, { recursive: true })\n const claimPath = this.claimPath(claim)\n const existing = await readClaimIfPresent(claimPath)\n if (existing) {\n assertSameSlot(existing.claim, claim, claimPath)\n return rejectedExistingClaim(existing.claim, claim)\n }\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n const retryFailure = await this.retryFailure(claim)\n if (retryFailure) return rejectedRetry(claim, retryFailure)\n\n const lease = newLease(claim)\n const acquired = await writeRecordIfAbsent(this.directory, claimPath, {\n ...claim,\n phase: 'claimed',\n leaseDigest: leaseDigest(lease),\n })\n if (acquired) return Object.freeze({ acquired: true, claim, lease })\n\n const winner = await readClaim(claimPath)\n assertSameSlot(winner.claim, claim, claimPath)\n return rejectedExistingClaim(winner.claim, claim)\n }\n\n async getAttempt(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n return await this.storedAttempt(sealAttemptRef(requestedAttempt))\n }\n\n async markCandidateMayRun(\n requestedLease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n if (state.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n if (state.staged) {\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const marked = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, 1),\n {\n kind: 'candidate-execution-phase',\n executionId: stored.claim.executionId,\n attempt: stored.claim.attempt,\n executionPlanDigest: stored.claim.executionPlanDigest,\n phase: 'candidate-may-run',\n },\n this.ownerPublication(stored.claim),\n )\n if (marked) return Object.freeze({ marked: true, phase: 'candidate-may-run' })\n const winner = await this.transitionState(stored.claim)\n if (winner.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n\n async stageTerminal(\n requestedLease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const terminal = terminalRecord(stored.claim, result)\n const state = await this.transitionState(stored.claim)\n if (state.staged) return rejectedStage(state.staged, terminal)\n assertTerminalAllowedInPhase(state.phase, terminal)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const transition = state.phase === 'claimed' ? 1 : 2\n const staged = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, transition),\n {\n kind: 'candidate-execution-pending-terminal',\n terminal,\n },\n this.ownerPublication(stored.claim),\n )\n if (staged) return Object.freeze({ staged: true, terminal })\n const winner = await this.transitionState(stored.claim)\n if (!winner.staged) {\n throw new Error('candidate execution phase transition won while staging terminal')\n }\n return rejectedStage(winner.staged, terminal)\n }\n\n async finish(\n requestedLease: AgentCandidateExecutionLease,\n requestedTerminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const lease = sealLease(requestedLease)\n const terminalDigest = sealTerminalDigest(requestedTerminalDigest)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n const staged = requireStagedTerminal(state.staged, terminalDigest)\n const terminalPath = this.terminalPath(lease)\n const existing = await readTerminalIfPresent(terminalPath)\n if (existing) {\n assertTerminalMatchesClaim(existing, stored.claim, terminalPath)\n assertTerminalMatchesStaged(existing, staged, terminalPath)\n return rejectedFinish(existing, terminalDigest)\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const finished = await writeRecordIfAbsent(\n this.directory,\n terminalPath,\n {\n terminal: staged,\n },\n this.ownerPublication(stored.claim),\n )\n if (finished) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, lease, terminalPath)\n assertTerminalMatchesClaim(winner, stored.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, terminalDigest)\n }\n\n async recoverExpired(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const attempt = sealAttemptRef(requestedAttempt)\n const record = await this.storedAttempt(attempt)\n if (!record) throw new Error('candidate execution recovery does not name an acquired attempt')\n const recovered = recoveredTerminalRecord(record.claim, record.phase, evidence)\n if (record.staged) assertRecoveryMatchesStaged(record.staged, recovered)\n const requestedDigest = record.staged?.terminalDigest ?? recovered.terminalDigest\n if (record.terminal) return rejectedFinish(record.terminal, requestedDigest)\n assertExpiredLease(record.claim.leaseExpiresAtMs, this.now())\n\n let staged = record.staged\n if (!staged) {\n const transition = record.phase === 'claimed' ? 1 : 2\n const didStage = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(record.claim, transition),\n {\n kind: 'candidate-execution-pending-terminal',\n terminal: recovered,\n },\n )\n if (didStage) {\n staged = recovered\n } else {\n const winner = await this.transitionState(record.claim)\n if (!winner.staged) {\n throw new Error(\n 'candidate execution recovery lost terminal staging to a phase transition',\n )\n }\n assertRecoveryMatchesStaged(winner.staged, recovered)\n staged = winner.staged\n }\n }\n\n const terminalPath = this.terminalPath(attempt)\n const didFinish = await writeRecordIfAbsent(this.directory, terminalPath, {\n terminal: staged,\n })\n if (didFinish) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, attempt, terminalPath)\n assertTerminalMatchesClaim(winner, record.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, staged.terminalDigest)\n }\n\n private async storedAttempt(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n const claimPath = this.claimPath(claim)\n const stored = await readClaimIfPresent(claimPath)\n if (!stored) return undefined\n assertSameSlot(stored.claim, claim, claimPath)\n const terminalPath = this.terminalPath(claim)\n const terminal = await readTerminalIfPresent(terminalPath)\n // Terminal publication follows its immutable staged outbox, so read that prerequisite later.\n const state = await this.transitionState(stored.claim)\n if (terminal) {\n assertTerminalMatchesClaim(terminal, stored.claim, terminalPath)\n if (!state.staged) {\n throw new Error(\n `candidate execution terminal record at ${terminalPath} has no staged outbox`,\n )\n }\n assertTerminalMatchesStaged(terminal, state.staged, terminalPath)\n }\n return attemptRecord(stored.claim, state.phase, state.staged, terminal)\n }\n\n private async transitionState(claim: AgentCandidateExecutionClaim): Promise<{\n phase: AgentCandidateExecutionPhase\n staged?: AgentCandidateExecutionTerminalRecord\n }> {\n const firstPath = this.transitionPath(claim, 1)\n const first = await readTransitionIfPresent(firstPath, claim)\n if (!first) return { phase: 'claimed' }\n if (first.kind === 'pending') return { phase: 'claimed', staged: first.terminal }\n const secondPath = this.transitionPath(claim, 2)\n const second = await readTransitionIfPresent(secondPath, claim)\n if (!second) return { phase: 'candidate-may-run' }\n if (second.kind !== 'pending') {\n throw new Error(`candidate execution transition at ${secondPath} repeats the phase marker`)\n }\n return { phase: 'candidate-may-run', staged: second.terminal }\n }\n\n private async retryFailure(\n claim: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateRetryRejection | undefined> {\n if (claim.attempt === 1) return undefined\n return retryRejection(\n claim,\n await this.storedAttempt({\n executionId: claim.executionId,\n attempt: claim.attempt - 1,\n }),\n )\n }\n\n private ownerPublication(claim: AgentCandidateExecutionClaim): {\n authorizePublish: () => true\n } {\n return {\n authorizePublish: () => {\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n return true\n },\n }\n }\n\n private claimPath(claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>): string {\n return join(this.directory, `${claimSlot(claim)}.claim.json`)\n }\n\n private terminalPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.terminal.json`)\n }\n\n private transitionPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ordinal: 1 | 2,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.transition-${ordinal}.json`)\n }\n}\n\n/**\n * Candidate records keep this async writer because lease authorization must run after the\n * asynchronous temp-file fsync and immediately before synchronous link publication. The\n * supervisor durability helper is synchronous and has no lease hook, so combining them would\n * either move authorization earlier or add an async race to the claim boundary.\n */\nasync function writeRecordIfAbsent(\n directory: string,\n destination: string,\n record: object,\n options: {\n /** Synchronous authorization checked after temp fsync, immediately before atomic publication. */\n authorizePublish?: () => true\n } = {},\n): Promise<boolean> {\n const temporaryPath = join(directory, `.candidate-execution-${process.pid}-${randomUUID()}.tmp`)\n const handle = await open(temporaryPath, 'wx', 0o600)\n try {\n await handle.writeFile(\n Buffer.concat([Buffer.from(canonicalCandidateBytes(record)), Buffer.from('\\n')]),\n )\n await handle.sync()\n } finally {\n await handle.close()\n }\n\n let written = false\n try {\n if (options.authorizePublish && options.authorizePublish() !== true) {\n throw new Error('candidate execution record publication was not authorized')\n }\n // Authorization and the atomic filesystem call are one synchronous critical\n // section so the event loop cannot advance an injected lease clock between them.\n linkSync(temporaryPath, destination)\n written = true\n await syncDirectory(directory)\n } catch (error) {\n if (!isNodeError(error, 'EEXIST')) throw error\n } finally {\n await unlink(temporaryPath).catch((error: unknown) => {\n if (!isNodeError(error, 'ENOENT')) throw error\n })\n }\n return written\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n const handle = await open(directory, 'r')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n )\n}\n","import { candidateCleanupDeadline, withinCandidateCleanupDeadline } from './cleanup'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport {\n assertPreparedCandidateIntegrity,\n beginPreparedCandidateDisposal,\n consumePreparedCandidateExecution,\n} from './prepared-state'\nimport type { PreparedAgentCandidateExecution } from './types'\n\nexport interface DisposePreparedAgentCandidateOptions {\n cleanupTimeoutMs?: number\n}\n\n/** Revoke reservations held by a prepared candidate that will not be executed. */\nexport async function disposePreparedAgentCandidateExecution(\n prepared: PreparedAgentCandidateExecution,\n options: DisposePreparedAgentCandidateOptions = {},\n): Promise<{ disposed: true }> {\n const initialState = assertPreparedCandidateIntegrity(prepared)\n const cleanupTimeoutMs = options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs\n if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {\n throw new Error('disposal cleanup timeout exceeds the frozen preparation bound')\n }\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const state = beginPreparedCandidateDisposal(prepared)\n const cleanup: Array<Promise<unknown>> = []\n\n if (state.memory.mode === 'isolated') {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const closed = await state.ports.memory.close({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n reason: 'abandoned',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('abandoned isolated memory access did not acknowledge closure')\n }\n },\n cleanupDeadlineAtMs,\n 'isolated memory disposal',\n ),\n )\n }\n\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const settlement = sealAgentCandidateModelSettlement(\n await state.ports.models.settleGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n reason: 'abandoned',\n }),\n {\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n model: state.resolvedModel.model,\n },\n )\n if (settlement.usage.modelCalls !== 0) {\n throw new Error('unexecuted model reservation unexpectedly contains calls')\n }\n },\n cleanupDeadlineAtMs,\n 'model reservation disposal',\n ),\n )\n\n const results = await Promise.allSettled(cleanup)\n const failures = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason)\n if (failures.length > 0) {\n consumePreparedCandidateExecution(prepared, 'disposal-failed')\n throw new AggregateError(failures, 'candidate preparation disposal failed')\n }\n\n consumePreparedCandidateExecution(prepared, 'disposed')\n return Object.freeze({ disposed: true as const })\n}\n","import type { AgentCandidateResolvedModel } from '@tangle-network/agent-interface'\n\nimport type {\n AgentCandidateModelGrantActivateInput,\n AgentCandidateModelGrantReserveInput,\n AgentCandidateModelGrantSettleInput,\n} from './protected-model-port'\nimport type {\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\n/** Reservation fields supplied by a caller before Runtime resolves the model. */\nexport type AgentCandidateModelGrantRunReservationInput = Omit<\n AgentCandidateModelGrantReserveInput,\n 'resolved'\n>\n\n/** Values available only while one protected model grant is active. */\nexport interface ProtectedAgentCandidateModelGrantContext {\n readonly activation: AgentCandidateProtectedModelActivation\n readonly reservation: AgentCandidateProtectedModelReservation\n readonly resolved: AgentCandidateResolvedModel\n}\n\n/** Inputs for one protected grant scoped to one bounded caller unit. */\nexport interface RunProtectedAgentCandidateModelGrantOptions<TResult> {\n /** Runtime port that validates and settles the evaluator-owned grant. */\n readonly port: AgentCandidateModelPort\n /** Provider-neutral model request resolved before any grant is reserved. */\n readonly resolve: Parameters<AgentCandidateModelPort['resolve']>[0]\n /** One bounded unit's immutable identity, attempt, expiry, and limits. */\n readonly reserve: AgentCandidateModelGrantRunReservationInput\n /** Must be no later than the reservation expiry. */\n readonly deadlineAtMs: AgentCandidateModelGrantActivateInput['deadlineAtMs']\n /** Execute exactly one bounded unit while the activated environment is valid. */\n readonly execute: (context: ProtectedAgentCandidateModelGrantContext) => Promise<TResult>\n}\n\n/** Result and sealed settlement returned after one protected grant closes. */\nexport interface RunProtectedAgentCandidateModelGrantResult<TResult> {\n readonly value: TResult\n readonly resolved: AgentCandidateResolvedModel\n readonly reservation: AgentCandidateProtectedModelReservation\n readonly settlement: AgentCandidateProtectedModelSettlement\n}\n\nconst SETTLEMENT_RETRY_INITIAL_DELAY_MS = 25\nconst SETTLEMENT_RETRY_MAX_DELAY_MS = 1_000\n\n/**\n * Run one bounded unit under a protected model grant.\n *\n * Runtime owns the grant lifecycle; callers own the unit boundary and any\n * durable scheduling or accounting around it. A reserved grant is settled\n * after activation failure or callback failure, and the callback error is\n * preserved when settlement also fails.\n */\nexport async function runProtectedAgentCandidateModelGrant<TResult>(\n options: RunProtectedAgentCandidateModelGrantOptions<TResult>,\n): Promise<RunProtectedAgentCandidateModelGrantResult<TResult>> {\n if (typeof options.execute !== 'function') {\n throw new TypeError('protected model grant execute callback is required')\n }\n\n const resolved = await options.port.resolve(options.resolve)\n const reservation = await options.port.reserveGrant({\n ...options.reserve,\n resolved,\n })\n\n let value!: TResult\n let executionError: unknown\n let executionFailed = false\n let activated = false\n let reason: AgentCandidateModelGrantSettleInput['reason'] = 'preparation-failed'\n\n try {\n const activation = await options.port.activateGrant({\n executionId: options.reserve.executionId,\n preparationId: options.reserve.preparationId,\n grantDigest: reservation.digest,\n resolved,\n deadlineAtMs: options.deadlineAtMs,\n })\n activated = true\n value = await options.execute({ activation, reservation, resolved })\n reason = 'completed'\n } catch (error) {\n executionError = error\n executionFailed = true\n if (activated) reason = 'failed'\n }\n\n let settlement: AgentCandidateProtectedModelSettlement\n try {\n settlement = await settleProtectedModelGrant(options, {\n executionId: options.reserve.executionId,\n preparationId: options.reserve.preparationId,\n grantDigest: reservation.digest,\n resolved,\n reason,\n })\n } catch (settlementError) {\n if (executionFailed) {\n throw new AggregateError(\n [executionError, settlementError],\n 'protected model execution failed and its grant did not settle',\n )\n }\n throw settlementError\n }\n\n if (executionFailed) throw executionError\n return { value, resolved, reservation, settlement }\n}\n\nasync function settleProtectedModelGrant<TResult>(\n options: RunProtectedAgentCandidateModelGrantOptions<TResult>,\n input: AgentCandidateModelGrantSettleInput,\n): Promise<AgentCandidateProtectedModelSettlement> {\n let delayMs = SETTLEMENT_RETRY_INITIAL_DELAY_MS\n for (;;) {\n try {\n return await options.port.settleGrant(input)\n } catch (error) {\n if (!isCandidateGrantDrainingError(error)) throw error\n const remainingMs = options.deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw error\n await waitForSettlementRetry(Math.min(delayMs, remainingMs))\n if (Date.now() >= options.deadlineAtMs) throw error\n delayMs = Math.min(delayMs * 2, SETTLEMENT_RETRY_MAX_DELAY_MS)\n }\n }\n}\n\nfunction waitForSettlementRetry(delayMs: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delayMs))\n}\n\n/** Only the gateway's explicit draining state is retryable; auth and ledger errors fail closed. */\nfunction isCandidateGrantDrainingError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false\n const candidate = error as { code?: unknown; message?: unknown }\n if (candidate.code === 'candidate_grant_draining') return true\n return (\n typeof candidate.message === 'string' && /\\bcandidate_grant_draining\\b/u.test(candidate.message)\n )\n}\n","import { lstat } from 'node:fs/promises'\nimport { isAbsolute, resolve } from 'node:path'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateWorkspaceSnapshotEvidence,\n agentCandidateArtifactRefSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n} from '@tangle-network/agent-interface'\nimport { verifiedArtifactChunks } from './artifact-streams'\nimport { canonicalCandidateBytes, deepFreezeCandidate } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\nimport { type AgentCandidateWorkspaceArchiveLimits, workspaceLimits } from './workspace-archive'\nimport {\n type CaptureAgentCandidateWorkspaceOptions,\n captureAgentCandidateWorkspace,\n createAgentCandidateWorkspacePort,\n} from './workspace-archive-local'\n\n/** The canonical workspace evidence without manifest material or embedded file bytes. */\nexport type AgentCandidateWorkspaceSnapshotReferences = Pick<\n AgentCandidateWorkspaceSnapshotEvidence,\n 'kind' | 'digest'\n> & {\n readonly manifest: AgentCandidateArtifactRef\n readonly archive: AgentCandidateArtifactRef\n}\n\nexport type CaptureAgentWorkspaceSnapshotOptions = Omit<\n CaptureAgentCandidateWorkspaceOptions,\n 'artifactPersistence'\n> & {\n artifactPersistence: NonNullable<CaptureAgentCandidateWorkspaceOptions['artifactPersistence']>\n}\n\n/**\n * Capture through the canonical archive owner and return references only.\n * The caller holds its existing private source workspace lease throughout capture, and binds\n * its public source provenance at the SDK boundary. Choose includeRepository and working-tree\n * explicitly when staged, dirty, deleted and unignored untracked Git files must travel.\n */\nexport async function captureAgentWorkspaceSnapshot(\n root: string,\n options: CaptureAgentWorkspaceSnapshotOptions,\n): Promise<AgentCandidateWorkspaceSnapshotReferences> {\n if (!options?.artifactPersistence) {\n throw new Error('portable workspace capture requires artifactPersistence')\n }\n const captured = await captureAgentCandidateWorkspace(root, {\n ...options,\n ...(options.limits ? { limits: { ...options.limits } } : {}),\n artifactPersistence: { ...options.artifactPersistence },\n })\n return workspaceReferences(captured.snapshot)\n}\n\nexport interface MaterializeAgentWorkspaceSnapshotOptions {\n snapshot: AgentCandidateWorkspaceSnapshotReferences\n /** Authorizes each immutable reference for the accepted transfer owner; must stream reads. */\n artifacts: AgentCandidateArtifactPort\n /** Absent destination inside a caller-owned private allocation scope. */\n destination: string\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n signal?: AbortSignal\n}\n\n/**\n * Restore canonical workspace references before an agent starts.\n * The SDK boundary validates source provenance and the accepted snapshot digest before this\n * byte-level composition runs. Artifact references identify content; the injected port owns\n * authorization. The archive owner verifies all files and Git state before publishing fresh\n * staging. Destinations present before or during artifact reads are refused. The caller owns\n * the allocation scope against other writers; Node directory rename is not atomic no-replace.\n */\nexport async function materializeAgentWorkspaceSnapshot(\n input: MaterializeAgentWorkspaceSnapshotOptions,\n): Promise<void> {\n input.signal?.throwIfAborted()\n const snapshot = workspaceReferences(input.snapshot)\n const limits = workspaceLimits(input.limits)\n if (!input.artifacts.readStream) {\n throw new Error('portable workspace restore requires an authorized readStream')\n }\n if (!isAbsolute(input.destination)) {\n throw new Error('portable workspace destination must be absolute')\n }\n const destination = resolve(input.destination)\n await assertAbsentDestination(destination)\n for (const artifact of [snapshot.manifest, snapshot.archive]) {\n if (artifact.byteLength > limits.maxArchiveBytes) {\n throw new Error('portable workspace artifact exceeds maxArchiveBytes')\n }\n }\n const manifest = await readArtifact(snapshot.manifest, input.artifacts, input.signal)\n const material = agentCandidateWorkspaceManifestMaterialSchema.parse(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(manifest)),\n )\n if (!Buffer.from(canonicalCandidateBytes(material)).equals(manifest)) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n const evidence = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({ ...snapshot, material })\n const archive = await readArtifact(snapshot.archive, input.artifacts, input.signal)\n input.signal?.throwIfAborted()\n // The artifact resolver may await remote storage. A destination that appeared while waiting\n // belongs to its creator, even when it is empty.\n await assertAbsentDestination(destination)\n input.signal?.throwIfAborted()\n await createAgentCandidateWorkspacePort({ limits }).materialize({\n role: 'task',\n snapshot: evidence,\n archive,\n destination,\n ...(input.signal ? { signal: input.signal } : {}),\n })\n}\n\nfunction workspaceReferences(\n snapshot: Pick<\n AgentCandidateWorkspaceSnapshotEvidence,\n 'kind' | 'digest' | 'manifest' | 'archive'\n >,\n): AgentCandidateWorkspaceSnapshotReferences {\n if (snapshot.kind !== 'agent-candidate-workspace-snapshot') {\n throw new Error('portable workspace snapshot kind is invalid')\n }\n const manifest = agentCandidateArtifactRefSchema.parse(snapshot.manifest)\n const archive = agentCandidateArtifactRefSchema.parse(snapshot.archive)\n for (const artifact of [manifest, archive]) {\n if (!Number.isSafeInteger(artifact.byteLength) || artifact.byteLength < 1) {\n throw new Error('portable workspace artifacts require positive safe byte lengths')\n }\n }\n if (snapshot.digest !== manifest.sha256) {\n throw new Error('workspace digest must equal the canonical manifest hash')\n }\n return deepFreezeCandidate({ kind: snapshot.kind, digest: snapshot.digest, manifest, archive })\n}\n\nasync function readArtifact(\n reference: AgentCandidateArtifactRef,\n artifacts: AgentCandidateArtifactPort,\n signal?: AbortSignal,\n): Promise<Buffer> {\n const chunks: Buffer[] = []\n for await (const chunk of verifiedArtifactChunks(reference, artifacts, signal)) {\n chunks.push(Buffer.from(chunk))\n }\n return Buffer.concat(chunks)\n}\n\nasync function assertAbsentDestination(destination: string): Promise<void> {\n try {\n await lstat(destination)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n throw new Error('portable workspace destination already exists')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,SAAgB,0BACd,OAC6C;CAU7C,OAAO,yBAAyB;EAR9B,MAAM;EACN,iBAAiB;EACjB,SAAS,wBAAwB,MAAM,OAAO;EAC9C,MAAM,qBAAqB,MAAM,IAAI;EACrC,WAAW,MAAM;EACjB,GAAI,MAAM,cAAc,KAAA,IAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;EACtE,QAAQ,MAAM;CAEqB,CAAC;AACxC;AAEA,SAAS,wBAAwB,QAA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AiE;CAGrF,IAAI,SAAS,WAAW,SAAS,QAC/B,MAAM,IAAI,MAAM,yDAAyD;CAE3E,OAAO,oBAAoB;EAAE,MAAM,SAAS;EAAM,QAAQ,SAAS;EAAQ;EAAU;CAAQ,CAAC;AAChG;AAEA,eAAe,aACb,WACA,WACA,QACiB;CACjB,MAAM,SAAmB,CAAC;CAC1B,WAAW,MAAM,SAAS,uBAAuB,WAAW,WAAW,MAAM,GAC3E,OAAO,KAAK,OAAO,KAAK,KAAK,CAAC;CAEhC,OAAO,OAAO,OAAO,MAAM;AAC7B;AAEA,eAAe,wBAAwB,aAAoC;CACzE,IAAI;EACF,MAAM,MAAM,WAAW;CACzB,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU;EACxD,MAAM;CACR;CACA,MAAM,IAAI,MAAM,+CAA+C;AACjE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["canonicalCandidateBytes","canonicalCandidateBytes"],"sources":["../../src/candidate-execution/builder.ts","../../src/candidate-execution/claim-file-store.ts","../../src/candidate-execution/dispose.ts","../../src/candidate-execution/protected-model-grant.ts","../../src/candidate-execution/workspace-transfer.ts"],"sourcesContent":["import type { CodeSurface } from '@tangle-network/agent-eval/campaign'\nimport { verifyCodeSurface } from '@tangle-network/agent-eval/campaign'\nimport type {\n AgentCandidateCodeDisabled,\n AgentCandidateCodeNoOp,\n AgentCandidateExecution,\n AgentCandidateGitHubRepository,\n AgentCandidateKnowledge,\n AgentCandidateMemoryPolicy,\n AgentCandidateProfile,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { type AgentCandidateBundleInput, sealAgentCandidateBundle } from './bundle'\nimport { embeddedCandidateArtifact } from './digest'\nimport {\n applyExactAgentProfileDiff,\n freezeGenericAgentCandidateProfile,\n parseExactAgentProfile,\n parseExactAgentProfileDiff,\n parseExactCandidateProfile,\n} from './profile'\n\n/** A complete profile that can be frozen without losing behavior. */\nexport type AgentCandidateProfileSource =\n | {\n kind: 'profile'\n profile: AgentProfile\n }\n | {\n kind: 'profile-diffs'\n base: AgentProfile\n /** Applied in order before the resulting profile is frozen into the bundle. */\n diffs: readonly AgentProfileDiff[]\n }\n | {\n kind: 'candidate-profile'\n /** Already converted to the closed, secret-free candidate profile contract. */\n profile: AgentCandidateProfile\n }\n\n/** The only accepted path from an agent-eval code candidate to executable bytes. */\nexport interface AgentCandidateCodeSurfaceSource {\n kind: 'code-surface'\n surface: CodeSurface\n repository: AgentCandidateGitHubRepository\n /** Optional parent directory used to resolve a relative `surface.worktreeRef`. */\n worktreeDir?: string\n}\n\n/** Explicit control/no-op code or one finalized CodeSurface whose bytes must still verify. */\nexport type AgentCandidateCodeSource =\n | AgentCandidateCodeDisabled\n | AgentCandidateCodeNoOp\n | AgentCandidateCodeSurfaceSource\n\n/** Complete measured surfaces and execution policy compiled into one candidate bundle. */\nexport interface BuildAgentCandidateBundleInput {\n profile: AgentCandidateProfileSource\n code: AgentCandidateCodeSource\n execution: AgentCandidateExecution\n knowledge?: AgentCandidateKnowledge\n memory: AgentCandidateMemoryPolicy\n}\n\n/**\n * Compile one measured profile/code candidate into the immutable execution\n * contract. Code bytes are re-read and verified by agent-eval before they are\n * embedded. The returned bundle is schema-validated, canonically digested, and\n * deeply immutable; call `verifyAgentCandidateBundle` at the execution boundary\n * to re-read external memory, repository, and workspace artifacts.\n */\nexport function buildAgentCandidateBundle(\n input: BuildAgentCandidateBundleInput,\n): ReturnType<typeof sealAgentCandidateBundle> {\n const bundle: AgentCandidateBundleInput = {\n kind: 'agent-candidate-bundle',\n digestAlgorithm: 'rfc8785-sha256',\n profile: compileCandidateProfile(input.profile),\n code: compileCandidateCode(input.code),\n execution: input.execution,\n ...(input.knowledge !== undefined ? { knowledge: input.knowledge } : {}),\n memory: input.memory,\n }\n return sealAgentCandidateBundle(bundle)\n}\n\nfunction compileCandidateProfile(source: AgentCandidateProfileSource): AgentCandidateProfile {\n if (source.kind === 'candidate-profile') {\n return parseExactCandidateProfile(source.profile)\n }\n\n if (source.kind === 'profile') {\n return freezeGenericAgentCandidateProfile(source.profile)\n }\n\n if (source.kind !== 'profile-diffs') {\n throw new Error(\n `unsupported candidate profile source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n if (source.diffs.length === 0) {\n throw new Error('profile-diffs source requires at least one AgentProfileDiff')\n }\n let profile = parseExactAgentProfile(source.base, 'base profile')\n for (const [index, inputDiff] of source.diffs.entries()) {\n const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`)\n profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`)\n }\n return freezeGenericAgentCandidateProfile(profile)\n}\n\nfunction compileCandidateCode(source: AgentCandidateCodeSource): AgentCandidateBundleInput['code'] {\n if (source.kind === 'disabled' || source.kind === 'no-op') return source\n if (source.kind !== 'code-surface') {\n throw new Error(\n `unsupported candidate code source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n\n const verified = verifyCodeSurface(source.surface, source.worktreeDir)\n const patch = embeddedCandidateArtifact(verified.patchBytes)\n if (\n patch.sha256 !== source.surface.patch.sha256 ||\n patch.byteLength !== source.surface.patch.byteLength\n ) {\n throw new Error('verified CodeSurface patch bytes do not match its content identity')\n }\n return {\n kind: 'git-patch',\n repository: source.repository,\n baseCommit: source.surface.baseCommit,\n baseTree: source.surface.baseTree,\n candidateTree: source.surface.candidateTree,\n patch: { format: 'git-diff-binary', artifact: patch },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { linkSync } from 'node:fs'\nimport { mkdir, open, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport {\n type AgentCandidateExecutionAttemptRecord,\n type AgentCandidateExecutionAttemptRef,\n type AgentCandidateExecutionClaim,\n type AgentCandidateExecutionClaimResult,\n type AgentCandidateExecutionClaimStore,\n type AgentCandidateExecutionFinishResult,\n type AgentCandidateExecutionLease,\n type AgentCandidateExecutionPhase,\n type AgentCandidateExecutionPhaseResult,\n type AgentCandidateExecutionRecoveryEvidence,\n type AgentCandidateExecutionStageResult,\n type AgentCandidateExecutionTerminalRecord,\n type AgentCandidateExecutionTerminalResult,\n type AgentCandidateRetryRejection,\n candidateClaimFileInternals,\n} from './claim'\nimport {\n assertRecoveryMatchesStaged,\n assertTerminalAllowedInPhase,\n assertTerminalMatchesClaim,\n assertTerminalMatchesStaged,\n recoveredTerminalRecord,\n rejectedFinish,\n rejectedStage,\n requireStagedTerminal,\n sealTerminalDigest,\n terminalRecord,\n} from './claim-terminal'\nimport { canonicalCandidateBytes } from './digest'\n\nconst {\n assertExpiredLease,\n assertLease,\n assertSameSlot,\n assertUnexpiredLease,\n attemptRecord,\n claimSlot,\n leaseDigest,\n newLease,\n readClaim,\n readClaimIfPresent,\n readTerminal,\n readTerminalIfPresent,\n readTransitionIfPresent,\n rejectedExistingClaim,\n rejectedRetry,\n retryRejection,\n sealAttemptRef,\n sealClaim,\n sealLease,\n} = candidateClaimFileInternals\n\nexport interface FileAgentCandidateExecutionClaimStoreOptions {\n /** Evaluator-owned directory shared by every process allowed to execute candidates. */\n directory: string\n /** Testable evaluator clock; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** Cross-process lifecycle implemented as fsynced, create-if-absent records. */\nexport class FileAgentCandidateExecutionClaimStore implements AgentCandidateExecutionClaimStore {\n private readonly directory: string\n private readonly now: () => number\n\n constructor(options: FileAgentCandidateExecutionClaimStoreOptions) {\n if (options.directory.length === 0) {\n throw new Error('candidate execution claim directory must not be empty')\n }\n this.directory = options.directory\n this.now = options.now ?? Date.now\n }\n\n async tryClaim(\n requested: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateExecutionClaimResult> {\n const claim = sealClaim(requested)\n await mkdir(this.directory, { recursive: true })\n const claimPath = this.claimPath(claim)\n const existing = await readClaimIfPresent(claimPath)\n if (existing) {\n assertSameSlot(existing.claim, claim, claimPath)\n return rejectedExistingClaim(existing.claim, claim)\n }\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n const retryFailure = await this.retryFailure(claim)\n if (retryFailure) return rejectedRetry(claim, retryFailure)\n\n const lease = newLease(claim)\n const acquired = await writeRecordIfAbsent(this.directory, claimPath, {\n ...claim,\n phase: 'claimed',\n leaseDigest: leaseDigest(lease),\n })\n if (acquired) return Object.freeze({ acquired: true, claim, lease })\n\n const winner = await readClaim(claimPath)\n assertSameSlot(winner.claim, claim, claimPath)\n return rejectedExistingClaim(winner.claim, claim)\n }\n\n async getAttempt(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n return await this.storedAttempt(sealAttemptRef(requestedAttempt))\n }\n\n async markCandidateMayRun(\n requestedLease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n if (state.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n if (state.staged) {\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const marked = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, 1),\n {\n kind: 'candidate-execution-phase',\n executionId: stored.claim.executionId,\n attempt: stored.claim.attempt,\n executionPlanDigest: stored.claim.executionPlanDigest,\n phase: 'candidate-may-run',\n },\n this.ownerPublication(stored.claim),\n )\n if (marked) return Object.freeze({ marked: true, phase: 'candidate-may-run' })\n const winner = await this.transitionState(stored.claim)\n if (winner.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n\n async stageTerminal(\n requestedLease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const terminal = terminalRecord(stored.claim, result)\n const state = await this.transitionState(stored.claim)\n if (state.staged) return rejectedStage(state.staged, terminal)\n assertTerminalAllowedInPhase(state.phase, terminal)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const transition = state.phase === 'claimed' ? 1 : 2\n const staged = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, transition),\n {\n kind: 'candidate-execution-pending-terminal',\n terminal,\n },\n this.ownerPublication(stored.claim),\n )\n if (staged) return Object.freeze({ staged: true, terminal })\n const winner = await this.transitionState(stored.claim)\n if (!winner.staged) {\n throw new Error('candidate execution phase transition won while staging terminal')\n }\n return rejectedStage(winner.staged, terminal)\n }\n\n async finish(\n requestedLease: AgentCandidateExecutionLease,\n requestedTerminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const lease = sealLease(requestedLease)\n const terminalDigest = sealTerminalDigest(requestedTerminalDigest)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n const staged = requireStagedTerminal(state.staged, terminalDigest)\n const terminalPath = this.terminalPath(lease)\n const existing = await readTerminalIfPresent(terminalPath)\n if (existing) {\n assertTerminalMatchesClaim(existing, stored.claim, terminalPath)\n assertTerminalMatchesStaged(existing, staged, terminalPath)\n return rejectedFinish(existing, terminalDigest)\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const finished = await writeRecordIfAbsent(\n this.directory,\n terminalPath,\n {\n terminal: staged,\n },\n this.ownerPublication(stored.claim),\n )\n if (finished) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, lease, terminalPath)\n assertTerminalMatchesClaim(winner, stored.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, terminalDigest)\n }\n\n async recoverExpired(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const attempt = sealAttemptRef(requestedAttempt)\n const record = await this.storedAttempt(attempt)\n if (!record) throw new Error('candidate execution recovery does not name an acquired attempt')\n const recovered = recoveredTerminalRecord(record.claim, record.phase, evidence)\n if (record.staged) assertRecoveryMatchesStaged(record.staged, recovered)\n const requestedDigest = record.staged?.terminalDigest ?? recovered.terminalDigest\n if (record.terminal) return rejectedFinish(record.terminal, requestedDigest)\n assertExpiredLease(record.claim.leaseExpiresAtMs, this.now())\n\n let staged = record.staged\n if (!staged) {\n const transition = record.phase === 'claimed' ? 1 : 2\n const didStage = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(record.claim, transition),\n {\n kind: 'candidate-execution-pending-terminal',\n terminal: recovered,\n },\n )\n if (didStage) {\n staged = recovered\n } else {\n const winner = await this.transitionState(record.claim)\n if (!winner.staged) {\n throw new Error(\n 'candidate execution recovery lost terminal staging to a phase transition',\n )\n }\n assertRecoveryMatchesStaged(winner.staged, recovered)\n staged = winner.staged\n }\n }\n\n const terminalPath = this.terminalPath(attempt)\n const didFinish = await writeRecordIfAbsent(this.directory, terminalPath, {\n terminal: staged,\n })\n if (didFinish) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, attempt, terminalPath)\n assertTerminalMatchesClaim(winner, record.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, staged.terminalDigest)\n }\n\n private async storedAttempt(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n const claimPath = this.claimPath(claim)\n const stored = await readClaimIfPresent(claimPath)\n if (!stored) return undefined\n assertSameSlot(stored.claim, claim, claimPath)\n const terminalPath = this.terminalPath(claim)\n const terminal = await readTerminalIfPresent(terminalPath)\n // Terminal publication follows its immutable staged outbox, so read that prerequisite later.\n const state = await this.transitionState(stored.claim)\n if (terminal) {\n assertTerminalMatchesClaim(terminal, stored.claim, terminalPath)\n if (!state.staged) {\n throw new Error(\n `candidate execution terminal record at ${terminalPath} has no staged outbox`,\n )\n }\n assertTerminalMatchesStaged(terminal, state.staged, terminalPath)\n }\n return attemptRecord(stored.claim, state.phase, state.staged, terminal)\n }\n\n private async transitionState(claim: AgentCandidateExecutionClaim): Promise<{\n phase: AgentCandidateExecutionPhase\n staged?: AgentCandidateExecutionTerminalRecord\n }> {\n const firstPath = this.transitionPath(claim, 1)\n const first = await readTransitionIfPresent(firstPath, claim)\n if (!first) return { phase: 'claimed' }\n if (first.kind === 'pending') return { phase: 'claimed', staged: first.terminal }\n const secondPath = this.transitionPath(claim, 2)\n const second = await readTransitionIfPresent(secondPath, claim)\n if (!second) return { phase: 'candidate-may-run' }\n if (second.kind !== 'pending') {\n throw new Error(`candidate execution transition at ${secondPath} repeats the phase marker`)\n }\n return { phase: 'candidate-may-run', staged: second.terminal }\n }\n\n private async retryFailure(\n claim: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateRetryRejection | undefined> {\n if (claim.attempt === 1) return undefined\n return retryRejection(\n claim,\n await this.storedAttempt({\n executionId: claim.executionId,\n attempt: claim.attempt - 1,\n }),\n )\n }\n\n private ownerPublication(claim: AgentCandidateExecutionClaim): {\n authorizePublish: () => true\n } {\n return {\n authorizePublish: () => {\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n return true\n },\n }\n }\n\n private claimPath(claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>): string {\n return join(this.directory, `${claimSlot(claim)}.claim.json`)\n }\n\n private terminalPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.terminal.json`)\n }\n\n private transitionPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ordinal: 1 | 2,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.transition-${ordinal}.json`)\n }\n}\n\n/**\n * Candidate records keep this async writer because lease authorization must run after the\n * asynchronous temp-file fsync and immediately before synchronous link publication. The\n * supervisor durability helper is synchronous and has no lease hook, so combining them would\n * either move authorization earlier or add an async race to the claim boundary.\n */\nasync function writeRecordIfAbsent(\n directory: string,\n destination: string,\n record: object,\n options: {\n /** Synchronous authorization checked after temp fsync, immediately before atomic publication. */\n authorizePublish?: () => true\n } = {},\n): Promise<boolean> {\n const temporaryPath = join(directory, `.candidate-execution-${process.pid}-${randomUUID()}.tmp`)\n const handle = await open(temporaryPath, 'wx', 0o600)\n try {\n await handle.writeFile(\n Buffer.concat([Buffer.from(canonicalCandidateBytes(record)), Buffer.from('\\n')]),\n )\n await handle.sync()\n } finally {\n await handle.close()\n }\n\n let written = false\n try {\n if (options.authorizePublish && options.authorizePublish() !== true) {\n throw new Error('candidate execution record publication was not authorized')\n }\n // Authorization and the atomic filesystem call are one synchronous critical\n // section so the event loop cannot advance an injected lease clock between them.\n linkSync(temporaryPath, destination)\n written = true\n await syncDirectory(directory)\n } catch (error) {\n if (!isNodeError(error, 'EEXIST')) throw error\n } finally {\n await unlink(temporaryPath).catch((error: unknown) => {\n if (!isNodeError(error, 'ENOENT')) throw error\n })\n }\n return written\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n const handle = await open(directory, 'r')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n )\n}\n","import { candidateCleanupDeadline, withinCandidateCleanupDeadline } from './cleanup'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport {\n assertPreparedCandidateIntegrity,\n beginPreparedCandidateDisposal,\n consumePreparedCandidateExecution,\n} from './prepared-state'\nimport type { PreparedAgentCandidateExecution } from './types'\n\nexport interface DisposePreparedAgentCandidateOptions {\n cleanupTimeoutMs?: number\n}\n\n/** Revoke reservations held by a prepared candidate that will not be executed. */\nexport async function disposePreparedAgentCandidateExecution(\n prepared: PreparedAgentCandidateExecution,\n options: DisposePreparedAgentCandidateOptions = {},\n): Promise<{ disposed: true }> {\n const initialState = assertPreparedCandidateIntegrity(prepared)\n const cleanupTimeoutMs = options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs\n if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {\n throw new Error('disposal cleanup timeout exceeds the frozen preparation bound')\n }\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const state = beginPreparedCandidateDisposal(prepared)\n const cleanup: Array<Promise<unknown>> = []\n\n if (state.memory.mode === 'isolated') {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const closed = await state.ports.memory.close({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n reason: 'abandoned',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('abandoned isolated memory access did not acknowledge closure')\n }\n },\n cleanupDeadlineAtMs,\n 'isolated memory disposal',\n ),\n )\n }\n\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const settlement = sealAgentCandidateModelSettlement(\n await state.ports.models.settleGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n reason: 'abandoned',\n }),\n {\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n model: state.resolvedModel.model,\n },\n )\n if (settlement.usage.modelCalls !== 0) {\n throw new Error('unexecuted model reservation unexpectedly contains calls')\n }\n },\n cleanupDeadlineAtMs,\n 'model reservation disposal',\n ),\n )\n\n const results = await Promise.allSettled(cleanup)\n const failures = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason)\n if (failures.length > 0) {\n consumePreparedCandidateExecution(prepared, 'disposal-failed')\n throw new AggregateError(failures, 'candidate preparation disposal failed')\n }\n\n consumePreparedCandidateExecution(prepared, 'disposed')\n return Object.freeze({ disposed: true as const })\n}\n","import type { AgentCandidateResolvedModel } from '@tangle-network/agent-interface'\n\nimport type {\n AgentCandidateModelGrantActivateInput,\n AgentCandidateModelGrantReserveInput,\n AgentCandidateModelGrantSettleInput,\n} from './protected-model-port'\nimport type {\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\n/** Reservation fields supplied by a caller before Runtime resolves the model. */\nexport type AgentCandidateModelGrantRunReservationInput = Omit<\n AgentCandidateModelGrantReserveInput,\n 'resolved'\n>\n\n/** Values available only while one protected model grant is active. */\nexport interface ProtectedAgentCandidateModelGrantContext {\n readonly activation: AgentCandidateProtectedModelActivation\n readonly reservation: AgentCandidateProtectedModelReservation\n readonly resolved: AgentCandidateResolvedModel\n}\n\n/** Inputs for one protected grant scoped to one bounded caller unit. */\nexport interface RunProtectedAgentCandidateModelGrantOptions<TResult> {\n /** Runtime port that validates and settles the evaluator-owned grant. */\n readonly port: AgentCandidateModelPort\n /** Provider-neutral model request resolved before any grant is reserved. */\n readonly resolve: Parameters<AgentCandidateModelPort['resolve']>[0]\n /** One bounded unit's immutable identity, attempt, expiry, and limits. */\n readonly reserve: AgentCandidateModelGrantRunReservationInput\n /** Must be no later than the reservation expiry. */\n readonly deadlineAtMs: AgentCandidateModelGrantActivateInput['deadlineAtMs']\n /** Execute exactly one bounded unit while the activated environment is valid. */\n readonly execute: (context: ProtectedAgentCandidateModelGrantContext) => Promise<TResult>\n}\n\n/** Result and sealed settlement returned after one protected grant closes. */\nexport interface RunProtectedAgentCandidateModelGrantResult<TResult> {\n readonly value: TResult\n readonly resolved: AgentCandidateResolvedModel\n readonly reservation: AgentCandidateProtectedModelReservation\n readonly settlement: AgentCandidateProtectedModelSettlement\n}\n\nconst SETTLEMENT_RETRY_INITIAL_DELAY_MS = 25\nconst SETTLEMENT_RETRY_MAX_DELAY_MS = 1_000\n\n/**\n * Run one bounded unit under a protected model grant.\n *\n * Runtime owns the grant lifecycle; callers own the unit boundary and any\n * durable scheduling or accounting around it. A reserved grant is settled\n * after activation failure or callback failure, and the callback error is\n * preserved when settlement also fails.\n */\nexport async function runProtectedAgentCandidateModelGrant<TResult>(\n options: RunProtectedAgentCandidateModelGrantOptions<TResult>,\n): Promise<RunProtectedAgentCandidateModelGrantResult<TResult>> {\n if (typeof options.execute !== 'function') {\n throw new TypeError('protected model grant execute callback is required')\n }\n\n const resolved = await options.port.resolve(options.resolve)\n const reservation = await options.port.reserveGrant({\n ...options.reserve,\n resolved,\n })\n\n let value!: TResult\n let executionError: unknown\n let executionFailed = false\n let activated = false\n let reason: AgentCandidateModelGrantSettleInput['reason'] = 'preparation-failed'\n\n try {\n const activation = await options.port.activateGrant({\n executionId: options.reserve.executionId,\n preparationId: options.reserve.preparationId,\n grantDigest: reservation.digest,\n resolved,\n deadlineAtMs: options.deadlineAtMs,\n })\n activated = true\n value = await options.execute({ activation, reservation, resolved })\n reason = 'completed'\n } catch (error) {\n executionError = error\n executionFailed = true\n if (activated) reason = 'failed'\n }\n\n let settlement: AgentCandidateProtectedModelSettlement\n try {\n settlement = await settleProtectedModelGrant(options, {\n executionId: options.reserve.executionId,\n preparationId: options.reserve.preparationId,\n grantDigest: reservation.digest,\n resolved,\n reason,\n })\n } catch (settlementError) {\n if (executionFailed) {\n throw new AggregateError(\n [executionError, settlementError],\n 'protected model execution failed and its grant did not settle',\n )\n }\n throw settlementError\n }\n\n if (executionFailed) throw executionError\n return { value, resolved, reservation, settlement }\n}\n\nasync function settleProtectedModelGrant<TResult>(\n options: RunProtectedAgentCandidateModelGrantOptions<TResult>,\n input: AgentCandidateModelGrantSettleInput,\n): Promise<AgentCandidateProtectedModelSettlement> {\n let delayMs = SETTLEMENT_RETRY_INITIAL_DELAY_MS\n for (;;) {\n try {\n return await options.port.settleGrant(input)\n } catch (error) {\n if (!isCandidateGrantDrainingError(error)) throw error\n const remainingMs = options.deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw error\n await waitForSettlementRetry(Math.min(delayMs, remainingMs))\n if (Date.now() >= options.deadlineAtMs) throw error\n delayMs = Math.min(delayMs * 2, SETTLEMENT_RETRY_MAX_DELAY_MS)\n }\n }\n}\n\nfunction waitForSettlementRetry(delayMs: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, delayMs))\n}\n\n/** Only the gateway's explicit draining state is retryable; auth and ledger errors fail closed. */\nfunction isCandidateGrantDrainingError(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false\n const candidate = error as { code?: unknown; message?: unknown }\n if (candidate.code === 'candidate_grant_draining') return true\n return (\n typeof candidate.message === 'string' && /\\bcandidate_grant_draining\\b/u.test(candidate.message)\n )\n}\n","import { lstat } from 'node:fs/promises'\nimport { isAbsolute, resolve } from 'node:path'\nimport {\n type AgentCandidateArtifactRef,\n type AgentCandidateWorkspaceSnapshotEvidence,\n agentCandidateArtifactRefSchema,\n agentCandidateWorkspaceManifestMaterialSchema,\n agentCandidateWorkspaceSnapshotEvidenceSchema,\n} from '@tangle-network/agent-interface'\nimport { verifiedArtifactChunks } from './artifact-streams'\nimport { canonicalCandidateBytes, deepFreezeCandidate } from './digest'\nimport type { AgentCandidateArtifactPort } from './types'\nimport { type AgentCandidateWorkspaceArchiveLimits, workspaceLimits } from './workspace-archive'\nimport {\n type CaptureAgentCandidateWorkspaceOptions,\n captureAgentCandidateWorkspace,\n createAgentCandidateWorkspacePort,\n} from './workspace-archive-local'\n\n/** The canonical workspace evidence without manifest material or embedded file bytes. */\nexport type AgentCandidateWorkspaceSnapshotReferences = Pick<\n AgentCandidateWorkspaceSnapshotEvidence,\n 'kind' | 'digest'\n> & {\n readonly manifest: AgentCandidateArtifactRef\n readonly archive: AgentCandidateArtifactRef\n}\n\nexport type CaptureAgentWorkspaceSnapshotOptions = Omit<\n CaptureAgentCandidateWorkspaceOptions,\n 'artifactPersistence'\n> & {\n artifactPersistence: NonNullable<CaptureAgentCandidateWorkspaceOptions['artifactPersistence']>\n}\n\n/**\n * Capture through the canonical archive owner and return references only.\n * The caller holds its existing private source workspace lease throughout capture, and binds\n * its public source provenance at the SDK boundary. Choose includeRepository and working-tree\n * explicitly when staged, dirty, deleted and unignored untracked Git files must travel.\n */\nexport async function captureAgentWorkspaceSnapshot(\n root: string,\n options: CaptureAgentWorkspaceSnapshotOptions,\n): Promise<AgentCandidateWorkspaceSnapshotReferences> {\n if (!options?.artifactPersistence) {\n throw new Error('portable workspace capture requires artifactPersistence')\n }\n const captured = await captureAgentCandidateWorkspace(root, {\n ...options,\n ...(options.limits ? { limits: { ...options.limits } } : {}),\n artifactPersistence: { ...options.artifactPersistence },\n })\n return workspaceReferences(captured.snapshot)\n}\n\nexport interface MaterializeAgentWorkspaceSnapshotOptions {\n snapshot: AgentCandidateWorkspaceSnapshotReferences\n /** Authorizes each immutable reference for the accepted transfer owner; must stream reads. */\n artifacts: AgentCandidateArtifactPort\n /** Absent destination inside a caller-owned private allocation scope. */\n destination: string\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n signal?: AbortSignal\n}\n\n/**\n * Restore canonical workspace references before an agent starts.\n * The SDK boundary validates source provenance and the accepted snapshot digest before this\n * byte-level composition runs. Artifact references identify content; the injected port owns\n * authorization. The archive owner verifies all files and Git state before publishing fresh\n * staging. Destinations present before or during artifact reads are refused. The caller owns\n * the allocation scope against other writers; Node directory rename is not atomic no-replace.\n */\nexport async function materializeAgentWorkspaceSnapshot(\n input: MaterializeAgentWorkspaceSnapshotOptions,\n): Promise<void> {\n input.signal?.throwIfAborted()\n const snapshot = workspaceReferences(input.snapshot)\n const limits = workspaceLimits(input.limits)\n if (!input.artifacts.readStream) {\n throw new Error('portable workspace restore requires an authorized readStream')\n }\n if (!isAbsolute(input.destination)) {\n throw new Error('portable workspace destination must be absolute')\n }\n const destination = resolve(input.destination)\n await assertAbsentDestination(destination)\n for (const artifact of [snapshot.manifest, snapshot.archive]) {\n if (artifact.byteLength > limits.maxArchiveBytes) {\n throw new Error('portable workspace artifact exceeds maxArchiveBytes')\n }\n }\n const manifest = await readArtifact(snapshot.manifest, input.artifacts, input.signal)\n const material = agentCandidateWorkspaceManifestMaterialSchema.parse(\n JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(manifest)),\n )\n if (!Buffer.from(canonicalCandidateBytes(material)).equals(manifest)) {\n throw new Error('workspace manifest artifact is not the exact canonical manifest material')\n }\n const evidence = agentCandidateWorkspaceSnapshotEvidenceSchema.parse({ ...snapshot, material })\n const archive = await readArtifact(snapshot.archive, input.artifacts, input.signal)\n input.signal?.throwIfAborted()\n // The artifact resolver may await remote storage. A destination that appeared while waiting\n // belongs to its creator, even when it is empty.\n await assertAbsentDestination(destination)\n input.signal?.throwIfAborted()\n await createAgentCandidateWorkspacePort({ limits }).materialize({\n role: 'task',\n snapshot: evidence,\n archive,\n destination,\n ...(input.signal ? { signal: input.signal } : {}),\n })\n}\n\nfunction workspaceReferences(\n snapshot: Pick<\n AgentCandidateWorkspaceSnapshotEvidence,\n 'kind' | 'digest' | 'manifest' | 'archive'\n >,\n): AgentCandidateWorkspaceSnapshotReferences {\n if (snapshot.kind !== 'agent-candidate-workspace-snapshot') {\n throw new Error('portable workspace snapshot kind is invalid')\n }\n const manifest = agentCandidateArtifactRefSchema.parse(snapshot.manifest)\n const archive = agentCandidateArtifactRefSchema.parse(snapshot.archive)\n for (const artifact of [manifest, archive]) {\n if (!Number.isSafeInteger(artifact.byteLength) || artifact.byteLength < 1) {\n throw new Error('portable workspace artifacts require positive safe byte lengths')\n }\n }\n if (snapshot.digest !== manifest.sha256) {\n throw new Error('workspace digest must equal the canonical manifest hash')\n }\n return deepFreezeCandidate({ kind: snapshot.kind, digest: snapshot.digest, manifest, archive })\n}\n\nasync function readArtifact(\n reference: AgentCandidateArtifactRef,\n artifacts: AgentCandidateArtifactPort,\n signal?: AbortSignal,\n): Promise<Buffer> {\n const chunks: Buffer[] = []\n for await (const chunk of verifiedArtifactChunks(reference, artifacts, signal)) {\n chunks.push(Buffer.from(chunk))\n }\n return Buffer.concat(chunks)\n}\n\nasync function assertAbsentDestination(destination: string): Promise<void> {\n try {\n await lstat(destination)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n throw new Error('portable workspace destination already exists')\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,SAAgB,0BACd,OAC6C;CAC7C,MAAM,SAAoC;EACxC,MAAM;EACN,iBAAiB;EACjB,SAAS,wBAAwB,MAAM,OAAO;EAC9C,MAAM,qBAAqB,MAAM,IAAI;EACrC,WAAW,MAAM;EACjB,GAAI,MAAM,cAAc,KAAA,IAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;EACtE,QAAQ,MAAM;CAChB;CACA,OAAO,yBAAyB,MAAM;AACxC;AAEA,SAAS,wBAAwB,QAA4D;CAC3F,IAAI,OAAO,SAAS,qBAClB,OAAO,2BAA2B,OAAO,OAAO;CAGlD,IAAI,OAAO,SAAS,WAClB,OAAO,mCAAmC,OAAO,OAAO;CAG1D,IAAI,OAAO,SAAS,iBAClB,MAAM,IAAI,MACR,yCAAyC,OAAQ,OAA8B,IAAI,GACrF;CAEF,IAAI,OAAO,MAAM,WAAW,GAC1B,MAAM,IAAI,MAAM,6DAA6D;CAE/E,IAAI,UAAU,uBAAuB,OAAO,MAAM,cAAc;CAChE,KAAK,MAAM,CAAC,OAAO,cAAc,OAAO,MAAM,QAAQ,GAAG;EACvD,MAAM,OAA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