@tangle-network/agent-runtime 0.174.1 → 0.177.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/{activation-CsdJWRXX.js → activation-XVI_z1g3.js} +3 -3
- package/dist/{activation-CsdJWRXX.js.map → activation-XVI_z1g3.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -2
- package/dist/{authoring-DsLNInAz.js → authoring-bXmPNfCI.js} +2 -2
- package/dist/{authoring-DsLNInAz.js.map → authoring-bXmPNfCI.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-BbMbyhgC.js → candidate-execution-fBNUyWyE.js} +10 -4
- package/dist/candidate-execution-fBNUyWyE.js.map +1 -0
- package/dist/{conversation-7XGKoDM6.js → conversation-BREx2hi-.js} +3 -3
- package/dist/{conversation-7XGKoDM6.js.map → conversation-BREx2hi-.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/coordination-driver-xO1tkxy-.js +3063 -0
- package/dist/coordination-driver-xO1tkxy-.js.map +1 -0
- package/dist/durable-file-g3YdfEh4.js +131 -0
- package/dist/durable-file-g3YdfEh4.js.map +1 -0
- package/dist/durable.d.ts +2 -2
- package/dist/durable.js +1 -1
- package/dist/{environment-provider-DWjbGH8W.d.ts → environment-provider-5E82esWE.d.ts} +6 -3
- package/dist/{environment-provider-Bn3652YU.js → environment-provider-DKyMWQJd.js} +121 -17
- package/dist/environment-provider-DKyMWQJd.js.map +1 -0
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-BbeHgLXH.js → graph-DwJXa1Ph.js} +3 -3
- package/dist/graph-DwJXa1Ph.js.map +1 -0
- package/dist/graph.d.ts +11 -3
- package/dist/graph.js +35 -4
- package/dist/graph.js.map +1 -1
- package/dist/{improvement-cycle-DKGDCukL.js → improvement-cycle-eiSv6aH4.js} +5 -5
- package/dist/{improvement-cycle-DKGDCukL.js.map → improvement-cycle-eiSv6aH4.js.map} +1 -1
- package/dist/{index-CIhkH7mq.d.ts → index-BnAiQVLD.d.ts} +290 -29
- package/dist/{index-CFMB9ux3.d.ts → index-Bs0uhf-y.d.ts} +2 -2
- package/dist/{index-Dk5X9eKg.d.ts → index-C9XTLVP1.d.ts} +4 -4
- package/dist/index.d.ts +7 -7
- package/dist/index.js +13 -13
- package/dist/intelligence.d.ts +4 -4
- package/dist/intelligence.js +6 -6
- package/dist/kernel.d.ts +6 -6
- package/dist/kernel.js +13 -11
- package/dist/{knowledge-BaAX0HVu.js → knowledge-Bmtj_7u7.js} +5 -5
- package/dist/{knowledge-BaAX0HVu.js.map → knowledge-Bmtj_7u7.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-DRYApMiu.d.ts → loop-runner-bin-ChS5deJ0.d.ts} +3 -3
- package/dist/{loop-runner-bin-D63Tytdk.js → loop-runner-bin-GTN5wqCt.js} +3 -3
- package/dist/{loop-runner-bin-D63Tytdk.js.map → loop-runner-bin-GTN5wqCt.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/{materialization-Ct3I4wu3.js → materialization-CekWK6OO.js} +5 -3
- package/dist/materialization-CekWK6OO.js.map +1 -0
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +3 -3
- package/dist/mcp/index.js +5 -4
- package/dist/mcp/index.js.map +1 -1
- package/dist/{openai-tools-BBgjWYNw.js → openai-tools-BBj1QGJp.js} +2 -2
- package/dist/{openai-tools-BBgjWYNw.js.map → openai-tools-BBj1QGJp.js.map} +1 -1
- package/dist/{prepare-BAyaNoZu.js → prepare-Tip-2ZoZ.js} +2 -2
- package/dist/{prepare-BAyaNoZu.js.map → prepare-Tip-2ZoZ.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/{protected-model-port-T2UWrDNQ.js → protected-model-port-Dd3a1SRm.js} +2 -2
- package/dist/{protected-model-port-T2UWrDNQ.js.map → protected-model-port-Dd3a1SRm.js.map} +1 -1
- package/dist/provision-supervisor-zA__ayUX.js +1020 -0
- package/dist/provision-supervisor-zA__ayUX.js.map +1 -0
- package/dist/{redact-DvLf4x1m.d.ts → redact-DkRLcSiE.d.ts} +3 -3
- package/dist/run-layout-Cd_l2XWV.js +645 -0
- package/dist/run-layout-Cd_l2XWV.js.map +1 -0
- package/dist/{runtime-D5u1M6T5.d.ts → runtime-B2eZ76kG.d.ts} +3 -3
- package/dist/{runtime-CojgP-hr.js → runtime-CJNlF5wM.js} +16 -1095
- package/dist/runtime-CJNlF5wM.js.map +1 -0
- package/dist/{spawn-journal-Tgvp5VS5.js → spawn-journal--N8Ten1q.js} +3 -1
- package/dist/{spawn-journal-Tgvp5VS5.js.map → spawn-journal--N8Ten1q.js.map} +1 -1
- package/dist/{stream-agent-turn-DxQ3GOuR.d.ts → stream-agent-turn-ByY8po9W.d.ts} +2 -2
- package/dist/{stream-agent-turn-CKIpCbSq.js → stream-agent-turn-CPj9SqVm.js} +2 -2
- package/dist/{stream-agent-turn-CKIpCbSq.js.map → stream-agent-turn-CPj9SqVm.js.map} +1 -1
- package/dist/{structural-rollout-BUYA61iV.js → structural-rollout-BeAUK7Ta.js} +4 -4
- package/dist/{structural-rollout-BUYA61iV.js.map → structural-rollout-BeAUK7Ta.js.map} +1 -1
- package/dist/{supervise-Ci0RfWQF.js → supervise-HsRKOlKY.js} +405 -3374
- package/dist/supervise-HsRKOlKY.js.map +1 -0
- package/dist/{supervisor-Bt1XLCVq.js → supervisor-ChLgoYhG.js} +1620 -33
- package/dist/supervisor-ChLgoYhG.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +13 -12
- package/dist/testing.js.map +1 -1
- package/dist/{top-app-3rYfFPTW.js → top-app-DIBApkt1.js} +25 -9
- package/dist/top-app-DIBApkt1.js.map +1 -0
- package/dist/tui/bin.js +1 -1
- package/dist/tui/index.d.ts +9 -1
- package/dist/tui/index.js +3 -2
- package/dist/{types-DjVO-p7R.d.ts → types-a2ZZUl80.d.ts} +25 -2
- package/dist/{workspace-archive-B0Hqp2eJ.js → workspace-archive-DOZAeeKU.js} +2 -2
- package/dist/{workspace-archive-B0Hqp2eJ.js.map → workspace-archive-DOZAeeKU.js.map} +1 -1
- package/package.json +5 -4
- package/dist/candidate-execution-BbMbyhgC.js.map +0 -1
- package/dist/environment-provider-Bn3652YU.js.map +0 -1
- package/dist/graph-BbeHgLXH.js.map +0 -1
- package/dist/materialization-Ct3I4wu3.js.map +0 -1
- package/dist/run-layout-C2jgwsCq.js +0 -393
- package/dist/run-layout-C2jgwsCq.js.map +0 -1
- package/dist/runtime-CojgP-hr.js.map +0 -1
- package/dist/supervise-Ci0RfWQF.js.map +0 -1
- package/dist/supervisor-Bt1XLCVq.js.map +0 -1
- package/dist/top-app-3rYfFPTW.js.map +0 -1
|
@@ -1,23 +1,24 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import "./
|
|
4
|
-
import { n as detachedSnapshot } from "./snapshot-CTAf4uuA.js";
|
|
5
|
-
import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, s as insideCursorNamespace, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal-Tgvp5VS5.js";
|
|
1
|
+
import { m as ValidationError, n as AnalystError, s as PlannerError } from "./errors-CDZ8XsVj.js";
|
|
2
|
+
import "./stream-agent-turn-CPj9SqVm.js";
|
|
3
|
+
import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, s as insideCursorNamespace, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal--N8Ten1q.js";
|
|
6
4
|
import { c as isAbortError, d as randomSuffix, i as cloneSpend, m as stringifySafe, p as sleep, r as chargedTokens, s as hasCompleteCacheBreakdown, t as addSpend, y as zeroSpend } from "./util-D6ZEuBMi.js";
|
|
7
5
|
import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-CDfsCI5s.js";
|
|
8
6
|
import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction--F3v1oo8.js";
|
|
9
|
-
import { c as notifySandboxEventObserver
|
|
7
|
+
import { c as notifySandboxEventObserver } from "./sandbox-events-BVjstFgb.js";
|
|
10
8
|
import { n as executableAgentSpecSnapshot, t as executableAgentProfileSnapshot } from "./executable-spec-CkGvdPds.js";
|
|
11
9
|
import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-Sw4ywhtL.js";
|
|
12
|
-
import {
|
|
13
|
-
import "./environment-provider-
|
|
10
|
+
import { Bt as probeSandboxCapabilities, Ht as routerBrain, It as defaultSelectWinner, Rt as runAgentRounds, Ut as runBrainLoop, W as rollingDispatch, Wt as canonicalObservedModel, at as createExecutorRegistry, f as withDriverExecutor, ht as createPushTraceSource, it as createExecutor, n as createSupervisor, st as createWorktreeCliExecutor, y as settledToIteration, zt as createSandboxLineage } from "./supervisor-ChLgoYhG.js";
|
|
11
|
+
import "./environment-provider-DKyMWQJd.js";
|
|
14
12
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
|
|
15
|
-
import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-
|
|
16
|
-
import
|
|
13
|
+
import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-BeAUK7Ta.js";
|
|
14
|
+
import "./coordination-driver-xO1tkxy-.js";
|
|
15
|
+
import { mt as mapExecutorResult, n as supervise, pt as gateOnDeliverable } from "./supervise-HsRKOlKY.js";
|
|
16
|
+
import "./run-layout-Cd_l2XWV.js";
|
|
17
|
+
import "./provision-supervisor-zA__ayUX.js";
|
|
17
18
|
import { t as assertAuthoredCode } from "./authored-code-DzYtiflw.js";
|
|
18
|
-
import "./authoring-
|
|
19
|
-
import "./graph-
|
|
20
|
-
import {
|
|
19
|
+
import "./authoring-bXmPNfCI.js";
|
|
20
|
+
import "./graph-DwJXa1Ph.js";
|
|
21
|
+
import { agentProfileSchema, canonicalAgentProfileDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
21
22
|
import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
22
23
|
import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
|
|
23
24
|
import { createHash, randomUUID } from "node:crypto";
|
|
@@ -3473,1086 +3474,6 @@ function promotionGate(opts) {
|
|
|
3473
3474
|
};
|
|
3474
3475
|
}
|
|
3475
3476
|
//#endregion
|
|
3476
|
-
//#region src/runtime/retained-interactive-handle.ts
|
|
3477
|
-
function createRetainedInteractiveRunHandle(environment, inputRef, capabilities, requestedStart) {
|
|
3478
|
-
const ref = freezeInteractiveRef(inputRef);
|
|
3479
|
-
const source = environment.interactive(ref);
|
|
3480
|
-
if (!sameInteractiveRef(source.ref, ref)) throw new Error("provider reconstructed a different interactive process");
|
|
3481
|
-
if (!source.sendPrompt) throw new Error("provider declared interactive prompt support but exposed no prompt method");
|
|
3482
|
-
return Object.freeze({
|
|
3483
|
-
ref,
|
|
3484
|
-
capabilities,
|
|
3485
|
-
claimControl: async (request, options) => exactClaim(ref, request, await awaitAbortable(Promise.resolve().then(() => source.claimControl(request, options)), options?.signal)),
|
|
3486
|
-
status: async (options) => exactStatus(ref, await awaitAbortable(Promise.resolve().then(() => source.status(options)), options?.signal), requestedStart),
|
|
3487
|
-
attach: async (request, options) => exactTerminal(ref, request, await awaitAbortable(Promise.resolve().then(() => source.attach(request, options)), options?.signal)),
|
|
3488
|
-
sendPrompt: async (command, options) => exactPrompt(ref, await awaitAbortable(Promise.resolve().then(() => source.sendPrompt(command, options)), options?.signal), command),
|
|
3489
|
-
stop: async (command, options) => exactStop(ref, await awaitAbortable(Promise.resolve().then(() => source.stop(command, options)), options?.signal), command)
|
|
3490
|
-
});
|
|
3491
|
-
}
|
|
3492
|
-
function freezeInteractiveRef(value) {
|
|
3493
|
-
return detachedSnapshot(AgentInteractiveSessionRefSchema.parse(value), "interactive session ref");
|
|
3494
|
-
}
|
|
3495
|
-
function exactClaim(ref, request, value) {
|
|
3496
|
-
const acknowledgement = parseProviderAcknowledgement(AgentInteractiveSessionControlClaimAcknowledgementSchema, value, "control claim");
|
|
3497
|
-
if (!agentInteractiveSessionControlClaimAcknowledgementMatchesRequest(request, acknowledgement)) throw new RetainedRunProviderContractError("provider returned a control claim acknowledgement for another request");
|
|
3498
|
-
if (acknowledgement.control && !agentInteractiveSessionControlClaimMatchesRef(ref, acknowledgement.control)) throw new RetainedRunProviderContractError("provider returned a control claim for another interactive process");
|
|
3499
|
-
return acknowledgement;
|
|
3500
|
-
}
|
|
3501
|
-
function exactPrompt(ref, value, command) {
|
|
3502
|
-
const acknowledgement = parseProviderAcknowledgement(AgentInteractiveSessionPromptAcknowledgementSchema, value, "prompt");
|
|
3503
|
-
if (!agentInteractiveSessionPromptAcknowledgementMatchesCommand(command, acknowledgement)) throw new RetainedRunProviderContractError("provider returned a prompt acknowledgement for another request");
|
|
3504
|
-
if (!agentInteractiveSessionControlClaimMatchesRef(ref, acknowledgement.control)) throw new RetainedRunProviderContractError("provider returned a prompt acknowledgement for another interactive process");
|
|
3505
|
-
return acknowledgement;
|
|
3506
|
-
}
|
|
3507
|
-
function exactStop(ref, value, command) {
|
|
3508
|
-
const acknowledgement = parseProviderAcknowledgement(AgentInteractiveSessionStopAcknowledgementSchema, value, "stop");
|
|
3509
|
-
if (!agentInteractiveSessionStopAcknowledgementMatchesCommand(command, acknowledgement)) throw new RetainedRunProviderContractError("provider returned a stop acknowledgement for another request");
|
|
3510
|
-
if (!agentInteractiveSessionControlClaimMatchesRef(ref, acknowledgement.control)) throw new RetainedRunProviderContractError("provider returned a stop acknowledgement for another interactive process");
|
|
3511
|
-
return acknowledgement;
|
|
3512
|
-
}
|
|
3513
|
-
function parseProviderAcknowledgement(schema, value, operation) {
|
|
3514
|
-
try {
|
|
3515
|
-
return schema.parse(value);
|
|
3516
|
-
} catch {
|
|
3517
|
-
throw new RetainedRunProviderContractError(`provider returned an invalid interactive ${operation} acknowledgement`);
|
|
3518
|
-
}
|
|
3519
|
-
}
|
|
3520
|
-
function exactStatus(ref, value, requestedStart) {
|
|
3521
|
-
let status;
|
|
3522
|
-
try {
|
|
3523
|
-
status = AgentInteractiveSessionStatusSchema.parse(value);
|
|
3524
|
-
} catch (error) {
|
|
3525
|
-
if (requestedStart === void 0) throw error;
|
|
3526
|
-
throw new RetainedInteractiveBindingError(detachedSnapshot(requestedStart, "interactive status binding request"), {}, { cause: error });
|
|
3527
|
-
}
|
|
3528
|
-
if (!agentInteractiveSessionStatusMatchesRef(ref, status)) {
|
|
3529
|
-
if (requestedStart !== void 0) throw new RetainedInteractiveBindingError(detachedSnapshot(requestedStart, "interactive status binding request"), detachedSnapshot({ status: detachedSnapshot(status, "interactive provider status") }, "interactive provider status result"), { cause: /* @__PURE__ */ new Error("provider returned status for another interactive process") });
|
|
3530
|
-
throw new Error("provider returned status for another interactive process");
|
|
3531
|
-
}
|
|
3532
|
-
return status;
|
|
3533
|
-
}
|
|
3534
|
-
function exactTerminal(ref, request, terminal) {
|
|
3535
|
-
const terminalRef = TerminalSessionRefSchema.parse(terminal.ref);
|
|
3536
|
-
TerminalReplayWindowSchema.parse(terminal.cursors);
|
|
3537
|
-
if (terminalRef.parentExecutionId !== ref.run.executionId) throw new Error("provider attached a terminal from another interactive run");
|
|
3538
|
-
AgentInteractiveSessionControlClaimSchema.parse(terminal.control);
|
|
3539
|
-
if (!agentInteractiveSessionControlClaimMatchesRef(ref, terminal.control)) throw new Error("provider attached a terminal with a claim for another interactive process");
|
|
3540
|
-
if (canonicalCandidateDigest(terminal.control) !== canonicalCandidateDigest(request.control)) throw new Error("provider attached a terminal with a different interactive control claim");
|
|
3541
|
-
return terminal;
|
|
3542
|
-
}
|
|
3543
|
-
function sameInteractiveRef(left, right) {
|
|
3544
|
-
return canonicalCandidateDigest(left) === canonicalCandidateDigest(right);
|
|
3545
|
-
}
|
|
3546
|
-
//#endregion
|
|
3547
|
-
//#region src/runtime/retained-interactive-lifecycle.ts
|
|
3548
|
-
const INTERACTIVE_CLEANUP_TIMEOUT_MS = 3e4;
|
|
3549
|
-
/** Create one environment while retaining ownership if cancellation wins the race. */
|
|
3550
|
-
async function createInteractiveEnvironment(create, signal) {
|
|
3551
|
-
if (signal?.aborted) throw abortError(signal.reason);
|
|
3552
|
-
const creation = Promise.resolve().then(create);
|
|
3553
|
-
if (signal === void 0) return creation;
|
|
3554
|
-
return new Promise((resolve, reject) => {
|
|
3555
|
-
let owner = "pending";
|
|
3556
|
-
const removeAbortListener = () => signal.removeEventListener("abort", onAbort);
|
|
3557
|
-
const onAbort = () => {
|
|
3558
|
-
if (owner !== "pending") return;
|
|
3559
|
-
owner = "runtime";
|
|
3560
|
-
removeAbortListener();
|
|
3561
|
-
disposeInteractiveEnvironment(creation, signal.reason);
|
|
3562
|
-
reject(abortError(signal.reason));
|
|
3563
|
-
};
|
|
3564
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
3565
|
-
creation.then((environment) => {
|
|
3566
|
-
if (owner !== "pending") return;
|
|
3567
|
-
owner = "caller";
|
|
3568
|
-
removeAbortListener();
|
|
3569
|
-
resolve(environment);
|
|
3570
|
-
}, (error) => {
|
|
3571
|
-
if (owner !== "pending") return;
|
|
3572
|
-
owner = "runtime";
|
|
3573
|
-
removeAbortListener();
|
|
3574
|
-
reject(error);
|
|
3575
|
-
});
|
|
3576
|
-
});
|
|
3577
|
-
}
|
|
3578
|
-
/** Start one process while destroying its unreturned environment on cancellation. */
|
|
3579
|
-
async function startInteractiveProcess(environment, start, signal) {
|
|
3580
|
-
if (signal?.aborted) {
|
|
3581
|
-
disposeInteractiveEnvironment(Promise.resolve(environment), signal.reason);
|
|
3582
|
-
throw abortError(signal.reason);
|
|
3583
|
-
}
|
|
3584
|
-
const pending = Promise.resolve().then(start);
|
|
3585
|
-
if (signal === void 0) return pending;
|
|
3586
|
-
return new Promise((resolve, reject) => {
|
|
3587
|
-
let owner = "pending";
|
|
3588
|
-
const removeAbortListener = () => signal.removeEventListener("abort", onAbort);
|
|
3589
|
-
const onAbort = () => {
|
|
3590
|
-
if (owner !== "pending") return;
|
|
3591
|
-
owner = "runtime";
|
|
3592
|
-
removeAbortListener();
|
|
3593
|
-
disposeInteractiveEnvironment(Promise.resolve(environment), signal.reason);
|
|
3594
|
-
reject(abortError(signal.reason));
|
|
3595
|
-
};
|
|
3596
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
3597
|
-
pending.then((result) => {
|
|
3598
|
-
if (owner !== "pending") return;
|
|
3599
|
-
owner = "caller";
|
|
3600
|
-
removeAbortListener();
|
|
3601
|
-
resolve(result);
|
|
3602
|
-
}, (error) => {
|
|
3603
|
-
if (owner !== "pending") return;
|
|
3604
|
-
owner = "runtime";
|
|
3605
|
-
removeAbortListener();
|
|
3606
|
-
reject(error);
|
|
3607
|
-
});
|
|
3608
|
-
});
|
|
3609
|
-
}
|
|
3610
|
-
/** Destroy an environment with fresh, bounded cleanup authority. */
|
|
3611
|
-
async function destroyInteractiveEnvironment(environment) {
|
|
3612
|
-
if (!environment.destroy) throw new Error(`provider environment "${environment.id}" does not expose destroy()`);
|
|
3613
|
-
const controller = new AbortController();
|
|
3614
|
-
const timeout = /* @__PURE__ */ new Error("interactive environment cleanup timed out");
|
|
3615
|
-
let timer;
|
|
3616
|
-
const destruction = Promise.resolve().then(() => environment.destroy?.({ signal: controller.signal }));
|
|
3617
|
-
destruction.catch(() => void 0);
|
|
3618
|
-
try {
|
|
3619
|
-
await Promise.race([destruction, new Promise((_resolve, reject) => {
|
|
3620
|
-
timer = setTimeout(() => {
|
|
3621
|
-
controller.abort(timeout);
|
|
3622
|
-
reject(timeout);
|
|
3623
|
-
}, INTERACTIVE_CLEANUP_TIMEOUT_MS);
|
|
3624
|
-
})]);
|
|
3625
|
-
} finally {
|
|
3626
|
-
if (timer !== void 0) clearTimeout(timer);
|
|
3627
|
-
}
|
|
3628
|
-
}
|
|
3629
|
-
function disposeInteractiveEnvironment(environment, abortReason) {
|
|
3630
|
-
environment.then(destroyInteractiveEnvironment, () => void 0).catch((cleanupError) => {
|
|
3631
|
-
const reason = abortReason instanceof Error ? abortReason : new Error(String(abortReason));
|
|
3632
|
-
const failure = new AggregateError([reason, cleanupError], "cancelled interactive environment cleanup failed");
|
|
3633
|
-
process.emitWarning(failure, { code: "AGENT_RUNTIME_INTERACTIVE_CLEANUP_FAILED" });
|
|
3634
|
-
});
|
|
3635
|
-
}
|
|
3636
|
-
//#endregion
|
|
3637
|
-
//#region src/runtime/retained-run-intent.ts
|
|
3638
|
-
/**
|
|
3639
|
-
* Project environment creation input into public digest material.
|
|
3640
|
-
*
|
|
3641
|
-
* Opaque values never enter the material or its digest. Public scalar fields
|
|
3642
|
-
* remain bound directly, while opaque records retain only their key names.
|
|
3643
|
-
* Secret names remain public binding data, so changing requested credentials
|
|
3644
|
-
* still conflicts before provider effects begin.
|
|
3645
|
-
*/
|
|
3646
|
-
function retainedCreateMaterial(environment) {
|
|
3647
|
-
return {
|
|
3648
|
-
...environment.backend === void 0 ? {} : { backend: environment.backend },
|
|
3649
|
-
...environment.workspace === void 0 ? {} : { workspaceDigest: canonicalCandidateDigest(publicWorkspaceMaterial(environment.workspace)) },
|
|
3650
|
-
...environment.resources === void 0 ? {} : { resourcesDigest: canonicalCandidateDigest(publicResourceMaterial(environment.resources)) },
|
|
3651
|
-
...environment.name === void 0 ? {} : { name: environment.name },
|
|
3652
|
-
...environment.env === void 0 ? {} : { environmentVariableNames: retainedObjectNames(environment.env) },
|
|
3653
|
-
...environment.secrets === void 0 ? {} : { secretNames: retainedSecretNames(environment.secrets) },
|
|
3654
|
-
...environment.metadata === void 0 ? {} : { metadataKeys: retainedObjectNames(environment.metadata) },
|
|
3655
|
-
...environment.providerOptions === void 0 ? {} : { providerOptionNames: retainedObjectNames(environment.providerOptions) }
|
|
3656
|
-
};
|
|
3657
|
-
}
|
|
3658
|
-
/** Add the retained ownership marker without attaching turn identity. */
|
|
3659
|
-
function retainedEnvironmentMetadata(metadata, idempotencyKey) {
|
|
3660
|
-
return {
|
|
3661
|
-
...metadata,
|
|
3662
|
-
retainedIdempotencyKey: idempotencyKey
|
|
3663
|
-
};
|
|
3664
|
-
}
|
|
3665
|
-
function publicWorkspaceMaterial(workspace) {
|
|
3666
|
-
return {
|
|
3667
|
-
...workspace.environment === void 0 ? {} : { environment: workspace.environment },
|
|
3668
|
-
...workspace.image === void 0 ? {} : { image: workspace.image },
|
|
3669
|
-
...workspace.repoUrl === void 0 ? {} : { repoUrl: workspace.repoUrl },
|
|
3670
|
-
...workspace.gitRef === void 0 ? {} : { gitRef: workspace.gitRef },
|
|
3671
|
-
...workspace.cwd === void 0 ? {} : { cwd: workspace.cwd },
|
|
3672
|
-
...workspace.providerOptions === void 0 ? {} : { providerOptionNames: retainedObjectNames(workspace.providerOptions) }
|
|
3673
|
-
};
|
|
3674
|
-
}
|
|
3675
|
-
function publicResourceMaterial(resources) {
|
|
3676
|
-
return {
|
|
3677
|
-
...resources.cpu === void 0 ? {} : { cpu: resources.cpu },
|
|
3678
|
-
...resources.memoryMb === void 0 ? {} : { memoryMb: resources.memoryMb },
|
|
3679
|
-
...resources.diskMb === void 0 ? {} : { diskMb: resources.diskMb },
|
|
3680
|
-
...resources.gpu === void 0 ? {} : { gpu: resources.gpu },
|
|
3681
|
-
...resources.providerOptions === void 0 ? {} : { providerOptionNames: retainedObjectNames(resources.providerOptions) }
|
|
3682
|
-
};
|
|
3683
|
-
}
|
|
3684
|
-
function retainedObjectNames(value) {
|
|
3685
|
-
return Object.keys(value).sort();
|
|
3686
|
-
}
|
|
3687
|
-
function retainedSecretNames(secrets) {
|
|
3688
|
-
return Array.isArray(secrets) ? [...secrets].sort() : Object.keys(secrets).sort();
|
|
3689
|
-
}
|
|
3690
|
-
/** Project one headless turn into the material that `freshTurnInput` forwards. */
|
|
3691
|
-
function retainedTurnMaterial(input) {
|
|
3692
|
-
return {
|
|
3693
|
-
...input.prompt === void 0 ? {} : { prompt: input.prompt },
|
|
3694
|
-
...input.parts === void 0 ? {} : { parts: input.parts },
|
|
3695
|
-
...input.model === void 0 ? {} : { model: input.model },
|
|
3696
|
-
...input.timeoutMs === void 0 ? {} : { timeoutMs: input.timeoutMs },
|
|
3697
|
-
...input.context === void 0 ? {} : { context: input.context },
|
|
3698
|
-
...input.interactions === void 0 ? {} : { interactions: input.interactions },
|
|
3699
|
-
...input.providerOptions === void 0 ? {} : { providerOptions: input.providerOptions }
|
|
3700
|
-
};
|
|
3701
|
-
}
|
|
3702
|
-
//#endregion
|
|
3703
|
-
//#region src/runtime/interaction-capabilities.ts
|
|
3704
|
-
/**
|
|
3705
|
-
* Check one turn's interaction request before the provider can dispatch it.
|
|
3706
|
-
*
|
|
3707
|
-
* A requested interaction is durable only when the provider can replay its
|
|
3708
|
-
* event and safely replay the response command. An unsupported request fails
|
|
3709
|
-
* before environment creation or dispatch begins.
|
|
3710
|
-
*/
|
|
3711
|
-
function assertRequestedInteractionCapabilities(providerName, requested, capabilities) {
|
|
3712
|
-
const requestedKinds = Object.entries(requested ?? {}).filter(([, enabled]) => enabled === true).map(([kind]) => kind);
|
|
3713
|
-
if (requestedKinds.length === 0) return;
|
|
3714
|
-
const interactions = capabilities.interactions;
|
|
3715
|
-
if (!interactions) throw new Error(`provider "${providerName}" does not support requested interactions: ${requestedKinds.join(", ")}`);
|
|
3716
|
-
const unsupportedKinds = requestedKinds.filter((kind) => !interactions.kinds.includes(kind));
|
|
3717
|
-
if (unsupportedKinds.length > 0) throw new Error(`provider "${providerName}" does not support requested interaction kinds: ${unsupportedKinds.join(", ")}`);
|
|
3718
|
-
if (interactions.replay !== true || interactions.responseIdempotency !== true) throw new Error(`provider "${providerName}" cannot safely dispatch requested interactions without replay and response idempotency`);
|
|
3719
|
-
}
|
|
3720
|
-
//#endregion
|
|
3721
|
-
//#region src/runtime/retained-run-events.ts
|
|
3722
|
-
async function* retainedRunEvents(session, controlRef, options, now) {
|
|
3723
|
-
const after = options?.after;
|
|
3724
|
-
if (after) {
|
|
3725
|
-
assertStableText(after.cursor, "replay cursor");
|
|
3726
|
-
assertSequence(after.sequence, "replay sequence");
|
|
3727
|
-
}
|
|
3728
|
-
let nextSequence = after === void 0 ? 1 : after.sequence + 1;
|
|
3729
|
-
let lastSequence = after?.sequence ?? -1;
|
|
3730
|
-
const seen = /* @__PURE__ */ new Set();
|
|
3731
|
-
let firstAfterEvent = after !== void 0;
|
|
3732
|
-
const iterator = session.events({
|
|
3733
|
-
...after === void 0 ? {} : { since: after.cursor },
|
|
3734
|
-
...controlRef.executionId === void 0 ? {} : { executionId: controlRef.executionId },
|
|
3735
|
-
...options?.signal === void 0 ? {} : { signal: options.signal }
|
|
3736
|
-
})[Symbol.asyncIterator]();
|
|
3737
|
-
try {
|
|
3738
|
-
for (;;) {
|
|
3739
|
-
const next = await awaitAbortable(Promise.resolve().then(() => iterator.next()), options?.signal);
|
|
3740
|
-
if (next.done) break;
|
|
3741
|
-
const source = next.value;
|
|
3742
|
-
const identity = extractTransportEventIdentity(source);
|
|
3743
|
-
const sourceCursor = identity.cursor ?? identity.eventId;
|
|
3744
|
-
assertEventBinding(source, controlRef);
|
|
3745
|
-
if (sourceCursor === after?.cursor) continue;
|
|
3746
|
-
const event = canonicalEvent(source);
|
|
3747
|
-
if (!event) continue;
|
|
3748
|
-
assertCanonicalEventBinding(controlRef, event);
|
|
3749
|
-
if (firstAfterEvent && after !== void 0) {
|
|
3750
|
-
if (identity.sequence !== void 0 && identity.sequence <= after.sequence) throw new Error("provider replay did not prove that the first event follows the requested cursor");
|
|
3751
|
-
firstAfterEvent = false;
|
|
3752
|
-
}
|
|
3753
|
-
const eventId = identity.eventId ?? identity.cursor;
|
|
3754
|
-
if (!eventId) throw new Error("replayable canonical event has no stable provider event id or cursor");
|
|
3755
|
-
assertStableText(eventId, "provider event id");
|
|
3756
|
-
if (seen.has(eventId)) throw new Error(`provider replay repeated event id "${eventId}"`);
|
|
3757
|
-
seen.add(eventId);
|
|
3758
|
-
const sequence = identity.sequence ?? nextSequence;
|
|
3759
|
-
if (sequence <= lastSequence) throw new Error(`provider event sequence is not monotonic: ${sequence} follows ${lastSequence}`);
|
|
3760
|
-
const occurredAt = identity.occurredAt;
|
|
3761
|
-
yield RuntimeEventEnvelopeSchema.parse({
|
|
3762
|
-
runId: controlRef.runId,
|
|
3763
|
-
eventId,
|
|
3764
|
-
sequence,
|
|
3765
|
-
cursor: identity.cursor ?? eventId,
|
|
3766
|
-
...occurredAt === void 0 ? {} : { occurredAt },
|
|
3767
|
-
receivedAt: new Date(now()).toISOString(),
|
|
3768
|
-
event
|
|
3769
|
-
});
|
|
3770
|
-
lastSequence = sequence;
|
|
3771
|
-
nextSequence = sequence + 1;
|
|
3772
|
-
}
|
|
3773
|
-
} catch (error) {
|
|
3774
|
-
if (options?.signal?.aborted) {
|
|
3775
|
-
try {
|
|
3776
|
-
Promise.resolve(iterator.return?.()).catch(() => void 0);
|
|
3777
|
-
} catch {}
|
|
3778
|
-
throw abortError(options.signal.reason);
|
|
3779
|
-
}
|
|
3780
|
-
throw error;
|
|
3781
|
-
} finally {
|
|
3782
|
-
if (!options?.signal?.aborted) await iterator.return?.();
|
|
3783
|
-
}
|
|
3784
|
-
}
|
|
3785
|
-
function canonicalEvent(source) {
|
|
3786
|
-
return parseCanonicalTransportEvent(source.type, source.data, source.normalized ?? source.data.normalized, "provider");
|
|
3787
|
-
}
|
|
3788
|
-
//#endregion
|
|
3789
|
-
//#region src/runtime/retained-run-handle.ts
|
|
3790
|
-
function createRetainedRunHandle(environment, session, initialControlRef, capabilities, now) {
|
|
3791
|
-
const clock = now ?? Date.now;
|
|
3792
|
-
const measuredCapabilities = structuredClone(capabilities);
|
|
3793
|
-
let activeControlRef = freezeControlRef(initialControlRef);
|
|
3794
|
-
const snapshot = async (reason, signal) => {
|
|
3795
|
-
if (signal?.aborted) throw abortError(signal.reason);
|
|
3796
|
-
let status;
|
|
3797
|
-
try {
|
|
3798
|
-
status = await awaitAbortable(Promise.resolve().then(() => session.status({ signal })), signal);
|
|
3799
|
-
} catch {
|
|
3800
|
-
if (signal?.aborted) throw abortError(signal.reason);
|
|
3801
|
-
status = "unknown";
|
|
3802
|
-
}
|
|
3803
|
-
const effect = status === "cancelled" ? "cancelled" : status === "completed" || status === "failed" || status === "expired" ? "not_live" : "unknown";
|
|
3804
|
-
return {
|
|
3805
|
-
runId: activeControlRef.runId,
|
|
3806
|
-
controlRef: copyControlRef(activeControlRef),
|
|
3807
|
-
status,
|
|
3808
|
-
effect,
|
|
3809
|
-
observedAt: new Date(clock()).toISOString(),
|
|
3810
|
-
...reason === void 0 ? {} : { reason },
|
|
3811
|
-
...signal?.aborted ? { signal: String(signal.reason ?? "aborted") } : {}
|
|
3812
|
-
};
|
|
3813
|
-
};
|
|
3814
|
-
return {
|
|
3815
|
-
get controlRef() {
|
|
3816
|
-
return copyControlRef(activeControlRef);
|
|
3817
|
-
},
|
|
3818
|
-
get capabilities() {
|
|
3819
|
-
return structuredClone(measuredCapabilities);
|
|
3820
|
-
},
|
|
3821
|
-
status: async (options) => {
|
|
3822
|
-
const waitMs = options?.waitMs ?? 0;
|
|
3823
|
-
assertWaitDuration(waitMs, "retained status wait");
|
|
3824
|
-
const initial = await snapshot(void 0, options?.signal);
|
|
3825
|
-
if (waitMs === 0 || isTerminalSessionStatus(initial.status)) return initial;
|
|
3826
|
-
const deadline = Date.now() + waitMs;
|
|
3827
|
-
let current = initial;
|
|
3828
|
-
while (Date.now() < deadline) {
|
|
3829
|
-
await delay(Math.min(25, Math.max(1, deadline - Date.now())), options?.signal);
|
|
3830
|
-
current = await snapshot(void 0, options?.signal);
|
|
3831
|
-
if (current.status !== initial.status || isTerminalSessionStatus(current.status)) return current;
|
|
3832
|
-
}
|
|
3833
|
-
return current;
|
|
3834
|
-
},
|
|
3835
|
-
events: (options) => retainedRunEvents(session, copyControlRef(activeControlRef), options, clock),
|
|
3836
|
-
result: async () => {
|
|
3837
|
-
const result = AgentTurnResultSchema.parse(await exactSessionResult(session));
|
|
3838
|
-
assertResultBinding(activeControlRef, result);
|
|
3839
|
-
return structuredClone(result);
|
|
3840
|
-
},
|
|
3841
|
-
async respondToInteraction(command, options) {
|
|
3842
|
-
const exactCommand = InteractionResponseCommandSchema.parse(command);
|
|
3843
|
-
assertInteractionBinding(activeControlRef, exactCommand);
|
|
3844
|
-
if (measuredCapabilities.interactions?.replay !== true || measuredCapabilities.interactions.responseIdempotency !== true) throw new Error(`provider "${activeControlRef.provider}" does not promise retry-safe interaction responses`);
|
|
3845
|
-
const respond = session.respondToInteraction ?? environment.respondToInteraction;
|
|
3846
|
-
if (!respond) throw new Error(`provider "${activeControlRef.provider}" does not support interaction responses`);
|
|
3847
|
-
const acknowledgement = InteractionAcknowledgementSchema.parse(await awaitAbortable(Promise.resolve().then(() => respond.call(session.respondToInteraction ? session : environment, exactCommand, options)), options?.signal));
|
|
3848
|
-
if (acknowledgement.operationId !== exactCommand.operationId || acknowledgement.commandDigest !== exactCommand.commandDigest || canonicalCandidateDigest(acknowledgement.binding) !== canonicalCandidateDigest(exactCommand.binding)) throw new Error("provider returned an interaction acknowledgement for another command");
|
|
3849
|
-
return structuredClone(acknowledgement);
|
|
3850
|
-
},
|
|
3851
|
-
async contextBoundary(options) {
|
|
3852
|
-
if (!session.contextBoundary) return null;
|
|
3853
|
-
const proof = await awaitAbortable(Promise.resolve().then(() => session.contextBoundary(options)), options?.signal);
|
|
3854
|
-
if (proof === null) return null;
|
|
3855
|
-
const exactProof = NativeContextBoundaryProofSchema.parse(proof);
|
|
3856
|
-
assertBoundaryBinding(activeControlRef, exactProof);
|
|
3857
|
-
return structuredClone(exactProof);
|
|
3858
|
-
},
|
|
3859
|
-
async continueNative(request, turn) {
|
|
3860
|
-
const exactRequest = NativeContextContinuationRequestSchema.parse(request);
|
|
3861
|
-
if (!sameControlCoordinates(exactRequest.run, activeControlRef)) throw new Error("native continuation request targets another retained run");
|
|
3862
|
-
const { timeoutMs, signal, ...semanticTurn } = turn;
|
|
3863
|
-
if (nativeContextContinuationTurnDigest(semanticTurn) !== exactRequest.turnDigest) throw new Error("native continuation request targets another user turn");
|
|
3864
|
-
if (measuredCapabilities.nativeContinuation?.atomicBoundary !== true || measuredCapabilities.nativeContinuation.requestIdempotency !== true || !session.continueNative) throw new Error(`provider "${activeControlRef.provider}" does not support retry-safe native continuation`);
|
|
3865
|
-
const outcome = AgentNativeContextContinuationResultSchema.parse(await awaitAbortable(Promise.resolve().then(() => session.continueNative(exactRequest, {
|
|
3866
|
-
turn: semanticTurn,
|
|
3867
|
-
...timeoutMs === void 0 ? {} : { timeoutMs },
|
|
3868
|
-
...signal === void 0 ? {} : { signal }
|
|
3869
|
-
})), signal));
|
|
3870
|
-
if (outcome.acknowledgement.operationId !== exactRequest.operationId || outcome.acknowledgement.requestDigest !== exactRequest.requestDigest) throw new Error("provider returned a native continuation result for another request");
|
|
3871
|
-
if (outcome.acknowledgement.actualBoundary !== void 0) {
|
|
3872
|
-
const actualBoundary = NativeContextBoundaryProofSchema.parse(outcome.acknowledgement.actualBoundary);
|
|
3873
|
-
assertBoundaryBinding(exactRequest.run, actualBoundary);
|
|
3874
|
-
}
|
|
3875
|
-
if (outcome.acknowledgement.status !== "accepted" && outcome.acknowledgement.status !== "replayed") return structuredClone(outcome);
|
|
3876
|
-
if (!("result" in outcome) || !("controlRef" in outcome)) throw new Error("provider omitted the successful native continuation result");
|
|
3877
|
-
if (!agentNativeContextContinuationResultMatchesRequest(exactRequest, outcome)) throw new Error("provider returned a native continuation result for another request");
|
|
3878
|
-
const nextControlRef = exactContinuedControlRef(outcome.controlRef, activeControlRef);
|
|
3879
|
-
assertResultBinding(nextControlRef, outcome.result);
|
|
3880
|
-
activeControlRef = freezeControlRef(nextControlRef);
|
|
3881
|
-
return structuredClone({
|
|
3882
|
-
...outcome,
|
|
3883
|
-
controlRef: copyControlRef(activeControlRef)
|
|
3884
|
-
});
|
|
3885
|
-
},
|
|
3886
|
-
async cancel(options) {
|
|
3887
|
-
assertStableText(options.operationId, "retained cancellation operation id");
|
|
3888
|
-
if (options.reason !== void 0) assertStableText(options.reason, "retained cancellation reason");
|
|
3889
|
-
if (options.signal?.aborted) throw abortError(options.signal.reason);
|
|
3890
|
-
if (!hasDurableCancel(session)) throw new Error(`provider "${activeControlRef.provider}" does not expose durable cancellation operations`);
|
|
3891
|
-
const request = cancellationRequest(activeControlRef, options.operationId, options.reason);
|
|
3892
|
-
let effect = "unknown";
|
|
3893
|
-
let providerStatus;
|
|
3894
|
-
try {
|
|
3895
|
-
const acknowledgement = await exactSessionCancel(session, request, { signal: options.signal });
|
|
3896
|
-
effect = acknowledgement.effect;
|
|
3897
|
-
providerStatus = acknowledgement.status;
|
|
3898
|
-
} catch (error) {
|
|
3899
|
-
if (error instanceof RetainedRunProviderContractError) throw error;
|
|
3900
|
-
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
3901
|
-
effect = "unknown";
|
|
3902
|
-
}
|
|
3903
|
-
const current = await snapshot(options.reason, options.signal);
|
|
3904
|
-
const observedEffect = effect === "unknown" && providerStatus === void 0 && current.status === "cancelled" ? "cancelled" : effect;
|
|
3905
|
-
const acknowledgement = {
|
|
3906
|
-
operationId: options.operationId,
|
|
3907
|
-
requestDigest: request.requestDigest,
|
|
3908
|
-
status: providerStatus ?? (observedEffect === "unknown" ? "unknown" : "accepted"),
|
|
3909
|
-
effect: observedEffect,
|
|
3910
|
-
snapshot: {
|
|
3911
|
-
...current,
|
|
3912
|
-
effect: observedEffect
|
|
3913
|
-
},
|
|
3914
|
-
...options.reason === void 0 ? {} : { reason: options.reason },
|
|
3915
|
-
...options.signal?.aborted ? { signal: String(options.signal.reason ?? "aborted") } : {}
|
|
3916
|
-
};
|
|
3917
|
-
return structuredClone(acknowledgement);
|
|
3918
|
-
}
|
|
3919
|
-
};
|
|
3920
|
-
}
|
|
3921
|
-
//#endregion
|
|
3922
|
-
//#region src/runtime/retained-run-start.ts
|
|
3923
|
-
/**
|
|
3924
|
-
* Mint deterministic dispatch coordinates from the two caller-supplied keys.
|
|
3925
|
-
* The same `(idempotencyKey, turnId)` pair yields the same coordinates in
|
|
3926
|
-
* every process, so a pre-dispatch admission record always names the exact
|
|
3927
|
-
* session and execution the dispatch will request. Format is readable, not
|
|
3928
|
-
* hashed, following `deriveExecutionId`: components are URL-encoded so
|
|
3929
|
-
* delimiters inside caller keys cannot collapse distinct pairs, and the
|
|
3930
|
-
* result stays inside the 256-byte identifier bound.
|
|
3931
|
-
*/
|
|
3932
|
-
function mintRetainedIdentity(idempotencyKey, turnId) {
|
|
3933
|
-
const base = `${encodeURIComponent(idempotencyKey)}:${encodeURIComponent(turnId)}`;
|
|
3934
|
-
const sessionId = `retained-session:${base}`;
|
|
3935
|
-
const executionId = `retained-execution:${base}`;
|
|
3936
|
-
if (executionId.length > 256) throw new RangeError("minted retained identity must not exceed 256 bytes");
|
|
3937
|
-
return {
|
|
3938
|
-
sessionId,
|
|
3939
|
-
executionId
|
|
3940
|
-
};
|
|
3941
|
-
}
|
|
3942
|
-
/**
|
|
3943
|
-
* Dispatch one detached, replayable run and return only after exact durable
|
|
3944
|
-
* coordinates are confirmed by the provider and persisted by the caller.
|
|
3945
|
-
*
|
|
3946
|
-
* The required `onAdmission` hook first records a digest-only intent before
|
|
3947
|
-
* creation, then records recovery coordinates and the verified exact control
|
|
3948
|
-
* reference. The returned promise resolves only after the dispatched admission
|
|
3949
|
-
* is durable, so a crash cannot lose a successful start's exact reference.
|
|
3950
|
-
*
|
|
3951
|
-
* @stable
|
|
3952
|
-
*/
|
|
3953
|
-
async function startRetainedRun(options) {
|
|
3954
|
-
assertStableText(options.environment.idempotencyKey, "environment idempotency key");
|
|
3955
|
-
assertStableText(options.turn.turnId, "turn idempotency key");
|
|
3956
|
-
if (options.identity !== void 0) {
|
|
3957
|
-
assertStableText(options.identity.sessionId, "retained session id");
|
|
3958
|
-
assertStableText(options.identity.executionId, "retained execution id");
|
|
3959
|
-
}
|
|
3960
|
-
if (typeof options.onAdmission !== "function") throw new Error("startRetainedRun requires an awaited onAdmission durability hook");
|
|
3961
|
-
const identity = options.identity ?? mintRetainedIdentity(options.environment.idempotencyKey, options.turn.turnId);
|
|
3962
|
-
if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
|
|
3963
|
-
const intent = retainedRunIntent(options, identity);
|
|
3964
|
-
if (options.intent === void 0) await admitDurably(options.onAdmission, intent);
|
|
3965
|
-
else assertExactRetainedRunIntent(options.intent, intent);
|
|
3966
|
-
const providerCapabilities = await assertRetainedCapabilities(options.provider);
|
|
3967
|
-
assertRequestedInteractionCapabilities(options.provider.name, options.turn.interactions, providerCapabilities);
|
|
3968
|
-
const environment = await options.provider.create({
|
|
3969
|
-
...options.environment,
|
|
3970
|
-
metadata: retainedEnvironmentMetadata(options.environment.metadata, options.environment.idempotencyKey)
|
|
3971
|
-
});
|
|
3972
|
-
let capabilities;
|
|
3973
|
-
try {
|
|
3974
|
-
capabilities = retainedCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
|
|
3975
|
-
assertRequestedInteractionCapabilities(options.provider.name, options.turn.interactions, capabilities);
|
|
3976
|
-
} catch (error) {
|
|
3977
|
-
try {
|
|
3978
|
-
await environment.destroy?.();
|
|
3979
|
-
} catch (cleanupError) {
|
|
3980
|
-
throw new AggregateError([error, cleanupError], "retained run environment published invalid capabilities and could not be destroyed");
|
|
3981
|
-
}
|
|
3982
|
-
throw error;
|
|
3983
|
-
}
|
|
3984
|
-
if (!environment.dispatch || !environment.session) {
|
|
3985
|
-
try {
|
|
3986
|
-
await environment.destroy?.();
|
|
3987
|
-
} catch (cleanupError) {
|
|
3988
|
-
throw new AggregateError([/* @__PURE__ */ new Error(`provider "${options.provider.name}" does not expose detached session control`), cleanupError], "retained run could not start and its unused environment could not be destroyed");
|
|
3989
|
-
}
|
|
3990
|
-
throw new Error(`provider "${options.provider.name}" does not expose detached session control`);
|
|
3991
|
-
}
|
|
3992
|
-
return dispatchRetainedRun({
|
|
3993
|
-
provider: options.provider,
|
|
3994
|
-
environment,
|
|
3995
|
-
environmentIdempotencyKey: options.environment.idempotencyKey,
|
|
3996
|
-
turn: options.turn,
|
|
3997
|
-
identity,
|
|
3998
|
-
onAdmission: options.onAdmission,
|
|
3999
|
-
capabilities,
|
|
4000
|
-
now: options.now
|
|
4001
|
-
});
|
|
4002
|
-
}
|
|
4003
|
-
/**
|
|
4004
|
-
* Dispatch a fresh retained session inside an existing provider environment.
|
|
4005
|
-
*
|
|
4006
|
-
* This operation reuses only the environment. It does not append to a prior
|
|
4007
|
-
* harness chat and does not claim native conversation continuity. The caller
|
|
4008
|
-
* must use `RetainedRunHandle.continueNative` for a verified same-chat turn.
|
|
4009
|
-
*
|
|
4010
|
-
* @stable
|
|
4011
|
-
*/
|
|
4012
|
-
async function startRetainedRunInEnvironment(options) {
|
|
4013
|
-
assertStableText(options.environment.id, "retained environment id");
|
|
4014
|
-
assertStableText(options.environment.idempotencyKey, "environment idempotency key");
|
|
4015
|
-
assertStableText(options.turn.turnId, "turn idempotency key");
|
|
4016
|
-
if (options.identity !== void 0) {
|
|
4017
|
-
assertStableText(options.identity.sessionId, "retained session id");
|
|
4018
|
-
assertStableText(options.identity.executionId, "retained execution id");
|
|
4019
|
-
}
|
|
4020
|
-
if (typeof options.onAdmission !== "function") throw new Error("startRetainedRunInEnvironment requires an awaited onAdmission durability hook");
|
|
4021
|
-
const identity = options.identity ?? mintRetainedIdentity(options.environment.idempotencyKey, options.turn.turnId);
|
|
4022
|
-
const providerCapabilities = await assertRetainedCapabilities(options.provider);
|
|
4023
|
-
if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
|
|
4024
|
-
const environment = await options.provider.get(options.environment.id);
|
|
4025
|
-
if (!environment) throw new Error(`provider "${options.provider.name}" no longer holds environment "${options.environment.id}"`);
|
|
4026
|
-
if (environment.id !== options.environment.id || environment.provider !== options.provider.name) throw new Error("provider reconstructed a different retained environment");
|
|
4027
|
-
const capabilities = retainedCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
|
|
4028
|
-
assertRequestedInteractionCapabilities(options.provider.name, options.turn.interactions, capabilities);
|
|
4029
|
-
if (!environment.dispatch || !environment.session) throw new Error(`provider "${options.provider.name}" does not expose detached session control`);
|
|
4030
|
-
await assertRetainedEnvironmentOwnership(options.provider, environment.id, options.environment.idempotencyKey);
|
|
4031
|
-
return dispatchRetainedRun({
|
|
4032
|
-
provider: options.provider,
|
|
4033
|
-
environment,
|
|
4034
|
-
environmentIdempotencyKey: options.environment.idempotencyKey,
|
|
4035
|
-
turn: options.turn,
|
|
4036
|
-
identity,
|
|
4037
|
-
onAdmission: options.onAdmission,
|
|
4038
|
-
capabilities,
|
|
4039
|
-
now: options.now
|
|
4040
|
-
});
|
|
4041
|
-
}
|
|
4042
|
-
async function assertRetainedEnvironmentOwnership(provider, environmentId, idempotencyKey) {
|
|
4043
|
-
if (!provider.list) throw new Error(`provider "${provider.name}" cannot prove retained environment ownership by metadata`);
|
|
4044
|
-
const matches = (await provider.list({ metadata: { retainedIdempotencyKey: idempotencyKey } })).filter((summary) => summary.id === environmentId && summary.provider === provider.name);
|
|
4045
|
-
if (matches.length !== 1 || matches[0]?.metadata?.retainedIdempotencyKey !== idempotencyKey) throw new Error(`provider "${provider.name}" could not bind environment "${environmentId}" to its retained idempotency key`);
|
|
4046
|
-
}
|
|
4047
|
-
async function dispatchRetainedRun(options) {
|
|
4048
|
-
const { environment, identity } = options;
|
|
4049
|
-
assertRequestedInteractionCapabilities(options.provider.name, options.turn.interactions, options.capabilities);
|
|
4050
|
-
await admitDurably(options.onAdmission, {
|
|
4051
|
-
phase: "environment",
|
|
4052
|
-
provider: options.provider.name,
|
|
4053
|
-
environmentId: environment.id,
|
|
4054
|
-
idempotencyKey: options.environmentIdempotencyKey,
|
|
4055
|
-
turnId: options.turn.turnId,
|
|
4056
|
-
sessionId: identity.sessionId,
|
|
4057
|
-
executionId: identity.executionId
|
|
4058
|
-
});
|
|
4059
|
-
const destroyIfCreated = async (cause) => {
|
|
4060
|
-
if (environment.creation !== "created") throw cause;
|
|
4061
|
-
try {
|
|
4062
|
-
await environment.destroy?.();
|
|
4063
|
-
} catch (cleanupError) {
|
|
4064
|
-
throw new AggregateError([cause, cleanupError], "retained run dispatch failed and the environment it created could not be destroyed");
|
|
4065
|
-
}
|
|
4066
|
-
throw cause;
|
|
4067
|
-
};
|
|
4068
|
-
let reference;
|
|
4069
|
-
try {
|
|
4070
|
-
reference = await environment.dispatch(freshTurnInput(options.turn, {
|
|
4071
|
-
turnId: options.turn.turnId,
|
|
4072
|
-
detach: true,
|
|
4073
|
-
...identity
|
|
4074
|
-
}));
|
|
4075
|
-
} catch (error) {
|
|
4076
|
-
await destroyIfCreated(error);
|
|
4077
|
-
throw error;
|
|
4078
|
-
}
|
|
4079
|
-
let exact;
|
|
4080
|
-
try {
|
|
4081
|
-
if (reference.provider !== void 0 && reference.provider !== options.provider.name) throw new Error("provider dispatch returned a session reference for another provider");
|
|
4082
|
-
if (reference.id !== identity.sessionId) throw new Error("provider dispatched into another session than the requested identity");
|
|
4083
|
-
const controlRef = exactControlRef(reference.controlRef, {
|
|
4084
|
-
provider: options.provider.name,
|
|
4085
|
-
environmentId: environment.id,
|
|
4086
|
-
sessionId: identity.sessionId
|
|
4087
|
-
});
|
|
4088
|
-
if (controlRef.executionId !== identity.executionId) throw new Error("provider bound another execution than the requested identity");
|
|
4089
|
-
exact = exactSession(environment, controlRef);
|
|
4090
|
-
} catch (error) {
|
|
4091
|
-
const bindingError = new RetainedRunDispatchBindingError({
|
|
4092
|
-
provider: options.provider.name,
|
|
4093
|
-
environmentId: environment.id,
|
|
4094
|
-
sessionId: identity.sessionId,
|
|
4095
|
-
executionId: identity.executionId
|
|
4096
|
-
}, {
|
|
4097
|
-
...reference.id === void 0 ? {} : { id: reference.id },
|
|
4098
|
-
...reference.provider === void 0 ? {} : { provider: reference.provider },
|
|
4099
|
-
...reference.controlRef === void 0 ? {} : { controlRef: reference.controlRef }
|
|
4100
|
-
}, { cause: error });
|
|
4101
|
-
await destroyIfCreated(bindingError);
|
|
4102
|
-
throw bindingError;
|
|
4103
|
-
}
|
|
4104
|
-
await admitDurably(options.onAdmission, {
|
|
4105
|
-
phase: "dispatched",
|
|
4106
|
-
controlRef: freezeControlRef(exact.controlRef),
|
|
4107
|
-
idempotencyKey: options.environmentIdempotencyKey,
|
|
4108
|
-
turnId: options.turn.turnId
|
|
4109
|
-
});
|
|
4110
|
-
return createRetainedRunHandle(environment, exact.session, exact.controlRef, options.capabilities, options.now);
|
|
4111
|
-
}
|
|
4112
|
-
/**
|
|
4113
|
-
* Await one admission record through the caller's durability hook. A rejection
|
|
4114
|
-
* keeps the environment alive — the provider state plus any partial admission
|
|
4115
|
-
* record is the recovery path — and surfaces as `RetainedRunAdmissionError` so
|
|
4116
|
-
* callers can distinguish a persistence failure from a provider failure.
|
|
4117
|
-
*/
|
|
4118
|
-
async function admitDurably(onAdmission, admission) {
|
|
4119
|
-
const stableAdmission = detachedSnapshot(admission, "retained run admission");
|
|
4120
|
-
try {
|
|
4121
|
-
await onAdmission(stableAdmission);
|
|
4122
|
-
} catch (error) {
|
|
4123
|
-
if (isInteractiveAdmission(stableAdmission)) throw new RetainedInteractiveAdmissionError(stableAdmission, { cause: error });
|
|
4124
|
-
throw new RetainedRunAdmissionError(stableAdmission, { cause: error });
|
|
4125
|
-
}
|
|
4126
|
-
}
|
|
4127
|
-
function isInteractiveAdmission(admission) {
|
|
4128
|
-
return admission.phase === "interactive_intent" || admission.phase === "interactive_environment" || admission.phase === "interactive_started";
|
|
4129
|
-
}
|
|
4130
|
-
async function recoverRetainedRun(options) {
|
|
4131
|
-
if ("admission" in options) {
|
|
4132
|
-
if (options.admission.provider !== options.provider.name) throw new Error("retained run intent belongs to another provider");
|
|
4133
|
-
return {
|
|
4134
|
-
outcome: "recovered",
|
|
4135
|
-
handle: await startRetainedRun({
|
|
4136
|
-
provider: options.provider,
|
|
4137
|
-
...options.replay,
|
|
4138
|
-
intent: options.admission,
|
|
4139
|
-
onAdmission: options.onAdmission,
|
|
4140
|
-
now: options.now
|
|
4141
|
-
})
|
|
4142
|
-
};
|
|
4143
|
-
}
|
|
4144
|
-
assertStableText(options.environmentId, "retained environment id");
|
|
4145
|
-
assertStableText(options.sessionId, "retained session id");
|
|
4146
|
-
assertStableText(options.executionId, "retained execution id");
|
|
4147
|
-
const providerCapabilities = await assertRetainedCapabilities(options.provider);
|
|
4148
|
-
if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
|
|
4149
|
-
const environment = await options.provider.get(options.environmentId);
|
|
4150
|
-
if (!environment) return { outcome: "not_found" };
|
|
4151
|
-
const capabilities = retainedCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
|
|
4152
|
-
if (!environment.session) return {
|
|
4153
|
-
outcome: "unverifiable",
|
|
4154
|
-
environment
|
|
4155
|
-
};
|
|
4156
|
-
let session;
|
|
4157
|
-
try {
|
|
4158
|
-
session = environment.session(options.sessionId);
|
|
4159
|
-
} catch {
|
|
4160
|
-
return {
|
|
4161
|
-
outcome: "unverifiable",
|
|
4162
|
-
environment
|
|
4163
|
-
};
|
|
4164
|
-
}
|
|
4165
|
-
const parsed = AgentExactRunControlRefSchema.safeParse(session.controlRef);
|
|
4166
|
-
if (!parsed.success) return {
|
|
4167
|
-
outcome: "unverifiable",
|
|
4168
|
-
environment
|
|
4169
|
-
};
|
|
4170
|
-
const controlRef = parsed.data;
|
|
4171
|
-
if (controlRef.provider !== options.provider.name || controlRef.environmentId !== options.environmentId || controlRef.sessionId !== options.sessionId || controlRef.executionId !== options.executionId) throw new Error("provider session is bound to other retained run coordinates");
|
|
4172
|
-
const exact = exactSession(environment, controlRef);
|
|
4173
|
-
return {
|
|
4174
|
-
outcome: "recovered",
|
|
4175
|
-
handle: createRetainedRunHandle(environment, exact.session, exact.controlRef, capabilities, options.now)
|
|
4176
|
-
};
|
|
4177
|
-
}
|
|
4178
|
-
function retainedRunIntent(options, identity) {
|
|
4179
|
-
const requestedProfileDigest = canonicalCandidateDigest(options.environment.profile);
|
|
4180
|
-
const requestDigest = canonicalCandidateDigest({
|
|
4181
|
-
kind: "retained-run-intent.v1",
|
|
4182
|
-
provider: options.provider.name,
|
|
4183
|
-
idempotencyKey: options.environment.idempotencyKey,
|
|
4184
|
-
turnId: options.turn.turnId,
|
|
4185
|
-
sessionId: identity.sessionId,
|
|
4186
|
-
executionId: identity.executionId,
|
|
4187
|
-
requestedProfileDigest,
|
|
4188
|
-
create: retainedCreateMaterial(options.environment),
|
|
4189
|
-
turn: retainedTurnMaterial(options.turn)
|
|
4190
|
-
});
|
|
4191
|
-
return {
|
|
4192
|
-
phase: "intent",
|
|
4193
|
-
provider: options.provider.name,
|
|
4194
|
-
idempotencyKey: options.environment.idempotencyKey,
|
|
4195
|
-
turnId: options.turn.turnId,
|
|
4196
|
-
sessionId: identity.sessionId,
|
|
4197
|
-
executionId: identity.executionId,
|
|
4198
|
-
runId: `retained-intent-run:${requestDigest.slice(7)}`,
|
|
4199
|
-
requestedProfileDigest,
|
|
4200
|
-
requestDigest
|
|
4201
|
-
};
|
|
4202
|
-
}
|
|
4203
|
-
function assertExactRetainedRunIntent(received, expected) {
|
|
4204
|
-
if (canonicalCandidateDigest(parseRetainedRunIntent(received)) !== canonicalCandidateDigest(expected)) throw new Error("retained run intent conflicts with replay material");
|
|
4205
|
-
}
|
|
4206
|
-
function parseRetainedRunIntent(value) {
|
|
4207
|
-
const stable = detachedSnapshot(value, "retained run intent");
|
|
4208
|
-
if (stable === null || typeof stable !== "object" || Array.isArray(stable)) throw new Error("retained run intent is malformed");
|
|
4209
|
-
const record = stable;
|
|
4210
|
-
const allowed = /* @__PURE__ */ new Set([
|
|
4211
|
-
"phase",
|
|
4212
|
-
"provider",
|
|
4213
|
-
"idempotencyKey",
|
|
4214
|
-
"turnId",
|
|
4215
|
-
"sessionId",
|
|
4216
|
-
"executionId",
|
|
4217
|
-
"runId",
|
|
4218
|
-
"requestedProfileDigest",
|
|
4219
|
-
"requestDigest"
|
|
4220
|
-
]);
|
|
4221
|
-
if (Object.keys(record).some((key) => !allowed.has(key))) throw new Error("retained run intent contains unsupported material");
|
|
4222
|
-
if (record.phase !== "intent") throw new Error("retained run intent has an invalid phase");
|
|
4223
|
-
for (const [key, value] of Object.entries(record)) {
|
|
4224
|
-
if (key === "phase") continue;
|
|
4225
|
-
if (typeof value !== "string" || value.length === 0) throw new Error(`retained run intent field "${key}" is invalid`);
|
|
4226
|
-
}
|
|
4227
|
-
assertDigest$1(record.requestedProfileDigest, "retained run intent profile digest");
|
|
4228
|
-
assertDigest$1(record.requestDigest, "retained run intent request digest");
|
|
4229
|
-
return stable;
|
|
4230
|
-
}
|
|
4231
|
-
function assertDigest$1(value, label) {
|
|
4232
|
-
if (typeof value !== "string" || !/^sha256:[a-f0-9]{64}$/u.test(value)) throw new Error(`${label} is invalid`);
|
|
4233
|
-
}
|
|
4234
|
-
/** Rebuild a retained-run client without retaining any object from the starter. @stable */
|
|
4235
|
-
async function reconnectRetainedRun(options) {
|
|
4236
|
-
const controlRef = AgentExactRunControlRefSchema.parse(options.controlRef);
|
|
4237
|
-
if (controlRef.provider !== options.provider.name) throw new Error(`run provider "${controlRef.provider}" does not match "${options.provider.name}"`);
|
|
4238
|
-
const providerCapabilities = await assertRetainedCapabilities(options.provider);
|
|
4239
|
-
if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
|
|
4240
|
-
const environment = await options.provider.get(controlRef.environmentId);
|
|
4241
|
-
if (!environment) return null;
|
|
4242
|
-
const capabilities = retainedCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
|
|
4243
|
-
const exact = exactSession(environment, controlRef);
|
|
4244
|
-
return createRetainedRunHandle(environment, exact.session, exact.controlRef, capabilities, options.now);
|
|
4245
|
-
}
|
|
4246
|
-
async function assertRetainedCapabilities(provider) {
|
|
4247
|
-
const capabilities = AgentEnvironmentCapabilitiesSchema.parse(await provider.capabilities());
|
|
4248
|
-
assertRetainedCapabilityRequirements(provider.name, capabilities);
|
|
4249
|
-
return capabilities;
|
|
4250
|
-
}
|
|
4251
|
-
/**
|
|
4252
|
-
* Select the capability document for one concrete environment.
|
|
4253
|
-
*
|
|
4254
|
-
* A measured environment document is authoritative. An absent document uses
|
|
4255
|
-
* the provider document because that provider claims the same guarantee for
|
|
4256
|
-
* every environment it creates.
|
|
4257
|
-
*/
|
|
4258
|
-
function retainedCapabilitiesForEnvironment(providerName, providerCapabilities, environment) {
|
|
4259
|
-
if (environment.capabilities === void 0) return providerCapabilities;
|
|
4260
|
-
const measured = AgentEnvironmentCapabilitiesSchema.parse(environment.capabilities);
|
|
4261
|
-
assertRetainedCapabilityRequirements(providerName, measured);
|
|
4262
|
-
return measured;
|
|
4263
|
-
}
|
|
4264
|
-
function assertRetainedCapabilityRequirements(providerName, capabilities) {
|
|
4265
|
-
const retained = capabilities.retainedControl;
|
|
4266
|
-
if (retained?.exactRunIdentity !== true || retained.resultIdentity !== true || retained.eventIdentity !== true || retained.cancellationIdempotency !== true || !capabilities.streaming.detach || !capabilities.streaming.replay || !capabilities.streaming.turnIdempotency) throw new Error(`provider "${providerName}" cannot control a retry-safe retained run`);
|
|
4267
|
-
}
|
|
4268
|
-
//#endregion
|
|
4269
|
-
//#region src/runtime/retained-interactive.ts
|
|
4270
|
-
/**
|
|
4271
|
-
* Start one retry-safe native coding-agent TUI without dispatching a headless turn.
|
|
4272
|
-
* The intent admission is durable before provider.create; the environment and
|
|
4273
|
-
* process admissions follow only after their exact provider coordinates exist.
|
|
4274
|
-
* @stable
|
|
4275
|
-
*/
|
|
4276
|
-
async function startRetainedInteractiveRun(options) {
|
|
4277
|
-
options.signal?.throwIfAborted();
|
|
4278
|
-
assertStableText(options.environment.idempotencyKey, "environment idempotency key");
|
|
4279
|
-
assertStableText(options.interactiveIdempotencyKey, "interactive idempotency key");
|
|
4280
|
-
if (typeof options.onAdmission !== "function") throw new Error("startRetainedInteractiveRun requires an awaited onAdmission durability hook");
|
|
4281
|
-
if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
|
|
4282
|
-
const profile = agentProfileSchema.parse(options.environment.profile);
|
|
4283
|
-
if (profile.harness === void 0) throw new Error("retained interactive runs require AgentProfile.harness");
|
|
4284
|
-
const requestedProfileDigest = canonicalAgentProfileDigest(profile);
|
|
4285
|
-
const identity = mintRetainedIdentity(options.environment.idempotencyKey, options.interactiveIdempotencyKey);
|
|
4286
|
-
const intent = interactiveIntent(options, profile, identity);
|
|
4287
|
-
if (options.intent === void 0) await admitDurably(options.onAdmission, intent);
|
|
4288
|
-
else assertExactInteractiveIntent(options.intent, intent);
|
|
4289
|
-
const providerCapabilities = AgentEnvironmentCapabilitiesSchema.parse(await awaitAbortable(Promise.resolve().then(() => options.provider.capabilities()), options.signal));
|
|
4290
|
-
assertInteractiveCapabilities(options.provider.name, providerCapabilities);
|
|
4291
|
-
const environment = await createInteractiveEnvironment(() => options.provider.create({
|
|
4292
|
-
...options.environment,
|
|
4293
|
-
profile,
|
|
4294
|
-
signal: options.signal,
|
|
4295
|
-
metadata: retainedEnvironmentMetadata(options.environment.metadata, options.environment.idempotencyKey)
|
|
4296
|
-
}), options.signal);
|
|
4297
|
-
let capabilities;
|
|
4298
|
-
try {
|
|
4299
|
-
assertExactEnvironment(options.provider.name, environment);
|
|
4300
|
-
options.signal?.throwIfAborted();
|
|
4301
|
-
capabilities = interactiveCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
|
|
4302
|
-
assertInteractiveMethods(options.provider.name, environment);
|
|
4303
|
-
} catch (error) {
|
|
4304
|
-
await destroyUnusedEnvironment(environment, error);
|
|
4305
|
-
throw error;
|
|
4306
|
-
}
|
|
4307
|
-
const request = interactiveRequest(options, environment, profile, requestedProfileDigest, identity);
|
|
4308
|
-
await admitDurably(options.onAdmission, {
|
|
4309
|
-
phase: "interactive_environment",
|
|
4310
|
-
provider: options.provider.name,
|
|
4311
|
-
environmentId: environment.id,
|
|
4312
|
-
idempotencyKey: options.environment.idempotencyKey,
|
|
4313
|
-
interactiveIdempotencyKey: options.interactiveIdempotencyKey,
|
|
4314
|
-
request
|
|
4315
|
-
});
|
|
4316
|
-
const ref = exactStartedRef(request, await startInteractiveProcess(environment, () => environment.startInteractive(request, { signal: options.signal }), options.signal));
|
|
4317
|
-
await admitDurably(options.onAdmission, {
|
|
4318
|
-
phase: "interactive_started",
|
|
4319
|
-
idempotencyKey: options.environment.idempotencyKey,
|
|
4320
|
-
interactiveIdempotencyKey: options.interactiveIdempotencyKey,
|
|
4321
|
-
ref
|
|
4322
|
-
});
|
|
4323
|
-
return createRetainedInteractiveRunHandle(environment, ref, capabilities, request);
|
|
4324
|
-
}
|
|
4325
|
-
/** Retry one exact start after its provider response may have been lost. @stable */
|
|
4326
|
-
async function recoverRetainedInteractiveRun(options) {
|
|
4327
|
-
options.signal?.throwIfAborted();
|
|
4328
|
-
if (typeof options.onAdmission !== "function") throw new Error("recoverRetainedInteractiveRun requires an awaited onAdmission durability hook");
|
|
4329
|
-
const admission = options.admission;
|
|
4330
|
-
if (admission.provider !== options.provider.name) throw new Error("interactive admission belongs to another provider");
|
|
4331
|
-
if (admission.phase === "interactive_intent") {
|
|
4332
|
-
if (options.replay === void 0) throw new Error("recoverRetainedInteractiveRun requires the original start material for an interactive intent");
|
|
4333
|
-
return startRetainedInteractiveRun({
|
|
4334
|
-
provider: options.provider,
|
|
4335
|
-
...options.replay,
|
|
4336
|
-
intent: admission,
|
|
4337
|
-
onAdmission: options.onAdmission,
|
|
4338
|
-
signal: options.signal
|
|
4339
|
-
});
|
|
4340
|
-
}
|
|
4341
|
-
const request = exactRecoveryRequest(admission);
|
|
4342
|
-
const { environment, capabilities } = await reconstructEnvironment(options.provider, admission.environmentId, options.signal);
|
|
4343
|
-
if (!environment || !capabilities) return null;
|
|
4344
|
-
const ref = exactStartedRef(request, await awaitAbortable(Promise.resolve().then(() => environment.startInteractive(request, { signal: options.signal })), options.signal));
|
|
4345
|
-
await admitDurably(options.onAdmission, {
|
|
4346
|
-
phase: "interactive_started",
|
|
4347
|
-
idempotencyKey: admission.idempotencyKey,
|
|
4348
|
-
interactiveIdempotencyKey: admission.interactiveIdempotencyKey,
|
|
4349
|
-
ref
|
|
4350
|
-
});
|
|
4351
|
-
return createRetainedInteractiveRunHandle(environment, ref, capabilities, request);
|
|
4352
|
-
}
|
|
4353
|
-
function exactRecoveryRequest(admission) {
|
|
4354
|
-
assertStableText(admission.environmentId, "interactive environment id");
|
|
4355
|
-
assertStableText(admission.idempotencyKey, "environment idempotency key");
|
|
4356
|
-
assertStableText(admission.interactiveIdempotencyKey, "interactive idempotency key");
|
|
4357
|
-
const request = exactAgentInteractiveSessionStart(admission.request);
|
|
4358
|
-
const identity = mintRetainedIdentity(admission.idempotencyKey, admission.interactiveIdempotencyKey);
|
|
4359
|
-
if (request.run.provider !== admission.provider || request.run.environmentId !== admission.environmentId || request.run.sessionId !== identity.sessionId || request.run.executionId !== identity.executionId) throw new Error("interactive admission does not match its recovery coordinates");
|
|
4360
|
-
return request;
|
|
4361
|
-
}
|
|
4362
|
-
/** Rebuild controls for one exact provider-owned coding-agent process. @stable */
|
|
4363
|
-
async function reconnectRetainedInteractiveRun(options) {
|
|
4364
|
-
options.signal?.throwIfAborted();
|
|
4365
|
-
const ref = AgentInteractiveSessionRefSchema.parse(options.ref);
|
|
4366
|
-
if (ref.run.provider !== options.provider.name) throw new Error("interactive session reference belongs to another provider");
|
|
4367
|
-
const { environment, capabilities } = await reconstructEnvironment(options.provider, ref.run.environmentId, options.signal);
|
|
4368
|
-
if (!environment || !capabilities) return null;
|
|
4369
|
-
const handle = createRetainedInteractiveRunHandle(environment, ref, capabilities);
|
|
4370
|
-
await handle.status({ signal: options.signal });
|
|
4371
|
-
return handle;
|
|
4372
|
-
}
|
|
4373
|
-
function interactiveRequest(options, environment, profile, requestedProfileDigest, identity) {
|
|
4374
|
-
const start = {
|
|
4375
|
-
profile,
|
|
4376
|
-
requestedProfileDigest,
|
|
4377
|
-
...options.initialPrompt === void 0 ? {} : { initialPrompt: options.initialPrompt },
|
|
4378
|
-
...options.cwd === void 0 ? {} : { cwd: options.cwd },
|
|
4379
|
-
...options.cols === void 0 ? {} : { cols: options.cols },
|
|
4380
|
-
...options.rows === void 0 ? {} : { rows: options.rows }
|
|
4381
|
-
};
|
|
4382
|
-
return exactAgentInteractiveSessionStart({
|
|
4383
|
-
run: agentInteractiveSessionRunRef({
|
|
4384
|
-
provider: options.provider.name,
|
|
4385
|
-
environmentId: environment.id,
|
|
4386
|
-
...identity
|
|
4387
|
-
}, start),
|
|
4388
|
-
...start
|
|
4389
|
-
});
|
|
4390
|
-
}
|
|
4391
|
-
function interactiveIntent(options, profile, identity) {
|
|
4392
|
-
const requestedProfileDigest = canonicalAgentProfileDigest(profile);
|
|
4393
|
-
const requestDigest = canonicalCandidateDigest({
|
|
4394
|
-
kind: "retained-interactive-intent.v1",
|
|
4395
|
-
provider: options.provider.name,
|
|
4396
|
-
idempotencyKey: options.environment.idempotencyKey,
|
|
4397
|
-
interactiveIdempotencyKey: options.interactiveIdempotencyKey,
|
|
4398
|
-
sessionId: identity.sessionId,
|
|
4399
|
-
executionId: identity.executionId,
|
|
4400
|
-
requestedProfileDigest,
|
|
4401
|
-
create: retainedCreateMaterial(options.environment),
|
|
4402
|
-
start: sanitizedStartMaterial(options)
|
|
4403
|
-
});
|
|
4404
|
-
return {
|
|
4405
|
-
phase: "interactive_intent",
|
|
4406
|
-
provider: options.provider.name,
|
|
4407
|
-
idempotencyKey: options.environment.idempotencyKey,
|
|
4408
|
-
interactiveIdempotencyKey: options.interactiveIdempotencyKey,
|
|
4409
|
-
sessionId: identity.sessionId,
|
|
4410
|
-
executionId: identity.executionId,
|
|
4411
|
-
runId: `interactive-intent-run:${requestDigest.slice(7)}`,
|
|
4412
|
-
requestedProfileDigest,
|
|
4413
|
-
requestDigest
|
|
4414
|
-
};
|
|
4415
|
-
}
|
|
4416
|
-
function sanitizedStartMaterial(options) {
|
|
4417
|
-
return {
|
|
4418
|
-
...options.initialPrompt === void 0 ? {} : { initialPrompt: options.initialPrompt },
|
|
4419
|
-
...options.cwd === void 0 ? {} : { cwd: options.cwd },
|
|
4420
|
-
...options.cols === void 0 ? {} : { cols: options.cols },
|
|
4421
|
-
...options.rows === void 0 ? {} : { rows: options.rows }
|
|
4422
|
-
};
|
|
4423
|
-
}
|
|
4424
|
-
function assertExactInteractiveIntent(received, expected) {
|
|
4425
|
-
if (canonicalCandidateDigest(parseInteractiveIntent(received)) !== canonicalCandidateDigest(expected)) throw new Error("interactive intent conflicts with replay material");
|
|
4426
|
-
}
|
|
4427
|
-
function parseInteractiveIntent(value) {
|
|
4428
|
-
const stable = detachedSnapshot(value, "interactive intent");
|
|
4429
|
-
if (stable === null || typeof stable !== "object" || Array.isArray(stable)) throw new Error("interactive intent is malformed");
|
|
4430
|
-
const record = stable;
|
|
4431
|
-
const allowed = /* @__PURE__ */ new Set([
|
|
4432
|
-
"phase",
|
|
4433
|
-
"provider",
|
|
4434
|
-
"idempotencyKey",
|
|
4435
|
-
"interactiveIdempotencyKey",
|
|
4436
|
-
"sessionId",
|
|
4437
|
-
"executionId",
|
|
4438
|
-
"runId",
|
|
4439
|
-
"requestedProfileDigest",
|
|
4440
|
-
"requestDigest"
|
|
4441
|
-
]);
|
|
4442
|
-
if (Object.keys(record).some((key) => !allowed.has(key))) throw new Error("interactive intent contains unsupported material");
|
|
4443
|
-
if (record.phase !== "interactive_intent") throw new Error("interactive intent has an invalid phase");
|
|
4444
|
-
for (const [key, value] of Object.entries(record)) {
|
|
4445
|
-
if (key === "phase") continue;
|
|
4446
|
-
if (typeof value !== "string" || value.length === 0) throw new Error(`interactive intent field "${key}" is invalid`);
|
|
4447
|
-
}
|
|
4448
|
-
assertDigest(record.requestedProfileDigest, "interactive intent profile digest");
|
|
4449
|
-
assertDigest(record.requestDigest, "interactive intent request digest");
|
|
4450
|
-
return stable;
|
|
4451
|
-
}
|
|
4452
|
-
function assertDigest(value, label) {
|
|
4453
|
-
if (typeof value !== "string" || !/^sha256:[a-f0-9]{64}$/u.test(value)) throw new Error(`${label} is invalid`);
|
|
4454
|
-
}
|
|
4455
|
-
async function reconstructEnvironment(provider, environmentId, signal) {
|
|
4456
|
-
if (!provider.get) throw new Error(`provider "${provider.name}" cannot reconstruct an environment by id`);
|
|
4457
|
-
const providerCapabilities = AgentEnvironmentCapabilitiesSchema.parse(await awaitAbortable(Promise.resolve().then(() => provider.capabilities()), signal));
|
|
4458
|
-
assertInteractiveCapabilities(provider.name, providerCapabilities);
|
|
4459
|
-
const environment = await awaitAbortable(Promise.resolve().then(() => provider.get(environmentId, { signal })), signal);
|
|
4460
|
-
if (!environment) return {
|
|
4461
|
-
environment: null,
|
|
4462
|
-
capabilities: null
|
|
4463
|
-
};
|
|
4464
|
-
assertExactEnvironment(provider.name, environment, environmentId);
|
|
4465
|
-
const capabilities = interactiveCapabilitiesForEnvironment(provider.name, providerCapabilities, environment);
|
|
4466
|
-
assertInteractiveMethods(provider.name, environment);
|
|
4467
|
-
return {
|
|
4468
|
-
environment,
|
|
4469
|
-
capabilities
|
|
4470
|
-
};
|
|
4471
|
-
}
|
|
4472
|
-
function exactStartedRef(request, value) {
|
|
4473
|
-
const stableRequest = detachedSnapshot(request, "interactive start binding request");
|
|
4474
|
-
let ref;
|
|
4475
|
-
try {
|
|
4476
|
-
ref = AgentInteractiveSessionRefSchema.parse(value);
|
|
4477
|
-
} catch (error) {
|
|
4478
|
-
throw new RetainedInteractiveBindingError(stableRequest, {}, { cause: error });
|
|
4479
|
-
}
|
|
4480
|
-
if (!agentInteractiveSessionRefMatchesStart(request, ref)) throw new RetainedInteractiveBindingError(stableRequest, detachedSnapshot({ ref: detachedSnapshot(ref, "interactive provider start reference") }, "interactive provider start result"), { cause: /* @__PURE__ */ new Error("provider started another interactive run than requested") });
|
|
4481
|
-
return freezeInteractiveRef(ref);
|
|
4482
|
-
}
|
|
4483
|
-
function assertExactEnvironment(providerName, environment, environmentId) {
|
|
4484
|
-
if (environment.provider !== providerName || environmentId && environment.id !== environmentId) throw new Error("provider returned another interactive environment");
|
|
4485
|
-
assertStableText(environment.id, "interactive environment id");
|
|
4486
|
-
}
|
|
4487
|
-
function interactiveCapabilitiesForEnvironment(providerName, providerCapabilities, environment) {
|
|
4488
|
-
const capabilities = environment.capabilities === void 0 ? providerCapabilities : AgentEnvironmentCapabilitiesSchema.parse(environment.capabilities);
|
|
4489
|
-
assertInteractiveCapabilities(providerName, capabilities);
|
|
4490
|
-
return capabilities;
|
|
4491
|
-
}
|
|
4492
|
-
function assertInteractiveCapabilities(providerName, capabilities) {
|
|
4493
|
-
const interactive = capabilities.interactiveAgent;
|
|
4494
|
-
if (!interactive?.start || !interactive.control || !interactive.status || !interactive.attach || !interactive.reattach || !interactive.sendPrompt || !interactive.input || !interactive.resize || !interactive.stop) throw new Error(`provider "${providerName}" cannot control an exact interactive agent`);
|
|
4495
|
-
}
|
|
4496
|
-
function assertInteractiveMethods(providerName, environment) {
|
|
4497
|
-
if (!environment.startInteractive || !environment.interactive) throw new Error(`provider "${providerName}" exposes incomplete interactive agent controls`);
|
|
4498
|
-
}
|
|
4499
|
-
async function destroyUnusedEnvironment(environment, cause) {
|
|
4500
|
-
try {
|
|
4501
|
-
await destroyInteractiveEnvironment(environment);
|
|
4502
|
-
} catch (cleanupError) {
|
|
4503
|
-
throw new AggregateError([cause, cleanupError], "interactive environment was invalid and could not be destroyed");
|
|
4504
|
-
}
|
|
4505
|
-
}
|
|
4506
|
-
//#endregion
|
|
4507
|
-
//#region src/runtime/retained-interactive-control.ts
|
|
4508
|
-
const MAX_GENERATION_CONFLICTS = 8;
|
|
4509
|
-
/**
|
|
4510
|
-
* Acquire provider-issued write authority without reading authority from status.
|
|
4511
|
-
*
|
|
4512
|
-
* A new coordinator starts at generation zero. If another claim already exists,
|
|
4513
|
-
* the provider returns its public generation and this helper retries one new
|
|
4514
|
-
* compare-and-swap operation. Every generation has a deterministic operation
|
|
4515
|
-
* identifier, so retrying after an ambiguous response cannot create two claims.
|
|
4516
|
-
* @stable
|
|
4517
|
-
*/
|
|
4518
|
-
async function claimRetainedInteractiveControl(options) {
|
|
4519
|
-
const expected = options.expectedGeneration ?? 0;
|
|
4520
|
-
if (!Number.isSafeInteger(expected) || expected < 0) throw new Error("interactive control expectedGeneration must be a non-negative integer");
|
|
4521
|
-
let generation = expected;
|
|
4522
|
-
for (let conflict = 0; conflict <= MAX_GENERATION_CONFLICTS; conflict += 1) {
|
|
4523
|
-
if (options.signal?.aborted) throw abortError(options.signal.reason);
|
|
4524
|
-
const material = {
|
|
4525
|
-
operationId: controlClaimOperationId(options.handle, options.holderId, generation),
|
|
4526
|
-
ref: options.handle.ref,
|
|
4527
|
-
holderId: options.holderId,
|
|
4528
|
-
expectedGeneration: generation
|
|
4529
|
-
};
|
|
4530
|
-
const acknowledgement = await options.handle.claimControl({
|
|
4531
|
-
...material,
|
|
4532
|
-
requestDigest: agentInteractiveSessionControlClaimRequestDigest(material)
|
|
4533
|
-
}, options.signal === void 0 ? void 0 : { signal: options.signal });
|
|
4534
|
-
if (acknowledgement.status === "accepted" || acknowledgement.status === "replayed") {
|
|
4535
|
-
const control = acknowledgement.control;
|
|
4536
|
-
if (control === void 0) throw new Error("provider accepted interactive control without returning its claim");
|
|
4537
|
-
if (Date.parse(control.expiresAt) <= Date.now()) throw new Error("provider returned an expired interactive control claim");
|
|
4538
|
-
return control;
|
|
4539
|
-
}
|
|
4540
|
-
if (acknowledgement.status !== "conflict" || acknowledgement.conflictReason !== "generation_mismatch") throw new Error(acknowledgement.status === "unknown" ? "interactive control claim outcome is unknown; retry the same acquisition" : "interactive control claim operation conflicts with different request material");
|
|
4541
|
-
const current = acknowledgement.currentGeneration;
|
|
4542
|
-
if (current === void 0 || current <= generation) throw new Error("provider returned a non-advancing interactive control generation");
|
|
4543
|
-
generation = current;
|
|
4544
|
-
}
|
|
4545
|
-
throw new Error("interactive control changed too often to acquire safely");
|
|
4546
|
-
}
|
|
4547
|
-
function controlClaimOperationId(handle, holderId, expectedGeneration) {
|
|
4548
|
-
return `interactive-claim-${canonicalCandidateDigest({
|
|
4549
|
-
kind: "retained-interactive-control-claim.v1",
|
|
4550
|
-
ref: handle.ref,
|
|
4551
|
-
holderId,
|
|
4552
|
-
expectedGeneration
|
|
4553
|
-
}).slice(7, 47)}`;
|
|
4554
|
-
}
|
|
4555
|
-
//#endregion
|
|
4556
3477
|
//#region src/runtime/run-benchmark.ts
|
|
4557
3478
|
/**
|
|
4558
3479
|
* runBenchmark — the packaged optimization suite. Define a domain by implementing an
|
|
@@ -7358,6 +6279,6 @@ function tail(s) {
|
|
|
7358
6279
|
return s.slice(-400);
|
|
7359
6280
|
}
|
|
7360
6281
|
//#endregion
|
|
7361
|
-
export {
|
|
6282
|
+
export { InMemoryCorpus as $, chatWorkerSeam as A, renderLeaderboardSvg as At, SandboxRunAbortError as B, mcpSecretEnvMetadataKey as Bt, withUntrackedArtifacts as C, deterministicCompletion as Ct, codeModeSupervisorTools as D, pairwiseSignificance as Dt, runCoderChecks as E, leaderboard as Et, selectChampion as F, connectStdioMcp as Ft, equalKOnCost as G, printBenchmarkReport as H, resolveSecretEnv as Ht, assertStrategyContract as I, materializeLocalMcp as It, runPersonified as J, trajectoryReport as K, authorStrategy as L, createMcpEnvironment as Lt, discriminatingMeans as M, auditIntent as Mt, pickChampion as N, defaultAuditorInstruction as Nt, unsafeInProcessRunner as O, renderLeaderboardHtml as Ot, runStrategyEvolution as P, McpSpawnFault as Pt, FileCorpus as Q, strategyAuthorContract as R, sanitizeMcpToolSchema as Rt, copyUntrackedIntoClone as S, completionAuthorizes as St, patchDelivered as T, stopSentinel as Tt, runBenchmark as U, secretEnvOfMcpServer as Ut, openSandboxRun as V, resolveMcpServerLaunch as Vt, promotionGate as W, createShapeRegistry as X, builtinShapes as Y, registerShape as Z, NOTE_MAX_CHARS as _, localSandboxClient as _t, localShell as a, pipeline as at, composeWorkerEvidence as b, loopDispatch as bt, createVerifierEnvironment as c, widen as ct, harvestSurfaceDiffs as d, createScopeAnalyst as dt, renderCorpusToInstructions as et, analystsFromRegistry as f, registryScopeAnalyst as ft, EVIDENCE_MAX_CHARS as g, resolveSandboxClient as gt, worktreeFanout as h, defineLeaderboard as ht, jjWorkspace as i, panel as it, createChatSessionStore as j, renderPairwiseMarkdown as jt, chatTransportExecutor as k, renderLeaderboardMarkdown as kt, boxSurfaceReader as l, assertTraceDerivedFindings as lt, superviseSurface as m, harvestCorpus as mt, makeFinding$1 as n, flatWidenGate as nt, runInWorkspace as o, selectValidWinner as ot, failuresAnalyst as p, inProcessSandboxClient as pt, definePersona as q, gitWorkspace as r, loopUntil as rt, createWaterfallCollector as s, verify as st, computeFindingId$1 as t, fanout as tt, fsSurfaceReader as u, buildSteerContext as ut, VERIFY_TAIL_CHARS as v, inlineSandboxClient as vt, analyzeTrace as w, sentinelCompletion as wt, settledWorkerOut as x, superviseDispatch as xt, closingWorkerNote as y, loopCampaignDispatch as yt, strategyAuthorSystemPrompt as z, envKeyProvider as zt };
|
|
7362
6283
|
|
|
7363
|
-
//# sourceMappingURL=runtime-
|
|
6284
|
+
//# sourceMappingURL=runtime-CJNlF5wM.js.map
|