@tangle-network/agent-runtime 7.0.0 → 8.0.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/CHANGELOG.md +68 -0
- package/README.md +0 -3
- package/dist/{activation-Ba9IAgQ3.js → activation-Ce4zUcu8.js} +4 -4
- package/dist/{activation-Ba9IAgQ3.js.map → activation-Ce4zUcu8.js.map} +1 -1
- package/dist/{activation-DIkTEBWF.d.ts → activation-xxvLF1-1.d.ts} +2 -2
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +3 -3
- package/dist/{bundle-Cy5igJdv.js → bundle-CcpL2lfr.js} +2 -2
- package/dist/{bundle-Cy5igJdv.js.map → bundle-CcpL2lfr.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/continuation-CIyKnS1Q.js +451 -0
- package/dist/continuation-CIyKnS1Q.js.map +1 -0
- package/dist/{coordination-manager-DQZ2u6L-.js → coordination-manager-sa_PkISw.js} +194 -148
- package/dist/coordination-manager-sa_PkISw.js.map +1 -0
- package/dist/{coordination-map-routing-CKRNZSaV.js → coordination-map-routing-XZXTlCmn.js} +2 -4
- package/dist/coordination-map-routing-XZXTlCmn.js.map +1 -0
- package/dist/{delegate-DFLSVjFG.js → delegate-DhTkJIta.js} +3 -3
- package/dist/{delegate-DFLSVjFG.js.map → delegate-DhTkJIta.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +13 -12
- package/dist/durable.js.map +1 -1
- package/dist/{errors-AzSuGI23.js → errors-DG8yufqX.js} +8 -1
- package/dist/errors-DG8yufqX.js.map +1 -0
- package/dist/{failure-cause-rJTm_Tx8.js → failure-cause-CVB-YE88.js} +12 -8
- package/dist/{failure-cause-rJTm_Tx8.js.map → failure-cause-CVB-YE88.js.map} +1 -1
- package/dist/{graph-registry-7X2nrreR.js → graph-registry-czAwYwNj.js} +133 -9
- package/dist/graph-registry-czAwYwNj.js.map +1 -0
- package/dist/{graph-registry-gYbq4L5Z.js → graph-registry-uTIyyy7A.js} +1 -1
- package/dist/graph-tSIT_eWK.js +1793 -0
- package/dist/graph-tSIT_eWK.js.map +1 -0
- package/dist/{improve-BolbYegO.js → improve-H08hiIw9.js} +19 -48
- package/dist/improve-H08hiIw9.js.map +1 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +16 -16
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +8 -8
- package/dist/intelligence.js.map +1 -1
- package/dist/kernel.d.ts +2 -2
- package/dist/kernel.js +16 -15
- package/dist/{loop-runner-Cs9IJ6Nk.d.ts → loop-runner-BGwhcn1p.d.ts} +2 -2
- package/dist/{loop-runner-C9W3T_3T.js → loop-runner-ChqK8kSz.js} +3 -3
- package/dist/{loop-runner-C9W3T_3T.js.map → loop-runner-ChqK8kSz.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 +7 -5
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +9 -9
- package/dist/mcp/memory-bin.js +2 -2
- package/dist/{model-policy-JOcg3NRs.js → model-policy-yxOrDTTj.js} +9 -9
- package/dist/model-policy-yxOrDTTj.js.map +1 -0
- package/dist/{prepare-Dtfk_Wi_.js → prepare-BnF8nGIg.js} +4 -4
- package/dist/{prepare-Dtfk_Wi_.js.map → prepare-BnF8nGIg.js.map} +1 -1
- package/dist/{profile-CNSQjOes.js → profile-CD25rTJF.js} +4 -4
- package/dist/{profile-CNSQjOes.js.map → profile-CD25rTJF.js.map} +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.js +2 -2
- package/dist/{provision-supervisor-BQFHjCtN.js → provision-supervisor-Dx4TXTMM.js} +8 -8
- package/dist/{provision-supervisor-BQFHjCtN.js.map → provision-supervisor-Dx4TXTMM.js.map} +1 -1
- package/dist/{run-cancellation-B84X8ZAP.js → run-cancellation-DYszFJtQ.js} +4 -4
- package/dist/{run-cancellation-B84X8ZAP.js.map → run-cancellation-DYszFJtQ.js.map} +1 -1
- package/dist/{run-state-Dh1bGERI.js → run-state-DHBoJjaF.js} +5 -5
- package/dist/{run-state-Dh1bGERI.js.map → run-state-DHBoJjaF.js.map} +1 -1
- package/dist/{runtime-C9F1PG2A.js → runtime-CaM5Gbbv.js} +76 -987
- package/dist/runtime-CaM5Gbbv.js.map +1 -0
- package/dist/{sandbox-profile-compat-oFGWESLn.js → sandbox-profile-compat-l-SLQnGb.js} +2 -2
- package/dist/{sandbox-profile-compat-oFGWESLn.js.map → sandbox-profile-compat-l-SLQnGb.js.map} +1 -1
- package/dist/{search-executor-CKR9_6NR.js → search-executor-B9L8W_1O.js} +17 -46
- package/dist/search-executor-B9L8W_1O.js.map +1 -0
- package/dist/{server-Dh3SQGQT.js → server-BlDV8sj_.js} +32 -8
- package/dist/{server-Dh3SQGQT.js.map → server-BlDV8sj_.js.map} +1 -1
- package/dist/{settle-record-C6LdVvok.js → settle-record-WWQasnDq.js} +2 -2
- package/dist/{settle-record-C6LdVvok.js.map → settle-record-WWQasnDq.js.map} +1 -1
- package/dist/{snapshot-Cgj2Wzi6.js → snapshot-BKI_w3JD.js} +19 -5
- package/dist/snapshot-BKI_w3JD.js.map +1 -0
- package/dist/{structural-rollout-Dapf2aZY.js → structural-rollout-C1xxoWcN.js} +18 -54
- package/dist/structural-rollout-C1xxoWcN.js.map +1 -0
- package/dist/{supervise-xwl2D6q3.js → supervise-DWiSgPLB.js} +101 -111
- package/dist/supervise-DWiSgPLB.js.map +1 -0
- package/dist/{supervision-discovery-B47U8TH5.js → supervision-discovery-C9kfBLKy.js} +4 -4
- package/dist/{supervision-discovery-B47U8TH5.js.map → supervision-discovery-C9kfBLKy.js.map} +1 -1
- package/dist/{supervisor-gC-u_PRk.js → supervisor-Dpeu7rnZ.js} +206 -693
- package/dist/supervisor-Dpeu7rnZ.js.map +1 -0
- package/dist/{supervisor-accounting-DxLQ_TQe.js → supervisor-accounting-Bw4MJk-b.js} +434 -423
- package/dist/supervisor-accounting-Bw4MJk-b.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +13 -13
- package/dist/{tool-server-Dg350Bgz.js → tool-server-DYwRbi0I.js} +3 -3
- package/dist/{tool-server-Dg350Bgz.js.map → tool-server-DYwRbi0I.js.map} +1 -1
- package/dist/{top-web-BJLnFQdr.js → top-web-B3HOAtrZ.js} +9 -7
- package/dist/{top-web-BJLnFQdr.js.map → top-web-B3HOAtrZ.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +2 -2
- package/dist/{types-Jg274chm.d.ts → types-C_qbnw9N.d.ts} +1335 -1413
- package/dist/{util-C_cdPNC4.js → util-fcckrkKp.js} +39 -113
- package/dist/util-fcckrkKp.js.map +1 -0
- package/dist/{workspace-streams-B7yNMahl.js → workspace-streams-DA9R3j-p.js} +2 -2
- package/dist/{workspace-streams-B7yNMahl.js.map → workspace-streams-DA9R3j-p.js.map} +1 -1
- package/package.json +1 -1
- package/dist/coordination-manager-DQZ2u6L-.js.map +0 -1
- package/dist/coordination-map-routing-CKRNZSaV.js.map +0 -1
- package/dist/errors-AzSuGI23.js.map +0 -1
- package/dist/graph-BjQF2syl.js +0 -579
- package/dist/graph-BjQF2syl.js.map +0 -1
- package/dist/graph-registry-7X2nrreR.js.map +0 -1
- package/dist/improve-BolbYegO.js.map +0 -1
- package/dist/model-policy-JOcg3NRs.js.map +0 -1
- package/dist/runtime-C9F1PG2A.js.map +0 -1
- package/dist/search-executor-CKR9_6NR.js.map +0 -1
- package/dist/snapshot-Cgj2Wzi6.js.map +0 -1
- package/dist/structural-rollout-Dapf2aZY.js.map +0 -1
- package/dist/supervise-xwl2D6q3.js.map +0 -1
- package/dist/supervisor-accounting-DxLQ_TQe.js.map +0 -1
- package/dist/supervisor-gC-u_PRk.js.map +0 -1
- package/dist/util-C_cdPNC4.js.map +0 -1
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError$1, r as BackendTransportError, t as AgentEvalError } from "./errors-
|
|
3
|
-
import { C as unreportedSpend, D as addResourceSpend, E as zeroTokenUsage, F as ROOT_DEADLINE_REASON, H as teardownSurfaces, I as armDeadlineTimer, S as unmeteredSpend, T as zeroSpend, _ as roundBoxMinutes, b as throwAbort, c as errorMessage, d as isAbortError, f as isAsyncIterable, g as randomUuid, h as randomSuffix, j as ACCEPTED_RESULT_GRACE_MS, m as promptCacheTokenClasses, n as addSpend, o as cloneTokenUsage, p as mapWithConcurrency, r as addTokenUsage, s as deleteBoxSafe, v as sleep, w as withTimeout, x as throwIfAborted, y as stringifySafe, z as isDeadlineAbortReason } from "./util-
|
|
1
|
+
import { $n as harnessTranscriptFromLines, $r as awaitAbortable, $t as ownedTreeRootSpawn, An as environmentGone, Bt as scopeRetainedOwnerSettled, Dr as knownExecutionBindingReceipt, Er as inheritRuntimeOwnedExecutorAttestation, Fn as mergeTraceEnv, Fr as recordRuntimeOwnedProviderModel, G as appendSpawnEvents, Gr as executableAgentProfileSnapshot, Hr as runtimeOwnedScopeOwnerRuntime, J as reenteredWorkers, Jt as bindScopeRetainedOwnerProvider, Kr as executableAgentSpecSnapshot, Kt as scopeRetainedOwnerCheckpointing, L as nestedScopeSeamKey, Lr as runtimeOwnedExecutorExecutionBinding, M as prepareScopeResume, Mn as workerTraceEnv, Mr as recordRuntimeOwnedProviderAttemptStart, Nn as workerTraceHeaders, Nr as recordRuntimeOwnedProviderDispatchNotStarted, Or as knownMaterializationReceipt, Pr as recordRuntimeOwnedProviderIdentityConflict, Qr as assertEventBinding, Qt as loadSpawnForest, Rr as runtimeOwnedExecutorMaterialization, Tr as finalizeRuntimeOwnedPendingExecutor, Ur as unknownExecutionBindingReceipt, Vr as runtimeOwnedScopeOwnerControl, Wr as unknownMaterializationReceipt, X as assertRecursiveReservationPolicy, Yn as HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS, Zn as captureHarnessTranscript, Zr as RetainedRunProviderContractError, _n as reconnectRetainedRun, _t as waitForScopeChildren, ai as abortReason, an as encodeResultBlob, br as attestRuntimeOwnedExecutor, cn as executorObservation, cr as createActivityLog, dn as describeRetainedNativeStops, dr as isLiveNodeStatus, dt as releaseHeldEnvironments, ei as exactSession, er as harnessTranscriptUnavailable, fn as stopRetainedNativeExecution, ft as releaseRetainedEnvironments, gn as mintRetainedIdentity, gt as unconfirmedTeardowns, hn as assertRetainedRunReplayMaterial, ht as startScopeRecoveries, ii as RunCancellationReason, j as resolveWorkerSlots, jn as WORKER_TRACE_PROPAGATION, kr as newExecutionAttemptId, kt as finalizeScopeOwnerMaterialization, lr as describeToolArgs, mn as RetainedMaterializationTimeoutError, mt as settleManagerWork, n as terminalAccounting, ni as retainedSessionReplaced, nn as driverRuntime, nt as closeScopeAdmission, oi as linkAbort, on as SpawnEventIndex, pn as verifyWorkspaceMarker, pt as retryUnconfirmedTeardowns, q as appendTeardownConfirmation, r as createScope, ri as sameControlCoordinates, rn as nestedDriverTreeRoot, rt as hasRetriableTeardowns, si as runAbortable, t as isNonEmptySpend, ti as freezeControlRef, tn as attestNestedDriverTreeOwner, tt as closeRetainedSlots, ui as promptOptionsFromAgentTurnInput, un as observeModelRequest, ut as registerNestedTeardownScope, vn as recoverRetainedRun, vr as subscriptionUsageLimitSignal, xr as attestRuntimeOwnedPendingExecutor, yn as startRetainedRun, yr as attestRuntimeOwnedDeferredExecutor } from "./supervisor-accounting-Bw4MJk-b.js";
|
|
2
|
+
import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError$1, r as BackendTransportError, t as AgentEvalError } from "./errors-DG8yufqX.js";
|
|
3
|
+
import { C as unreportedSpend, D as addResourceSpend, E as zeroTokenUsage, F as ROOT_DEADLINE_REASON, H as teardownSurfaces, I as armDeadlineTimer, S as unmeteredSpend, T as zeroSpend, _ as roundBoxMinutes, b as throwAbort, c as errorMessage, d as isAbortError, f as isAsyncIterable, g as randomUuid, h as randomSuffix, j as ACCEPTED_RESULT_GRACE_MS, m as promptCacheTokenClasses, n as addSpend, o as cloneTokenUsage, p as mapWithConcurrency, r as addTokenUsage, s as deleteBoxSafe, v as sleep, w as withTimeout, x as throwIfAborted, y as stringifySafe, z as isDeadlineAbortReason } from "./util-fcckrkKp.js";
|
|
4
4
|
import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
|
|
5
|
-
import { B as
|
|
6
|
-
import { a as errMessage,
|
|
7
|
-
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-
|
|
8
|
-
import { r as nativeSystemPrompt, t as assertSandboxProfileCompatibility } from "./sandbox-profile-compat-
|
|
5
|
+
import { B as hashJson, D as unavailableResumeAt, E as unavailablePauseMs, F as executorFailureInfra, H as isCredentialRefusal, J as createBudgetPool, M as contentAddress, N as contentRef, O as unavailableSignalOfFailure, R as turnFailureOf, T as reportedResetAt, Tt as recordValue, V as credentialCommandExit, _t as isSandboxTerminalEvent, a as runtimeProviderCode, at as sandboxLeafOutputFromEvents, b as UNAVAILABLE_CODES, bt as sandboxEventServedBackend, c as DISPATCH_EXECUTION_CHANGED_CODE, d as TRANSPORT_ERROR_CODES, ft as assertSandboxServedModel, ht as createSandboxUsageLedger, i as runtimeFailureRemediationSchema, l as DISPATCH_NOT_ADMITTED_CODE, m as isSchemaRejection, mt as createSandboxTurnEventCollector, n as runtimeFailureCause, nt as createSandboxToolPartState, ot as sandboxOutputMarker, p as isProvisioningRefusal, pt as canonicalSandboxUsageMode, st as sandboxProgressEvents, t as reportedFailureCause, u as RetainedExecutionPendingError, ut as extractTransportEventIdentity, v as retainedExecutorContext, vt as notifySandboxEventObserver, w as printedStatus, wt as parseCodexUsageRecord, x as UNAVAILABLE_STATUSES, xt as sandboxTerminalUsageField, y as retainedExecutorSeamKey, yt as sameModelId, z as turnFailurePolicy } from "./failure-cause-CVB-YE88.js";
|
|
6
|
+
import { a as errMessage, i as causeChain, l as errorText, n as detachedSnapshot, o as errorHttpStatus, s as errorProperty, u as defaultRedactor } from "./snapshot-BKI_w3JD.js";
|
|
7
|
+
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-yxOrDTTj.js";
|
|
8
|
+
import { r as nativeSystemPrompt, t as assertSandboxProfileCompatibility } from "./sandbox-profile-compat-l-SLQnGb.js";
|
|
9
9
|
import { l as sha256 } from "./jsonl-file-DsxVI0E_.js";
|
|
10
|
-
import { V as hasControlCharacter } from "./workspace-streams-
|
|
10
|
+
import { V as hasControlCharacter } from "./workspace-streams-DA9R3j-p.js";
|
|
11
|
+
import { i as checkVerdictOf, s as isFiniteNumber } from "./continuation-CIyKnS1Q.js";
|
|
11
12
|
import { a as writeAtomicDurableFile, s as fenceRunWrite } from "./durable-file-DstVeHcj.js";
|
|
12
|
-
import { t as PROTOCOL_VERSION } from "./tool-server-
|
|
13
|
+
import { t as PROTOCOL_VERSION } from "./tool-server-DYwRbi0I.js";
|
|
13
14
|
import { i as notifyRuntimeHookEvent } from "./runtime-hooks-CsW2pfFk.js";
|
|
14
15
|
import { AGENT_PROFILE_MATERIALIZATION_AXES, AgentExactRunControlRefSchema, AgentRunCancellationRequestSchema, AgentTurnInputSchema, REASONING_EFFORTS, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalWorkspaceCwd, harnessTypeSchema, mergeProxySecretBindings, nativeReasoningControl, profileMaterializationAxes, profileMaterializationAxes as profileMaterializationAxes$1, renderInputPartsAsText, sha256DigestSchema } from "@tangle-network/agent-interface";
|
|
15
16
|
import { createAgentRunOutcomeTracker } from "@tangle-network/sandbox/runtime";
|
|
@@ -225,23 +226,6 @@ const sandboxActProfileMaterialization = defineProfileMaterializationContract({
|
|
|
225
226
|
name: "createSandboxAct",
|
|
226
227
|
axes: sandboxProfileMaterialization.axes
|
|
227
228
|
});
|
|
228
|
-
defineProfileMaterializationContract({
|
|
229
|
-
name: "prompt-only-message",
|
|
230
|
-
axes: ["systemPrompt", "instructions"]
|
|
231
|
-
});
|
|
232
|
-
defineProfileMaterializationContract({
|
|
233
|
-
name: "prompt-resource-attachment",
|
|
234
|
-
axes: [
|
|
235
|
-
"systemPrompt",
|
|
236
|
-
"instructions",
|
|
237
|
-
"files",
|
|
238
|
-
"resourceTools",
|
|
239
|
-
"skills",
|
|
240
|
-
"resourceAgents",
|
|
241
|
-
"commands",
|
|
242
|
-
"resourceInstructions"
|
|
243
|
-
]
|
|
244
|
-
});
|
|
245
229
|
/** Define the profile axes a concrete run path actually carries into execution. */
|
|
246
230
|
function defineProfileMaterializationContract(options) {
|
|
247
231
|
const name = options.name.trim();
|
|
@@ -2186,6 +2170,10 @@ async function runSettledCommand(opts) {
|
|
|
2186
2170
|
return new Promise((resolve, reject) => {
|
|
2187
2171
|
const child = spawn(opts.command, opts.args ?? [], {
|
|
2188
2172
|
cwd: opts.cwd,
|
|
2173
|
+
...opts.env ? { env: {
|
|
2174
|
+
...process.env,
|
|
2175
|
+
...opts.env
|
|
2176
|
+
} } : {},
|
|
2189
2177
|
stdio: [
|
|
2190
2178
|
"ignore",
|
|
2191
2179
|
"pipe",
|
|
@@ -2577,9 +2565,11 @@ function bridgeUpstreamError(error, prefix, httpStatus) {
|
|
|
2577
2565
|
const upstreamCode = runtimeProviderCode(safe.type);
|
|
2578
2566
|
const remedy = (status === 403 && (httpStatus === 403 || raw.status === 403) ? subscriptionErrorSchema.safeParse(raw) : void 0)?.success ? runtimeFailureRemediationSchema.readonly().safeParse(safe) : void 0;
|
|
2579
2567
|
const message = typeof safe.message === "string" ? safe.message : upstreamCode ?? "unknown";
|
|
2580
|
-
|
|
2568
|
+
const capacity = raw.capacity === true ? "bridge executor at capacity: " : "";
|
|
2569
|
+
return new BackendTransportError("bridge", `${prefix}: ${capacity}${message}`.slice(0, 512), {
|
|
2581
2570
|
status,
|
|
2582
2571
|
upstreamCode,
|
|
2572
|
+
...capacity ? { capacity: true } : {},
|
|
2583
2573
|
...raw.provider_dispatch === "not_started" ? { providerDispatch: "not_started" } : {},
|
|
2584
2574
|
...remedy?.success ? { remediation: remedy.data } : {},
|
|
2585
2575
|
...typeof redacted.body === "string" ? { body: redacted.body.slice(0, 2048) } : {}
|
|
@@ -3972,24 +3962,7 @@ function priceTokens(work) {
|
|
|
3972
3962
|
return Math.max(0, work.inputTokens - cacheRead - cacheWrite) * price.input + cacheRead * (price.cachedInput ?? price.input) + cacheWrite * (price.cacheWrite ?? price.input) + work.outputTokens * price.output;
|
|
3973
3963
|
}
|
|
3974
3964
|
// src/runtime/supervise/cost-estimate.ts
|
|
3975
|
-
/**
|
|
3976
|
-
* Pricing for work that arrived without a provider receipt.
|
|
3977
|
-
*
|
|
3978
|
-
* A turn whose provider reported no billed dollars used to reach the dollar channel as a
|
|
3979
|
-
* known `$0`, so a run that certainly spent money reported a dollar total of zero. A catalog
|
|
3980
|
-
* price is not a receipt, so what this module produces is always marked, never promoted.
|
|
3981
|
-
* The catalog is the Router's (`src/pricing/router-prices.ts`).
|
|
3982
|
-
*/
|
|
3983
|
-
/**
|
|
3984
|
-
* Price one unit of work that no provider receipt covered.
|
|
3985
|
-
*
|
|
3986
|
-
* The event always carries `usdKnown: false`: a catalog price approximates what a provider
|
|
3987
|
-
* WOULD bill, never measures what it did. The priced amount is repeated in `usdEstimated` so
|
|
3988
|
-
* a consumer can subtract it from `usd` and recover the dollars a provider actually billed.
|
|
3989
|
-
*
|
|
3990
|
-
* A model the Router does not price yields `usd: 0` with `usdKnown: false` and no `usdEstimated`.
|
|
3991
|
-
* The turn then reads as unknown dollars, which is true, rather than as a free turn.
|
|
3992
|
-
*/
|
|
3965
|
+
/** Unreceipted work stays `usdKnown: false`. A subscription seat stays uncaptured. */
|
|
3993
3966
|
function priceUnreceiptedWork(work) {
|
|
3994
3967
|
const unknown = {
|
|
3995
3968
|
kind: "cost",
|
|
@@ -3997,7 +3970,7 @@ function priceUnreceiptedWork(work) {
|
|
|
3997
3970
|
usdKnown: false,
|
|
3998
3971
|
provenance: "uncaptured"
|
|
3999
3972
|
};
|
|
4000
|
-
if (work.model === void 0) return unknown;
|
|
3973
|
+
if (work.credentialSource === "subscription" || work.model === void 0) return unknown;
|
|
4001
3974
|
const usd = priceTokens({
|
|
4002
3975
|
model: work.model,
|
|
4003
3976
|
inputTokens: work.inputTokens,
|
|
@@ -4029,10 +4002,7 @@ function newTurnTally() {
|
|
|
4029
4002
|
outputTokens: 0
|
|
4030
4003
|
};
|
|
4031
4004
|
}
|
|
4032
|
-
/**
|
|
4033
|
-
* Open the harness store named on the seam, or nothing when the caller named none. A harness with
|
|
4034
|
-
* no reader is REFUSED: ignoring it would hand back the same `{0, 0}` the store was meant to fix.
|
|
4035
|
-
*/
|
|
4005
|
+
/** Open the named harness store. No reader is a refusal, not a silent `{0, 0}`. */
|
|
4036
4006
|
function openBridgeHarnessStore(store) {
|
|
4037
4007
|
if (store === void 0) return void 0;
|
|
4038
4008
|
if (store.harness !== "codex") throw new ValidationError$1(`bridgeExecutor: harnessStore.harness ${JSON.stringify(store.harness)} has no store reader; only "codex" is readable today`);
|
|
@@ -4041,8 +4011,7 @@ function openBridgeHarnessStore(store) {
|
|
|
4041
4011
|
...store.workspaceRoot === void 0 ? {} : { workspaceRoot: store.workspaceRoot }
|
|
4042
4012
|
});
|
|
4043
4013
|
}
|
|
4044
|
-
/**
|
|
4045
|
-
* returns nothing: the store is extra evidence and must never end a turn whose work happened. */
|
|
4014
|
+
/** One turn of the harness store. A failed read is noted and returns nothing. */
|
|
4046
4015
|
async function readHarnessStoreDelta(reader, observation) {
|
|
4047
4016
|
try {
|
|
4048
4017
|
return await reader.read();
|
|
@@ -4056,16 +4025,8 @@ async function readHarnessStoreDelta(reader, observation) {
|
|
|
4056
4025
|
return;
|
|
4057
4026
|
}
|
|
4058
4027
|
}
|
|
4059
|
-
/**
|
|
4060
|
-
*
|
|
4061
|
-
* none. cli-bridge counts the model traffic through its scoped-loopback endpoint and publishes it
|
|
4062
|
-
* as `inference.observation.usage`, harness-agnostic BY CONSTRUCTION, so the runtime holds NO
|
|
4063
|
-
* per-harness bridge decoder (`harness-usage.ts` serves the sandbox stream).
|
|
4064
|
-
*
|
|
4065
|
-
* A receipt states a turn's tokens only when it names BOTH totals; anything less leaves the turn
|
|
4066
|
-
* unknown with the reason named, never a zero. The counters beside the totals CLASSIFY the prompt
|
|
4067
|
-
* total and add nothing to it (the receipt carries no reasoning counter).
|
|
4068
|
-
*/
|
|
4028
|
+
/** Receipt tokens, or why none. Both totals required; cache counters only classify.
|
|
4029
|
+
* No per-harness bridge decoder. */
|
|
4069
4030
|
function readBridgeReceiptTokens(usage) {
|
|
4070
4031
|
if (usage === void 0) return { reason: "usage-unreadable: the turn receipt carried no bridge inference observation" };
|
|
4071
4032
|
const input = usage.inputTokens;
|
|
@@ -4090,10 +4051,7 @@ function readBridgeReceiptTokens(usage) {
|
|
|
4090
4051
|
...contradiction
|
|
4091
4052
|
} };
|
|
4092
4053
|
}
|
|
4093
|
-
/**
|
|
4094
|
-
* The accounting of one cli-bridge session across its turns: what each turn's stream, receipt,
|
|
4095
|
-
* and harness store proved, what stayed unknown and why, and the artifact the session settles as.
|
|
4096
|
-
*/
|
|
4054
|
+
/** One cli-bridge session: what each turn proved, what stayed unknown, and the settled artifact. */
|
|
4097
4055
|
var BridgeSessionLedger = class {
|
|
4098
4056
|
tokens = zeroTokenUsage();
|
|
4099
4057
|
tokensKnown = true;
|
|
@@ -4177,11 +4135,8 @@ var BridgeSessionLedger = class {
|
|
|
4177
4135
|
this.sawEstimatedUsd = true;
|
|
4178
4136
|
}
|
|
4179
4137
|
}
|
|
4180
|
-
/**
|
|
4181
|
-
*
|
|
4182
|
-
* what no receipt billed. Every channel nothing proved stays unknown, never zero.
|
|
4183
|
-
*/
|
|
4184
|
-
async *settleTurn(receiptUsage, harnessStore, observation, providerModel) {
|
|
4138
|
+
/** Close the turn. Every unproven channel stays unknown, never zero. */
|
|
4139
|
+
async *settleTurn(receiptUsage, harnessStore, observation, providerModel, credentialSource) {
|
|
4185
4140
|
if (!this.turn.sawTokenUsage) {
|
|
4186
4141
|
const receipt = readBridgeReceiptTokens(receiptUsage);
|
|
4187
4142
|
if ("event" in receipt) {
|
|
@@ -4195,7 +4150,7 @@ var BridgeSessionLedger = class {
|
|
|
4195
4150
|
if (!turn.sawTokenUsage || !turn.tokensKnown) this.tokensKnown = false;
|
|
4196
4151
|
if (!turn.sawCostStatus || !turn.usdKnown) {
|
|
4197
4152
|
this.usdKnown = false;
|
|
4198
|
-
yield this.priceUnreceiptedTurn(providerModel);
|
|
4153
|
+
yield this.priceUnreceiptedTurn(providerModel, credentialSource);
|
|
4199
4154
|
}
|
|
4200
4155
|
}
|
|
4201
4156
|
async *creditHarnessStore(harnessStore, observation) {
|
|
@@ -4222,12 +4177,13 @@ var BridgeSessionLedger = class {
|
|
|
4222
4177
|
this.tokensUnknownReason ??= `harness-store: ${delta.unresolved.length} forked rollout(s) could not be attributed to a turn; ${delta.unresolved[0]?.reason ?? "no reason recorded"}`;
|
|
4223
4178
|
}
|
|
4224
4179
|
}
|
|
4225
|
-
priceUnreceiptedTurn(providerModel) {
|
|
4180
|
+
priceUnreceiptedTurn(providerModel, credentialSource) {
|
|
4226
4181
|
const { turn } = this;
|
|
4227
4182
|
const priced = turn.knownCostSubtotal === 0 ? priceUnreceiptedWork({
|
|
4228
4183
|
inputTokens: turn.inputTokens,
|
|
4229
4184
|
outputTokens: turn.outputTokens,
|
|
4230
|
-
model: this.observedModel ?? providerModel
|
|
4185
|
+
model: this.observedModel ?? providerModel,
|
|
4186
|
+
...credentialSource === "subscription" ? { credentialSource } : {}
|
|
4231
4187
|
}) : {
|
|
4232
4188
|
kind: "cost",
|
|
4233
4189
|
usd: 0,
|
|
@@ -4410,9 +4366,14 @@ function silenceBoundRefusal(seam, base, wireModel, route) {
|
|
|
4410
4366
|
};
|
|
4411
4367
|
}
|
|
4412
4368
|
/**
|
|
4413
|
-
* Read the
|
|
4414
|
-
*
|
|
4415
|
-
*
|
|
4369
|
+
* Read the gates that decide a spawn from `GET /health`. The host executor
|
|
4370
|
+
* (`executor.in_flight` of `executor.max`, `BRIDGE_HOST_MAX_CONCURRENCY`) gates a
|
|
4371
|
+
* spawn sooner than the bulk admission lane (default 6 vs 4): a spawn the lane
|
|
4372
|
+
* admits still waits on the executor semaphore for `acquire_deadline_ms` and is
|
|
4373
|
+
* then refused as capacity (#1186). When the bridge reports executor counters they
|
|
4374
|
+
* decide the answer; the bulk admission lane (Runtime sends no reserved-client
|
|
4375
|
+
* header, so overall capacity can look free) and then the overall counters remain
|
|
4376
|
+
* the fallback for older bridges.
|
|
4416
4377
|
*/
|
|
4417
4378
|
async function bridgeAdmissionRefusal(seam, signal) {
|
|
4418
4379
|
let answer;
|
|
@@ -4428,7 +4389,18 @@ async function bridgeAdmissionRefusal(seam, signal) {
|
|
|
4428
4389
|
} catch {
|
|
4429
4390
|
return;
|
|
4430
4391
|
}
|
|
4431
|
-
const
|
|
4392
|
+
const health = parsed;
|
|
4393
|
+
const admission = health?.admission;
|
|
4394
|
+
const executorInFlight = health?.executor?.in_flight;
|
|
4395
|
+
const executorMax = health?.executor?.max;
|
|
4396
|
+
const executorQueued = health?.executor?.queued;
|
|
4397
|
+
if (isFiniteNumber(executorInFlight) && executorInFlight >= 0 && isFiniteNumber(executorMax) && executorMax >= 0) {
|
|
4398
|
+
if (executorInFlight + 1 > executorMax) {
|
|
4399
|
+
const queued = isFiniteNumber(executorQueued) && executorQueued >= 0 ? `, ${executorQueued} queued` : "";
|
|
4400
|
+
return `bridge ${seam.bridgeUrl.replace(/\/$/, "")} executor is full: in_flight ${executorInFlight} of max ${executorMax}${queued}; the spawn would wait on the host semaphore and be refused as capacity`;
|
|
4401
|
+
}
|
|
4402
|
+
return;
|
|
4403
|
+
}
|
|
4432
4404
|
const active = admission?.active;
|
|
4433
4405
|
const maxActive = admission?.maxActive;
|
|
4434
4406
|
const bulkActive = admission?.activeByClass?.bulk;
|
|
@@ -4799,474 +4771,6 @@ var BridgeTurnSignals = class {
|
|
|
4799
4771
|
if (this.silenceTimer !== void 0) clearTimeout(this.silenceTimer);
|
|
4800
4772
|
}
|
|
4801
4773
|
};
|
|
4802
|
-
// src/finite-number.ts
|
|
4803
|
-
function isFiniteNumber(value) {
|
|
4804
|
-
return typeof value === "number" && Number.isFinite(value);
|
|
4805
|
-
}
|
|
4806
|
-
// src/runtime/supervise/continuation.ts
|
|
4807
|
-
/**
|
|
4808
|
-
* The continuation: what a manager with a completion check is told when its turn ends and the
|
|
4809
|
-
* check is unmet, and the one rule that decides whether it is sent back.
|
|
4810
|
-
*
|
|
4811
|
-
* Measured on discovery-lab before this module (670 settled runs, 1,596 re-entries):
|
|
4812
|
-
* 1,565 re-entries followed a failed turn and resent the original task, and 31 carried note text.
|
|
4813
|
-
* The note Runtime wrote itself held seven fixed lines and no field for the check's verdict. Of 40
|
|
4814
|
-
* episodes where the director ended on its own and the outside check disagreed, 33 were told
|
|
4815
|
-
* nothing before they ended. 100 of 236 resubmits sent the identical packet. So the director
|
|
4816
|
-
* mostly graded itself, and when it was wrong it heard nothing it could use.
|
|
4817
|
-
*
|
|
4818
|
-
* The design (discovery `docs/38-one-loop-and-continuation.md`) makes three things single, and
|
|
4819
|
-
* this module holds the part Runtime owns:
|
|
4820
|
-
*
|
|
4821
|
-
* - ONE CHECK. A check reading is a {@link CheckVerdict}: pass, the items it read, the composite,
|
|
4822
|
-
* and one `FAIL <item> <where>: <reason>` line per failed item. The same check decides
|
|
4823
|
-
* `submit_result`, runs when a turn ends without an accepted result, scores the finished run,
|
|
4824
|
-
* and ranks versions. A check that could not run gives no verdict ({@link CheckUnavailableError}),
|
|
4825
|
-
* and the loop pauses instead of blaming the director.
|
|
4826
|
-
* - ONE RESEND RULE. {@link ContinuationPolicy} is required for a manager with a check. It holds
|
|
4827
|
-
* `maxBarren`, the re-entered turns in a row that may end without progress before each further
|
|
4828
|
-
* continuation waits a barren pause, and an optional deadline. There is no re-prompt count and
|
|
4829
|
-
* no default: a retry default in source is a research decision.
|
|
4830
|
-
* - ONE NOTE. {@link composeContinuationNote} writes it. Runtime owns the facts and their order;
|
|
4831
|
-
* the {@link ContinuationProfile} owns every instruction word, so an optimizer can change the
|
|
4832
|
-
* words without touching code. A play may append a section, never remove or rewrite one.
|
|
4833
|
-
*
|
|
4834
|
-
* Evidence behind the note's shape: located errors help (given the first mistake's true location,
|
|
4835
|
-
* fix rates rose 23.5 to 43.9 points, Tyen 2023); unsupported pressure does not (threats and tips
|
|
4836
|
-
* had no significant effect, Wharton 2025; challenges without evidence flipped correct answers,
|
|
4837
|
-
* FlipFlop); repeated summaries drop detail while itemized additions do not (ACE). So the note is
|
|
4838
|
-
* a list of located facts, findings are added and marked resolved rather than rewritten, and the
|
|
4839
|
-
* profile, not this file, decides how blunt the words are.
|
|
4840
|
-
*/
|
|
4841
|
-
/** Read a check function's return value into a verdict. Anything but `true` or a passing verdict
|
|
4842
|
-
* is a failure: a check fails closed. */
|
|
4843
|
-
function checkVerdictOf(outcome) {
|
|
4844
|
-
if (outcome === true) return { pass: true };
|
|
4845
|
-
if (typeof outcome !== "object" || outcome === null || Array.isArray(outcome)) return { pass: false };
|
|
4846
|
-
const raw = outcome;
|
|
4847
|
-
const items = typeof raw.items === "object" && raw.items !== null && !Array.isArray(raw.items) ? Object.fromEntries(Object.entries(raw.items).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1]))) : void 0;
|
|
4848
|
-
const failures = Array.isArray(raw.failures) ? raw.failures.filter((line) => typeof line === "string" && line.trim() !== "") : void 0;
|
|
4849
|
-
return Object.freeze({
|
|
4850
|
-
pass: raw.pass === true,
|
|
4851
|
-
...items === void 0 ? {} : { items: Object.freeze(items) },
|
|
4852
|
-
...isFiniteNumber(raw.composite) ? { composite: raw.composite } : {},
|
|
4853
|
-
...isFiniteNumber(raw.threshold) ? { threshold: raw.threshold } : {},
|
|
4854
|
-
...failures === void 0 ? {} : { failures: Object.freeze(failures) },
|
|
4855
|
-
...typeof raw.review === "string" && raw.review.trim() !== "" ? { review: raw.review.trim() } : {}
|
|
4856
|
-
});
|
|
4857
|
-
}
|
|
4858
|
-
/** Items that fail in `verdict`: every item below 1, or the named items of its FAIL lines. */
|
|
4859
|
-
function failedItems(verdict) {
|
|
4860
|
-
if (verdict.items !== void 0) return Object.entries(verdict.items).filter(([, value]) => value < 1).map(([name]) => name);
|
|
4861
|
-
return (verdict.failures ?? []).map((line) => line.slice(5).split(/[\s:]/u)[0] ?? "");
|
|
4862
|
-
}
|
|
4863
|
-
/** Items that pass in `verdict`. */
|
|
4864
|
-
function passedItems(verdict) {
|
|
4865
|
-
return Object.entries(verdict.items ?? {}).filter(([, value]) => value >= 1).map(([name]) => name);
|
|
4866
|
-
}
|
|
4867
|
-
/** Resolve and check a policy before any compute. Returns the deadline in epoch ms, or undefined
|
|
4868
|
-
* when the policy sets none. */
|
|
4869
|
-
function admitContinuationPolicy(policy, context) {
|
|
4870
|
-
if (typeof policy !== "object" || policy === null) throw new ValidationError$1(`${context}: continuation must be an object`);
|
|
4871
|
-
const deadlineMs = typeof policy.deadline === "string" ? Date.parse(policy.deadline) : policy.deadline;
|
|
4872
|
-
if (deadlineMs !== void 0 && (typeof deadlineMs !== "number" || !Number.isFinite(deadlineMs) || deadlineMs <= 0)) throw new ValidationError$1(`${context}: continuation.deadline, when set, must be a finite time (epoch ms or ISO 8601)`);
|
|
4873
|
-
if (!Number.isInteger(policy.maxBarren) || policy.maxBarren < 1) throw new ValidationError$1(`${context}: continuation.maxBarren must be an integer >= 1`);
|
|
4874
|
-
if (policy.failures !== "verbatim" && policy.failures !== "off") throw new ValidationError$1(`${context}: continuation.failures must be 'verbatim' or 'off'`);
|
|
4875
|
-
if (policy.panel !== "on" && policy.panel !== "off") throw new ValidationError$1(`${context}: continuation.panel must be 'on' or 'off'`);
|
|
4876
|
-
if (policy.bar !== "on" && policy.bar !== "off") throw new ValidationError$1(`${context}: continuation.bar must be 'on' or 'off'`);
|
|
4877
|
-
if (policy.panel === "on") {
|
|
4878
|
-
if (typeof policy.runPanel !== "function") throw new ValidationError$1(`${context}: continuation.panel 'on' needs runPanel`);
|
|
4879
|
-
const usd = policy.panelUsd;
|
|
4880
|
-
if (usd === void 0 || !isFiniteNumber(usd.perContinuation) || !isFiniteNumber(usd.perRun) || usd.perContinuation <= 0 || usd.perRun < usd.perContinuation) throw new ValidationError$1(`${context}: continuation.panel 'on' needs panelUsd with 0 < perContinuation <= perRun`);
|
|
4881
|
-
}
|
|
4882
|
-
if (policy.append !== void 0 && typeof policy.append !== "function") throw new ValidationError$1(`${context}: continuation.append must be a function`);
|
|
4883
|
-
if (policy.session !== void 0 && policy.session !== "native" && policy.session !== "fresh") throw new ValidationError$1(`${context}: continuation.session must be 'native' or 'fresh'`);
|
|
4884
|
-
admitContinuationProfile(policy.profile, context);
|
|
4885
|
-
return deadlineMs;
|
|
4886
|
-
}
|
|
4887
|
-
/** The facts a profile template may name. */
|
|
4888
|
-
const CONTINUATION_FACTS = [
|
|
4889
|
-
"composite",
|
|
4890
|
-
"threshold",
|
|
4891
|
-
"failed",
|
|
4892
|
-
"total",
|
|
4893
|
-
"reads",
|
|
4894
|
-
"owed",
|
|
4895
|
-
"settled",
|
|
4896
|
-
"delivered",
|
|
4897
|
-
"continuation"
|
|
4898
|
-
];
|
|
4899
|
-
const factNames = new Set(CONTINUATION_FACTS);
|
|
4900
|
-
const placeholder = /\{([a-zA-Z]+)\}/gu;
|
|
4901
|
-
function admitContinuationProfile(profile, context) {
|
|
4902
|
-
if (typeof profile !== "object" || profile === null) throw new ValidationError$1(`${context}: continuation.profile must be an object`);
|
|
4903
|
-
if (typeof profile.id !== "string" || profile.id.trim() === "") throw new ValidationError$1(`${context}: continuation.profile.id must be non-empty`);
|
|
4904
|
-
const texts = [
|
|
4905
|
-
["opening", profile.opening],
|
|
4906
|
-
["plan", profile.plan],
|
|
4907
|
-
["rules", profile.rules],
|
|
4908
|
-
...Object.entries(profile.headings ?? {}).map(([key, value]) => [`headings.${key}`, value]),
|
|
4909
|
-
...profile.barRule === void 0 ? [] : [["barRule", profile.barRule]]
|
|
4910
|
-
];
|
|
4911
|
-
for (const key of [
|
|
4912
|
-
"failures",
|
|
4913
|
-
"protected",
|
|
4914
|
-
"changed",
|
|
4915
|
-
"findings",
|
|
4916
|
-
"bar",
|
|
4917
|
-
"plan",
|
|
4918
|
-
"rules"
|
|
4919
|
-
]) if (typeof profile.headings?.[key] !== "string") throw new ValidationError$1(`${context}: continuation.profile.headings.${key} must be a string`);
|
|
4920
|
-
for (const [key, text] of texts) {
|
|
4921
|
-
if (typeof text !== "string") throw new ValidationError$1(`${context}: continuation.profile.${key} must be a string`);
|
|
4922
|
-
for (const match of text.matchAll(placeholder)) if (!factNames.has(match[1] ?? "")) throw new ValidationError$1(`${context}: continuation.profile.${key} names {${match[1]}}, which is not a fact Runtime supplies (${CONTINUATION_FACTS.join(", ")})`);
|
|
4923
|
-
}
|
|
4924
|
-
if (profile.review !== void 0) {
|
|
4925
|
-
if (typeof profile.review !== "string" || profile.review.trim() === "") throw new ValidationError$1(`${context}: continuation.profile.review must be non-empty`);
|
|
4926
|
-
for (const match of profile.review.matchAll(placeholder)) if (![
|
|
4927
|
-
"version",
|
|
4928
|
-
"path",
|
|
4929
|
-
"score"
|
|
4930
|
-
].includes(match[1] ?? "")) throw new ValidationError$1(`${context}: continuation.profile.review names {${match[1]}}; it may name {version}, {path} and {score}`);
|
|
4931
|
-
}
|
|
4932
|
-
if (profile.opening.trim() === "") throw new ValidationError$1(`${context}: continuation.profile.opening must be non-empty`);
|
|
4933
|
-
for (const [index, question] of (profile.questions ?? []).entries()) if (typeof question !== "string" || question.trim() === "") throw new ValidationError$1(`${context}: continuation.profile.questions[${index}] must be a non-empty string`);
|
|
4934
|
-
}
|
|
4935
|
-
/** Findings reach the note only when every citation resolves, at least two distinct spans are
|
|
4936
|
-
* cited, and the independent verifier agreed. The best method in Who&When found the failing step
|
|
4937
|
-
* 14.2% of the time, so an unverified finding is noise with a citation. */
|
|
4938
|
-
function admitFinding(finding) {
|
|
4939
|
-
if (!finding.verified) return false;
|
|
4940
|
-
if (finding.citations.length === 0) return false;
|
|
4941
|
-
if (!finding.citations.every((citation) => citation.resolved)) return false;
|
|
4942
|
-
return new Set(finding.citations.map((citation) => citation.uri)).size >= 2;
|
|
4943
|
-
}
|
|
4944
|
-
/** About 1,500 tokens of findings. */
|
|
4945
|
-
const FINDINGS_CHAR_CAP = 6e3;
|
|
4946
|
-
/**
|
|
4947
|
-
* Rank the admitted findings by how many failed items they explain, drop repeats, and keep them
|
|
4948
|
-
* within the note's cap. Earlier findings stay as they were written (ACE: itemized additions keep
|
|
4949
|
-
* detail that repeated rewrites lose); a finding whose items all pass now is marked resolved.
|
|
4950
|
-
*/
|
|
4951
|
-
function distillFindings(prior, proposed, failing, continuation) {
|
|
4952
|
-
const key = (claim) => claim.toLowerCase().replace(/\s+/gu, " ").trim();
|
|
4953
|
-
const known = new Set(prior.map((finding) => key(finding.claim)));
|
|
4954
|
-
const carried = prior.map((finding) => finding.resolvedAt === void 0 && (finding.items?.length ?? 0) > 0 && (finding.items ?? []).every((item) => !failing.has(item)) ? {
|
|
4955
|
-
...finding,
|
|
4956
|
-
resolvedAt: continuation
|
|
4957
|
-
} : finding);
|
|
4958
|
-
const fresh = proposed.filter(admitFinding).filter((finding) => {
|
|
4959
|
-
const k = key(finding.claim);
|
|
4960
|
-
if (known.has(k)) return false;
|
|
4961
|
-
known.add(k);
|
|
4962
|
-
return true;
|
|
4963
|
-
}).map((finding) => ({
|
|
4964
|
-
finding,
|
|
4965
|
-
links: (finding.items ?? []).filter((item) => failing.has(item)).length
|
|
4966
|
-
})).sort((a, b) => b.links - a.links);
|
|
4967
|
-
const out = [...carried];
|
|
4968
|
-
let used = carried.filter((finding) => finding.resolvedAt === void 0).reduce((sum, finding) => sum + finding.claim.length, 0);
|
|
4969
|
-
for (const { finding } of fresh) {
|
|
4970
|
-
if (used + finding.claim.length > FINDINGS_CHAR_CAP) break;
|
|
4971
|
-
used += finding.claim.length;
|
|
4972
|
-
out.push({
|
|
4973
|
-
...finding,
|
|
4974
|
-
admittedAt: continuation
|
|
4975
|
-
});
|
|
4976
|
-
}
|
|
4977
|
-
return out;
|
|
4978
|
-
}
|
|
4979
|
-
/** Expand the profile's question templates over the failed items and the settled workers. */
|
|
4980
|
-
function expandQuestions(templates, failing, workers) {
|
|
4981
|
-
const out = [];
|
|
4982
|
-
for (const template of templates) {
|
|
4983
|
-
const hasItem = template.includes("{item}");
|
|
4984
|
-
const hasWorker = template.includes("{worker}");
|
|
4985
|
-
if (!hasItem && !hasWorker) {
|
|
4986
|
-
out.push(template);
|
|
4987
|
-
continue;
|
|
4988
|
-
}
|
|
4989
|
-
const items = hasItem ? failing : [""];
|
|
4990
|
-
const each = hasWorker ? workers.map((worker) => `${worker.id} (${worker.label})`) : [""];
|
|
4991
|
-
for (const item of items) for (const worker of each) out.push(template.replaceAll("{item}", item).replaceAll("{worker}", worker));
|
|
4992
|
-
}
|
|
4993
|
-
return out;
|
|
4994
|
-
}
|
|
4995
|
-
/**
|
|
4996
|
-
* Write one continuation note, sections 1 to 8 of docs/38. Section 9, the run's state, is
|
|
4997
|
-
* `composeReentryTask`, which wraps this text. Pure: the same input writes the same note.
|
|
4998
|
-
*/
|
|
4999
|
-
function composeContinuationNote(input) {
|
|
5000
|
-
const { profile, verdict } = input;
|
|
5001
|
-
const items = verdict?.items ?? {};
|
|
5002
|
-
const total = Object.keys(items).length;
|
|
5003
|
-
const failing = verdict === void 0 ? [] : failedItems(verdict);
|
|
5004
|
-
const facts = {
|
|
5005
|
-
composite: verdict?.composite === void 0 ? "unknown" : format(verdict.composite),
|
|
5006
|
-
threshold: verdict?.threshold === void 0 ? "unknown" : format(verdict.threshold),
|
|
5007
|
-
failed: verdict === void 0 || total === 0 && (verdict.failures?.length ?? 0) === 0 ? "unknown" : String(failing.length),
|
|
5008
|
-
total: total === 0 ? "unknown" : String(total),
|
|
5009
|
-
reads: String(input.reads),
|
|
5010
|
-
owed: input.owed?.trim() || "not described",
|
|
5011
|
-
settled: String(input.progress.settledCount),
|
|
5012
|
-
delivered: String(input.progress.deliveredCount ?? 0),
|
|
5013
|
-
continuation: String(input.continuation)
|
|
5014
|
-
};
|
|
5015
|
-
const fill = (text) => text.replace(placeholder, (_, name) => facts[name] ?? `{${name}}`);
|
|
5016
|
-
const sections = [verdict === void 0 ? "No check verdict is available yet." + (input.canSubmitResult === true ? " Submit a result through submit_result to request the check." : "") : verdict.pass ? "The check passes on the current state, but no result has been accepted." + (input.canSubmitResult === true ? " Call submit_result to request acceptance." : "") : fill(profile.opening).trim()];
|
|
5017
|
-
const section = (heading, body) => {
|
|
5018
|
-
if (body.length === 0) return;
|
|
5019
|
-
sections.push([...heading.trim() === "" ? [] : [`## ${fill(heading)}`], ...body].join("\n"));
|
|
5020
|
-
};
|
|
5021
|
-
if (input.failures === "verbatim" && verdict !== void 0) {
|
|
5022
|
-
const lines = verdict.failures ?? [];
|
|
5023
|
-
const shown = lines.slice(0, 40);
|
|
5024
|
-
const more = lines.length - shown.length;
|
|
5025
|
-
section(profile.headings.failures, [...shown, ...more > 0 ? [input.canReadMore ? `${more} more failure lines: call read_continuation with continuation ${input.continuation}.` : `${more} more failure lines are not shown.`] : []]);
|
|
5026
|
-
const passing = passedItems(verdict);
|
|
5027
|
-
section(profile.headings.protected, passing.length === 0 ? [] : [passing.join(", ")]);
|
|
5028
|
-
if (input.previous !== void 0) {
|
|
5029
|
-
const before = new Set(failedItems(input.previous));
|
|
5030
|
-
const now = new Set(failing);
|
|
5031
|
-
const fixed = [...before].filter((item) => !now.has(item));
|
|
5032
|
-
const broke = [...now].filter((item) => !before.has(item));
|
|
5033
|
-
section(profile.headings.changed, [
|
|
5034
|
-
...fixed.length === 0 ? [] : [`Now passing: ${fixed.join(", ")}.`],
|
|
5035
|
-
...broke.length === 0 ? [] : [`Newly failing: ${broke.join(", ")}.`],
|
|
5036
|
-
...fixed.length === 0 && broke.length === 0 ? ["No item changed since the last note."] : [],
|
|
5037
|
-
...input.previous.composite !== void 0 && verdict.composite !== void 0 ? [`Composite: ${format(input.previous.composite)} then ${format(verdict.composite)}.`] : []
|
|
5038
|
-
]);
|
|
5039
|
-
}
|
|
5040
|
-
}
|
|
5041
|
-
if (input.findings !== void 0) {
|
|
5042
|
-
const open = input.findings.filter((finding) => finding.resolvedAt === void 0);
|
|
5043
|
-
const resolved = input.findings.filter((finding) => finding.resolvedAt === input.continuation);
|
|
5044
|
-
section(profile.headings.findings, [...open.map((finding) => `- [hypothesis] ${finding.claim}` + (finding.items?.length ? ` (items: ${finding.items.join(", ")})` : "") + ` Evidence: ${finding.citations.map((citation) => citation.uri).join(", ")}`), ...resolved.map((finding) => `- [resolved] ${finding.claim}`)]);
|
|
5045
|
-
}
|
|
5046
|
-
if (input.bar !== void 0 && verdict !== void 0) {
|
|
5047
|
-
const body = [];
|
|
5048
|
-
if (profile.barRule?.trim()) body.push(fill(profile.barRule).trim());
|
|
5049
|
-
for (const [item, value] of Object.entries(items)) {
|
|
5050
|
-
const best = input.bar.best?.verdict.items?.[item];
|
|
5051
|
-
body.push(`- ${item}: ${value >= 1 ? "passes" : `fails (${format(value)})`}` + (best === void 0 ? "" : ` / ${input.bar.best?.label}: ${best >= 1 ? "passes" : `fails (${format(best)})`}`));
|
|
5052
|
-
}
|
|
5053
|
-
if (input.bar.best?.verdict.composite !== void 0) body.push(`Best version ${input.bar.best.label}: composite ${format(input.bar.best.verdict.composite)}.`);
|
|
5054
|
-
if (input.bar.reference?.trim()) body.push(`Reference result: ${input.bar.reference.trim()}`);
|
|
5055
|
-
if (verdict.review?.trim()) body.push(`The check's review: ${verdict.review.trim()}`);
|
|
5056
|
-
section(profile.headings.bar, body);
|
|
5057
|
-
}
|
|
5058
|
-
section(profile.headings.plan, profile.plan.trim() === "" ? [] : [fill(profile.plan).trim()]);
|
|
5059
|
-
section(profile.headings.rules, [...profile.rules.trim() === "" ? [] : [fill(profile.rules).trim()], ...input.sealed ? ["The score comes from cases you cannot see."] : []]);
|
|
5060
|
-
for (const appended of input.appended ?? []) section(appended.heading, appended.text.trim() === "" ? [] : [appended.text.trim()]);
|
|
5061
|
-
return sections.join("\n\n");
|
|
5062
|
-
}
|
|
5063
|
-
function summarizeVerdict(verdict) {
|
|
5064
|
-
if (verdict === void 0) return null;
|
|
5065
|
-
const total = Object.keys(verdict.items ?? {}).length;
|
|
5066
|
-
return {
|
|
5067
|
-
pass: verdict.pass,
|
|
5068
|
-
...verdict.composite === void 0 ? {} : { composite: verdict.composite },
|
|
5069
|
-
...total === 0 ? {} : {
|
|
5070
|
-
failed: failedItems(verdict).length,
|
|
5071
|
-
total
|
|
5072
|
-
}
|
|
5073
|
-
};
|
|
5074
|
-
}
|
|
5075
|
-
function noteDigest(note) {
|
|
5076
|
-
return `sha256:${sha256(note)}`;
|
|
5077
|
-
}
|
|
5078
|
-
/** A run directory's continuation files: the root's at `<runDir>/continuations/<n>/`, a nested
|
|
5079
|
-
* manager's at `<runDir>/continuations/managers/<owner>/<n>/`. */
|
|
5080
|
-
const CONTINUATIONS_DIR = "continuations";
|
|
5081
|
-
/**
|
|
5082
|
-
* Write one continuation's files under `<dir>/<n>/`: `note.md`, `verdict.json`, and
|
|
5083
|
-
* `panel.jsonl` when the panel ran. The director reads them through `read_continuation`, because
|
|
5084
|
-
* its box cannot read the driver's run directory.
|
|
5085
|
-
*/
|
|
5086
|
-
async function writeContinuationFiles(dir, continuation, files) {
|
|
5087
|
-
const at = join(dir, String(continuation));
|
|
5088
|
-
await mkdir(at, { recursive: true });
|
|
5089
|
-
writeAtomicDurableFile(join(at, "note.md"), `${files.note}\n`);
|
|
5090
|
-
writeAtomicDurableFile(join(at, "verdict.json"), `${JSON.stringify(files.verdict ?? null, null, 2)}\n`);
|
|
5091
|
-
if (files.panel !== void 0) writeAtomicDurableFile(join(at, "panel.jsonl"), files.panel.map((line) => JSON.stringify(line)).join("\n") + (files.panel.length ? "\n" : ""));
|
|
5092
|
-
}
|
|
5093
|
-
/** The best composite across `reads`, or `undefined` when no read scored. */
|
|
5094
|
-
function bestComposite(reads) {
|
|
5095
|
-
let best;
|
|
5096
|
-
for (const read of reads) {
|
|
5097
|
-
const value = read.verdict?.composite;
|
|
5098
|
-
if (value !== void 0 && (best === void 0 || value > best)) best = value;
|
|
5099
|
-
}
|
|
5100
|
-
return best;
|
|
5101
|
-
}
|
|
5102
|
-
function format(value) {
|
|
5103
|
-
return Number.isInteger(value) ? String(value) : value.toFixed(3).replace(/0+$/u, "");
|
|
5104
|
-
}
|
|
5105
|
-
/** Build the continuation state for one manager with a check. */
|
|
5106
|
-
function createContinuationKeeper(input) {
|
|
5107
|
-
const { policy } = input;
|
|
5108
|
-
const failures = input.feedback === "pass-only" ? "off" : policy.failures;
|
|
5109
|
-
const entries = [];
|
|
5110
|
-
const notes = [];
|
|
5111
|
-
let findings = [];
|
|
5112
|
-
let panelUsd = 0;
|
|
5113
|
-
let panelUsdKnown = true;
|
|
5114
|
-
const latestVerdict = () => {
|
|
5115
|
-
const reads = input.reads();
|
|
5116
|
-
for (let i = reads.length - 1; i >= 0; i -= 1) {
|
|
5117
|
-
const read = reads[i];
|
|
5118
|
-
if (read?.verdict !== void 0) return {
|
|
5119
|
-
verdict: read.verdict,
|
|
5120
|
-
read: read.read
|
|
5121
|
-
};
|
|
5122
|
-
}
|
|
5123
|
-
return { read: 0 };
|
|
5124
|
-
};
|
|
5125
|
-
const closePrevious = () => {
|
|
5126
|
-
const last = entries.at(-1);
|
|
5127
|
-
const lastNote = notes.at(-1);
|
|
5128
|
-
if (last === void 0 || lastNote === void 0) return;
|
|
5129
|
-
const latest = latestVerdict();
|
|
5130
|
-
entries[entries.length - 1] = {
|
|
5131
|
-
...last,
|
|
5132
|
-
after: latest.read > lastNote.read ? summarizeVerdict(latest.verdict) : null
|
|
5133
|
-
};
|
|
5134
|
-
};
|
|
5135
|
-
return {
|
|
5136
|
-
async compose(context) {
|
|
5137
|
-
closePrevious();
|
|
5138
|
-
const continuation = entries.length + 1;
|
|
5139
|
-
const { verdict, read } = latestVerdict();
|
|
5140
|
-
const failing = verdict === void 0 ? [] : failedItems(verdict);
|
|
5141
|
-
let panelRecord;
|
|
5142
|
-
let panelLines;
|
|
5143
|
-
if (policy.panel === "on" && policy.runPanel !== void 0 && policy.panelUsd !== void 0) {
|
|
5144
|
-
const workers = input.workers();
|
|
5145
|
-
const questions = expandQuestions(policy.profile.questions ?? [], failing, workers);
|
|
5146
|
-
const left = policy.panelUsd.perRun - panelUsd;
|
|
5147
|
-
const usdCap = Math.min(policy.panelUsd.perContinuation, left);
|
|
5148
|
-
const asking = questions.length > 0 && usdCap > 0 && panelUsdKnown;
|
|
5149
|
-
let traces;
|
|
5150
|
-
let unavailable;
|
|
5151
|
-
if (asking) try {
|
|
5152
|
-
traces = await input.traces?.();
|
|
5153
|
-
if (traces === void 0) unavailable = "the run has recorded no trace yet";
|
|
5154
|
-
} catch (error) {
|
|
5155
|
-
unavailable = `the run's traces could not be read: ${error instanceof Error ? error.message : String(error)}`;
|
|
5156
|
-
}
|
|
5157
|
-
if (asking && traces !== void 0) {
|
|
5158
|
-
const result = await policy.runPanel({
|
|
5159
|
-
continuation,
|
|
5160
|
-
task: input.task,
|
|
5161
|
-
...verdict === void 0 ? {} : { verdict },
|
|
5162
|
-
reads: input.reads(),
|
|
5163
|
-
questions,
|
|
5164
|
-
traces,
|
|
5165
|
-
workers,
|
|
5166
|
-
...policy.best === void 0 ? {} : { bar: policy.best },
|
|
5167
|
-
...policy.reference === void 0 ? {} : { reference: policy.reference },
|
|
5168
|
-
usdCap,
|
|
5169
|
-
signal: context.signal
|
|
5170
|
-
});
|
|
5171
|
-
if (result.usd === null) panelUsdKnown = false;
|
|
5172
|
-
else panelUsd += result.usd;
|
|
5173
|
-
findings = distillFindings(findings, result.findings, new Set(failing), continuation);
|
|
5174
|
-
panelRecord = {
|
|
5175
|
-
asked: questions.length,
|
|
5176
|
-
proposed: result.findings.length,
|
|
5177
|
-
admitted: findings.filter((finding) => finding.admittedAt === continuation).length,
|
|
5178
|
-
usd: result.usd
|
|
5179
|
-
};
|
|
5180
|
-
panelLines = [...result.findings.map((finding) => ({
|
|
5181
|
-
kind: "finding",
|
|
5182
|
-
admitted: admitFinding(finding),
|
|
5183
|
-
...finding
|
|
5184
|
-
})), ...result.receipts === void 0 ? [] : [{
|
|
5185
|
-
kind: "receipts",
|
|
5186
|
-
receipts: result.receipts
|
|
5187
|
-
}]];
|
|
5188
|
-
} else panelRecord = {
|
|
5189
|
-
asked: 0,
|
|
5190
|
-
proposed: 0,
|
|
5191
|
-
admitted: 0,
|
|
5192
|
-
usd: 0,
|
|
5193
|
-
...unavailable === void 0 ? {} : { unavailable }
|
|
5194
|
-
};
|
|
5195
|
-
}
|
|
5196
|
-
const appended = policy.append ? await policy.append({
|
|
5197
|
-
continuation,
|
|
5198
|
-
...verdict === void 0 ? {} : { verdict },
|
|
5199
|
-
reads: input.reads(),
|
|
5200
|
-
signal: context.signal
|
|
5201
|
-
}) : void 0;
|
|
5202
|
-
const note = composeContinuationNote({
|
|
5203
|
-
profile: policy.profile,
|
|
5204
|
-
continuation,
|
|
5205
|
-
...verdict === void 0 ? {} : { verdict },
|
|
5206
|
-
...notes.at(-1)?.verdict === void 0 ? {} : { previous: notes.at(-1)?.verdict },
|
|
5207
|
-
reads: input.reads().length,
|
|
5208
|
-
failures,
|
|
5209
|
-
...policy.panel === "on" ? { findings } : {},
|
|
5210
|
-
...policy.bar === "on" ? { bar: {
|
|
5211
|
-
...policy.best === void 0 ? {} : { best: policy.best },
|
|
5212
|
-
...policy.reference === void 0 ? {} : { reference: policy.reference }
|
|
5213
|
-
} } : {},
|
|
5214
|
-
...appended === void 0 ? {} : { appended: [appended] },
|
|
5215
|
-
...input.owed === void 0 ? {} : { owed: input.owed },
|
|
5216
|
-
progress: context.progress,
|
|
5217
|
-
canReadMore: input.canReadMore,
|
|
5218
|
-
canSubmitResult: input.canSubmitResult === true,
|
|
5219
|
-
...input.sealed === true ? { sealed: true } : {}
|
|
5220
|
-
});
|
|
5221
|
-
notes.push({
|
|
5222
|
-
note,
|
|
5223
|
-
...verdict === void 0 ? {} : { verdict },
|
|
5224
|
-
...panelLines === void 0 ? {} : { panel: panelLines },
|
|
5225
|
-
read
|
|
5226
|
-
});
|
|
5227
|
-
entries.push({
|
|
5228
|
-
continuation,
|
|
5229
|
-
attempt: context.attempt,
|
|
5230
|
-
noteDigest: noteDigest(note),
|
|
5231
|
-
profile: policy.profile.id,
|
|
5232
|
-
switches: {
|
|
5233
|
-
failures,
|
|
5234
|
-
panel: policy.panel,
|
|
5235
|
-
bar: policy.bar
|
|
5236
|
-
},
|
|
5237
|
-
before: summarizeVerdict(verdict),
|
|
5238
|
-
after: null,
|
|
5239
|
-
...panelRecord === void 0 ? {} : { panel: panelRecord },
|
|
5240
|
-
appended: appended === void 0 ? 0 : 1
|
|
5241
|
-
});
|
|
5242
|
-
if (input.dir !== void 0) await writeContinuationFiles(input.dir, continuation, {
|
|
5243
|
-
note,
|
|
5244
|
-
...verdict === void 0 ? {} : { verdict },
|
|
5245
|
-
...panelLines === void 0 ? {} : { panel: panelLines }
|
|
5246
|
-
});
|
|
5247
|
-
return note;
|
|
5248
|
-
},
|
|
5249
|
-
read(continuation) {
|
|
5250
|
-
const index = continuation === void 0 ? notes.length - 1 : continuation - 1;
|
|
5251
|
-
const entry = notes[index];
|
|
5252
|
-
if (entry === void 0) return {
|
|
5253
|
-
found: false,
|
|
5254
|
-
reason: notes.length === 0 ? "no continuation has been sent in this run" : `continuations run from 1 to ${notes.length}`
|
|
5255
|
-
};
|
|
5256
|
-
return {
|
|
5257
|
-
found: true,
|
|
5258
|
-
continuation: index + 1,
|
|
5259
|
-
note: entry.note,
|
|
5260
|
-
verdict: failures === "off" && entry.verdict !== void 0 ? { pass: entry.verdict.pass } : entry.verdict ?? null,
|
|
5261
|
-
findings: findings.filter((finding) => finding.admittedAt <= index + 1)
|
|
5262
|
-
};
|
|
5263
|
-
},
|
|
5264
|
-
entries() {
|
|
5265
|
-
closePrevious();
|
|
5266
|
-
return entries.map((entry) => ({ ...entry }));
|
|
5267
|
-
}
|
|
5268
|
-
};
|
|
5269
|
-
}
|
|
5270
4774
|
// src/runtime/supervise/completion-gate.ts
|
|
5271
4775
|
/**
|
|
5272
4776
|
* Wrap an `Executor` so its settlement `valid` reflects the deliverable check, not the
|
|
@@ -5584,13 +5088,7 @@ async function preflightPublicCoordination(input) {
|
|
|
5584
5088
|
/** Sandbox's `PartialFailureError` on `error` or a cause, read by name: packages that hold their own
|
|
5585
5089
|
* copy of the class would miss an `instanceof`. */
|
|
5586
5090
|
const causedByPartialFailure = (error) => causeChain(error).some((cause) => cause instanceof Error && errorProperty(cause, "name") === "PartialFailureError");
|
|
5587
|
-
/**
|
|
5588
|
-
* The pending invocation a failure left, when abandoning it is the resolution: the provider could
|
|
5589
|
-
* not resolve the execution (`unobservable`), or a nested manager's recovery could not be rebuilt
|
|
5590
|
-
* (`nested-recovery`). A lost transport waits in the outage window instead, and a capacity refusal
|
|
5591
|
-
* pauses, so neither starts a second execution beside one that may still run. A request refused
|
|
5592
|
-
* before it ran has nothing to abandon. A contract violation stays terminal (#1204).
|
|
5593
|
-
*/
|
|
5091
|
+
/** Abandon only `unobservable` or `nested-recovery`. Transport and capacity stay; a refused request and a contract violation do not start a second execution. */
|
|
5594
5092
|
function abandonablePending(error) {
|
|
5595
5093
|
return error instanceof RetainedExecutionPendingError && (error.pendingCause === "unobservable" || error.pendingCause === "nested-recovery") ? error : void 0;
|
|
5596
5094
|
}
|
|
@@ -5602,11 +5100,7 @@ const DETERMINISTIC_BRIDGE_CODES = /* @__PURE__ */ new Set([
|
|
|
5602
5100
|
"MODEL_NOT_FOUND",
|
|
5603
5101
|
"SEAT_NOT_LOGGED_IN"
|
|
5604
5102
|
]);
|
|
5605
|
-
/**
|
|
5606
|
-
* A model provider's content-filter refusal, which Codex names only in text under the generic
|
|
5607
|
-
* `AGENT_EXECUTION_FAILED`. It stays transient; the retry loop bounds a streak of them and stops
|
|
5608
|
-
* with this reason, for the parent to reword or re-scope the task.
|
|
5609
|
-
*/
|
|
5103
|
+
/** Content-filter text under `AGENT_EXECUTION_FAILED` stays transient; a streak of it stops for the parent to reword. */
|
|
5610
5104
|
const CONTENT_FILTER_REASON = "refused by the model provider's content filter";
|
|
5611
5105
|
const isContentFilterRefusal = (error) => causeChain(error).some((cause) => cause instanceof Error && /\bcontent was flagged for possible\b/iu.test(errorProperty(cause, "message") ?? ""));
|
|
5612
5106
|
/** A completed failed turn enters retry with its producer classification and legacy metadata intact. */
|
|
@@ -5681,6 +5175,9 @@ function upstreamUnavailableSignal(error) {
|
|
|
5681
5175
|
};
|
|
5682
5176
|
return (harness ? subscriptionUsageLimitSignal(failure) : void 0) ?? unavailableSignalOfFailure(failure);
|
|
5683
5177
|
}
|
|
5178
|
+
function materializationTimedOut(error) {
|
|
5179
|
+
return causeChain(error).some((cause) => cause instanceof Error && errorProperty(cause, "name") === "RetainedMaterializationTimeoutError");
|
|
5180
|
+
}
|
|
5684
5181
|
/** Capacity encountered while reconciling an admitted execution pauses that same execution. */
|
|
5685
5182
|
function reconciliationCapacityRefusal(error) {
|
|
5686
5183
|
if (!(error instanceof RetainedExecutionPendingError) || error.phase !== "execution") return void 0;
|
|
@@ -5700,6 +5197,7 @@ function ownCode(error) {
|
|
|
5700
5197
|
/** Runtime cancellation/contracts dominate producer policy; untyped foreign failures retain legacy rules. */
|
|
5701
5198
|
function classifyDriverFailure(error, signal, stopSignal) {
|
|
5702
5199
|
if (signal?.aborted) return "terminal";
|
|
5200
|
+
if (materializationTimedOut(error)) return "terminal";
|
|
5703
5201
|
if (error instanceof CheckUnavailableError || error instanceof CoordinationUnreachableError) return "unavailable";
|
|
5704
5202
|
if (error instanceof RetainedExecutionPendingError && error.pendingCause === "provider-contract") return "terminal";
|
|
5705
5203
|
if (undispatchedCredentialExit(error) !== void 0) return "unavailable";
|
|
@@ -5765,12 +5263,7 @@ function retainedAdmissionCause(error) {
|
|
|
5765
5263
|
}
|
|
5766
5264
|
}
|
|
5767
5265
|
}
|
|
5768
|
-
/**
|
|
5769
|
-
* A foreign error's HTTP status, read by the transport branch's rule: 408 and 5xx are a bad
|
|
5770
|
-
* moment, any other 4xx fails identically forever. A provider SDK's own classes reach here: a
|
|
5771
|
-
* Sandbox create refused `HTTP 400 {"code":"CONFIG_ERROR"}` for a fully reserved key was retried
|
|
5772
|
-
* 14-22 times per node as transient. Capacity statuses were answered before this point.
|
|
5773
|
-
*/
|
|
5266
|
+
/** 408 and 5xx are transient. Any other 4xx fails identically, including a sandbox `CONFIG_ERROR`. Capacity was already classified. */
|
|
5774
5267
|
function foreignHttpStatusVerdict(error) {
|
|
5775
5268
|
if (!(error instanceof Error)) return void 0;
|
|
5776
5269
|
const status = errorHttpStatus(error);
|
|
@@ -5879,9 +5372,7 @@ function taskToPrompt$1(task) {
|
|
|
5879
5372
|
return JSON.stringify(task);
|
|
5880
5373
|
}
|
|
5881
5374
|
// src/runtime/supervise/bridge-session-stream.ts
|
|
5882
|
-
/**
|
|
5883
|
-
* turn fires ONLY when the inbox has a steer/answer to fold, re-calling the SAME `session_id`.
|
|
5884
|
-
* Mirrors `routerToolsInlineExecutor`'s take→turn→settle loop with a full harness call per turn. */
|
|
5375
|
+
/** Resumable cli-bridge loop. Later turns fire only for a folded steer, on the same session. */
|
|
5885
5376
|
async function* streamBridgeSession(args) {
|
|
5886
5377
|
const { seam, inbox, observation } = args;
|
|
5887
5378
|
const started = Date.now();
|
|
@@ -5930,7 +5421,7 @@ async function* streamBridgeSession(args) {
|
|
|
5930
5421
|
kind: "turn",
|
|
5931
5422
|
label: `turn ${ledger.turns}`
|
|
5932
5423
|
});
|
|
5933
|
-
yield* ledger.settleTurn(activeRun.profileMaterialization?.inference?.observation?.usage, harnessStore, observation, seam.providerModel);
|
|
5424
|
+
yield* ledger.settleTurn(activeRun.profileMaterialization?.inference?.observation?.usage, harnessStore, observation, seam.providerModel, args.profile.model?.metadata?.credentialSource);
|
|
5934
5425
|
yield { kind: "iteration" };
|
|
5935
5426
|
if (!interrupted) {
|
|
5936
5427
|
if (ledger.turn.text) ledger.lastText = ledger.turn.text;
|
|
@@ -5962,9 +5453,7 @@ function foldTurnMessages(turnLease, inbox, observation) {
|
|
|
5962
5453
|
});
|
|
5963
5454
|
return folded;
|
|
5964
5455
|
}
|
|
5965
|
-
/** Prove
|
|
5966
|
-
* an attempt with no-dispatch evidence; the empty active-run map keeps teardown from cancelling
|
|
5967
|
-
* work the bridge never accepted. */
|
|
5456
|
+
/** Prove the bridge can accept the turn before a remote run id. A refusal dispatches nothing. */
|
|
5968
5457
|
async function preflightBridgeTurn(args, signals, turns) {
|
|
5969
5458
|
const { seam, observation } = args;
|
|
5970
5459
|
let initialModelCredential;
|
|
@@ -6078,10 +5567,7 @@ async function* streamBridgeTurn(args, turn) {
|
|
|
6078
5567
|
interrupted
|
|
6079
5568
|
};
|
|
6080
5569
|
}
|
|
6081
|
-
/**
|
|
6082
|
-
* A failed turn stream: a forceful steer's interruption returns once the durable run is terminal;
|
|
6083
|
-
* anything else throws, as the turn failure it is.
|
|
6084
|
-
*/
|
|
5570
|
+
/** A forceful steer returns after the run is terminal. Anything else throws. */
|
|
6085
5571
|
async function settleFailedTurn(error, args, signals, activeRun, external) {
|
|
6086
5572
|
const { seam } = args;
|
|
6087
5573
|
if (signals.interrupt.aborted && !args.signal.aborted && !args.controller.signal.aborted) {
|
|
@@ -6278,39 +5764,9 @@ function bridgeTranscript(seam, sessionId, profile, runs, node) {
|
|
|
6278
5764
|
}
|
|
6279
5765
|
// src/runtime/supervise/peer-mail.ts
|
|
6280
5766
|
/**
|
|
6281
|
-
*
|
|
6282
|
-
*
|
|
6283
|
-
*
|
|
6284
|
-
* Before this, a worker could only be reached by its parent: the inbox understood `steer` and
|
|
6285
|
-
* `answer`, both parent-authored, and the only worker-to-worker path fired at SETTLE time through
|
|
6286
|
-
* an analyst lens. Two live workers therefore could not compare results, one could not challenge
|
|
6287
|
-
* another's claim, and a blocked worker could not ask the peer that already had the fact.
|
|
6288
|
-
*
|
|
6289
|
-
* The mailbox is a POST OFFICE the parent owns, not a socket between workers. A worker never
|
|
6290
|
-
* touches another worker's inbox: it calls `send_mail` on a capability endpoint, and THIS module —
|
|
6291
|
-
* running with the parent's `Scope` — decides whether the envelope is admitted and then calls
|
|
6292
|
-
* `Scope.send`. Every decision, including every refusal, is published as a coordination event, so
|
|
6293
|
-
* the parent stays the auditor of a channel it no longer has to relay.
|
|
6294
|
-
*
|
|
6295
|
-
* Four properties this module is responsible for, each of which fails CLOSED:
|
|
6296
|
-
*
|
|
6297
|
-
* - IDENTITY. `from` is never a tool argument. A capability id is minted per spawn assignment and
|
|
6298
|
-
* bound to that assignment's concrete worker id once the spawn succeeds; the sender is read from
|
|
6299
|
-
* the binding. An unbound capability can send nothing (`sender-unbound`). The capability is the
|
|
6300
|
-
* ONLY thing a worker holds, and it carries no coordination verb — a worker that can send mail
|
|
6301
|
-
* still cannot spawn, steer, or stop anything.
|
|
6302
|
-
* - AUTHORITY. Peer mail is information, never instruction. A body or subject that tries to speak
|
|
6303
|
-
* as the supervisor is refused at intake (`forged-authority`) and the receiver's render fences
|
|
6304
|
-
* what survives — see {@link AUTHORITY_MARKERS} and the inbox's peer block.
|
|
6305
|
-
* - BOUNDS. A per-sender send quota, a per-receiver inbox cap in both count and bytes, a maximum
|
|
6306
|
-
* reply depth, and hard byte caps on subject and body. Every attempt that reaches the quota
|
|
6307
|
-
* check consumes one unit whether or not it delivers, so probing for refusals is not free.
|
|
6308
|
-
* - PROVENANCE. Mail may carry evidence refs for the receiver to re-check. Mail confers no
|
|
6309
|
-
* verification: evidence is judged by the reader and the external claim audit, not by the mail
|
|
6310
|
-
* form. Nothing is promoted because a peer asserted it.
|
|
6311
|
-
*
|
|
6312
|
-
* Scope is ONE run: siblings under one manager's live scope. No cross-run, no cross-org, no
|
|
6313
|
-
* outbound HTTP.
|
|
5767
|
+
* The parent mailbox. A worker calls `send_mail`; `from` is the capability binding, never a
|
|
5768
|
+
* tool argument. Forged authority is refused. A quota check consumes the attempt. Mail confers
|
|
5769
|
+
* no verification. One run only.
|
|
6314
5770
|
*
|
|
6315
5771
|
* @experimental
|
|
6316
5772
|
*/
|
|
@@ -6575,51 +6031,15 @@ function peerMailTools(mailbox, capabilityId) {
|
|
|
6575
6031
|
}
|
|
6576
6032
|
// src/runtime/supervise/inbox.ts
|
|
6577
6033
|
/**
|
|
6578
|
-
*
|
|
6579
|
-
*
|
|
6580
|
-
*
|
|
6581
|
-
*
|
|
6582
|
-
*
|
|
6583
|
-
*
|
|
6584
|
-
*
|
|
6585
|
-
*
|
|
6586
|
-
*
|
|
6587
|
-
* in-flight turn immediately, then re-plan with the message folded in — breaking the worker out
|
|
6588
|
-
* of a wrong path mid-task instead of waiting for it to finish the step.
|
|
6589
|
-
*
|
|
6590
|
-
* Taking is a LEASE, never a removal. A loop calls {@link Inbox.take}, folds the messages into its
|
|
6591
|
-
* next model input, and commits each one only once the provider accepted that input. Any failure,
|
|
6592
|
-
* abort or re-entry before then releases the lease, and the messages return to the head of the
|
|
6593
|
-
* queue ahead of later arrivals. A failed turn therefore cannot lose what it took: in run 18b a
|
|
6594
|
-
* director ruling and a failed-check notice were drained into a turn that failed, and the next two
|
|
6595
|
-
* prompts said "Events waiting for you: none".
|
|
6596
|
-
*
|
|
6597
|
-
* Every authority message ends in exactly one receipt to its sender: `consumed`, naming the
|
|
6598
|
-
* attempt whose accepted input carried it, or `failed`, naming why. Two rules bound the wait:
|
|
6599
|
-
*
|
|
6600
|
-
* - PROMOTION: an authority message still unconsumed {@link AUTHORITY_PROMOTION_MS} after it
|
|
6601
|
-
* arrived becomes an interrupt and aborts the turn in flight, so the next input carries it.
|
|
6602
|
-
* A promoted message gets that one attempt; if the lease holding it is released again, the
|
|
6603
|
-
* message fails instead of waiting another boundary. The sender hears within 15 minutes plus
|
|
6604
|
-
* one attempt.
|
|
6605
|
-
* - SETTLE: a recipient that stops with messages still held calls {@link Inbox.failPending},
|
|
6606
|
-
* which reports each one failed. A recipient that cannot run another turn (no budget, a stop
|
|
6607
|
-
* request, a failed run) therefore settles, and its sender learns the steer was not read.
|
|
6608
|
-
*
|
|
6609
|
-
* A THIRD kind arrives here too: peer mail from a sibling worker (`./peer-mail`). It is carried on
|
|
6610
|
-
* its own wire property, and this file keeps it strictly apart from the two authority kinds:
|
|
6611
|
-
*
|
|
6612
|
-
* - It can never be forceful. `interrupt` is written as `false` and the wire field is ignored, so
|
|
6613
|
-
* a peer cannot abort a peer's in-flight turn and hold it at zero progress.
|
|
6614
|
-
* - It never blocks a settle. The pre-settle fence counts {@link Inbox.pendingAuthority}, not
|
|
6615
|
-
* total pending, because a peer that keeps mail arriving would otherwise deny a FINISHED worker
|
|
6616
|
-
* its settlement.
|
|
6617
|
-
* - It renders in its own block, fenced with a per-fold nonce and attributed to its sender. The
|
|
6618
|
-
* `[SUPERVISOR]` header is emitted for authority messages ONLY, so a mixed lease cannot present
|
|
6619
|
-
* a peer's message as an instruction from the parent.
|
|
6620
|
-
*
|
|
6621
|
-
* `deliver` never throws — a malformed message is ignored and returns `false`, so no caller can
|
|
6622
|
-
* report delivery for bytes this inbox discarded.
|
|
6034
|
+
* Worker inbox behind `Executor.deliver`. Queued `steer_agent` / `answer_question` messages are
|
|
6035
|
+
* taken at the next step boundary, including before settle. `interrupt: true` aborts the turn in
|
|
6036
|
+
* flight. {@link Inbox.take} is a lease: commit only after the provider accepts the input, otherwise
|
|
6037
|
+
* the messages return to the head of the queue. Each authority message gets one receipt, `consumed`
|
|
6038
|
+
* or `failed`. After {@link AUTHORITY_PROMOTION_MS} an unconsumed authority message interrupts once;
|
|
6039
|
+
* a released lease then fails it. A recipient that stops calls {@link Inbox.failPending}. Peer mail
|
|
6040
|
+
* (`./peer-mail`) is never forceful, never blocks settle ({@link Inbox.pendingAuthority} is the
|
|
6041
|
+
* fence), and renders in its own block without the `[SUPERVISOR]` header. `deliver` returns `false`
|
|
6042
|
+
* for a malformed message and does not throw.
|
|
6623
6043
|
*
|
|
6624
6044
|
* @experimental
|
|
6625
6045
|
*/
|
|
@@ -8802,6 +8222,19 @@ function retainedDispatchMaterial(args, retention, selectedTurn, signal) {
|
|
|
8802
8222
|
const environmentKey = priorSession?.idempotencyKey ?? `runtime:${args.executionId}`;
|
|
8803
8223
|
const turnId = `${args.executionId}:turn:0`;
|
|
8804
8224
|
const restore = priorSession === void 0 ? retention.restoreWorkspace : void 0;
|
|
8225
|
+
const attachments = priorSession && args.options.defaults?.runtimeAttachments?.mcp;
|
|
8226
|
+
const backend = recordValue(selectedTurn.providerOptions?.backend);
|
|
8227
|
+
const mcp = {
|
|
8228
|
+
...attachments,
|
|
8229
|
+
...recordValue(recordValue(backend?.runtimeAttachments)?.mcp)
|
|
8230
|
+
};
|
|
8231
|
+
const providerOptions = {
|
|
8232
|
+
...selectedTurn.providerOptions,
|
|
8233
|
+
backend: {
|
|
8234
|
+
...backend,
|
|
8235
|
+
runtimeAttachments: { mcp }
|
|
8236
|
+
}
|
|
8237
|
+
};
|
|
8805
8238
|
return {
|
|
8806
8239
|
material: {
|
|
8807
8240
|
environment: {
|
|
@@ -8816,7 +8249,8 @@ function retainedDispatchMaterial(args, retention, selectedTurn, signal) {
|
|
|
8816
8249
|
},
|
|
8817
8250
|
turn: {
|
|
8818
8251
|
...selectedTurn,
|
|
8819
|
-
turnId
|
|
8252
|
+
turnId,
|
|
8253
|
+
...attachments ? { providerOptions } : {}
|
|
8820
8254
|
},
|
|
8821
8255
|
preserveEnvironment: retention.preserveEnvironment,
|
|
8822
8256
|
...priorSession === void 0 ? {} : {
|
|
@@ -8921,7 +8355,8 @@ async function retainedExecution(args, retention, turn, selectedTurn, signal) {
|
|
|
8921
8355
|
retained: true
|
|
8922
8356
|
};
|
|
8923
8357
|
} catch (error) {
|
|
8924
|
-
if (
|
|
8358
|
+
if (error instanceof RetainedMaterializationTimeoutError) throw error;
|
|
8359
|
+
if (proof.admitted && !retainedSessionReplaced(error)) throw new RetainedExecutionPendingError(error, proof.executionAdmitted ? "execution" : "admission");
|
|
8925
8360
|
throw error;
|
|
8926
8361
|
}
|
|
8927
8362
|
}
|
|
@@ -9504,7 +8939,7 @@ var ProviderTurnSettlement = class {
|
|
|
9504
8939
|
async *fail(error) {
|
|
9505
8940
|
const { args } = this;
|
|
9506
8941
|
yield* this.usage.settleTurn();
|
|
9507
|
-
this.failure = this.retained ? new RetainedExecutionPendingError(error) : error;
|
|
8942
|
+
this.failure = this.retained && !retainedSessionReplaced(error) ? new RetainedExecutionPendingError(error) : error;
|
|
9508
8943
|
this.failed = true;
|
|
9509
8944
|
await this.stopEndedHarness();
|
|
9510
8945
|
args.scope.state.settleTranscript();
|
|
@@ -9543,6 +8978,8 @@ var ProviderUsageAccount = class {
|
|
|
9543
8978
|
ledger;
|
|
9544
8979
|
worker;
|
|
9545
8980
|
tokens = zeroTokenUsage();
|
|
8981
|
+
/** Live-stream tokens captured at the first broken-stream event, before its exact result replaces them. */
|
|
8982
|
+
streamedTokens;
|
|
9546
8983
|
usd = 0;
|
|
9547
8984
|
usdEstimated = 0;
|
|
9548
8985
|
sawCompleteTokenReceipt = false;
|
|
@@ -9569,18 +9006,16 @@ var ProviderUsageAccount = class {
|
|
|
9569
9006
|
this.sawUnknownCostReceipt = true;
|
|
9570
9007
|
}
|
|
9571
9008
|
*observe(event) {
|
|
9009
|
+
if (this.streamedTokens === void 0 && streamBroke(event)) this.streamedTokens = cloneTokenUsage(this.tokens);
|
|
9572
9010
|
yield* this.credit(this.ledger.observe(event, this.worker), event);
|
|
9573
9011
|
}
|
|
9574
9012
|
*settleTurn() {
|
|
9575
9013
|
yield* this.credit(this.ledger.settleTurn(this.worker));
|
|
9576
9014
|
}
|
|
9577
|
-
/**
|
|
9578
|
-
* Interim missing prices and catalog estimates may be covered by a later cumulative bill.
|
|
9579
|
-
* Only unresolved work becomes unknown at settlement; do not add a quote to that bill.
|
|
9580
|
-
*/
|
|
9015
|
+
/** Unresolved work stays unknown. Do not add a quote to a bill that already arrived. */
|
|
9581
9016
|
*settleUnpricedWork() {
|
|
9582
9017
|
if (!this.pendingUnpricedWork) return;
|
|
9583
|
-
const estimated = this.pendingEstimate ?? (this.usd === 0 ? this.catalogPrice() : void 0);
|
|
9018
|
+
const estimated = this.subscriptionSeat() ? void 0 : this.pendingEstimate ?? (this.usd === 0 ? this.catalogPrice() : void 0);
|
|
9584
9019
|
const estimate = estimated ?? 0;
|
|
9585
9020
|
this.sawUnknownCostReceipt = true;
|
|
9586
9021
|
this.usd += estimate;
|
|
@@ -9605,7 +9040,8 @@ var ProviderUsageAccount = class {
|
|
|
9605
9040
|
usd: this.usd,
|
|
9606
9041
|
usdKnown: this.sawCostReceipt && !this.sawUnknownCostReceipt,
|
|
9607
9042
|
...this.sawCostEstimate ? { usdEstimated: this.usdEstimated } : {},
|
|
9608
|
-
ms: Date.now() - started
|
|
9043
|
+
ms: Date.now() - started,
|
|
9044
|
+
...this.streamBreak()
|
|
9609
9045
|
};
|
|
9610
9046
|
const { carried } = this.args;
|
|
9611
9047
|
return carried === void 0 ? spent : {
|
|
@@ -9616,13 +9052,27 @@ var ProviderUsageAccount = class {
|
|
|
9616
9052
|
ms: Date.now() - this.args.executionStartedAt
|
|
9617
9053
|
};
|
|
9618
9054
|
}
|
|
9619
|
-
/**
|
|
9620
|
-
|
|
9621
|
-
|
|
9622
|
-
|
|
9623
|
-
|
|
9624
|
-
|
|
9055
|
+
/** What the live stream carried, and the exact-result remainder when that result exceeded it. */
|
|
9056
|
+
streamBreak() {
|
|
9057
|
+
if (this.streamedTokens === void 0) return {};
|
|
9058
|
+
const streamedTokens = cloneTokenUsage(this.streamedTokens);
|
|
9059
|
+
const gap = tokenGap(streamedTokens, this.tokens);
|
|
9060
|
+
const unobservedTokens = gap === void 0 ? void 0 : cloneTokenUsage(gap);
|
|
9061
|
+
return {
|
|
9062
|
+
streamedTokens,
|
|
9063
|
+
...unobservedTokens === void 0 ? {} : {
|
|
9064
|
+
unobservedTokens,
|
|
9065
|
+
iterationsKnown: false
|
|
9066
|
+
}
|
|
9067
|
+
};
|
|
9068
|
+
}
|
|
9069
|
+
/** A subscription seat is unpriced. Its profile declares no per-call bill. */
|
|
9070
|
+
subscriptionSeat() {
|
|
9071
|
+
return [this.args.profile, this.args.createProfile].some((profile) => profile.model?.metadata?.credentialSource === "subscription");
|
|
9072
|
+
}
|
|
9073
|
+
/** Catalog price of the whole token total, or undefined when nothing could be priced. */
|
|
9625
9074
|
catalogPrice() {
|
|
9075
|
+
if (this.subscriptionSeat()) return void 0;
|
|
9626
9076
|
const { tokens } = this;
|
|
9627
9077
|
for (const model of [
|
|
9628
9078
|
this.observedModel,
|
|
@@ -9640,8 +9090,7 @@ var ProviderUsageAccount = class {
|
|
|
9640
9090
|
if (priced.usdKnown === false && priced.usdEstimated !== void 0) return priced.usdEstimated;
|
|
9641
9091
|
}
|
|
9642
9092
|
}
|
|
9643
|
-
/** This invocation's
|
|
9644
|
-
* invocations already reported. */
|
|
9093
|
+
/** This invocation's tokens plus what a continuation already carried. */
|
|
9645
9094
|
executionTokens(own) {
|
|
9646
9095
|
const { carried } = this.args;
|
|
9647
9096
|
if (carried === void 0) return own;
|
|
@@ -9699,6 +9148,36 @@ var ProviderUsageAccount = class {
|
|
|
9699
9148
|
} else if (input > 0 || output > 0 || receipt.tokensKnown === false) this.pendingUnpricedWork = true;
|
|
9700
9149
|
}
|
|
9701
9150
|
};
|
|
9151
|
+
function streamBroke(event) {
|
|
9152
|
+
return event.data.eventStreamComplete === false;
|
|
9153
|
+
}
|
|
9154
|
+
/** Counters gained after `streamed`. A cache class past the input gap is omitted. */
|
|
9155
|
+
function tokenGap(streamed, recorded) {
|
|
9156
|
+
const input = Math.max(0, recorded.input - streamed.input);
|
|
9157
|
+
const output = Math.max(0, recorded.output - streamed.output);
|
|
9158
|
+
const gap = {
|
|
9159
|
+
input,
|
|
9160
|
+
output
|
|
9161
|
+
};
|
|
9162
|
+
for (const key of [
|
|
9163
|
+
"freshInput",
|
|
9164
|
+
"cacheRead",
|
|
9165
|
+
"cacheWrite"
|
|
9166
|
+
]) {
|
|
9167
|
+
const next = recorded[key];
|
|
9168
|
+
if (next === void 0) continue;
|
|
9169
|
+
const delta = next - (streamed[key] ?? 0);
|
|
9170
|
+
if (delta > 0) gap[key] = delta;
|
|
9171
|
+
}
|
|
9172
|
+
if ((gap.freshInput ?? 0) + (gap.cacheRead ?? 0) + (gap.cacheWrite ?? 0) > input) {
|
|
9173
|
+
delete gap.freshInput;
|
|
9174
|
+
delete gap.cacheRead;
|
|
9175
|
+
delete gap.cacheWrite;
|
|
9176
|
+
gap.cacheBreakdownKnown = false;
|
|
9177
|
+
}
|
|
9178
|
+
if (input === 0 && output === 0 && gap.cacheBreakdownKnown !== false) return void 0;
|
|
9179
|
+
return gap;
|
|
9180
|
+
}
|
|
9702
9181
|
// src/runtime/environment-provider/provider-invocation.ts
|
|
9703
9182
|
/** The turn this invocation sends: the task's turn under the provider's defaults and placement rules. */
|
|
9704
9183
|
function invocationTurn(args) {
|
|
@@ -9722,7 +9201,7 @@ async function* streamProviderExecutor(args) {
|
|
|
9722
9201
|
recordRuntimeOwnedProviderAttemptStart(args.scope.executor());
|
|
9723
9202
|
const source = await providerExecutionSource(args, turn, args.signal);
|
|
9724
9203
|
const environment = source.environment;
|
|
9725
|
-
args.onEnvironment(environment);
|
|
9204
|
+
await args.onEnvironment(environment);
|
|
9726
9205
|
const usage = new ProviderUsageAccount(args, turn.model);
|
|
9727
9206
|
const observer = new ProviderTurnObserver(args, usage, source.retained, turn.model);
|
|
9728
9207
|
const settlement = new ProviderTurnSettlement(args, environment, source.retained, observer, usage, started);
|
|
@@ -9738,19 +9217,52 @@ async function* streamProviderExecutor(args) {
|
|
|
9738
9217
|
}
|
|
9739
9218
|
// src/runtime/environment-provider/provider-execution-loop.ts
|
|
9740
9219
|
/** A new environment now backs this execution; the identity the provider issued is evidence. */
|
|
9741
|
-
function adoptEnvironment(scope, env) {
|
|
9220
|
+
async function adoptEnvironment(scope, env, signal) {
|
|
9742
9221
|
const { state, materialization } = scope;
|
|
9743
9222
|
state.environment = env;
|
|
9744
9223
|
state.resetWorkspace(env);
|
|
9745
9224
|
if (state.harnessTranscript.status === "unavailable" && state.harnessTranscript.reason === "execution-never-started") state.harnessTranscript = harnessTranscriptUnavailable("capture-did-not-run");
|
|
9225
|
+
const resources = await appliedResources(env, signal);
|
|
9746
9226
|
finalizeRuntimeOwnedPendingExecutor(scope.executor(), {
|
|
9747
9227
|
...materialization.plannedDeclaration,
|
|
9228
|
+
resources,
|
|
9748
9229
|
execution: {
|
|
9749
9230
|
kind: "environment",
|
|
9750
9231
|
id: env.id
|
|
9751
9232
|
}
|
|
9752
9233
|
}, materialization.plannedBinding);
|
|
9753
9234
|
}
|
|
9235
|
+
/** Read the applied box sizes from the created environment's normalized observation. Unknown is
|
|
9236
|
+
* the honest answer whenever the environment offers no observation, reports no known effective
|
|
9237
|
+
* size, or fails to answer; the request the create input carried is never a substitute. */
|
|
9238
|
+
async function appliedResources(env, signal) {
|
|
9239
|
+
if (env.observe === void 0) return {
|
|
9240
|
+
status: "unknown",
|
|
9241
|
+
reason: "created environment offers no observation"
|
|
9242
|
+
};
|
|
9243
|
+
try {
|
|
9244
|
+
const effective = (await env.observe({ signal })).resources?.effective;
|
|
9245
|
+
if (effective?.state !== "known") return {
|
|
9246
|
+
status: "unknown",
|
|
9247
|
+
reason: `created environment reported effective resources as ${effective === void 0 ? "none" : effective.state}`
|
|
9248
|
+
};
|
|
9249
|
+
const { value, provenance } = effective;
|
|
9250
|
+
return {
|
|
9251
|
+
status: "known",
|
|
9252
|
+
...value.cpu === void 0 ? {} : { cpu: value.cpu },
|
|
9253
|
+
...value.memoryMb === void 0 ? {} : { memoryMb: value.memoryMb },
|
|
9254
|
+
...value.diskMb === void 0 ? {} : { diskMb: value.diskMb },
|
|
9255
|
+
...value.accelerator === void 0 ? {} : { accelerator: value.accelerator },
|
|
9256
|
+
origin: provenance.origin,
|
|
9257
|
+
observedAt: provenance.observedAt
|
|
9258
|
+
};
|
|
9259
|
+
} catch (error) {
|
|
9260
|
+
return {
|
|
9261
|
+
status: "unknown",
|
|
9262
|
+
reason: `created environment observation failed: ${errorMessage(error)}`
|
|
9263
|
+
};
|
|
9264
|
+
}
|
|
9265
|
+
}
|
|
9754
9266
|
/** The seams one invocation reports through; `continued` marks a continuation of the execution. */
|
|
9755
9267
|
function invocationArgs(scope, invocation, signal, carried, executionStartedAt, continued) {
|
|
9756
9268
|
const { state, options, provider, node, nativeControl } = scope;
|
|
@@ -9776,8 +9288,8 @@ function invocationArgs(scope, invocation, signal, carried, executionStartedAt,
|
|
|
9776
9288
|
state.providerSessionId = state.workspaceControlRef.sessionId;
|
|
9777
9289
|
nativeControl.cancelRetainedOnManagerStop(handle);
|
|
9778
9290
|
},
|
|
9779
|
-
onEnvironment: (env) => {
|
|
9780
|
-
if (!continued) return adoptEnvironment(scope, env);
|
|
9291
|
+
onEnvironment: async (env) => {
|
|
9292
|
+
if (!continued) return adoptEnvironment(scope, env, signal);
|
|
9781
9293
|
if (env.id !== state.environment?.id) throw new ValidationError(`providerAsExecutor(${provider.name}): a continuation ran in environment ${env.id}, not ${state.environment?.id ?? "<none>"}`);
|
|
9782
9294
|
state.environment = env;
|
|
9783
9295
|
}
|
|
@@ -10608,12 +10120,13 @@ function throwRouterFailureWithAttempts(error, attempts) {
|
|
|
10608
10120
|
function routerErrorIdentity(error) {
|
|
10609
10121
|
return typeof error === "object" && error !== null || typeof error === "function" ? error : void 0;
|
|
10610
10122
|
}
|
|
10123
|
+
/** The parsed body; a usage with no cost takes the Router's exact `x-tangle-cost-usd` (#1587). */
|
|
10611
10124
|
async function routerResponseJson(response, attempts) {
|
|
10612
|
-
|
|
10613
|
-
|
|
10614
|
-
|
|
10615
|
-
|
|
10616
|
-
|
|
10125
|
+
const body = await response.json().catch((error) => throwRouterFailureWithAttempts(error, attempts));
|
|
10126
|
+
const cost = Number(response.headers.get("x-tangle-cost-usd") || NaN);
|
|
10127
|
+
const usage = body?.usage;
|
|
10128
|
+
if (cost >= 0 && usage?.cost === void 0 && usage?.cost_usd === void 0 && usage) usage.cost = cost;
|
|
10129
|
+
return body;
|
|
10617
10130
|
}
|
|
10618
10131
|
function agentCoreRetryConfig(retry, callerSignal) {
|
|
10619
10132
|
return {
|
|
@@ -16555,21 +16068,21 @@ async function settleRootResult(settled) {
|
|
|
16555
16068
|
pool.assertNoOpenTickets();
|
|
16556
16069
|
const outRef = contentAddress(out);
|
|
16557
16070
|
await settled.opts.blobs.put(outRef, out);
|
|
16558
|
-
const
|
|
16071
|
+
const accounting = await terminalAccounting(settled.journal, settled.opts.runId, settled.now() - settled.runEpochMs, settled.opts.requestedProfile);
|
|
16559
16072
|
return {
|
|
16560
16073
|
kind: "winner",
|
|
16561
16074
|
out,
|
|
16562
16075
|
outRef,
|
|
16563
|
-
tree:
|
|
16564
|
-
spentTotal,
|
|
16565
|
-
usage,
|
|
16566
|
-
providerModel,
|
|
16076
|
+
tree: accounting.tree,
|
|
16077
|
+
spentTotal: accounting.spentTotal,
|
|
16078
|
+
usage: accounting.usage,
|
|
16079
|
+
providerModel: accounting.providerModel,
|
|
16567
16080
|
...teardownUnconfirmed.length > 0 ? { teardownUnconfirmed } : {},
|
|
16568
|
-
...gaps.length > 0 ? { spendGaps: gaps } : {},
|
|
16569
|
-
fleetYield,
|
|
16570
|
-
...isNonEmptySpend(driverInference) ? { spentBreakdown: {
|
|
16571
|
-
driverInference,
|
|
16572
|
-
childWork
|
|
16081
|
+
...accounting.gaps.length > 0 ? { spendGaps: accounting.gaps } : {},
|
|
16082
|
+
fleetYield: accounting.fleetYield,
|
|
16083
|
+
...isNonEmptySpend(accounting.driverInference) ? { spentBreakdown: {
|
|
16084
|
+
driverInference: accounting.driverInference,
|
|
16085
|
+
childWork: accounting.childWork
|
|
16573
16086
|
} } : {}
|
|
16574
16087
|
};
|
|
16575
16088
|
}
|
|
@@ -16580,10 +16093,10 @@ async function settleRootResult(settled) {
|
|
|
16580
16093
|
/** A no-winner still carries `spentTotal`, summed off the SAME journal the winner path reads. */
|
|
16581
16094
|
async function noWinner(settled, rejection) {
|
|
16582
16095
|
const { controller, teardownUnconfirmed, leakedReservations } = settled;
|
|
16583
|
-
const { spentTotal, gaps, providerModel, fleetYield, usage } = await terminalAccounting(settled.journal, settled.opts.runId, settled.now() - settled.runEpochMs, settled.opts.requestedProfile);
|
|
16096
|
+
const { tree, spentTotal, gaps, providerModel, fleetYield, usage } = await terminalAccounting(settled.journal, settled.opts.runId, settled.now() - settled.runEpochMs, settled.opts.requestedProfile);
|
|
16584
16097
|
const common = {
|
|
16585
16098
|
kind: "no-winner",
|
|
16586
|
-
tree
|
|
16099
|
+
tree,
|
|
16587
16100
|
downCount: settled.breaker.downCount(),
|
|
16588
16101
|
spentTotal,
|
|
16589
16102
|
usage,
|
|
@@ -16623,6 +16136,6 @@ async function noWinner(settled, rejection) {
|
|
|
16623
16136
|
reason: "no-result-selected"
|
|
16624
16137
|
};
|
|
16625
16138
|
}
|
|
16626
|
-
export { DEFAULT_PEER_MAIL_LIMITS as $,
|
|
16139
|
+
export { DEFAULT_PEER_MAIL_LIMITS as $, createSandboxForSpec as A, bridgeRuntimeAttachmentsKey as At, createRouterTranscript as B, controlProfileMaterialization as Bt, createExecutor as C, priceTokens as Ct, runAgentRounds as D, harnessUsageIsEmpty as Dt, createSteerableSandboxSession as E, createCodexRolloutStoreReader as Et, codeModeArguments as F, LOCAL_HARNESSES as Ft, LEAF_CONTINUATION_TASK as G, promptModelProfileMaterialization as Gt, createAgentEnvironmentProviderRegistry as H, fullProfileMaterialization as Ht, codeModeModelOutput as I, harnessInvocation as It, createInPlaceCliExecutor as J, sandboxProfileMaterialization as Jt, providerAsSandboxClient as K, renderUnsupported as Kt, createCodeModeTools as L, terminateProcessTreeAndConfirm as Lt, acquireSandbox as M, defaultRunCommand as Mt, TERMINAL_DECISIONS as N, runSettledCommand as Nt, assertBoxlessPromptOptions as O, readCodexRolloutSession as Ot, defaultSelectWinner as P, runWorktreeHarness as Pt, AUTHORITY_MARKERS as Q, readSandboxOutcome as Qt, runCodeMode as R, assertProfileMaterialization as Rt, captureReusableExecutorConfig as S, bridgeModelRouteRefusal as St, DEFAULT_SANDBOX_STEERING_MAX_TURNS as T, addHarnessUsage as Tt, resolveAgentEnvironmentProvider as U, profileMaterializationAxes$1 as Ut, routerBrain as V, defineProfileMaterializationContract as Vt, providerAsExecutor as W, promptControlProfileMaterialization as Wt, createInbox as X, worktreeCliProfileMaterialization as Xt, INBOX_RECEIPT_KEY as Y, unsupportedProfileDimensions as Yt, failPendingAfter as Z, projectSandboxOutcome as Zt, withDriverExecutor as _, gateFactoryOnDeliverable as _t, assertRunParking as a, peerMailVerbNames as at, createExecutorRegistry as b, verdictFromJudgeScore as bt, sleepScopeWait as c, HarnessTurnFailedError as ct, runFinalizer as d, summarizeDriverAttempts as dt, PEER_MAIL_WIRE_KEY as et, runTree as f, transientFailureKind as ft, isDriverSpec as g, CheckUnavailableError as gt, driverExecutorFactory as h, preflightPublicCoordination as ht, RunParkedError as i, peerMailTools as it, createSandboxLineage as j, bridgeStopSignalKey as jt, readPromptOptions as k, createPushTraceSource as kt, withRunParking as l, abandonablePending as lt, driverChild as m, upstreamUnavailableSignal as mt, createSupervisor as n, createPeerMailbox as nt, bindScopeParkingDrain as o, taskToPrompt$1 as ot, createRootHandle as p, undispatchedCredentialExit as pt, createWorktreeCliExecutor as q, sandboxActProfileMaterialization as qt, assertResumeLimits as r, isPeerMailEnvelope as rt, readRunParking as s, DriverAttemptsExhaustedError as st, DEFAULT_MAX_DEPTH as t, claimsAuthority as tt, bestDelivered as u, classifyDriverFailure as ut, InMemoryResultBlobStore as v, gateOnDeliverable as vt, snapshotExecutorConfig as w, ROUTER_PRICE_SOURCE as wt, bindReusableExecutorExecutionId as x, bridgeAdmissionRefusal as xt, InMemorySpawnJournal as y, mapExecutorResult as yt, toolResultText as z, assertProfileMaterializes as zt };
|
|
16627
16140
|
|
|
16628
|
-
//# sourceMappingURL=supervisor-
|
|
16141
|
+
//# sourceMappingURL=supervisor-Dpeu7rnZ.js.map
|