@tangle-network/agent-runtime 0.318.0 → 0.319.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-CRG-tjnR.js → activation-DPpb2I8z.js} +3 -3
- package/dist/{activation-CRG-tjnR.js.map → activation-DPpb2I8z.js.map} +1 -1
- package/dist/{activation-RExX9RDm.d.ts → activation-OColGsfd.d.ts} +2 -2
- package/dist/agent.d.ts +3 -3
- package/dist/agent.js +3 -3
- package/dist/{bundle-RgHpAFDY.js → bundle-Cw-QdGmH.js} +2 -2
- package/dist/{bundle-RgHpAFDY.js.map → bundle-Cw-QdGmH.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +40 -3
- package/dist/candidate-execution/index.js +86 -7
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/{coordination-driver-DK3pI_HB.js → coordination-driver-woTI2Vpr.js} +3 -3
- package/dist/{coordination-driver-DK3pI_HB.js.map → coordination-driver-woTI2Vpr.js.map} +1 -1
- package/dist/{delegate-Co9vJIgE.js → delegate-DrFainK0.js} +2 -2
- package/dist/{delegate-Co9vJIgE.js.map → delegate-DrFainK0.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +4 -4
- package/dist/{graph-DYBCYZjg.js → graph-joXNwtkE.js} +5 -5
- package/dist/{graph-DYBCYZjg.js.map → graph-joXNwtkE.js.map} +1 -1
- package/dist/graph-registry-BuJbzTzF.js +211 -0
- package/dist/graph-registry-BuJbzTzF.js.map +1 -0
- package/dist/{improvement-cycle-jp80l_ZQ.js → improvement-cycle-Dkrb5nVc.js} +7 -7
- package/dist/{improvement-cycle-jp80l_ZQ.js.map → improvement-cycle-Dkrb5nVc.js.map} +1 -1
- package/dist/{index-CHlWvoo5.d.ts → index-Da7w2H86.d.ts} +268 -82
- package/dist/index.d.ts +5 -5
- package/dist/index.js +10 -10
- package/dist/intelligence.d.ts +4 -4
- package/dist/intelligence.js +7 -7
- package/dist/kernel.d.ts +3 -2
- package/dist/kernel.js +12 -11
- package/dist/{loop-runner-bin-C-QaaVE2.d.ts → loop-runner-bin-CbBoLC9D.d.ts} +2 -2
- package/dist/{loop-runner-bin-C8jLr2gR.js → loop-runner-bin-OYVzvqiL.js} +3 -3
- package/dist/{loop-runner-bin-C8jLr2gR.js.map → loop-runner-bin-OYVzvqiL.js.map} +1 -1
- 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 +2 -2
- package/dist/mcp/index.js +6 -6
- package/dist/{model-policy-B-rOb8Nj.js → model-policy-CNe257pB.js} +4 -4
- package/dist/{model-policy-B-rOb8Nj.js.map → model-policy-CNe257pB.js.map} +1 -1
- package/dist/{openai-tools-BuJB3JQH.d.ts → openai-tools-Cu9E1Bda.d.ts} +2 -2
- package/dist/placement.d.ts +1 -1
- package/dist/{prepare-CD9kR0gS.js → prepare-DjCLEN-q.js} +3 -3
- package/dist/prepare-DjCLEN-q.js.map +1 -0
- package/dist/{profile-CHXYmpGd.js → profile-DmVM4Gxb.js} +9 -2
- package/dist/profile-DmVM4Gxb.js.map +1 -0
- package/dist/{profile-materialization-Cca615eu.d.ts → profile-materialization-C5-t3HJ7.d.ts} +14 -3
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{protected-model-port-C9QtEf3y.d.ts → protected-model-port-CQg2gstJ.d.ts} +3 -3
- package/dist/{protected-model-port-B0pHd65J.js → protected-model-port-D1fcnYdj.js} +4 -4
- package/dist/{protected-model-port-B0pHd65J.js.map → protected-model-port-D1fcnYdj.js.map} +1 -1
- package/dist/{provision-supervisor-CunKnayY.js → provision-supervisor-CN16EdkE.js} +5 -5
- package/dist/{provision-supervisor-CunKnayY.js.map → provision-supervisor-CN16EdkE.js.map} +1 -1
- package/dist/{runtime-UG5tV_yf.js → runtime-BE4GW_q1.js} +307 -13
- package/dist/runtime-BE4GW_q1.js.map +1 -0
- package/dist/{search-executor-DMX6tCY4.js → search-executor-DuHd_fws.js} +4 -4
- package/dist/{search-executor-DMX6tCY4.js.map → search-executor-DuHd_fws.js.map} +1 -1
- package/dist/{server-fSBvPPLH.js → server-CYdjyARj.js} +4 -4
- package/dist/{server-fSBvPPLH.js.map → server-CYdjyARj.js.map} +1 -1
- package/dist/{supervise-C41ywfFd.js → supervise-CvKx8rlw.js} +5 -5
- package/dist/{supervise-C41ywfFd.js.map → supervise-CvKx8rlw.js.map} +1 -1
- package/dist/{supervisor-BXEL_Fxe.js → supervisor--nmU6w86.js} +259 -36
- package/dist/supervisor--nmU6w86.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +14 -14
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/workspace-store/index.d.ts +171 -3
- package/dist/workspace-store/index.js +529 -8
- package/dist/workspace-store/index.js.map +1 -1
- package/dist/{workspace-streams-DkijayqX.js → workspace-streams-DFAhW7hF.js} +300 -42
- package/dist/workspace-streams-DFAhW7hF.js.map +1 -0
- package/dist/{workspace-streams-CpSmt3zx.d.ts → workspace-streams-U6_UfOXu.d.ts} +10 -2
- package/package.json +13 -10
- package/skills/codemode/references/runtime-execution.md +10 -3
- package/skills/graph-designer/SKILL.md +57 -0
- package/dist/prepare-CD9kR0gS.js.map +0 -1
- package/dist/profile-CHXYmpGd.js.map +0 -1
- package/dist/runtime-UG5tV_yf.js.map +0 -1
- package/dist/supervisor-BXEL_Fxe.js.map +0 -1
- package/dist/workspace-streams-DkijayqX.js.map +0 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, f as RuntimeRunStateError, i as ConfigError, l as RetainedInteractiveBindingError, m as ValidationError$1, r as BackendTransportError, t as AgentEvalError$1, u as RetainedRunAdmissionError } from "./errors-DodWX-cb.js";
|
|
2
|
-
import { $ as
|
|
2
|
+
import { $ as promptCacheTokenClasses, Ct as checkInIdleMs, Dt as teardownSurfaces, Et as teardownExecutor, F as deepFreezeCandidate, G as cloneTokenUsage, H as addTokenUsage, J as fnv1a32Hex, K as deleteBoxSafe, Q as mapWithConcurrency, St as boundedChildDeadlineAt, Tt as singleFlightTeardown, U as chargedTokens, V as addSpend, W as cloneSpend, Y as hasCompleteCacheBreakdown, Z as isAsyncIterable$1, a as verifyAgentCandidateWorkspaceArtifacts, at as throwAbort, bt as ROOT_DEADLINE_REASON, ct as withTimeout, dt as addResourceSpend, et as randomSuffix, ft as assertResources, gt as CHILD_DEADLINE_REASON, ht as ACCEPTED_RESULT_GRACE_MS, i as readAgentCandidateWorkspaceArtifactFiles, it as stringifySafe, j as verifiedArtifactChunks, k as verifyWorkspaceSnapshotArtifacts, lt as zeroSpend, mt as withBudgetResources, nt as roundBoxMinutes, o as verifyAgentCandidateWorkspaceTree, ot as throwIfAborted, pt as resourceTelemetry, q as errorMessage, rt as sleep, st as unmeteredSpend, tt as randomUuid, u as verifyAgentCandidateWorkspaceArchive, ut as zeroTokenUsage, wt as isDeadlineAbortReason, xt as armDeadlineTimer } from "./workspace-streams-DFAhW7hF.js";
|
|
3
3
|
import { runTaskQueue } from "./task-queue.js";
|
|
4
|
-
import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutionSettings, d as assertRouterAutoDeclaration, f as assertRouterAutoResponse, g as observedModelMatchesDeclared, h as observedModelHasSnapshot, l as profileProviderModel, m as mergeObservedModelIdentity, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile, u as resolveRouterRetryPolicy } from "./model-policy-
|
|
4
|
+
import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutionSettings, d as assertRouterAutoDeclaration, f as assertRouterAutoResponse, g as observedModelMatchesDeclared, h as observedModelHasSnapshot, l as profileProviderModel, m as mergeObservedModelIdentity, o as enforceTokenLimits, s as profileBridgeWireModel, t as assertExecutableAgentProfile, u as resolveRouterRetryPolicy } from "./model-policy-CNe257pB.js";
|
|
5
5
|
import { n as assertNoSymlinkDescendant, r as publishExclusiveDurableFile } from "./durable-file-DWQA4ooo.js";
|
|
6
6
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
|
|
7
|
-
import { AGENT_PROFILE_MATERIALIZATION_AXES, AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentNativeContextContinuationResultSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, AgentTurnInputSchema, AgentTurnResultSchema, CanonicalStreamEventSchema, ContextTransferRequestSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, REASONING_EFFORTS, RuntimeEventEnvelopeSchema, TerminalReplayWindowSchema, TerminalSessionRefSchema, agentCandidateArtifactRefSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionRunRef, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, agentRunCancellationAcknowledgementMatchesRequest, agentRunCancellationRequestDigest, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalWorkspaceCwd, exactAgentInteractiveSessionStart, harnessTypeSchema, nativeContextContinuationTurnDigest, nativeReasoningControl, profileMaterializationAxes, profileMaterializationAxes as profileMaterializationAxes$1, renderInputPartsAsText, sha256DigestSchema, workspaceCheckpointRequestDigest, workspaceCheckpointResultMatchesRequest, workspaceCleanupAcknowledgementMatches, workspaceCleanupRequestDigest, workspaceForkRequestDigest, workspaceForkResultMatchesRequest } from "@tangle-network/agent-interface";
|
|
7
|
+
import { AGENT_PROFILE_MATERIALIZATION_AXES, AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentNativeContextContinuationResultSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, AgentTurnInputSchema, AgentTurnResultSchema, CanonicalStreamEventSchema, ContextTransferReceiptSchema, ContextTransferRequestSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, REASONING_EFFORTS, RuntimeEventEnvelopeSchema, TerminalReplayWindowSchema, TerminalSessionRefSchema, agentCandidateArtifactRefSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionRunRef, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, agentRunCancellationAcknowledgementMatchesRequest, agentRunCancellationRequestDigest, agentWorkspaceSnapshotRefDigest, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalWorkspaceCwd, contextTransferReceiptMatches, exactAgentInteractiveSessionStart, harnessTypeSchema, nativeContextContinuationTurnDigest, nativeReasoningControl, profileMaterializationAxes, profileMaterializationAxes as profileMaterializationAxes$1, renderInputPartsAsText, sha256DigestSchema, workspaceCheckpointRequestDigest, workspaceCheckpointResultMatchesRequest, workspaceCleanupAcknowledgementMatches, workspaceCleanupRequestDigest, workspaceForkRequestDigest, workspaceForkResultMatchesRequest } from "@tangle-network/agent-interface";
|
|
8
8
|
import { isToolSpan, toolSpansToTraceAnalysisStore } from "@tangle-network/agent-eval";
|
|
9
9
|
import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
|
|
10
10
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
@@ -7809,6 +7809,43 @@ function assertRequestedInteractionCapabilities(providerName, requested, capabil
|
|
|
7809
7809
|
if (interactions.replay !== true || interactions.responseIdempotency !== true) throw new Error(`provider "${providerName}" cannot safely dispatch requested interactions without replay and response idempotency`);
|
|
7810
7810
|
}
|
|
7811
7811
|
//#endregion
|
|
7812
|
+
//#region src/runtime/retained-context-transfer.ts
|
|
7813
|
+
/** Validate attachment authority before admission or any provider operation. */
|
|
7814
|
+
function retainedContextTransferReceipt(options, provider, request) {
|
|
7815
|
+
if (request === void 0) {
|
|
7816
|
+
if (options.contextTransferReceipt !== void 0) throw new Error("context transfer receipt requires its exact request");
|
|
7817
|
+
return;
|
|
7818
|
+
}
|
|
7819
|
+
if (options.contextTransferReceipt === void 0) throw new Error("retained context transfer requires an accepted receipt; it cannot create another environment");
|
|
7820
|
+
const receipt = detachedSnapshot(ContextTransferReceiptSchema.parse(options.contextTransferReceipt), "retained context transfer receipt");
|
|
7821
|
+
if (!contextTransferReceiptMatches(request, receipt) || receipt.provider !== provider) throw new Error("retained context transfer receipt does not match its exact request or provider");
|
|
7822
|
+
const { environment, turn } = options;
|
|
7823
|
+
const destination = request.plan.destination;
|
|
7824
|
+
if (request.profile === void 0 || typeof environment.profile === "string" || canonicalAgentProfileDigest(environment.profile) !== destination.profileDigest || turn.profile !== void 0 && canonicalAgentProfileDigest(turn.profile) !== destination.profileDigest) throw new Error("retained context transfer requires the accepted exact profile");
|
|
7825
|
+
if (environment.backend !== void 0 && environment.backend !== destination.runner) throw new Error("retained context transfer runner conflicts with the accepted destination");
|
|
7826
|
+
if (canonicalCandidateDigest(environment.workspace ?? null) !== canonicalCandidateDigest(request.workspace ?? null) || canonicalCandidateDigest(environment.resources ?? null) !== canonicalCandidateDigest(request.resources ?? null)) throw new Error("retained context transfer workspace or resources conflict with acceptance");
|
|
7827
|
+
if (environment.requestedId !== void 0 && environment.requestedId !== receipt.environmentId || options.existingEnvironmentId !== void 0 && options.existingEnvironmentId !== receipt.environmentId) throw new Error("retained context transfer targets another environment");
|
|
7828
|
+
if (environment.runtimeAttachments !== void 0 || environment.egress !== void 0 || environment.billingOwner !== void 0 || Object.keys(environment.env ?? {}).length > 0 || Object.keys(environment.secrets ?? {}).length > 0 || Object.keys(environment.providerOptions ?? {}).length > 0) throw new Error("retained context transfer attachment cannot apply unaccepted create-time options");
|
|
7829
|
+
return receipt;
|
|
7830
|
+
}
|
|
7831
|
+
function assertRetainedContextTransferIdentity(receipt, identity) {
|
|
7832
|
+
if (receipt !== void 0 && (identity.sessionId !== receipt.sessionId || identity.executionId !== receipt.executionId)) throw new Error("retained context transfer identity conflicts with the accepted receipt");
|
|
7833
|
+
}
|
|
7834
|
+
function assertRetainedContextTransferCapability(capabilities) {
|
|
7835
|
+
if (capabilities.contextTransfer?.attach !== true) throw new Error("provider cannot attach the accepted context transfer destination");
|
|
7836
|
+
}
|
|
7837
|
+
/** The provider get contract performs the authoritative operation lookup once. */
|
|
7838
|
+
function assertRetainedContextTransferEnvironment(environment, request, receipt) {
|
|
7839
|
+
const actual = ContextTransferReceiptSchema.safeParse(environment.contextTransferReceipt);
|
|
7840
|
+
if (!actual.success || !contextTransferReceiptMatches(request, actual.data) || environment.id !== receipt.environmentId || environment.provider !== receipt.provider || canonicalCandidateDigest({
|
|
7841
|
+
...actual.data,
|
|
7842
|
+
status: "accepted"
|
|
7843
|
+
}) !== canonicalCandidateDigest({
|
|
7844
|
+
...receipt,
|
|
7845
|
+
status: "accepted"
|
|
7846
|
+
})) throw new Error("provider did not reconstruct the authoritative accepted context transfer receipt");
|
|
7847
|
+
}
|
|
7848
|
+
//#endregion
|
|
7812
7849
|
//#region src/runtime/retained-run-events.ts
|
|
7813
7850
|
/** The runtime's own contract checks inside the stream loop, so the catch can tell a broken
|
|
7814
7851
|
* answer (a verdict) from a read the provider's iterator failed (a wrapper). */
|
|
@@ -8209,10 +8246,31 @@ function createRetainedRunHandle(environment, session, initialControlRef, capabi
|
|
|
8209
8246
|
* Secret names remain public binding data, so changing requested credentials
|
|
8210
8247
|
* still conflicts before provider effects begin.
|
|
8211
8248
|
*/
|
|
8249
|
+
/**
|
|
8250
|
+
* The pre-interface5 create-material projection: `requestedId`, `egress`,
|
|
8251
|
+
* `billingOwner`, and the workspace `snapshot` digest omitted — the shape
|
|
8252
|
+
* records persisted by the previous version digested. Accepted only when
|
|
8253
|
+
* validating replayed records (an upgrade must not strand an in-flight run
|
|
8254
|
+
* whose provider creation already completed); every new admission digests the
|
|
8255
|
+
* current projection.
|
|
8256
|
+
*/
|
|
8257
|
+
function legacyRetainedCreateMaterial(environment) {
|
|
8258
|
+
const { requestedId: _requestedId, egress: _egress, billingOwner: _billingOwner, workspace, ...preInterface5 } = environment;
|
|
8259
|
+
return retainedCreateMaterial(workspace === void 0 ? preInterface5 : {
|
|
8260
|
+
...preInterface5,
|
|
8261
|
+
workspace: (() => {
|
|
8262
|
+
const { snapshot: _snapshot, ...legacyWorkspace } = workspace;
|
|
8263
|
+
return legacyWorkspace;
|
|
8264
|
+
})()
|
|
8265
|
+
});
|
|
8266
|
+
}
|
|
8212
8267
|
function retainedCreateMaterial(environment) {
|
|
8213
8268
|
return {
|
|
8214
8269
|
...environment.metadata?.runtimeProviderPlacement === void 0 ? {} : { placement: environment.metadata.runtimeProviderPlacement },
|
|
8215
8270
|
...environment.backend === void 0 ? {} : { backend: environment.backend },
|
|
8271
|
+
...environment.requestedId === void 0 ? {} : { requestedId: environment.requestedId },
|
|
8272
|
+
...environment.egress === void 0 ? {} : { egress: environment.egress },
|
|
8273
|
+
...environment.billingOwner === void 0 ? {} : { billingOwner: environment.billingOwner },
|
|
8216
8274
|
...environment.workspace === void 0 ? {} : { workspaceDigest: canonicalCandidateDigest(publicWorkspaceMaterial(environment.workspace)) },
|
|
8217
8275
|
...environment.resources === void 0 ? {} : { resourcesDigest: canonicalCandidateDigest(publicResourceMaterial(environment.resources)) },
|
|
8218
8276
|
...environment.runtimeAttachments === void 0 ? {} : { runtimeAttachmentsDigest: canonicalCandidateDigest(environment.runtimeAttachments) },
|
|
@@ -8237,6 +8295,8 @@ function publicWorkspaceMaterial(workspace) {
|
|
|
8237
8295
|
...workspace.repoUrl === void 0 ? {} : { repoUrl: workspace.repoUrl },
|
|
8238
8296
|
...workspace.gitRef === void 0 ? {} : { gitRef: workspace.gitRef },
|
|
8239
8297
|
...workspace.cwd === void 0 ? {} : { cwd: workspace.cwd },
|
|
8298
|
+
...workspace.checkpoint === void 0 ? {} : { checkpoint: workspace.checkpoint },
|
|
8299
|
+
...workspace.snapshot === void 0 ? {} : { snapshotDigest: agentWorkspaceSnapshotRefDigest(workspace.snapshot) },
|
|
8240
8300
|
...workspace.providerOptions === void 0 ? {} : { providerOptionNames: retainedObjectNames(workspace.providerOptions) }
|
|
8241
8301
|
};
|
|
8242
8302
|
}
|
|
@@ -8293,7 +8353,7 @@ function mintRetainedIdentity(idempotencyKey, turnId) {
|
|
|
8293
8353
|
* coordinates are confirmed by the provider and persisted by the caller.
|
|
8294
8354
|
*
|
|
8295
8355
|
* The required `onAdmission` hook first records a digest-only intent before
|
|
8296
|
-
* creation, then records recovery coordinates and the verified exact control
|
|
8356
|
+
* creation or receipt-authorized attachment, then records recovery coordinates and the verified exact control
|
|
8297
8357
|
* reference. The returned promise resolves only after the dispatched admission
|
|
8298
8358
|
* is durable, so a crash cannot lose a successful start's exact reference.
|
|
8299
8359
|
*
|
|
@@ -8303,14 +8363,19 @@ async function startRetainedRun(options) {
|
|
|
8303
8363
|
assertStableText(options.environment.idempotencyKey, "environment idempotency key");
|
|
8304
8364
|
assertStableText(options.turn.turnId, "turn idempotency key");
|
|
8305
8365
|
if (typeof options.onAdmission !== "function") throw new Error("startRetainedRun requires an awaited onAdmission durability hook");
|
|
8306
|
-
const
|
|
8366
|
+
const contextTransfer = retainedContextTransfer(options.turn.contextTransfer);
|
|
8367
|
+
const transferReceipt = retainedContextTransferReceipt(options, options.provider.name, contextTransfer);
|
|
8368
|
+
const { sessionId, executionId } = options.identity ?? options.intent ?? (transferReceipt === void 0 ? void 0 : {
|
|
8369
|
+
sessionId: transferReceipt.sessionId,
|
|
8370
|
+
executionId: transferReceipt.executionId
|
|
8371
|
+
}) ?? mintRetainedIdentity(options.environment.idempotencyKey, options.turn.turnId);
|
|
8307
8372
|
const identity = {
|
|
8308
8373
|
sessionId,
|
|
8309
8374
|
executionId
|
|
8310
8375
|
};
|
|
8311
8376
|
assertStableText(identity.sessionId, "retained session id");
|
|
8312
8377
|
assertStableText(identity.executionId, "retained execution id");
|
|
8313
|
-
|
|
8378
|
+
assertRetainedContextTransferIdentity(transferReceipt, identity);
|
|
8314
8379
|
AgentTurnInputSchema.parse(freshTurnInput(options.turn, {
|
|
8315
8380
|
turnId: options.turn.turnId,
|
|
8316
8381
|
detach: true,
|
|
@@ -8322,11 +8387,22 @@ async function startRetainedRun(options) {
|
|
|
8322
8387
|
if (options.intent === void 0) await admitDurably(options.onAdmission, intent);
|
|
8323
8388
|
else assertExactRetainedRunIntent(options.intent, intent);
|
|
8324
8389
|
const providerCapabilities = await assertRetainedCapabilities(options.provider);
|
|
8390
|
+
if (transferReceipt !== void 0) assertRetainedContextTransferCapability(providerCapabilities);
|
|
8325
8391
|
assertRequestedInteractionCapabilities(options.provider.name, options.turn.interactions, providerCapabilities);
|
|
8326
8392
|
options.environment.signal?.throwIfAborted();
|
|
8327
8393
|
options.turn.signal?.throwIfAborted();
|
|
8394
|
+
const attachmentSignal = options.environment.signal === void 0 ? options.turn.signal : options.turn.signal === void 0 ? options.environment.signal : AbortSignal.any([options.environment.signal, options.turn.signal]);
|
|
8328
8395
|
let environment;
|
|
8329
|
-
if (
|
|
8396
|
+
if (transferReceipt !== void 0 && contextTransfer !== void 0) {
|
|
8397
|
+
const existing = await options.provider.get(transferReceipt.environmentId, {
|
|
8398
|
+
contextTransfer,
|
|
8399
|
+
...attachmentSignal === void 0 ? {} : { signal: attachmentSignal }
|
|
8400
|
+
});
|
|
8401
|
+
attachmentSignal?.throwIfAborted();
|
|
8402
|
+
if (!existing) throw new Error("accepted context transfer environment is unavailable; it cannot be replaced");
|
|
8403
|
+
assertRetainedContextTransferEnvironment(existing, contextTransfer, transferReceipt);
|
|
8404
|
+
environment = existing;
|
|
8405
|
+
} else if (options.existingEnvironmentId !== void 0) {
|
|
8330
8406
|
assertStableText(options.existingEnvironmentId, "retained environment id");
|
|
8331
8407
|
const existing = await options.provider.get(options.existingEnvironmentId);
|
|
8332
8408
|
if (!existing || existing.id !== options.existingEnvironmentId || existing.provider !== options.provider.name) throw new Error("retained provider environment is unavailable or has another identity");
|
|
@@ -8339,9 +8415,10 @@ async function startRetainedRun(options) {
|
|
|
8339
8415
|
let capabilities;
|
|
8340
8416
|
try {
|
|
8341
8417
|
capabilities = retainedCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
|
|
8418
|
+
if (transferReceipt !== void 0) assertRetainedContextTransferCapability(capabilities);
|
|
8342
8419
|
assertRequestedInteractionCapabilities(options.provider.name, options.turn.interactions, capabilities);
|
|
8343
8420
|
} catch (error) {
|
|
8344
|
-
if (options.existingEnvironmentId !== void 0) throw error;
|
|
8421
|
+
if (transferReceipt !== void 0 || options.existingEnvironmentId !== void 0) throw error;
|
|
8345
8422
|
try {
|
|
8346
8423
|
await environment.destroy?.();
|
|
8347
8424
|
} catch (cleanupError) {
|
|
@@ -8350,7 +8427,7 @@ async function startRetainedRun(options) {
|
|
|
8350
8427
|
throw error;
|
|
8351
8428
|
}
|
|
8352
8429
|
if (!environment.dispatch || !environment.session) {
|
|
8353
|
-
if (options.existingEnvironmentId !== void 0) throw new Error(`provider "${options.provider.name}" does not expose detached session control`);
|
|
8430
|
+
if (transferReceipt !== void 0 || options.existingEnvironmentId !== void 0) throw new Error(`provider "${options.provider.name}" does not expose detached session control`);
|
|
8354
8431
|
try {
|
|
8355
8432
|
await environment.destroy?.();
|
|
8356
8433
|
} catch (cleanupError) {
|
|
@@ -8361,15 +8438,16 @@ async function startRetainedRun(options) {
|
|
|
8361
8438
|
return dispatchRetainedRun({
|
|
8362
8439
|
provider: options.provider,
|
|
8363
8440
|
environment,
|
|
8364
|
-
signal:
|
|
8441
|
+
signal: attachmentSignal,
|
|
8365
8442
|
environmentIdempotencyKey: options.environment.idempotencyKey,
|
|
8366
8443
|
turn: options.turn,
|
|
8367
8444
|
contextTransfer,
|
|
8445
|
+
expectedRunId: transferReceipt?.runId,
|
|
8368
8446
|
identity,
|
|
8369
8447
|
onAdmission: options.onAdmission,
|
|
8370
8448
|
capabilities,
|
|
8371
8449
|
now: options.now,
|
|
8372
|
-
preserveEnvironment: options.existingEnvironmentId !== void 0
|
|
8450
|
+
preserveEnvironment: transferReceipt !== void 0 || options.existingEnvironmentId !== void 0
|
|
8373
8451
|
});
|
|
8374
8452
|
}
|
|
8375
8453
|
/**
|
|
@@ -8382,6 +8460,7 @@ async function startRetainedRun(options) {
|
|
|
8382
8460
|
* @stable
|
|
8383
8461
|
*/
|
|
8384
8462
|
async function startRetainedRunInEnvironment(options) {
|
|
8463
|
+
if (options.turn.contextTransfer !== void 0) throw new Error("accepted context transfer requires startRetainedRun with its exact profile and receipt");
|
|
8385
8464
|
assertStableText(options.environment.id, "retained environment id");
|
|
8386
8465
|
assertStableText(options.environment.idempotencyKey, "environment idempotency key");
|
|
8387
8466
|
assertStableText(options.turn.turnId, "turn idempotency key");
|
|
@@ -8486,6 +8565,7 @@ async function dispatchRetainedRun(options) {
|
|
|
8486
8565
|
sessionId: identity.sessionId
|
|
8487
8566
|
});
|
|
8488
8567
|
if (controlRef.executionId !== identity.executionId) throw new Error("provider bound another execution than the requested identity");
|
|
8568
|
+
if (options.expectedRunId !== void 0 && controlRef.runId !== options.expectedRunId) throw new Error("provider bound another run than the accepted context transfer receipt");
|
|
8489
8569
|
exact = exactSession(environment, controlRef);
|
|
8490
8570
|
} catch (error) {
|
|
8491
8571
|
const bindingError = new RetainedRunDispatchBindingError({
|
|
@@ -8545,10 +8625,12 @@ async function recoverRetainedRun(options) {
|
|
|
8545
8625
|
assertStableText(options.environmentId, "retained environment id");
|
|
8546
8626
|
assertStableText(options.sessionId, "retained session id");
|
|
8547
8627
|
assertStableText(options.executionId, "retained execution id");
|
|
8628
|
+
const contextTransfer = retainedContextTransfer(options.contextTransfer);
|
|
8548
8629
|
const providerCapabilities = await assertRetainedCapabilities(options.provider);
|
|
8549
8630
|
if (!options.provider.get) throw new Error(`provider "${options.provider.name}" cannot reconstruct an environment by id`);
|
|
8550
|
-
const environment = await options.provider.get(options.environmentId);
|
|
8631
|
+
const environment = contextTransfer === void 0 || options.transferReceipt === void 0 ? await options.provider.get(options.environmentId) : await options.provider.get(options.environmentId, { contextTransfer });
|
|
8551
8632
|
if (!environment) return { outcome: "not_found" };
|
|
8633
|
+
if (contextTransfer !== void 0 && options.transferReceipt !== void 0) assertRetainedContextTransferEnvironment(environment, contextTransfer, options.transferReceipt);
|
|
8552
8634
|
const capabilities = retainedCapabilitiesForEnvironment(options.provider.name, providerCapabilities, environment);
|
|
8553
8635
|
if (!environment.session) return {
|
|
8554
8636
|
outcome: "unverifiable",
|
|
@@ -8588,6 +8670,8 @@ function assertRetainedRunReplayMaterial(provider, replay, admission) {
|
|
|
8588
8670
|
}, identity, retainedContextTransfer(replay.turn.contextTransfer)));
|
|
8589
8671
|
}
|
|
8590
8672
|
function retainedRunIntent(options, identity, contextTransfer) {
|
|
8673
|
+
const receipt = retainedContextTransferReceipt(options, options.provider.name, contextTransfer);
|
|
8674
|
+
assertRetainedContextTransferIdentity(receipt, identity);
|
|
8591
8675
|
const { profile } = options.environment;
|
|
8592
8676
|
const requestedProfileDigest = typeof profile === "string" ? canonicalCandidateDigest(profile) : canonicalAgentProfileDigest(profile);
|
|
8593
8677
|
const requestDigest = canonicalCandidateDigest({
|
|
@@ -8599,6 +8683,10 @@ function retainedRunIntent(options, identity, contextTransfer) {
|
|
|
8599
8683
|
sessionId: identity.sessionId,
|
|
8600
8684
|
executionId: identity.executionId,
|
|
8601
8685
|
requestedProfileDigest,
|
|
8686
|
+
...receipt === void 0 ? {} : { contextTransferReceiptDigest: canonicalCandidateDigest({
|
|
8687
|
+
...receipt,
|
|
8688
|
+
status: "accepted"
|
|
8689
|
+
}) },
|
|
8602
8690
|
create: retainedCreateMaterial(options.environment),
|
|
8603
8691
|
turn: retainedTurnMaterial(options.turn, contextTransfer)
|
|
8604
8692
|
});
|
|
@@ -8616,7 +8704,9 @@ function retainedRunIntent(options, identity, contextTransfer) {
|
|
|
8616
8704
|
}
|
|
8617
8705
|
function retainedContextTransfer(value) {
|
|
8618
8706
|
if (value === void 0) return void 0;
|
|
8619
|
-
|
|
8707
|
+
const parsed = ContextTransferRequestSchema.safeParse(value);
|
|
8708
|
+
if (!parsed.success) throw new Error("retained context transfer request is invalid or uses an incompatible wire contract; preserve the original record and explicitly reconstruct and review an Interface 5 transfer request before retrying", { cause: parsed.error });
|
|
8709
|
+
return detachedSnapshot(parsed.data, "retained context transfer request");
|
|
8620
8710
|
}
|
|
8621
8711
|
function assertExactRetainedRunIntent(received, expected) {
|
|
8622
8712
|
if (canonicalCandidateDigest(parseRetainedRunIntent(received)) !== canonicalCandidateDigest(expected)) throw new Error("retained run intent conflicts with replay material");
|
|
@@ -11091,6 +11181,7 @@ function retainedExecutorContext(ctx) {
|
|
|
11091
11181
|
}
|
|
11092
11182
|
const causeMessages = {
|
|
11093
11183
|
unobservable: "retained provider execution requires reconciliation before replacement",
|
|
11184
|
+
"terminal-event-lost": "retained provider stream ended or stalled without a terminal event; exact result requires reconciliation",
|
|
11094
11185
|
"provider-contract": "retained provider response violated its contract; original execution remains unresolved",
|
|
11095
11186
|
"request-rejected": "retained provider execution was refused before it ran; nothing to reconcile",
|
|
11096
11187
|
transport: "retained provider execution lost its transport; status in doubt",
|
|
@@ -12368,6 +12459,33 @@ const NATIVE_STOP_TIMEOUT_MS = 3e4;
|
|
|
12368
12459
|
/** How long the final copy of a stopped harness waits for the provider to record how it ended. */
|
|
12369
12460
|
const NATIVE_SETTLE_WINDOW_MS = 15e3;
|
|
12370
12461
|
const NATIVE_SETTLE_POLL_MS = 1e3;
|
|
12462
|
+
/** The two waits together leave a minute for Runtime to record a pending result before ten minutes. */
|
|
12463
|
+
const RETAINED_OBSERVATION_IDLE_MS = 8 * 6e4;
|
|
12464
|
+
const RETAINED_RESULT_WAIT_MS = 6e4;
|
|
12465
|
+
var RetainedReadTimeoutError = class extends Error {
|
|
12466
|
+
constructor(label, ms) {
|
|
12467
|
+
super(`retained provider ${label} did not settle within ${ms} ms`);
|
|
12468
|
+
this.name = "RetainedReadTimeoutError";
|
|
12469
|
+
}
|
|
12470
|
+
};
|
|
12471
|
+
function retainedWaitBound(value, maximum, name) {
|
|
12472
|
+
if (value === void 0) return maximum;
|
|
12473
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value > maximum) throw new ValidationError(`${name} must be a positive integer at most ${maximum} ms`);
|
|
12474
|
+
return value;
|
|
12475
|
+
}
|
|
12476
|
+
/** Bound a provider read without confusing a lost observer with a cancelled execution. */
|
|
12477
|
+
function awaitRetainedRead(read, ms, label) {
|
|
12478
|
+
return new Promise((resolve, reject) => {
|
|
12479
|
+
const clear = armDeadlineTimer(ms, () => reject(new RetainedReadTimeoutError(label, ms)), true);
|
|
12480
|
+
read.then((value) => {
|
|
12481
|
+
clear();
|
|
12482
|
+
resolve(value);
|
|
12483
|
+
}, (error) => {
|
|
12484
|
+
clear();
|
|
12485
|
+
reject(error);
|
|
12486
|
+
});
|
|
12487
|
+
});
|
|
12488
|
+
}
|
|
12371
12489
|
/** The environment id the latest durable admission names, when creation got that far. */
|
|
12372
12490
|
function admittedEnvironmentId(retention) {
|
|
12373
12491
|
for (const admission of [...retention?.admissions ?? []].reverse()) {
|
|
@@ -12757,6 +12875,9 @@ async function providerExecutionSource(args, turn, signal) {
|
|
|
12757
12875
|
};
|
|
12758
12876
|
}
|
|
12759
12877
|
const retention = args.retention;
|
|
12878
|
+
const observationIdleMs = retainedWaitBound(args.options.retainedObservationIdleMs, RETAINED_OBSERVATION_IDLE_MS, "retainedObservationIdleMs");
|
|
12879
|
+
const resultWaitMs = retainedWaitBound(args.options.retainedResultWaitMs, RETAINED_RESULT_WAIT_MS, "retainedResultWaitMs");
|
|
12880
|
+
const resultDrainGraceMs = Math.min(15e3, Math.max(50, Math.floor(observationIdleMs / 10)));
|
|
12760
12881
|
let admitted = args.recovering;
|
|
12761
12882
|
let executionAdmitted = args.recovering && retention.admissions.some((admission) => admission.phase === "dispatched");
|
|
12762
12883
|
const onAdmission = async (admission) => {
|
|
@@ -12881,11 +13002,23 @@ async function providerExecutionSource(args, turn, signal) {
|
|
|
12881
13002
|
const session = exactSession(environment, handle.controlRef).session;
|
|
12882
13003
|
async function* events() {
|
|
12883
13004
|
let observationFailure;
|
|
13005
|
+
let exactResult;
|
|
13006
|
+
let exactWake;
|
|
13007
|
+
const readExactResult = () => {
|
|
13008
|
+
if (exactResult === void 0) {
|
|
13009
|
+
exactResult = awaitAbortable$1(handle.result(), signal);
|
|
13010
|
+
exactWake = exactResult.then(() => void 0, () => new Promise(() => {}));
|
|
13011
|
+
}
|
|
13012
|
+
return exactResult;
|
|
13013
|
+
};
|
|
12884
13014
|
let lastReplayPosition;
|
|
12885
13015
|
let sawTerminal = false;
|
|
13016
|
+
let lastObservedAt = Date.now();
|
|
13017
|
+
const seenEvents = /* @__PURE__ */ new Map();
|
|
12886
13018
|
const drain = async function* (open) {
|
|
12887
13019
|
let iterator;
|
|
12888
13020
|
let failed = false;
|
|
13021
|
+
let exactResultReady = false;
|
|
12889
13022
|
try {
|
|
12890
13023
|
iterator = open()[Symbol.asyncIterator]();
|
|
12891
13024
|
} catch (error) {
|
|
@@ -12897,7 +13030,21 @@ async function providerExecutionSource(args, turn, signal) {
|
|
|
12897
13030
|
while (true) {
|
|
12898
13031
|
let next;
|
|
12899
13032
|
try {
|
|
12900
|
-
|
|
13033
|
+
const remaining = observationIdleMs - (Date.now() - lastObservedAt);
|
|
13034
|
+
if (remaining <= 0) throw new RetainedReadTimeoutError("event stream", observationIdleMs);
|
|
13035
|
+
const eventRead = awaitAbortable$1(Promise.resolve().then(() => iterator.next()), signal).then((value) => ({
|
|
13036
|
+
kind: "event",
|
|
13037
|
+
value
|
|
13038
|
+
}));
|
|
13039
|
+
const observed = await awaitRetainedRead(exactWake !== void 0 && !sawTerminal ? Promise.race([eventRead, exactWake.then(() => ({ kind: "exact-result" }))]) : eventRead, remaining, "event stream");
|
|
13040
|
+
if (observed.kind === "exact-result") try {
|
|
13041
|
+
next = (await awaitRetainedRead(eventRead, resultDrainGraceMs, "buffered event stream")).value;
|
|
13042
|
+
} catch (error) {
|
|
13043
|
+
if (!(error instanceof RetainedReadTimeoutError)) throw error;
|
|
13044
|
+
exactResultReady = true;
|
|
13045
|
+
break;
|
|
13046
|
+
}
|
|
13047
|
+
else next = observed.value;
|
|
12901
13048
|
} catch (error) {
|
|
12902
13049
|
if (signal.aborted) throw error;
|
|
12903
13050
|
observationFailure = { error };
|
|
@@ -12913,12 +13060,31 @@ async function providerExecutionSource(args, turn, signal) {
|
|
|
12913
13060
|
cause: error
|
|
12914
13061
|
});
|
|
12915
13062
|
}
|
|
12916
|
-
|
|
13063
|
+
const identity = extractTransportEventIdentity(next.value);
|
|
13064
|
+
const eventId = identity.eventId ?? identity.cursor;
|
|
13065
|
+
if (eventId !== void 0) {
|
|
13066
|
+
const digest = canonicalCandidateDigest({
|
|
13067
|
+
type: next.value.type,
|
|
13068
|
+
data: next.value.data,
|
|
13069
|
+
...next.value.usage === void 0 ? {} : { usage: next.value.usage },
|
|
13070
|
+
...next.value.normalized === void 0 ? {} : { normalized: next.value.normalized }
|
|
13071
|
+
});
|
|
13072
|
+
const prior = seenEvents.get(eventId);
|
|
13073
|
+
if (prior !== void 0) {
|
|
13074
|
+
if (prior !== digest) throw new RetainedRunProviderContractError(`provider replay changed retained event ${eventId}`, { code: "RETAINED_EVENT_DUPLICATE_CHANGED" });
|
|
13075
|
+
continue;
|
|
13076
|
+
}
|
|
13077
|
+
seenEvents.set(eventId, digest);
|
|
13078
|
+
}
|
|
13079
|
+
lastObservedAt = Date.now();
|
|
13080
|
+
if (identity.cursor !== void 0) lastReplayPosition = identity.cursor;
|
|
13081
|
+
else if (eventId !== void 0) lastReplayPosition = eventId;
|
|
12917
13082
|
if (isTerminalEnvironmentEvent(next.value)) sawTerminal = true;
|
|
13083
|
+
else readExactResult();
|
|
12918
13084
|
yield next.value;
|
|
12919
13085
|
}
|
|
12920
13086
|
} finally {
|
|
12921
|
-
if (signal.aborted || failed) Promise.resolve().then(() => iterator?.return?.()).catch(() => void 0);
|
|
13087
|
+
if (signal.aborted || failed || exactResultReady || sawTerminal) Promise.resolve().then(() => iterator?.return?.()).catch(() => void 0);
|
|
12922
13088
|
else await iterator?.return?.();
|
|
12923
13089
|
}
|
|
12924
13090
|
return !failed;
|
|
@@ -12926,7 +13092,7 @@ async function providerExecutionSource(args, turn, signal) {
|
|
|
12926
13092
|
if (!(yield* drain(() => session.events({
|
|
12927
13093
|
executionId: handle.controlRef.executionId,
|
|
12928
13094
|
signal
|
|
12929
|
-
}))) && !sawTerminal && lastReplayPosition !== void 0) {
|
|
13095
|
+
}))) && !sawTerminal && lastReplayPosition !== void 0 && !(observationFailure?.error instanceof RetainedReadTimeoutError)) {
|
|
12930
13096
|
const firstFailure = observationFailure;
|
|
12931
13097
|
observationFailure = void 0;
|
|
12932
13098
|
if (!(yield* drain(() => session.events({
|
|
@@ -12935,11 +13101,14 @@ async function providerExecutionSource(args, turn, signal) {
|
|
|
12935
13101
|
signal
|
|
12936
13102
|
})))) observationFailure = firstFailure;
|
|
12937
13103
|
}
|
|
13104
|
+
if (!sawTerminal && observationFailure === void 0) observationFailure = { error: /* @__PURE__ */ new Error("retained provider stream did not yield a terminal event") };
|
|
12938
13105
|
let result;
|
|
12939
13106
|
try {
|
|
12940
|
-
result = await
|
|
13107
|
+
result = await awaitRetainedRead(readExactResult(), resultWaitMs, "exact result");
|
|
12941
13108
|
} catch (error) {
|
|
12942
|
-
if (
|
|
13109
|
+
if (signal.aborted) throw error;
|
|
13110
|
+
if (!sawTerminal && error instanceof RetainedReadTimeoutError) throw new RetainedExecutionPendingError(new AggregateError([observationFailure?.error, error], "retained event stream had no terminal event and its exact result is unavailable", { cause: error }), "terminal-event-lost");
|
|
13111
|
+
if (observationFailure === void 0) throw error;
|
|
12943
13112
|
throw new AggregateError([observationFailure.error, error], "retained event observation failed and its exact result could not be reconciled", { cause: error });
|
|
12944
13113
|
}
|
|
12945
13114
|
yield {
|
|
@@ -13833,6 +14002,7 @@ async function runBrainLoop(opts) {
|
|
|
13833
14002
|
role: "assistant",
|
|
13834
14003
|
content: r.content ?? "",
|
|
13835
14004
|
tool_calls: r.toolCalls.map((tc) => ({
|
|
14005
|
+
...tc.providerFields,
|
|
13836
14006
|
id: tc.id,
|
|
13837
14007
|
type: "function",
|
|
13838
14008
|
function: {
|
|
@@ -14016,6 +14186,17 @@ function splitReasoning(rawContent, fieldReasoning) {
|
|
|
14016
14186
|
...fieldReasoning ? { reasoning: fieldReasoning } : {}
|
|
14017
14187
|
};
|
|
14018
14188
|
}
|
|
14189
|
+
/** Keep provider extensions beside, never in place of, the canonical call identity and function.
|
|
14190
|
+
* Stream indices identify assembly slots and are not replay fields. */
|
|
14191
|
+
function toolCallProviderFields(call) {
|
|
14192
|
+
const fields = Object.fromEntries(Object.entries(call).filter(([key]) => ![
|
|
14193
|
+
"id",
|
|
14194
|
+
"type",
|
|
14195
|
+
"function",
|
|
14196
|
+
"index"
|
|
14197
|
+
].includes(key)));
|
|
14198
|
+
return Object.keys(fields).length === 0 ? void 0 : fields;
|
|
14199
|
+
}
|
|
14019
14200
|
/**
|
|
14020
14201
|
* A router completion WITH tool-calling — the operator driver's LLM seam. Passes OpenAI-shape
|
|
14021
14202
|
* `messages` (system/user/assistant-with-tool_calls/tool roles) + function `tools`, and returns the
|
|
@@ -14047,11 +14228,15 @@ async function routerChatWithTools(cfg, messages, tools, opts) {
|
|
|
14047
14228
|
const data = raw;
|
|
14048
14229
|
const msg = data.choices?.[0]?.message;
|
|
14049
14230
|
if (!msg) throw new ValidationError$1("router completion: no choices[0].message");
|
|
14050
|
-
const toolCalls = (msg?.tool_calls ?? []).map((tc, i) =>
|
|
14051
|
-
|
|
14052
|
-
|
|
14053
|
-
|
|
14054
|
-
|
|
14231
|
+
const toolCalls = (msg?.tool_calls ?? []).map((tc, i) => {
|
|
14232
|
+
const providerFields = toolCallProviderFields(tc);
|
|
14233
|
+
return {
|
|
14234
|
+
id: tc.id ?? `call_${i}`,
|
|
14235
|
+
name: tc.function?.name ?? "",
|
|
14236
|
+
arguments: tc.function?.arguments ?? "{}",
|
|
14237
|
+
...providerFields ? { providerFields } : {}
|
|
14238
|
+
};
|
|
14239
|
+
});
|
|
14055
14240
|
const { usage, resources, costUsd, costProvenance, billedCostUsd, cache } = meterTurn(data.usage, cfg.model, transportAttempts);
|
|
14056
14241
|
return {
|
|
14057
14242
|
response: raw,
|
|
@@ -14201,7 +14386,8 @@ async function streamRouterChatWithTools(cfg, messages, tools, opts) {
|
|
|
14201
14386
|
const toolCalls = [...streamed.calls.entries()].sort((a, b) => a[0] - b[0]).map(([index, call]) => ({
|
|
14202
14387
|
id: call.id ?? `call_${index}`,
|
|
14203
14388
|
name: call.name ?? "",
|
|
14204
|
-
arguments: call.arguments || "{}"
|
|
14389
|
+
arguments: call.arguments || "{}",
|
|
14390
|
+
...call.providerFields ? { providerFields: call.providerFields } : {}
|
|
14205
14391
|
}));
|
|
14206
14392
|
const { usage, resources, costUsd, costProvenance, billedCostUsd, cache } = meterTurn(streamed.rawUsage, cfg.model, streamed.transportAttempts);
|
|
14207
14393
|
return {
|
|
@@ -14315,6 +14501,11 @@ async function streamChatCompletion(context, cfg, requestBody, opts) {
|
|
|
14315
14501
|
if (tc.id) acc.id = tc.id;
|
|
14316
14502
|
if (tc.function?.name) acc.name = tc.function.name;
|
|
14317
14503
|
if (tc.function?.arguments) acc.arguments += tc.function.arguments;
|
|
14504
|
+
const providerFields = toolCallProviderFields(tc);
|
|
14505
|
+
if (providerFields) acc.providerFields = {
|
|
14506
|
+
...acc.providerFields,
|
|
14507
|
+
...providerFields
|
|
14508
|
+
};
|
|
14318
14509
|
calls.set(index, acc);
|
|
14319
14510
|
}
|
|
14320
14511
|
}
|
|
@@ -20333,6 +20524,33 @@ const routerInlineExecutor = (spec, ctx) => {
|
|
|
20333
20524
|
});
|
|
20334
20525
|
return executor;
|
|
20335
20526
|
};
|
|
20527
|
+
/** Compose node behavior with host state and ceilings; neither grants new tools. */
|
|
20528
|
+
function routerCodeModeSettings(profile, host) {
|
|
20529
|
+
if (profile === false || profile === void 0 && host === void 0) return void 0;
|
|
20530
|
+
const environment = typeof host === "object" ? host : {};
|
|
20531
|
+
const node = typeof profile === "object" ? profile : {};
|
|
20532
|
+
const limits = {};
|
|
20533
|
+
for (const key of [
|
|
20534
|
+
"timeoutMs",
|
|
20535
|
+
"memoryLimitBytes",
|
|
20536
|
+
"concurrency",
|
|
20537
|
+
"maxCalls"
|
|
20538
|
+
]) {
|
|
20539
|
+
const ceiling = environment[key];
|
|
20540
|
+
const requested = node[key];
|
|
20541
|
+
for (const value of [ceiling, requested]) {
|
|
20542
|
+
if (value === void 0 || key === "timeoutMs" && value === Infinity) continue;
|
|
20543
|
+
if (!Number.isSafeInteger(value) || value < 1 || key === "timeoutMs" && value > 2147483647) throw new ValidationError$1(`router-tools: invalid codeMode.${key}`);
|
|
20544
|
+
}
|
|
20545
|
+
const value = ceiling === void 0 ? requested : requested === void 0 ? ceiling : Math.min(ceiling, requested);
|
|
20546
|
+
if (value !== void 0) limits[key] = value;
|
|
20547
|
+
}
|
|
20548
|
+
return {
|
|
20549
|
+
...environment,
|
|
20550
|
+
...limits,
|
|
20551
|
+
...environment.directTools || node.directTools ? { directTools: [.../* @__PURE__ */ new Set([...environment.directTools ?? [], ...node.directTools ?? []])] } : {}
|
|
20552
|
+
};
|
|
20553
|
+
}
|
|
20336
20554
|
const routerToolsSeamKey = "router-tools";
|
|
20337
20555
|
function mergePromptCache(target, cache) {
|
|
20338
20556
|
if (!cache) return;
|
|
@@ -20373,6 +20591,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20373
20591
|
tools: seam.tools
|
|
20374
20592
|
}, { multiTurn: true });
|
|
20375
20593
|
if (model === "tangle/auto") assertRouterAutoDeclaration(profileExecution.extraBody?.auto, profileExecution.stream);
|
|
20594
|
+
const codeModeConfig = routerCodeModeSettings(profileExecution.codeMode, seam.codeMode);
|
|
20376
20595
|
const enabledToolNames = new Set(seam.tools.map((tool) => tool.function.name));
|
|
20377
20596
|
const maxTurns = profileExecution.maxTurns ?? 0;
|
|
20378
20597
|
const requestIdentity = routerRequestIdentity(ctx);
|
|
@@ -20446,14 +20665,13 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20446
20665
|
} catch {}
|
|
20447
20666
|
}
|
|
20448
20667
|
};
|
|
20449
|
-
const codeModeConfig = profileExecution.codeMode ?? seam.codeMode;
|
|
20450
20668
|
const codeMode = codeModeConfig ? createCodeModeTools(seam.tools.map(({ function: tool }) => ({
|
|
20451
20669
|
name: tool.name,
|
|
20452
20670
|
description: tool.description,
|
|
20453
20671
|
inputSchema: tool.parameters,
|
|
20454
20672
|
outputSchema: tool.outputSchema,
|
|
20455
20673
|
execute: (args, context) => executeGranted(tool.name, args, context)
|
|
20456
|
-
})), codeModeConfig
|
|
20674
|
+
})), codeModeConfig) : void 0;
|
|
20457
20675
|
const presentedTools = codeMode ? codeMode.tools.map((tool) => ({
|
|
20458
20676
|
type: "function",
|
|
20459
20677
|
function: {
|
|
@@ -20566,6 +20784,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
|
|
|
20566
20784
|
role: "assistant",
|
|
20567
20785
|
content: res.content ?? "",
|
|
20568
20786
|
tool_calls: toolCalls.map((tc) => ({
|
|
20787
|
+
...tc.providerFields,
|
|
20569
20788
|
id: tc.id,
|
|
20570
20789
|
type: "function",
|
|
20571
20790
|
function: {
|
|
@@ -22863,7 +23082,7 @@ async function startRetainedInteractiveRun(options) {
|
|
|
22863
23082
|
assertStableText(identity.executionId, "retained execution id");
|
|
22864
23083
|
const intent = interactiveIntent(startOptions, profile, identity);
|
|
22865
23084
|
if (startOptions.intent === void 0) await admitDurably(startOptions.onAdmission, intent);
|
|
22866
|
-
else assertExactInteractiveIntent(startOptions.intent, intent);
|
|
23085
|
+
else assertExactInteractiveIntent(startOptions.intent, intent, () => interactiveIntent(startOptions, profile, identity, legacyRetainedCreateMaterial));
|
|
22867
23086
|
const providerCapabilities = AgentEnvironmentCapabilitiesSchema.parse(await awaitAbortable$1(Promise.resolve().then(() => startOptions.provider.capabilities()), startOptions.signal));
|
|
22868
23087
|
assertInteractiveCapabilities(startOptions.provider.name, providerCapabilities);
|
|
22869
23088
|
const environment = await createInteractiveEnvironment(() => startOptions.provider.create({
|
|
@@ -22984,7 +23203,7 @@ function interactiveRequest(options, environment, profile, requestedProfileDiges
|
|
|
22984
23203
|
...start
|
|
22985
23204
|
});
|
|
22986
23205
|
}
|
|
22987
|
-
function interactiveIntent(options, profile, identity) {
|
|
23206
|
+
function interactiveIntent(options, profile, identity, createMaterial = retainedCreateMaterial) {
|
|
22988
23207
|
const requestedProfileDigest = canonicalAgentProfileDigest(profile);
|
|
22989
23208
|
const requestDigest = canonicalCandidateDigest({
|
|
22990
23209
|
kind: "retained-interactive-intent.v1",
|
|
@@ -22994,7 +23213,7 @@ function interactiveIntent(options, profile, identity) {
|
|
|
22994
23213
|
sessionId: identity.sessionId,
|
|
22995
23214
|
executionId: identity.executionId,
|
|
22996
23215
|
requestedProfileDigest,
|
|
22997
|
-
create:
|
|
23216
|
+
create: createMaterial(options.environment),
|
|
22998
23217
|
start: sanitizedStartMaterial(options)
|
|
22999
23218
|
});
|
|
23000
23219
|
return {
|
|
@@ -23017,8 +23236,11 @@ function sanitizedStartMaterial(options) {
|
|
|
23017
23236
|
...options.rows === void 0 ? {} : { rows: options.rows }
|
|
23018
23237
|
};
|
|
23019
23238
|
}
|
|
23020
|
-
function assertExactInteractiveIntent(received, expected) {
|
|
23021
|
-
|
|
23239
|
+
function assertExactInteractiveIntent(received, expected, legacyExpected) {
|
|
23240
|
+
const stableReceived = parseInteractiveIntent(received);
|
|
23241
|
+
if (canonicalCandidateDigest(stableReceived) !== canonicalCandidateDigest(expected)) {
|
|
23242
|
+
if (legacyExpected === void 0 || canonicalCandidateDigest(stableReceived) !== canonicalCandidateDigest(legacyExpected())) throw new Error("interactive intent conflicts with replay material");
|
|
23243
|
+
}
|
|
23022
23244
|
}
|
|
23023
23245
|
function parseInteractiveIntent(value) {
|
|
23024
23246
|
const stable = detachedSnapshot(value, "interactive intent");
|
|
@@ -29074,7 +29296,7 @@ function isUpstreamUnavailable(error) {
|
|
|
29074
29296
|
*/
|
|
29075
29297
|
function classifyDriverFailure(error, signal) {
|
|
29076
29298
|
if (signal?.aborted) return "terminal";
|
|
29077
|
-
if (error instanceof RetainedExecutionPendingError && error.pendingCause === "provider-contract") return "terminal";
|
|
29299
|
+
if (error instanceof RetainedExecutionPendingError && (error.pendingCause === "provider-contract" || error.pendingCause === "terminal-event-lost")) return "terminal";
|
|
29078
29300
|
const admission = retainedAdmissionCause(error);
|
|
29079
29301
|
if (admission !== void 0 && isDispatchNotAdmitted(admission)) return "terminal";
|
|
29080
29302
|
if (admission !== void 0) return classifyDriverFailure(admission, signal);
|
|
@@ -29312,6 +29534,7 @@ async function runDriverWithRetry(run) {
|
|
|
29312
29534
|
const after = run.progress();
|
|
29313
29535
|
const progressed = madeProgress(before, after);
|
|
29314
29536
|
if (progressed) abandonments = 0;
|
|
29537
|
+
const retainedFailure = error instanceof RetainedExecutionPendingError ? error : void 0;
|
|
29315
29538
|
const pending = abandonablePending(error);
|
|
29316
29539
|
samePending = pending === void 0 || classification !== "transient" ? void 0 : {
|
|
29317
29540
|
cause: pending.pendingCause,
|
|
@@ -29401,7 +29624,7 @@ async function runDriverWithRetry(run) {
|
|
|
29401
29624
|
classification,
|
|
29402
29625
|
madeProgress: progressed,
|
|
29403
29626
|
stop: retryStop,
|
|
29404
|
-
...
|
|
29627
|
+
...retainedFailure === void 0 ? {} : { pendingCause: retainedFailure.pendingCause }
|
|
29405
29628
|
});
|
|
29406
29629
|
throw new DriverAttemptsExhaustedError(error, attempts, retryStop);
|
|
29407
29630
|
}
|
|
@@ -30650,6 +30873,6 @@ function isNonEmptySpend(s) {
|
|
|
30650
30873
|
return s.iterations > 0 || s.tokens.input > 0 || s.tokens.output > 0 || s.usd > 0 || s.ms > 0 || s.tokensKnown === false || s.usdKnown === false || Object.values(s.resources ?? {}).some((resource) => resource.amount > 0 || !resource.known);
|
|
30651
30874
|
}
|
|
30652
30875
|
//#endregion
|
|
30653
|
-
export { environmentReader as $,
|
|
30876
|
+
export { environmentReader as $, runtimeOwnedScopeOwnerRuntime as $i, parseWorkerToolTraceArtifact as $n, loopEventToOtelSpan as $r, PEER_MAIL_WIRE_KEY as $t, scopeOwnerExecutorNodeContext as A, promptOnlyProfileMaterialization as Ai, resolveAgentEnvironmentProvider as An, resolveHarnessTranscriptCapture as Ar, captureReusableExecutorConfig as At, consumeScopeRetainedOwnerResult as B, authoredProfileDigest as Bi, InMemoryResultBlobStore as Bn, mergeTraceEnv as Br, createInPlaceCliExecutor as Bt, deriveNodeExecutionIdentity as C, promptFromAgentTurnInput as Ca, assertProfileMaterializes as Ci, readPromptOptions as Cn, abortError as Cr, createContinuationKeeper as Ct, recordScopeOwnerMaterialization as D, profileMaterializationAxes$1 as Di, createAgentEnvironmentProviderRegistry as Dn, harnessTranscriptArtifact as Dr, passedItems as Dt, recordScopeOwnerDriverAttempt as E, fullProfileMaterialization as Ei, LEAF_CONTINUATION_TASK as En, captureHarnessTranscript as Er, failedItems as Et, seatExecutionProfile as F, unsupportedProfileDimensions as Fi, retainedExecutorSeamKey as Fn, runCodeMode as Fr, snapshotExecutorConfig as Ft, scopeRetainedOwnerContext as G, newExecutionAttemptId as Gi, replaySpawnTree as Gn, resolveRedactor as Gr, workerTraceSeamKey as Gt, prepareScopeRetainedOwnerSeatSwitch as H, inheritRuntimeOwnedExecutorAttestation as Hi, insideCursorNamespace as Hn, traceContextToEnv as Hr, readWorkerTraceContext as Ht, abandonScopeRetainedOwnerInvocation as I, validateProfileMaterialization as Ii, unavailablePauseMs as In, priceTokens as Ir, createWorktreeCliExecutor as It, scopeRetainedOwnerResourceReader as J, runtimeOwnedDriveHarnessProviderEvidence as Ji, readCommittedJsonLines as Jn, buildRuntimeEventOtelSpans as Jr, createActivityLog as Jt, scopeRetainedOwnerJournalRoot as K, providerAttemptEvidence as Ki, isNoEntError as Kn, buildLoopOtelSpans as Kr, taskToPrompt as Kt, beginScopeRetainedOwnerDrive as L, worktreeCliProfileMaterialization as Li, unavailableSignalOfFailure as Ln, routerTokenPrice as Lr, DEFAULT_SANDBOX_STEERING_MAX_TURNS as Lt, SeatChain as M, renderProfileMaterializationIssues as Mi, decodeToolPart as Mn, contentAddress as Mr, cliWorktreeExecutor as Mt, SeatChainExhaustedError as N, renderUnsupported as Ni, sandboxSessionTraceSource as Nn, createCodeModeTools as Nr, createExecutor as Nt, recordScopeOwnerPause as O, promptControlProfileMaterialization as Oi, providerAsExecutor as On, persistHarnessTranscript as Or, verdictFromJudgeScore as Ot, authoredSeatStages as P, sandboxActProfileMaterialization as Pi, registerRetainedExecutorPreparation as Pn, describeCodeModeTools as Pr, createExecutorRegistry as Pt, SPAWN_RESOURCE_PATH_MAX_BYTES as Q, runtimeOwnedPendingExecutorMaterialization as Qi, isTraceAnalysisStore as Qn, generateSpanId as Qr, DEFAULT_PEER_MAIL_LIMITS as Qt, bindScopeRetainedOwnerEnvironmentId as R, attestRuntimeOwnedPendingExecutor as Ri, FileResultBlobStore as Rn, ROUTER_PRICE_SOURCE as Rr, createSteerableSandboxSession as Rt, createScope as S, awaitAbortable$1 as Sa, assertProfileMaterialization as Si, assertBoxlessPromptOptions as Sn, RunCancellationReason as Sr, checkVerdictOf as St, meterRuntimeOwnedProviderAttempt as T, providerMessageText as Ta, defineProfileMaterializationContract as Ti, runBrainLoop as Tn, runAbortable as Tr, expandQuestions as Tt, prepareScopeRetainedOwnerTask as U, knownExecutionBindingReceipt as Ui, loadSpawnForest as Un, defaultRedactor as Ur, workerTraceEnv as Ut, noteScopeRetainedOwnerCoordination as V, finalizeRuntimeOwnedPendingExecutor as Vi, InMemorySpawnJournal as Vn, readTraceContextFromEnv as Vr, WORKER_TRACE_PROPAGATION as Vt, reconcileScopeRetainedOwnerEnvironment as W, knownMaterializationReceipt as Wi, materializeTreeView as Wn, defaultRedactorIdentityMaterial as Wr, workerTraceHeaders as Wt, scopeRetainedOwnerResult as X, runtimeOwnedExecutorMaterialization as Xi, WORKER_TOOL_TRACE_SCHEMA_VERSION as Xn, createOtelExporter as Xr, createInbox as Xt, scopeRetainedOwnerRestorePoint as Y, runtimeOwnedExecutorExecutionBinding as Yi, writeAllBytes as Yn, createOpenInferenceFileExporter as Yr, readWorkerProgress as Yt, scopeRetainedOwnerTurnEnded as Z, runtimeOwnedExecutorProviderEvidence as Zi, captureWorkerTraceEvidence as Zn, flatOtelSpan as Zr, AUTHORITY_MARKERS as Zt, isDriverSpec as _, sandboxEventServedBackend as _a, localHarnessExecutable as _i, runAgentRounds as _n, retainedCreateMaterial as _r, CONTINUATION_FACTS as _t, collectDelivered as a, detachedSnapshot as aa, sanitizeAgentRuntimeEvent as ai, isLiveNodeStatus as an, createBudgetPool as ar, interactiveAdmissionSeamKey as at, assertRecursiveReservationPolicy as b, decodeHarnessUsage as ba, terminateProcessTreeAndConfirm as bi, SandboxEvidenceRetentionError as bn, createWorkerSlots as br, admitFinding as bt, runTree as c, assertSandboxServedModel as ca, runSettledCommand as ci, bridgeModelRouteRefusal as cn, spendFromUsageEvents as cr, reconnectRetainedInteractiveRun as ct, classifyDriverFailure as d, createSandboxUsageLedger as da, createWorktree as di, harnessUsageIsEmpty as dn, bridgeStopSignalKey as dr, freeSlots as dt, unknownExecutionBindingReceipt as ea, padSpanId as ei, claimsAuthority as en, workerTraceAnalysisStore as er, hostDirectoryReader as et, runDriverWithRetry as f, extractLlmCallEvent as fa, removeWorktree as fi, readCodexRolloutSession as fn, errMessage as fr, queueOf as ft, driverExecutorFactory as g, notifySandboxEventObserver as ga, harnessSupportsReasoningEffort as gi, isTerminalDecision as gn, startRetainedRunInEnvironment as gr, CONTINUATIONS_DIR as gt, driverChild as h, mapSandboxToolEvent as ha, harnessInvocation as hi, defaultSelectWinner as hn, startRetainedRun as hr, mapExecutorResult as ht, bestDelivered as i, detachedFrozen as ia, createRuntimeStreamEventCollector as ii, peerMailVerbNames as in, assertValidBudget as ir, providerVisibleProfile as it, settledToIteration as j, promptResourceProfileMaterialization as ji, createPushTraceSource as jn, retainHarnessTranscript as jr, cliInPlaceExecutor as jt, restoreScopeOwnerAcceptedExecution as k, promptModelProfileMaterialization as ki, providerAsSandboxClient as kn, readHarnessTranscript as kr, bindReusableExecutorExecutionId as kt, DriverAttemptsExhaustedError as l, canonicalStreamEventFromSandboxEvent as la, runWorktreeHarness as li, addHarnessUsage as ln, spendFromUsageTotals as lr, recoverRetainedInteractiveRun as lt, upstreamUnavailableSignal as m, mapSandboxEvent as ma, LOCAL_HARNESSES as mi, createSandboxForSpec as mn, recoverRetainedRun as mr, gateOnDeliverable as mt, createRootHandle as n, executableAgentProfileSnapshot as na, toOtelAttributes as ni, isPeerMailEnvelope as nn, BudgetReconcileFault as nr, coordinationMcpAlias as nt, pickBestDelivered as o, projectSandboxOutcome as oa, sanitizeKnowledgeReadinessReport as oi, isTerminalNodeStatus as on, meterUsageEvent as or, attachWorker as ot, summarizeDriverAttempts as p, isSandboxTerminalEvent as pa, DEFAULT_LOCAL_HARNESS as pi, TERMINAL_DECISIONS as pn, reconnectRetainedRun as pr, rollingDispatch as pt, scopeRetainedOwnerPriorSpend as q, recordRuntimeOwnedDriveHarnessProviderEvidence as qi, prepareJsonlAppend as qn, buildLoopSpanNodes as qr, DEFAULT_STALL_AFTER_MS as qt, createSupervisor as r, executableAgentSpecSnapshot as ra, createRuntimeEventCollector as ri, peerMailTools as rn, ReservationWaitRefused as rr, coordinationProfileToolPrefix as rt, runFinalizer as s, readSandboxOutcome as sa, sanitizeRuntimeStreamEvent as si, bridgeAdmissionRefusal as sn, newUsageTotals as sr, readWorkerInteractiveBinding as st, DEFAULT_MAX_DEPTH as t, unknownMaterializationReceipt as ta, padTraceId as ti, createPeerMailbox as tn, executorFailure as tr, resolveSpawnResourcePaths as tt, HarnessTurnFailedError as u, createSandboxToolPartState as ua, captureWorktreeDiff as ui, createCodexRolloutStoreReader as un, bridgeRuntimeAttachmentsKey as ur, startRetainedInteractiveRun as ut, withDriverExecutor as v, sandboxProgressEvents as va, parseCodexTokenUsage as vi, createSandboxLineage as vn, destroyInteractiveEnvironment as vr, CheckUnavailableError as vt, meterRuntimeOwnedAccounting as w, promptOptionsFromAgentTurnInput as wa, controlProfileMaterialization as wi, routerBrain as wn, linkAbort as wr, distillFindings as wt, beginScopeOwnerAttempt as x, abortError$1 as xa, AGENT_PROFILE_MATERIALIZATION_AXES as xi, captureBeforeDestroy as xn, openSlotGroup as xr, bestComposite as xt, SUBTREE_RESULT_LIMIT as y, sumSandboxUsage as ya, CodexExecutionDiagnosticError as yi, acquireSandbox as yn, environmentGone as yr, admitContinuationPolicy as yt, bindScopeRetainedOwnerProvider as z, attestRuntimeOwnedScopeOwner as zi, FileSpawnJournal as zn, createPropagatingTraceEmitter as zr, createRouterTranscript as zt };
|
|
30654
30877
|
|
|
30655
|
-
//# sourceMappingURL=supervisor
|
|
30878
|
+
//# sourceMappingURL=supervisor--nmU6w86.js.map
|