@tangle-network/agent-runtime 0.131.6 → 0.132.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 +38 -0
- package/dist/{activation-D-gsrgSq.js → activation-BTcytBme.js} +3 -3
- package/dist/{activation-D-gsrgSq.js.map → activation-BTcytBme.js.map} +1 -1
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +3 -3
- package/dist/{analyst-loop-BE8cDs5Q.js → analyst-loop-CBiT-ev1.js} +2 -2
- package/dist/{analyst-loop-BE8cDs5Q.js.map → analyst-loop-CBiT-ev1.js.map} +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/analyst-loop.js +1 -1
- package/dist/{authoring-DI778qK7.js → authoring-D0wM2FaY.js} +2 -2
- package/dist/{authoring-DI778qK7.js.map → authoring-D0wM2FaY.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-BNxKr-Bu.js → candidate-execution-DxL_I3xx.js} +4 -4
- package/dist/{candidate-execution-BNxKr-Bu.js.map → candidate-execution-DxL_I3xx.js.map} +1 -1
- package/dist/{conversation-9ZmilKp8.js → conversation-D95pue6P.js} +2 -2
- package/dist/{conversation-9ZmilKp8.js.map → conversation-D95pue6P.js.map} +1 -1
- package/dist/conversation.d.ts +1 -1
- package/dist/conversation.js +1 -1
- package/dist/{environment-provider-CxvSd1W6.d.ts → environment-provider-BDwgo2pu.d.ts} +5 -5
- package/dist/{environment-provider-Dyg8DtLK.js → environment-provider-mDsjfGjY.js} +2 -2
- package/dist/{environment-provider-Dyg8DtLK.js.map → environment-provider-mDsjfGjY.js.map} +1 -1
- package/dist/environment-provider.d.ts +1 -1
- package/dist/environment-provider.js +1 -1
- package/dist/{graph-CoN60QtH.js → graph-DyWVymtQ.js} +3 -3
- package/dist/{graph-CoN60QtH.js.map → graph-DyWVymtQ.js.map} +1 -1
- package/dist/{improvement-cycle-BGF0osPC.js → improvement-cycle-0H8-10KE.js} +6 -6
- package/dist/{improvement-cycle-BGF0osPC.js.map → improvement-cycle-0H8-10KE.js.map} +1 -1
- package/dist/{index-CoO7atyo.d.ts → index-BLIEkf7Y.d.ts} +3204 -3085
- package/dist/{index-DwGtu9nc.d.ts → index-D3SUI9Fc.d.ts} +4 -4
- package/dist/{index-qYHpsmG2.d.ts → index-qKm5g7mI.d.ts} +3 -3
- package/dist/index.d.ts +9 -9
- package/dist/index.js +14 -14
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +5 -5
- package/dist/intelligence.js +6 -6
- package/dist/kernel.d.ts +7 -7
- package/dist/kernel.js +11 -11
- package/dist/{knowledge-D4zNvxw5.js → knowledge-DOpOk7f5.js} +5 -5
- package/dist/{knowledge-D4zNvxw5.js.map → knowledge-DOpOk7f5.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-CI9Y0sxT.js → loop-runner-bin-D38yZAyS.js} +4 -4
- package/dist/{loop-runner-bin-CI9Y0sxT.js.map → loop-runner-bin-D38yZAyS.js.map} +1 -1
- package/dist/{loop-runner-bin-BwgZ8m_7.d.ts → loop-runner-bin-DHjRAhLD.d.ts} +3 -3
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +5 -5
- package/dist/mcp/index.js +5 -5
- package/dist/{openai-tools-CupeHJEv.js → openai-tools-CMrN2Ik_.js} +2 -2
- package/dist/{openai-tools-CupeHJEv.js.map → openai-tools-CMrN2Ik_.js.map} +1 -1
- package/dist/{openai-tools-D3oMyVGl.d.ts → openai-tools-CzEiSbPW.d.ts} +2 -2
- package/dist/{prepare-DYWjVcPx.js → prepare-BQ82nG06.js} +2 -2
- package/dist/{prepare-DYWjVcPx.js.map → prepare-BQ82nG06.js.map} +1 -1
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{protected-model-port-48ALLGxT.js → protected-model-port-BAOj4gQN.js} +2 -2
- package/dist/{protected-model-port-48ALLGxT.js.map → protected-model-port-BAOj4gQN.js.map} +1 -1
- package/dist/{redact-9_Gf-8m3.d.ts → redact-C49ag0R2.d.ts} +3 -3
- package/dist/{runtime-D-QfLbSd.d.ts → runtime-B0rxwNg7.d.ts} +4 -4
- package/dist/{runtime-ZNVnT8h1.js → runtime-D5GueIHH.js} +581 -31
- package/dist/runtime-D5GueIHH.js.map +1 -0
- package/dist/{sandbox-events-CRDwc5WN.js → sandbox-events-vIwmuPdl.js} +80 -2
- package/dist/sandbox-events-vIwmuPdl.js.map +1 -0
- package/dist/{spawn-journal-saHQzqYi.js → spawn-journal-Cd5L-Ie9.js} +20 -9
- package/dist/spawn-journal-Cd5L-Ie9.js.map +1 -0
- package/dist/{stream-agent-turn-DE8_alvm.js → stream-agent-turn-BxwZJVfZ.js} +2 -2
- package/dist/{stream-agent-turn-DE8_alvm.js.map → stream-agent-turn-BxwZJVfZ.js.map} +1 -1
- package/dist/{stream-agent-turn-C852AgMT.d.ts → stream-agent-turn-DcDznEnq.d.ts} +3 -3
- package/dist/{structural-rollout-n089ZP33.js → structural-rollout-9jcaIsxA.js} +4 -4
- package/dist/{structural-rollout-n089ZP33.js.map → structural-rollout-9jcaIsxA.js.map} +1 -1
- package/dist/{supervise-msTRhTN7.js → supervise-C9iPh1y6.js} +24 -6
- package/dist/supervise-C9iPh1y6.js.map +1 -0
- package/dist/{supervisor-C16p9KqO.js → supervisor-DAHeTMAT.js} +93 -82
- package/dist/supervisor-DAHeTMAT.js.map +1 -0
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +12 -12
- package/dist/{types-ebIY0dMG.d.ts → types-6zHo67jn.d.ts} +13 -1
- package/dist/{types-C6Q-J0Dt.d.ts → types-CIg5DBNF.d.ts} +12 -3
- package/dist/{util-Bw6srryQ.js → util-Dr--8wAL.js} +32 -3
- package/dist/util-Dr--8wAL.js.map +1 -0
- package/dist/{workspace-archive-aOfJ47ms.js → workspace-archive-CGcXL3zA.js} +2 -2
- package/dist/{workspace-archive-aOfJ47ms.js.map → workspace-archive-CGcXL3zA.js.map} +1 -1
- package/package.json +4 -4
- package/dist/runtime-ZNVnT8h1.js.map +0 -1
- package/dist/sandbox-events-CRDwc5WN.js.map +0 -1
- package/dist/spawn-journal-saHQzqYi.js.map +0 -1
- package/dist/supervise-msTRhTN7.js.map +0 -1
- package/dist/supervisor-C16p9KqO.js.map +0 -1
- package/dist/util-Bw6srryQ.js.map +0 -1
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import { n as AnalystError, s as PlannerError, u as ValidationError } from "./errors-DEAvWQPy.js";
|
|
2
|
-
import "./stream-agent-turn-
|
|
3
|
-
import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal-
|
|
4
|
-
import { a as
|
|
2
|
+
import "./stream-agent-turn-BxwZJVfZ.js";
|
|
3
|
+
import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal-Cd5L-Ie9.js";
|
|
4
|
+
import { a as isAbortError, i as hasCompleteCacheBreakdown, l as sleep, m as zeroTokenUsage, n as cloneTokenUsage, s as randomSuffix, t as addTokenUsage, u as stringifySafe } from "./util-Dr--8wAL.js";
|
|
5
5
|
import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction--F3v1oo8.js";
|
|
6
|
-
import { a as notifySandboxEventObserver } from "./sandbox-events-
|
|
6
|
+
import { a as notifySandboxEventObserver, c as parseCanonicalTransportEvent, s as extractTransportEventIdentity } from "./sandbox-events-vIwmuPdl.js";
|
|
7
7
|
import { c as profileProviderModel, i as concreteModelId, s as profileModelExecutionSettings, t as assertExecutableAgentProfile } from "./model-policy-mWSoToiQ.js";
|
|
8
8
|
import { v as executableAgentProfileSnapshot, y as executableAgentSpecSnapshot } from "./materialization-DBXuH34A.js";
|
|
9
|
-
import { $ as createSandboxLineage, I as createWorktreeCliExecutor, N as createExecutor, P as createExecutorRegistry, Q as runAgentRounds, U as createPushTraceSource, Z as defaultSelectWinner, et as probeSandboxCapabilities, l as withDriverExecutor, m as settledToIteration, n as createSupervisor, nt as routerBrain, rt as runBrainLoop, w as rollingDispatch } from "./supervisor-
|
|
10
|
-
import "./environment-provider-
|
|
9
|
+
import { $ as createSandboxLineage, I as createWorktreeCliExecutor, N as createExecutor, P as createExecutorRegistry, Q as runAgentRounds, U as createPushTraceSource, Z as defaultSelectWinner, et as probeSandboxCapabilities, l as withDriverExecutor, m as settledToIteration, n as createSupervisor, nt as routerBrain, rt as runBrainLoop, w as rollingDispatch } from "./supervisor-DAHeTMAT.js";
|
|
10
|
+
import "./environment-provider-mDsjfGjY.js";
|
|
11
11
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-C7iJOWm3.js";
|
|
12
|
-
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-
|
|
13
|
-
import { It as gateOnDeliverable, Lt as mapExecutorResult, n as supervise } from "./supervise-
|
|
14
|
-
import "./authoring-
|
|
15
|
-
import "./graph-
|
|
12
|
+
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-9jcaIsxA.js";
|
|
13
|
+
import { It as gateOnDeliverable, Lt as mapExecutorResult, n as supervise } from "./supervise-C9iPh1y6.js";
|
|
14
|
+
import "./authoring-D0wM2FaY.js";
|
|
15
|
+
import "./graph-DyWVymtQ.js";
|
|
16
16
|
import { CODING_HARNESSES, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
|
|
17
17
|
import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
|
|
18
|
-
import { agentProfileSchema, canonicalAgentProfileDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
18
|
+
import { AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentNativeContextContinuationResultSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, AgentTurnResultSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, RuntimeEventEnvelopeSchema, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, agentRunCancellationAcknowledgementMatchesRequest, agentRunCancellationRequestDigest, canonicalAgentProfileDigest, canonicalCandidateDigest, nativeContextContinuationTurnDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
|
|
19
19
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
20
20
|
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
21
21
|
import { appendFileSync, chmodSync, constants, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
|
@@ -1036,14 +1036,122 @@ async function runLoopWithCampaignContext(opts, loopOptions, ctx, cost) {
|
|
|
1036
1036
|
return (opts.toArtifact ?? ((r) => r.winner?.output))(result);
|
|
1037
1037
|
}
|
|
1038
1038
|
function loopCostReceipt(result, model) {
|
|
1039
|
+
return costReceiptFromUsage(result.tokenUsage, model, {
|
|
1040
|
+
usageUnknown: result.tokenUsage.tokensKnown === false,
|
|
1041
|
+
actualCostUsd: result.costUsdKnown !== false ? result.costUsd : void 0,
|
|
1042
|
+
costUnknown: result.costUsdKnown === false,
|
|
1043
|
+
estimatedCostUsd: result.estimatedCostUsd
|
|
1044
|
+
});
|
|
1045
|
+
}
|
|
1046
|
+
/** Map Runtime usage into Eval's canonical paid-call receipt without inventing cache classes. */
|
|
1047
|
+
function costReceiptFromUsage(usage, model, cost) {
|
|
1048
|
+
const cacheComplete = hasCompleteCacheBreakdown(usage) && (usage.freshInput !== void 0 || usage.cacheRead !== void 0 || usage.cacheWrite !== void 0);
|
|
1049
|
+
const cacheRead = cacheComplete ? usage.cacheRead ?? 0 : void 0;
|
|
1050
|
+
const cacheWrite = cacheComplete ? usage.cacheWrite ?? 0 : void 0;
|
|
1051
|
+
const classified = (cacheRead ?? 0) + (cacheWrite ?? 0);
|
|
1039
1052
|
return {
|
|
1040
1053
|
model,
|
|
1041
|
-
inputTokens:
|
|
1042
|
-
outputTokens:
|
|
1043
|
-
...
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1054
|
+
inputTokens: cacheComplete ? usage.input - classified : usage.input,
|
|
1055
|
+
outputTokens: usage.output,
|
|
1056
|
+
...cacheComplete ? {
|
|
1057
|
+
cachedTokens: cacheRead,
|
|
1058
|
+
cacheWriteTokens: cacheWrite
|
|
1059
|
+
} : {},
|
|
1060
|
+
...usage.tokensKnown === false || cost.usageUnknown ? { usageUnknown: true } : {},
|
|
1061
|
+
...cost.actualCostUsd !== void 0 ? { actualCostUsd: cost.actualCostUsd } : {},
|
|
1062
|
+
...cost.costUnknown ? { costUnknown: true } : {},
|
|
1063
|
+
...cost.estimatedCostUsd !== void 0 ? { estimatedCostUsd: cost.estimatedCostUsd } : {}
|
|
1064
|
+
};
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* Eval has one pre-admitted paid call for this dispatch. A tree can only settle that one call when
|
|
1068
|
+
* Runtime can prove every visible leaf used the same model. Child identities come from Runtime's
|
|
1069
|
+
* materialization receipts. A router root is validated against its exact profile model before
|
|
1070
|
+
* Runtime accepts each response. A nested tree is not flattened in this result view, so it remains
|
|
1071
|
+
* unknown rather than being relabelled from its parent. A caller-supplied override would be false.
|
|
1072
|
+
*/
|
|
1073
|
+
function supervisedTreeModel(result, rootProfile) {
|
|
1074
|
+
const models = /* @__PURE__ */ new Set();
|
|
1075
|
+
const rootModel = rootProfile.harness === void 0 || rootProfile.harness === "cli-base" ? rootProfile.model?.default : void 0;
|
|
1076
|
+
if (rootModel === void 0) return { kind: "unknown" };
|
|
1077
|
+
models.add(rootModel);
|
|
1078
|
+
let unknown = false;
|
|
1079
|
+
for (const node of result.tree.nodes) {
|
|
1080
|
+
if (node.ownedTreeRoot !== void 0) {
|
|
1081
|
+
unknown = true;
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
const materialization = node.materialization;
|
|
1085
|
+
if (materialization?.status !== "known" || materialization.model.status !== "known") {
|
|
1086
|
+
unknown = true;
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
models.add(materialization.model.id);
|
|
1090
|
+
}
|
|
1091
|
+
if (unknown || models.size === 0) return { kind: "unknown" };
|
|
1092
|
+
if (models.size !== 1) return {
|
|
1093
|
+
kind: "mixed",
|
|
1094
|
+
models: [...models].sort()
|
|
1095
|
+
};
|
|
1096
|
+
return {
|
|
1097
|
+
kind: "known",
|
|
1098
|
+
model: [...models][0]
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
/** The Eval receipt surface has no pre-admitted per-model recursive-tree receipt bundle yet. */
|
|
1102
|
+
var SupervisedTreeModelIdentityError = class extends Error {
|
|
1103
|
+
constructor(identity) {
|
|
1104
|
+
const detail = identity.kind === "mixed" ? `multiple models (${identity.models.join(", ")})` : "an unknown materialized model";
|
|
1105
|
+
super(`superviseDispatch: cannot settle one Eval paid-call receipt for a tree with ${detail}`);
|
|
1106
|
+
this.name = "SupervisedTreeModelIdentityError";
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
function unknownSupervisedTreeReceipt() {
|
|
1110
|
+
return {
|
|
1111
|
+
model: "unknown",
|
|
1112
|
+
inputTokens: 0,
|
|
1113
|
+
outputTokens: 0,
|
|
1114
|
+
usageUnknown: true,
|
|
1115
|
+
costUnknown: true
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
/** Run one recursive supervised tree inside Eval's pre-execution paid-call lifecycle. */
|
|
1119
|
+
function superviseDispatch(opts) {
|
|
1120
|
+
return async (profile, scenario, ctx) => {
|
|
1121
|
+
const superviseOptions = opts.toSuperviseOptions(scenario, profile);
|
|
1122
|
+
const task = opts.toTask(scenario, profile);
|
|
1123
|
+
const maximumCharge = typeof opts.maximumCharge === "function" ? opts.maximumCharge(scenario, profile) : opts.maximumCharge;
|
|
1124
|
+
const paid = await ctx.cost.runPaidCall({
|
|
1125
|
+
channel: "agent",
|
|
1126
|
+
actor: opts.costSource ?? "supervise",
|
|
1127
|
+
model: "unknown",
|
|
1128
|
+
signal: ctx.signal,
|
|
1129
|
+
...maximumCharge ? { maximumCharge } : {},
|
|
1130
|
+
execute: async (executionSignal) => {
|
|
1131
|
+
const result = await supervise(profile, task, {
|
|
1132
|
+
...superviseOptions,
|
|
1133
|
+
signal: executionSignal
|
|
1134
|
+
});
|
|
1135
|
+
const identity = supervisedTreeModel(result, profile);
|
|
1136
|
+
if (identity.kind !== "known") throw new SupervisedTreeModelIdentityError(identity);
|
|
1137
|
+
return result;
|
|
1138
|
+
},
|
|
1139
|
+
receipt: (result) => {
|
|
1140
|
+
const identity = supervisedTreeModel(result, profile);
|
|
1141
|
+
if (identity.kind !== "known") throw new SupervisedTreeModelIdentityError(identity);
|
|
1142
|
+
return costReceiptFromUsage(result.spentTotal.tokens, identity.model, {
|
|
1143
|
+
usageUnknown: result.spentTotal.tokensKnown === false,
|
|
1144
|
+
actualCostUsd: result.spentTotal.usdKnown !== false ? result.spentTotal.usd : void 0,
|
|
1145
|
+
costUnknown: result.spentTotal.usdKnown === false
|
|
1146
|
+
});
|
|
1147
|
+
},
|
|
1148
|
+
receiptFromError: (error) => error instanceof SupervisedTreeModelIdentityError ? unknownSupervisedTreeReceipt() : void 0
|
|
1149
|
+
});
|
|
1150
|
+
if (!paid.succeeded) throw paid.error;
|
|
1151
|
+
return (opts.toArtifact ?? ((result) => {
|
|
1152
|
+
if (result.kind !== "winner") throw new Error(`superviseDispatch: supervised tree ended without a winner (${result.reason})`);
|
|
1153
|
+
return result.out;
|
|
1154
|
+
}))(paid.value);
|
|
1047
1155
|
};
|
|
1048
1156
|
}
|
|
1049
1157
|
function modelFromLoopOptions(options) {
|
|
@@ -2936,7 +3044,7 @@ async function trajectoryReport(journal, blobs, root, options = {}) {
|
|
|
2936
3044
|
continue;
|
|
2937
3045
|
}
|
|
2938
3046
|
node.status = ev.status === "done" ? "done" : "failed";
|
|
2939
|
-
node.ownSpend = ev.spent;
|
|
3047
|
+
node.ownSpend = cloneSpend(ev.spent);
|
|
2940
3048
|
node.verdict = ev.verdict;
|
|
2941
3049
|
node.outRef = ev.outRef;
|
|
2942
3050
|
}
|
|
@@ -3072,13 +3180,13 @@ function zeroSpend() {
|
|
|
3072
3180
|
function addNodeSpend(a, b) {
|
|
3073
3181
|
return {
|
|
3074
3182
|
iterations: a.iterations + b.iterations,
|
|
3075
|
-
tokens: {
|
|
3076
|
-
|
|
3077
|
-
|
|
3078
|
-
|
|
3183
|
+
tokens: (() => {
|
|
3184
|
+
const tokens = cloneTokenUsage(a.tokens);
|
|
3185
|
+
addTokenUsage(tokens, b.tokens);
|
|
3186
|
+
return tokens;
|
|
3187
|
+
})(),
|
|
3079
3188
|
...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
|
|
3080
3189
|
usd: a.usd + b.usd,
|
|
3081
|
-
...a.tokensKnown === false || b.tokensKnown === false ? { tokensKnown: false } : {},
|
|
3082
3190
|
...a.usdKnown === false || b.usdKnown === false ? { usdKnown: false } : {},
|
|
3083
3191
|
ms: a.ms + b.ms
|
|
3084
3192
|
};
|
|
@@ -3086,13 +3194,9 @@ function addNodeSpend(a, b) {
|
|
|
3086
3194
|
function cloneSpend(spend) {
|
|
3087
3195
|
return {
|
|
3088
3196
|
iterations: spend.iterations,
|
|
3089
|
-
tokens:
|
|
3090
|
-
input: spend.tokens.input,
|
|
3091
|
-
output: spend.tokens.output
|
|
3092
|
-
},
|
|
3197
|
+
tokens: cloneTokenUsage(spend.tokens),
|
|
3093
3198
|
...spend.tokensKnown === false ? { tokensKnown: false } : {},
|
|
3094
3199
|
usd: spend.usd,
|
|
3095
|
-
...spend.tokensKnown === false ? { tokensKnown: false } : {},
|
|
3096
3200
|
...spend.usdKnown === false ? { usdKnown: false } : {},
|
|
3097
3201
|
ms: spend.ms
|
|
3098
3202
|
};
|
|
@@ -3103,7 +3207,6 @@ function addSpend(acc, delta) {
|
|
|
3103
3207
|
addTokenUsage(acc.tokens, delta.tokens);
|
|
3104
3208
|
if (delta.tokensKnown === false) acc.tokensKnown = false;
|
|
3105
3209
|
acc.usd += delta.usd;
|
|
3106
|
-
if (delta.tokensKnown === false) acc.tokensKnown = false;
|
|
3107
3210
|
if (delta.usdKnown === false) acc.usdKnown = false;
|
|
3108
3211
|
acc.ms += delta.ms;
|
|
3109
3212
|
}
|
|
@@ -3322,6 +3425,453 @@ function promotionGate(opts) {
|
|
|
3322
3425
|
};
|
|
3323
3426
|
}
|
|
3324
3427
|
//#endregion
|
|
3428
|
+
//#region src/runtime/retained-run-binding.ts
|
|
3429
|
+
function exactSession(environment, controlRef) {
|
|
3430
|
+
if (environment.id !== controlRef.environmentId || environment.provider !== controlRef.provider) throw new Error("provider reconstructed a different retained environment");
|
|
3431
|
+
if (!environment.session || !controlRef.sessionId) throw new Error("retained run control requires a provider session id");
|
|
3432
|
+
const session = environment.session(controlRef.sessionId, { controlRef });
|
|
3433
|
+
if (session.id !== controlRef.sessionId) throw new Error("provider reconstructed a different session");
|
|
3434
|
+
if (session.controlRef === void 0) throw new Error("provider session did not return its provider-owned run control reference");
|
|
3435
|
+
const currentControlRef = AgentExactRunControlRefSchema.parse(session.controlRef);
|
|
3436
|
+
if (!sameControlCoordinates(currentControlRef, controlRef)) throw new Error("provider session reconstructed a different retained session");
|
|
3437
|
+
if (canonicalCandidateDigest(currentControlRef) !== canonicalCandidateDigest(controlRef)) throw new Error("provider session did not retain the exact run control reference");
|
|
3438
|
+
return {
|
|
3439
|
+
session,
|
|
3440
|
+
controlRef: currentControlRef
|
|
3441
|
+
};
|
|
3442
|
+
}
|
|
3443
|
+
function sameControlCoordinates(left, right) {
|
|
3444
|
+
return canonicalCandidateDigest(left) === canonicalCandidateDigest(right);
|
|
3445
|
+
}
|
|
3446
|
+
function freezeControlRef(controlRef) {
|
|
3447
|
+
return Object.freeze({ ...AgentExactRunControlRefSchema.parse(controlRef) });
|
|
3448
|
+
}
|
|
3449
|
+
function copyControlRef(controlRef) {
|
|
3450
|
+
return { ...controlRef };
|
|
3451
|
+
}
|
|
3452
|
+
function exactControlRef(candidate, expected) {
|
|
3453
|
+
if (!candidate) throw new Error("provider dispatch returned no durable run control reference");
|
|
3454
|
+
const controlRef = AgentExactRunControlRefSchema.parse(candidate);
|
|
3455
|
+
if (controlRef.provider !== expected.provider || controlRef.environmentId !== expected.environmentId || controlRef.sessionId !== expected.sessionId) throw new Error("provider dispatch returned control coordinates for another run");
|
|
3456
|
+
return controlRef;
|
|
3457
|
+
}
|
|
3458
|
+
function exactContinuedControlRef(candidate, initial) {
|
|
3459
|
+
const controlRef = AgentExactRunControlRefSchema.parse(candidate);
|
|
3460
|
+
if (controlRef.provider !== initial.provider || controlRef.environmentId !== initial.environmentId || controlRef.sessionId !== initial.sessionId) throw new Error("provider continuation advanced to another retained session");
|
|
3461
|
+
if (controlRef.runId === initial.runId && controlRef.executionId === initial.executionId) throw new Error("provider continuation did not return a new exact run execution");
|
|
3462
|
+
return controlRef;
|
|
3463
|
+
}
|
|
3464
|
+
function assertInteractionBinding(controlRef, command) {
|
|
3465
|
+
if (command.binding.runId !== controlRef.runId || command.binding.provider !== controlRef.provider || command.binding.environmentId !== controlRef.environmentId || command.binding.sessionId !== controlRef.sessionId || command.binding.executionId !== controlRef.executionId || command.binding.requestDigest !== controlRef.requestDigest) throw new Error("interaction response command does not target this retained run");
|
|
3466
|
+
}
|
|
3467
|
+
function assertBoundaryBinding(controlRef, proof) {
|
|
3468
|
+
if (proof.runId !== controlRef.runId || proof.provider !== controlRef.provider || proof.environmentId !== controlRef.environmentId || proof.sessionId !== controlRef.sessionId || proof.executionId !== controlRef.executionId || proof.requestDigest !== controlRef.requestDigest) throw new Error("native context proof does not identify this retained run");
|
|
3469
|
+
}
|
|
3470
|
+
function assertSequence(value, label) {
|
|
3471
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${label} must be a non-negative safe integer`);
|
|
3472
|
+
}
|
|
3473
|
+
function assertResultBinding(controlRef, result) {
|
|
3474
|
+
if (result.sessionId !== controlRef.sessionId) throw new Error("provider returned a result for another retained session");
|
|
3475
|
+
const metadata = result.metadata;
|
|
3476
|
+
if (controlRef.executionId !== void 0 && metadata?.executionId !== controlRef.executionId) throw new Error("provider returned a result for another retained execution");
|
|
3477
|
+
if (metadata?.runId !== controlRef.runId) throw new Error("provider returned a result for another retained run");
|
|
3478
|
+
if (metadata?.requestDigest !== controlRef.requestDigest) throw new Error("provider returned a result for another retained request");
|
|
3479
|
+
}
|
|
3480
|
+
var RetainedRunProviderContractError = class extends Error {
|
|
3481
|
+
constructor(message) {
|
|
3482
|
+
super(message);
|
|
3483
|
+
this.name = "RetainedRunProviderContractError";
|
|
3484
|
+
}
|
|
3485
|
+
};
|
|
3486
|
+
function cancellationRequest(controlRef, operationId, reason) {
|
|
3487
|
+
const material = {
|
|
3488
|
+
operationId,
|
|
3489
|
+
run: AgentExactRunControlRefSchema.parse(controlRef),
|
|
3490
|
+
...reason === void 0 ? {} : { reason }
|
|
3491
|
+
};
|
|
3492
|
+
return AgentRunCancellationRequestSchema.parse({
|
|
3493
|
+
...material,
|
|
3494
|
+
requestDigest: agentRunCancellationRequestDigest(material)
|
|
3495
|
+
});
|
|
3496
|
+
}
|
|
3497
|
+
async function exactSessionCancel(session, request, options) {
|
|
3498
|
+
if (!session.cancelRun) throw new Error("provider session does not expose durable cancellation operations");
|
|
3499
|
+
let acknowledgement;
|
|
3500
|
+
try {
|
|
3501
|
+
acknowledgement = await awaitAbortable(Promise.resolve().then(() => session.cancelRun(request, options)), options.signal);
|
|
3502
|
+
} catch (error) {
|
|
3503
|
+
if (error instanceof RetainedRunProviderContractError) throw error;
|
|
3504
|
+
throw error;
|
|
3505
|
+
}
|
|
3506
|
+
let exactAcknowledgement;
|
|
3507
|
+
try {
|
|
3508
|
+
exactAcknowledgement = AgentRunCancellationAcknowledgementSchema.parse(acknowledgement);
|
|
3509
|
+
} catch {
|
|
3510
|
+
throw new RetainedRunProviderContractError("provider returned an invalid retained cancellation acknowledgement");
|
|
3511
|
+
}
|
|
3512
|
+
if (!agentRunCancellationAcknowledgementMatchesRequest(request, exactAcknowledgement)) throw new RetainedRunProviderContractError("provider returned a retained cancellation acknowledgement for another request");
|
|
3513
|
+
return exactAcknowledgement;
|
|
3514
|
+
}
|
|
3515
|
+
function hasDurableCancel(session) {
|
|
3516
|
+
return typeof session.cancelRun === "function";
|
|
3517
|
+
}
|
|
3518
|
+
async function awaitAbortable(work, signal) {
|
|
3519
|
+
if (signal === void 0) return await work;
|
|
3520
|
+
if (signal.aborted) {
|
|
3521
|
+
Promise.resolve(work).catch(() => void 0);
|
|
3522
|
+
throw abortError(signal.reason);
|
|
3523
|
+
}
|
|
3524
|
+
return await new Promise((resolve, reject) => {
|
|
3525
|
+
let settled = false;
|
|
3526
|
+
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
3527
|
+
const onAbort = () => {
|
|
3528
|
+
queueMicrotask(() => {
|
|
3529
|
+
if (settled) return;
|
|
3530
|
+
settled = true;
|
|
3531
|
+
cleanup();
|
|
3532
|
+
reject(abortError(signal.reason));
|
|
3533
|
+
});
|
|
3534
|
+
};
|
|
3535
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
3536
|
+
Promise.resolve(work).then((value) => {
|
|
3537
|
+
if (settled) return;
|
|
3538
|
+
settled = true;
|
|
3539
|
+
cleanup();
|
|
3540
|
+
resolve(value);
|
|
3541
|
+
}, (error) => {
|
|
3542
|
+
if (settled) return;
|
|
3543
|
+
settled = true;
|
|
3544
|
+
cleanup();
|
|
3545
|
+
reject(error);
|
|
3546
|
+
});
|
|
3547
|
+
});
|
|
3548
|
+
}
|
|
3549
|
+
async function exactSessionResult(session) {
|
|
3550
|
+
return session.result();
|
|
3551
|
+
}
|
|
3552
|
+
function assertEventBinding(source, controlRef) {
|
|
3553
|
+
const values = [
|
|
3554
|
+
isRecord(source) ? source : void 0,
|
|
3555
|
+
isRecord(source.data) ? source.data : void 0,
|
|
3556
|
+
isRecord(source.providerEvent) ? source.providerEvent : void 0
|
|
3557
|
+
].filter((value) => value !== void 0);
|
|
3558
|
+
for (const value of values) {
|
|
3559
|
+
if (value.runId !== void 0 && value.runId !== controlRef.runId) throw new Error("provider returned an event for another retained run");
|
|
3560
|
+
if (value.executionId !== void 0 && value.executionId !== controlRef.executionId) throw new Error("provider returned an event for another retained execution");
|
|
3561
|
+
if (value.sessionId !== void 0 && value.sessionId !== controlRef.sessionId) throw new Error("provider returned an event for another retained session");
|
|
3562
|
+
}
|
|
3563
|
+
}
|
|
3564
|
+
function isRecord(value) {
|
|
3565
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3566
|
+
}
|
|
3567
|
+
function assertStableText(value, label) {
|
|
3568
|
+
if (value.length === 0 || value.trim() !== value) throw new Error(`${label} must be non-empty and have no outer whitespace`);
|
|
3569
|
+
}
|
|
3570
|
+
function abortError(reason) {
|
|
3571
|
+
const error = new Error(reason === void 0 ? "aborted" : String(reason));
|
|
3572
|
+
error.name = "AbortError";
|
|
3573
|
+
return error;
|
|
3574
|
+
}
|
|
3575
|
+
function assertWaitDuration(value, label) {
|
|
3576
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${label} must be a non-negative safe integer`);
|
|
3577
|
+
}
|
|
3578
|
+
function isTerminalSessionStatus(status) {
|
|
3579
|
+
return status === "completed" || status === "failed" || status === "cancelled" || status === "expired";
|
|
3580
|
+
}
|
|
3581
|
+
function delay(ms, signal) {
|
|
3582
|
+
if (signal?.aborted) return Promise.reject(abortError(signal.reason));
|
|
3583
|
+
return new Promise((resolveDelay, rejectDelay) => {
|
|
3584
|
+
const timer = setTimeout(finish, ms);
|
|
3585
|
+
function finish() {
|
|
3586
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3587
|
+
resolveDelay();
|
|
3588
|
+
}
|
|
3589
|
+
function onAbort() {
|
|
3590
|
+
clearTimeout(timer);
|
|
3591
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3592
|
+
rejectDelay(abortError(signal?.reason));
|
|
3593
|
+
}
|
|
3594
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3595
|
+
});
|
|
3596
|
+
}
|
|
3597
|
+
//#endregion
|
|
3598
|
+
//#region src/runtime/retained-run-events.ts
|
|
3599
|
+
async function* retainedRunEvents(session, controlRef, options, now) {
|
|
3600
|
+
const after = options?.after;
|
|
3601
|
+
if (after) {
|
|
3602
|
+
assertStableText(after.cursor, "replay cursor");
|
|
3603
|
+
assertSequence(after.sequence, "replay sequence");
|
|
3604
|
+
}
|
|
3605
|
+
let nextSequence = after === void 0 ? 1 : after.sequence + 1;
|
|
3606
|
+
let lastSequence = after?.sequence ?? -1;
|
|
3607
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3608
|
+
let firstAfterEvent = after !== void 0;
|
|
3609
|
+
const iterator = session.events({
|
|
3610
|
+
...after === void 0 ? {} : { since: after.cursor },
|
|
3611
|
+
...controlRef.executionId === void 0 ? {} : { executionId: controlRef.executionId },
|
|
3612
|
+
...options?.signal === void 0 ? {} : { signal: options.signal }
|
|
3613
|
+
})[Symbol.asyncIterator]();
|
|
3614
|
+
try {
|
|
3615
|
+
for (;;) {
|
|
3616
|
+
const next = await awaitAbortable(Promise.resolve().then(() => iterator.next()), options?.signal);
|
|
3617
|
+
if (next.done) break;
|
|
3618
|
+
const source = next.value;
|
|
3619
|
+
const identity = extractTransportEventIdentity(source);
|
|
3620
|
+
const sourceCursor = identity.cursor ?? identity.eventId;
|
|
3621
|
+
assertEventBinding(source, controlRef);
|
|
3622
|
+
if (sourceCursor === after?.cursor) continue;
|
|
3623
|
+
const event = canonicalEvent(source);
|
|
3624
|
+
if (!event) continue;
|
|
3625
|
+
if (firstAfterEvent && after !== void 0) {
|
|
3626
|
+
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");
|
|
3627
|
+
firstAfterEvent = false;
|
|
3628
|
+
}
|
|
3629
|
+
const eventId = identity.eventId ?? identity.cursor;
|
|
3630
|
+
if (!eventId) throw new Error("replayable canonical event has no stable provider event id or cursor");
|
|
3631
|
+
assertStableText(eventId, "provider event id");
|
|
3632
|
+
if (seen.has(eventId)) throw new Error(`provider replay repeated event id "${eventId}"`);
|
|
3633
|
+
seen.add(eventId);
|
|
3634
|
+
const sequence = identity.sequence ?? nextSequence;
|
|
3635
|
+
if (sequence <= lastSequence) throw new Error(`provider event sequence is not monotonic: ${sequence} follows ${lastSequence}`);
|
|
3636
|
+
const occurredAt = identity.occurredAt;
|
|
3637
|
+
yield RuntimeEventEnvelopeSchema.parse({
|
|
3638
|
+
runId: controlRef.runId,
|
|
3639
|
+
eventId,
|
|
3640
|
+
sequence,
|
|
3641
|
+
cursor: identity.cursor ?? eventId,
|
|
3642
|
+
...occurredAt === void 0 ? {} : { occurredAt },
|
|
3643
|
+
receivedAt: new Date(now()).toISOString(),
|
|
3644
|
+
event
|
|
3645
|
+
});
|
|
3646
|
+
lastSequence = sequence;
|
|
3647
|
+
nextSequence = sequence + 1;
|
|
3648
|
+
}
|
|
3649
|
+
} catch (error) {
|
|
3650
|
+
if (options?.signal?.aborted) {
|
|
3651
|
+
try {
|
|
3652
|
+
Promise.resolve(iterator.return?.()).catch(() => void 0);
|
|
3653
|
+
} catch {}
|
|
3654
|
+
throw abortError(options.signal.reason);
|
|
3655
|
+
}
|
|
3656
|
+
throw error;
|
|
3657
|
+
} finally {
|
|
3658
|
+
if (!options?.signal?.aborted) await iterator.return?.();
|
|
3659
|
+
}
|
|
3660
|
+
}
|
|
3661
|
+
function canonicalEvent(source) {
|
|
3662
|
+
return parseCanonicalTransportEvent(source.type, source.data, source.normalized ?? source.data.normalized, "provider");
|
|
3663
|
+
}
|
|
3664
|
+
//#endregion
|
|
3665
|
+
//#region src/runtime/retained-run-handle.ts
|
|
3666
|
+
function createRetainedRunHandle(environment, session, initialControlRef, capabilities, now) {
|
|
3667
|
+
const clock = now ?? Date.now;
|
|
3668
|
+
let activeControlRef = freezeControlRef(initialControlRef);
|
|
3669
|
+
const snapshot = async (reason, signal) => {
|
|
3670
|
+
if (signal?.aborted) throw abortError(signal.reason);
|
|
3671
|
+
let status;
|
|
3672
|
+
try {
|
|
3673
|
+
status = await awaitAbortable(Promise.resolve().then(() => session.status({ signal })), signal);
|
|
3674
|
+
} catch {
|
|
3675
|
+
if (signal?.aborted) throw abortError(signal.reason);
|
|
3676
|
+
status = "unknown";
|
|
3677
|
+
}
|
|
3678
|
+
const effect = status === "cancelled" ? "cancelled" : status === "completed" || status === "failed" || status === "expired" ? "not_live" : "unknown";
|
|
3679
|
+
return {
|
|
3680
|
+
runId: activeControlRef.runId,
|
|
3681
|
+
controlRef: copyControlRef(activeControlRef),
|
|
3682
|
+
status,
|
|
3683
|
+
effect,
|
|
3684
|
+
observedAt: new Date(clock()).toISOString(),
|
|
3685
|
+
...reason === void 0 ? {} : { reason },
|
|
3686
|
+
...signal?.aborted ? { signal: String(signal.reason ?? "aborted") } : {}
|
|
3687
|
+
};
|
|
3688
|
+
};
|
|
3689
|
+
return {
|
|
3690
|
+
get controlRef() {
|
|
3691
|
+
return copyControlRef(activeControlRef);
|
|
3692
|
+
},
|
|
3693
|
+
status: async (options) => {
|
|
3694
|
+
const waitMs = options?.waitMs ?? 0;
|
|
3695
|
+
assertWaitDuration(waitMs, "retained status wait");
|
|
3696
|
+
const initial = await snapshot(void 0, options?.signal);
|
|
3697
|
+
if (waitMs === 0 || isTerminalSessionStatus(initial.status)) return initial;
|
|
3698
|
+
const deadline = Date.now() + waitMs;
|
|
3699
|
+
let current = initial;
|
|
3700
|
+
while (Date.now() < deadline) {
|
|
3701
|
+
await delay(Math.min(25, Math.max(1, deadline - Date.now())), options?.signal);
|
|
3702
|
+
current = await snapshot(void 0, options?.signal);
|
|
3703
|
+
if (current.status !== initial.status || isTerminalSessionStatus(current.status)) return current;
|
|
3704
|
+
}
|
|
3705
|
+
return current;
|
|
3706
|
+
},
|
|
3707
|
+
events: (options) => retainedRunEvents(session, copyControlRef(activeControlRef), options, clock),
|
|
3708
|
+
result: async () => {
|
|
3709
|
+
const result = AgentTurnResultSchema.parse(await exactSessionResult(session));
|
|
3710
|
+
assertResultBinding(activeControlRef, result);
|
|
3711
|
+
return structuredClone(result);
|
|
3712
|
+
},
|
|
3713
|
+
async respondToInteraction(command, options) {
|
|
3714
|
+
const exactCommand = InteractionResponseCommandSchema.parse(command);
|
|
3715
|
+
assertInteractionBinding(activeControlRef, exactCommand);
|
|
3716
|
+
if (capabilities.interactions?.responseIdempotency !== true) throw new Error(`provider "${activeControlRef.provider}" does not promise retry-safe interaction responses`);
|
|
3717
|
+
const respond = session.respondToInteraction ?? environment.respondToInteraction;
|
|
3718
|
+
if (!respond) throw new Error(`provider "${activeControlRef.provider}" does not support interaction responses`);
|
|
3719
|
+
const acknowledgement = InteractionAcknowledgementSchema.parse(await awaitAbortable(Promise.resolve().then(() => respond.call(session.respondToInteraction ? session : environment, exactCommand, options)), options?.signal));
|
|
3720
|
+
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");
|
|
3721
|
+
return structuredClone(acknowledgement);
|
|
3722
|
+
},
|
|
3723
|
+
async contextBoundary(options) {
|
|
3724
|
+
if (!session.contextBoundary) return null;
|
|
3725
|
+
const proof = await awaitAbortable(Promise.resolve().then(() => session.contextBoundary(options)), options?.signal);
|
|
3726
|
+
if (proof === null) return null;
|
|
3727
|
+
const exactProof = NativeContextBoundaryProofSchema.parse(proof);
|
|
3728
|
+
assertBoundaryBinding(activeControlRef, exactProof);
|
|
3729
|
+
return structuredClone(exactProof);
|
|
3730
|
+
},
|
|
3731
|
+
async continueNative(request, turn) {
|
|
3732
|
+
const exactRequest = NativeContextContinuationRequestSchema.parse(request);
|
|
3733
|
+
if (!sameControlCoordinates(exactRequest.run, activeControlRef)) throw new Error("native continuation request targets another retained run");
|
|
3734
|
+
const { timeoutMs, signal, ...semanticTurn } = turn;
|
|
3735
|
+
if (nativeContextContinuationTurnDigest(semanticTurn) !== exactRequest.turnDigest) throw new Error("native continuation request targets another user turn");
|
|
3736
|
+
if (capabilities.nativeContinuation?.atomicBoundary !== true || capabilities.nativeContinuation.requestIdempotency !== true || !session.continueNative) throw new Error(`provider "${activeControlRef.provider}" does not support retry-safe native continuation`);
|
|
3737
|
+
const outcome = AgentNativeContextContinuationResultSchema.parse(await awaitAbortable(Promise.resolve().then(() => session.continueNative(exactRequest, {
|
|
3738
|
+
turn: semanticTurn,
|
|
3739
|
+
...timeoutMs === void 0 ? {} : { timeoutMs },
|
|
3740
|
+
...signal === void 0 ? {} : { signal }
|
|
3741
|
+
})), signal));
|
|
3742
|
+
if (outcome.acknowledgement.operationId !== exactRequest.operationId || outcome.acknowledgement.requestDigest !== exactRequest.requestDigest) throw new Error("provider returned a native continuation result for another request");
|
|
3743
|
+
if (outcome.acknowledgement.actualBoundary !== void 0) {
|
|
3744
|
+
const actualBoundary = NativeContextBoundaryProofSchema.parse(outcome.acknowledgement.actualBoundary);
|
|
3745
|
+
assertBoundaryBinding(exactRequest.run, actualBoundary);
|
|
3746
|
+
}
|
|
3747
|
+
if (outcome.acknowledgement.status !== "accepted" && outcome.acknowledgement.status !== "replayed") return structuredClone(outcome);
|
|
3748
|
+
if (!("result" in outcome) || !("controlRef" in outcome)) throw new Error("provider omitted the successful native continuation result");
|
|
3749
|
+
if (!agentNativeContextContinuationResultMatchesRequest(exactRequest, outcome)) throw new Error("provider returned a native continuation result for another request");
|
|
3750
|
+
const nextControlRef = exactContinuedControlRef(outcome.controlRef, activeControlRef);
|
|
3751
|
+
assertResultBinding(nextControlRef, outcome.result);
|
|
3752
|
+
activeControlRef = freezeControlRef(nextControlRef);
|
|
3753
|
+
return structuredClone({
|
|
3754
|
+
...outcome,
|
|
3755
|
+
controlRef: copyControlRef(activeControlRef)
|
|
3756
|
+
});
|
|
3757
|
+
},
|
|
3758
|
+
async cancel(options) {
|
|
3759
|
+
assertStableText(options.operationId, "retained cancellation operation id");
|
|
3760
|
+
if (options.reason !== void 0) assertStableText(options.reason, "retained cancellation reason");
|
|
3761
|
+
if (options.signal?.aborted) throw abortError(options.signal.reason);
|
|
3762
|
+
if (!hasDurableCancel(session)) throw new Error(`provider "${activeControlRef.provider}" does not expose durable cancellation operations`);
|
|
3763
|
+
const request = cancellationRequest(activeControlRef, options.operationId, options.reason);
|
|
3764
|
+
let effect = "unknown";
|
|
3765
|
+
let providerStatus;
|
|
3766
|
+
try {
|
|
3767
|
+
const acknowledgement = await exactSessionCancel(session, request, { signal: options.signal });
|
|
3768
|
+
effect = acknowledgement.effect;
|
|
3769
|
+
providerStatus = acknowledgement.status;
|
|
3770
|
+
} catch (error) {
|
|
3771
|
+
if (error instanceof RetainedRunProviderContractError) throw error;
|
|
3772
|
+
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
3773
|
+
effect = "unknown";
|
|
3774
|
+
}
|
|
3775
|
+
const current = await snapshot(options.reason, options.signal);
|
|
3776
|
+
const observedEffect = effect === "unknown" && providerStatus === void 0 && current.status === "cancelled" ? "cancelled" : effect;
|
|
3777
|
+
const acknowledgement = {
|
|
3778
|
+
operationId: options.operationId,
|
|
3779
|
+
requestDigest: request.requestDigest,
|
|
3780
|
+
status: providerStatus ?? (observedEffect === "unknown" ? "unknown" : "accepted"),
|
|
3781
|
+
effect: observedEffect,
|
|
3782
|
+
snapshot: {
|
|
3783
|
+
...current,
|
|
3784
|
+
effect: observedEffect
|
|
3785
|
+
},
|
|
3786
|
+
...options.reason === void 0 ? {} : { reason: options.reason },
|
|
3787
|
+
...options.signal?.aborted ? { signal: String(options.signal.reason ?? "aborted") } : {}
|
|
3788
|
+
};
|
|
3789
|
+
return structuredClone(acknowledgement);
|
|
3790
|
+
}
|
|
3791
|
+
};
|
|
3792
|
+
}
|
|
3793
|
+
//#endregion
|
|
3794
|
+
//#region src/runtime/turn-input.ts
|
|
3795
|
+
/**
|
|
3796
|
+
* Copy only fields that describe a new provider turn.
|
|
3797
|
+
*
|
|
3798
|
+
* Session, replay, continuation, and transfer coordinates are runtime-owned
|
|
3799
|
+
* and are injected by the caller that owns that lifecycle. Keeping this copy
|
|
3800
|
+
* explicit also makes JavaScript callers subject to the same boundary.
|
|
3801
|
+
*/
|
|
3802
|
+
function freshTurnInput(input, runtime) {
|
|
3803
|
+
return {
|
|
3804
|
+
...input.prompt === void 0 ? {} : { prompt: input.prompt },
|
|
3805
|
+
...input.parts === void 0 ? {} : { parts: input.parts },
|
|
3806
|
+
...input.model === void 0 ? {} : { model: input.model },
|
|
3807
|
+
...input.timeoutMs === void 0 ? {} : { timeoutMs: input.timeoutMs },
|
|
3808
|
+
...input.context === void 0 ? {} : { context: input.context },
|
|
3809
|
+
...input.providerOptions === void 0 ? {} : { providerOptions: input.providerOptions },
|
|
3810
|
+
...input.signal === void 0 ? {} : { signal: input.signal },
|
|
3811
|
+
turnId: runtime.turnId,
|
|
3812
|
+
detach: runtime.detach,
|
|
3813
|
+
...runtime.sessionId === void 0 ? {} : { sessionId: runtime.sessionId },
|
|
3814
|
+
...runtime.executionId === void 0 ? {} : { executionId: runtime.executionId },
|
|
3815
|
+
...runtime.contextTransfer === void 0 ? {} : { contextTransfer: runtime.contextTransfer }
|
|
3816
|
+
};
|
|
3817
|
+
}
|
|
3818
|
+
//#endregion
|
|
3819
|
+
//#region src/runtime/retained-run-start.ts
|
|
3820
|
+
/**
|
|
3821
|
+
* Dispatch one detached, replayable run and return only after exact durable
|
|
3822
|
+
* coordinates are confirmed by the provider.
|
|
3823
|
+
*
|
|
3824
|
+
* @stable
|
|
3825
|
+
*/
|
|
3826
|
+
async function startRetainedRun(options) {
|
|
3827
|
+
assertStableText(options.environment.idempotencyKey, "environment idempotency key");
|
|
3828
|
+
assertStableText(options.turn.turnId, "turn idempotency key");
|
|
3829
|
+
if (options.identity !== void 0) {
|
|
3830
|
+
assertStableText(options.identity.sessionId, "retained session id");
|
|
3831
|
+
assertStableText(options.identity.executionId, "retained execution id");
|
|
3832
|
+
}
|
|
3833
|
+
const capabilities = await assertRetainedCapabilities(options.provider);
|
|
3834
|
+
if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
|
|
3835
|
+
const environment = await options.provider.create(options.environment);
|
|
3836
|
+
if (!environment.dispatch || !environment.session) {
|
|
3837
|
+
try {
|
|
3838
|
+
await environment.destroy?.();
|
|
3839
|
+
} catch (cleanupError) {
|
|
3840
|
+
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");
|
|
3841
|
+
}
|
|
3842
|
+
throw new Error(`provider "${options.provider.name}" does not expose detached session control`);
|
|
3843
|
+
}
|
|
3844
|
+
const reference = await environment.dispatch(freshTurnInput(options.turn, {
|
|
3845
|
+
turnId: options.turn.turnId,
|
|
3846
|
+
detach: true,
|
|
3847
|
+
...options.identity === void 0 ? {} : options.identity
|
|
3848
|
+
}));
|
|
3849
|
+
if (reference.provider !== void 0 && reference.provider !== options.provider.name) throw new Error("provider dispatch returned a session reference for another provider");
|
|
3850
|
+
const exact = exactSession(environment, exactControlRef(reference.controlRef, {
|
|
3851
|
+
provider: options.provider.name,
|
|
3852
|
+
environmentId: environment.id,
|
|
3853
|
+
sessionId: reference.id
|
|
3854
|
+
}));
|
|
3855
|
+
return createRetainedRunHandle(environment, exact.session, exact.controlRef, capabilities, options.now);
|
|
3856
|
+
}
|
|
3857
|
+
/** Rebuild a retained-run client without retaining any object from the starter. @stable */
|
|
3858
|
+
async function reconnectRetainedRun(options) {
|
|
3859
|
+
const controlRef = AgentExactRunControlRefSchema.parse(options.controlRef);
|
|
3860
|
+
if (controlRef.provider !== options.provider.name) throw new Error(`run provider "${controlRef.provider}" does not match "${options.provider.name}"`);
|
|
3861
|
+
const capabilities = await assertRetainedCapabilities(options.provider);
|
|
3862
|
+
if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
|
|
3863
|
+
const environment = await options.provider.get(controlRef.environmentId);
|
|
3864
|
+
if (!environment) return null;
|
|
3865
|
+
const exact = exactSession(environment, controlRef);
|
|
3866
|
+
return createRetainedRunHandle(environment, exact.session, exact.controlRef, capabilities, options.now);
|
|
3867
|
+
}
|
|
3868
|
+
async function assertRetainedCapabilities(provider) {
|
|
3869
|
+
const capabilities = AgentEnvironmentCapabilitiesSchema.parse(await provider.capabilities());
|
|
3870
|
+
const retained = capabilities.retainedControl;
|
|
3871
|
+
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 "${provider.name}" cannot control a retry-safe retained run`);
|
|
3872
|
+
return capabilities;
|
|
3873
|
+
}
|
|
3874
|
+
//#endregion
|
|
3325
3875
|
//#region src/runtime/run-benchmark.ts
|
|
3326
3876
|
/**
|
|
3327
3877
|
* runBenchmark — the packaged optimization suite. Define a domain by implementing an
|
|
@@ -5625,6 +6175,6 @@ function tail(s) {
|
|
|
5625
6175
|
return s.slice(-400);
|
|
5626
6176
|
}
|
|
5627
6177
|
//#endregion
|
|
5628
|
-
export {
|
|
6178
|
+
export { loopUntil as $, assertStrategyContract as A, McpSpawnFault as At, promotionGate as B, chatTransportExecutor as C, pairwiseSignificance as Ct, pickChampion as D, renderPairwiseMarkdown as Dt, discriminatingMeans as E, renderLeaderboardSvg as Et, openSandboxRun as F, envKeyProvider as Ft, builtinShapes as G, trajectoryReport as H, printBenchmarkReport as I, mcpSecretEnvMetadataKey as It, FileCorpus as J, createShapeRegistry as K, runBenchmark as L, resolveMcpServerLaunch as Lt, strategyAuthorContract as M, materializeLocalMcp as Mt, strategyAuthorSystemPrompt as N, createMcpEnvironment as Nt, runStrategyEvolution as O, auditIntent as Ot, SandboxRunAbortError as P, sanitizeMcpToolSchema as Pt, flatWidenGate as Q, reconnectRetainedRun as R, resolveSecretEnv as Rt, runCoderChecks as S, leaderboard as St, createChatSessionStore as T, renderLeaderboardMarkdown as Tt, definePersona as U, equalKOnCost as V, runPersonified as W, renderCorpusToInstructions as X, InMemoryCorpus as Y, fanout as Z, settledWorkerOut as _, superviseDispatch as _t, localShell as a, assertTraceDerivedFindings as at, analyzeTrace as b, sentinelCompletion as bt, createVerifierEnvironment as c, registryScopeAnalyst as ct, worktreeFanout as d, defineLeaderboard as dt, panel as et, EVIDENCE_MAX_CHARS as f, resolveSandboxClient as ft, composeWorkerEvidence as g, loopDispatch as gt, closingWorkerNote as h, loopCampaignDispatch as ht, jjWorkspace as i, widen as it, authorStrategy as j, connectStdioMcp as jt, selectChampion as k, defaultAuditorInstruction as kt, failuresAnalyst as l, inProcessSandboxClient as lt, VERIFY_TAIL_CHARS as m, inlineSandboxClient as mt, makeFinding$1 as n, selectValidWinner as nt, runInWorkspace as o, buildSteerContext as ot, NOTE_MAX_CHARS as p, localSandboxClient as pt, registerShape as q, gitWorkspace as r, verify as rt, createWaterfallCollector as s, createScopeAnalyst as st, computeFindingId$1 as t, pipeline as tt, superviseSurface as u, harvestCorpus as ut, copyUntrackedIntoClone as v, completionAuthorizes as vt, chatWorkerSeam as w, renderLeaderboardHtml as wt, patchDelivered as x, stopSentinel as xt, withUntrackedArtifacts as y, deterministicCompletion as yt, startRetainedRun as z, secretEnvOfMcpServer as zt };
|
|
5629
6179
|
|
|
5630
|
-
//# sourceMappingURL=runtime-
|
|
6180
|
+
//# sourceMappingURL=runtime-D5GueIHH.js.map
|