@tangle-network/agent-runtime 0.261.0 → 0.262.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.
Files changed (54) hide show
  1. package/dist/{activation-BwrMmguq.js → activation-C0AoYRgS.js} +2 -2
  2. package/dist/{activation-BwrMmguq.js.map → activation-C0AoYRgS.js.map} +1 -1
  3. package/dist/{activation-BpJ2CmXx.d.ts → activation-CozZXBTg.d.ts} +2 -2
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-LmDxHvAO.js → coordination-driver-COGC8FK2.js} +302 -23
  7. package/dist/coordination-driver-COGC8FK2.js.map +1 -0
  8. package/dist/{delegate-rkhJf5w7.js → delegate-BC7Au73v.js} +2 -2
  9. package/dist/{delegate-rkhJf5w7.js.map → delegate-BC7Au73v.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-Bn3wSH8-.js → graph-DgODOGWN.js} +3 -3
  13. package/dist/{graph-Bn3wSH8-.js.map → graph-DgODOGWN.js.map} +1 -1
  14. package/dist/{improvement-cycle-DYiwfjWY.js → improvement-cycle-DirqO-fX.js} +3 -3
  15. package/dist/{improvement-cycle-DYiwfjWY.js.map → improvement-cycle-DirqO-fX.js.map} +1 -1
  16. package/dist/{index-tubViIQJ.d.ts → index-B8tXCisZ.d.ts} +136 -288
  17. package/dist/index.d.ts +6 -6
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +3 -3
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +4 -4
  22. package/dist/kernel.js +9 -9
  23. package/dist/{loop-runner-bin-CL4W2pu1.d.ts → loop-runner-bin-BaZd1XIm.d.ts} +3 -3
  24. package/dist/{loop-runner-bin-Dxqxf91b.js → loop-runner-bin-C9P1ELVv.js} +3 -3
  25. package/dist/{loop-runner-bin-Dxqxf91b.js.map → loop-runner-bin-C9P1ELVv.js.map} +1 -1
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +3 -3
  29. package/dist/mcp/index.d.ts +6 -6
  30. package/dist/mcp/index.js +4 -4
  31. package/dist/{openai-tools-BlZHd0Nz.d.ts → openai-tools-CHwN_S24.d.ts} +2 -2
  32. package/dist/profiles.d.ts +2 -2
  33. package/dist/{provision-supervisor-By5oGk3t.js → provision-supervisor-9FMwo-Es.js} +3 -3
  34. package/dist/{provision-supervisor-By5oGk3t.js.map → provision-supervisor-9FMwo-Es.js.map} +1 -1
  35. package/dist/{runtime-BbQmK7qe.js → runtime-BXWVW51r.js} +8 -8
  36. package/dist/{runtime-BbQmK7qe.js.map → runtime-BXWVW51r.js.map} +1 -1
  37. package/dist/{server-CHlpLE22.js → server-6g6KFwUC.js} +3 -3
  38. package/dist/{server-CHlpLE22.js.map → server-6g6KFwUC.js.map} +1 -1
  39. package/dist/{stream-agent-turn-DTgxWXbR.d.ts → stream-agent-turn-u28hoxuR.d.ts} +2 -2
  40. package/dist/{structural-rollout-Dby60zHe.js → structural-rollout-WEfWpjub.js} +2 -2
  41. package/dist/{structural-rollout-Dby60zHe.js.map → structural-rollout-WEfWpjub.js.map} +1 -1
  42. package/dist/{substrate-CxwdhZri.d.ts → substrate-BeQiXkpa.d.ts} +2 -2
  43. package/dist/{supervise-1QzYAyS2.js → supervise-BeAI8-On.js} +221 -48
  44. package/dist/supervise-BeAI8-On.js.map +1 -0
  45. package/dist/{supervisor-yavsoQQo.js → supervisor-BGGvnXvV.js} +161 -17
  46. package/dist/{supervisor-yavsoQQo.js.map → supervisor-BGGvnXvV.js.map} +1 -1
  47. package/dist/testing.d.ts +2 -2
  48. package/dist/testing.js +12 -12
  49. package/dist/tui/index.d.ts +1 -1
  50. package/dist/tui/index.js +1 -1
  51. package/dist/{types-DNCNRu0E.d.ts → types-CP3iQ8Ji.d.ts} +354 -4
  52. package/package.json +2 -2
  53. package/dist/coordination-driver-LmDxHvAO.js.map +0 -1
  54. package/dist/supervise-1QzYAyS2.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { Gr as Driver, Ur as AgentRunSpec, _i as Validator, fi as OutputAdapter } from "./types-DNCNRu0E.js";
1
+ import { Ci as Driver, Wi as OutputAdapter, Yi as Validator, xi as AgentRunSpec } from "./types-CP3iQ8Ji.js";
2
2
  import { AgentProfile } from "@tangle-network/agent-interface";
3
3
  //#region src/profiles/coder.d.ts
4
4
  /**
@@ -281,4 +281,4 @@ interface UiFinding {
281
281
  }
282
282
  //#endregion
283
283
  export { CoderTask as _, UiFindingSeverity as a, KnowledgeUpdate as c, ResearchSource as d, ResearchTask as f, researcherProfile as g, multiHarnessResearcherFanout as h, UiFindingScreenshot as i, MultiHarnessResearcherFanoutOptions as l, createResearcherValidator as m, UI_LENSES as n, UiLens as o, ResearcherProfileOptions as p, UiFinding as r, KnowledgeItem as s, UI_FINDING_SEVERITIES as t, ResearchOutput as u, coderTaskToPrompt as v };
284
- //# sourceMappingURL=substrate-CxwdhZri.d.ts.map
284
+ //# sourceMappingURL=substrate-BeQiXkpa.d.ts.map
@@ -1,10 +1,10 @@
1
- import { $i as zeroSpend, B as scopeRetainedOwnerResult, Br as fullProfileMaterialization, C as recordScopeOwnerMaterialization, Cn as routerBrain, F as consumeScopeRetainedOwnerResult, Ft as newUsageTotals, Gn as RunCancellationReason, Hr as promptControlProfileMaterialization, I as prepareScopeRetainedOwnerTask, In as registerRetainedExecutorPreparation, Jn as runAbortable, L as scopeRetainedOwnerContext, Ln as retainedExecutorSeamKey, Lr as assertProfileMaterialization, Lt as spendFromUsageTotals, Mt as assertValidBudget, N as bindScopeRetainedOwnerEnvironmentId, P as bindScopeRetainedOwnerProvider, Pt as meterUsageEvent, Qi as withTimeout, Qr as isNoEntError, R as scopeRetainedOwnerPriorSpend, Rr as controlProfileMaterialization, Rt as WORKER_TRACE_PROPAGATION, S as meterRuntimeOwnedProviderAttempt, T as scopeOwnerExecutorNodeContext, Ur as promptModelProfileMaterialization, Vr as profileMaterializationAxes$1, Yr as unsupportedProfileDimensions, Zi as unmeteredSpend, Zr as worktreeCliProfileMaterialization, _ as assertRecursiveReservationPolicy, _i as runtimeOwnedPendingExecutorMaterialization, an as bridgeAdmissionRefusal, b as deriveNodeExecutionIdentity, ca as teardownExecutor, d as defaultUnmetContractSteer, di as providerAttemptEvidence, dn as bridgeRuntimeAttachmentsKey, dr as createOtelExporter, ea as addResourceSpend, ei as prepareJsonlAppend, f as runDriverWithRetry, fi as recordRuntimeOwnedDriveHarnessProviderEvidence, fn as bridgeStopSignalKey, ft as snapshotExecutorConfig, gi as runtimeOwnedExecutorProviderEvidence, h as isDriverSpec, hi as runtimeOwnedExecutorMaterialization, ii as attestRuntimeOwnedScopeOwner, in as executorFailure, jn as resolveAgentEnvironmentProvider, l as HarnessTurnFailedError, la as teardownSurfaces, m as driverExecutorFactory, mi as runtimeOwnedExecutorExecutionBinding, mr as generateSpanId, n as createSupervisor, na as withBudgetResources, o as runFinalizer, oa as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, on as bridgeModelRouteRefusal, ot as bindReusableExecutorExecutionId, p as driverChild, pi as runtimeOwnedDriveHarnessProviderEvidence, qi as sleep, qn as linkAbort, qr as renderUnsupported, qt as createInbox, r as bestDelivered, s as runTree, si as inheritRuntimeOwnedExecutorAttestation, st as captureReusableExecutorConfig, t as createRootHandle, ta as resourceTelemetry, ti as readCommittedJsonLines, tr as contentAddress, tt as errMessage, ut as createExecutor, v as beginScopeOwnerAttempt, vi as runtimeOwnedScopeOwnerRuntime, vr as toOtelAttributes, w as restoreScopeOwnerAcceptedExecution, wi as detachedSnapshot, x as meterRuntimeOwnedAccounting, z as scopeRetainedOwnerResourceReader, zi as addSpend, zr as defineProfileMaterializationContract } from "./supervisor-yavsoQQo.js";
1
+ import { B as scopeRetainedOwnerContext, Bn as retainedExecutorSeamKey, Br as assertProfileMaterialization, Bt as spendFromUsageTotals, C as meterRuntimeOwnedAccounting, D as scopeOwnerExecutorNodeContext, Di as detachedSnapshot, E as restoreScopeOwnerAcceptedExecution, En as routerBrain, F as bindScopeRetainedOwnerEnvironmentId, Ft as assertValidBudget, Gr as promptControlProfileMaterialization, H as scopeRetainedOwnerResourceReader, Hi as addSpend, Hr as defineProfileMaterializationContract, I as bindScopeRetainedOwnerProvider, Jn as RunCancellationReason, Kr as promptModelProfileMaterialization, L as consumeScopeRetainedOwnerResult, Lt as meterUsageEvent, Pn as resolveAgentEnvironmentProvider, Qr as unsupportedProfileDimensions, R as prepareScopeRetainedOwnerTask, Rt as newUsageTotals, S as deriveNodeExecutionIdentity, T as recordScopeOwnerMaterialization, U as scopeRetainedOwnerResult, Ur as fullProfileMaterialization, V as scopeRetainedOwnerPriorSpend, Vr as controlProfileMaterialization, Vt as WORKER_TRACE_PROPAGATION, Wr as profileMaterializationAxes$1, Xi as sleep, Xn as linkAbort, Xr as renderUnsupported, Xt as createInbox, Zn as runAbortable, _ as isDriverSpec, _i as runtimeOwnedExecutorExecutionBinding, _r as generateSpanId, aa as withBudgetResources, b as beginScopeOwnerAttempt, bi as runtimeOwnedPendingExecutorMaterialization, cn as bridgeAdmissionRefusal, da as teardownExecutor, ea as unmeteredSpend, ei as worktreeCliProfileMaterialization, f as defaultUnmetContractSteer, fa as teardownSurfaces, g as driverExecutorFactory, gi as runtimeOwnedDriveHarnessProviderEvidence, h as driverChild, hi as recordRuntimeOwnedDriveHarnessProviderEvidence, hn as bridgeStopSignalKey, ht as snapshotExecutorConfig, ia as resourceTelemetry, ii as readCommittedJsonLines, ir as contentAddress, it as errMessage, la as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, ln as bridgeModelRouteRefusal, lt as bindReusableExecutorExecutionId, m as summarizeDriverAttempts, mi as providerAttemptEvidence, mn as bridgeRuntimeAttachmentsKey, mr as createOtelExporter, n as createSupervisor, na as zeroSpend, o as runFinalizer, p as runDriverWithRetry, pt as createExecutor, r as bestDelivered, ra as addResourceSpend, ri as prepareJsonlAppend, s as runTree, si as attestRuntimeOwnedScopeOwner, sn as executorFailure, t as createRootHandle, ta as withTimeout, ti as isNoEntError, u as HarnessTurnFailedError, ui as inheritRuntimeOwnedExecutorAttestation, ut as captureReusableExecutorConfig, vi as runtimeOwnedExecutorMaterialization, w as meterRuntimeOwnedProviderAttempt, xi as runtimeOwnedScopeOwnerRuntime, xr as toOtelAttributes, y as assertRecursiveReservationPolicy, yi as runtimeOwnedExecutorProviderEvidence, z as reconcileScopeRetainedOwnerEnvironment, zn as registerRetainedExecutorPreparation } from "./supervisor-BGGvnXvV.js";
2
2
  import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError } from "./errors-DodWX-cb.js";
3
3
  import { a as concreteProfileModel, c as profileModelExecutionSettings, d as agentHarness, f as harnessRunsAgent, n as assertModelAllowed, o as enforceTokenLimits, r as assertProfileModelsAllowed, s as profileBridgeWireModel, t as assertExecutableAgentProfile } from "./model-policy-BbSCSak0.js";
4
4
  import { t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
5
5
  import { n as assertNoSymlinkDescendant } from "./durable-file-DWQA4ooo.js";
6
6
  import { n as createStdioToolServer, t as PROTOCOL_VERSION } from "./tool-server-x9NEhvHZ.js";
7
- import { D as coordinationVerbNames, S as watchRunCancellation, c as createProgressTracker, d as progressStop, k as createCoordinationToolsForManager, n as createSteerAcknowledger, r as driverAgent, t as createCancelAcknowledger, v as createFileRunContext, w as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, x as applyRunCancellation, y as createInMemoryRunContext } from "./coordination-driver-LmDxHvAO.js";
7
+ import { D as coordinationVerbNames, S as watchRunCancellation, c as createProgressTracker, d as progressStop, k as createCoordinationToolsForManager, n as createSteerAcknowledger, r as driverAgent, t as createCancelAcknowledger, v as createFileRunContext, w as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, x as applyRunCancellation, y as createInMemoryRunContext } from "./coordination-driver-COGC8FK2.js";
8
8
  import { k as writeRunCancellation, o as readRunCancelRequest, s as readRunCancellation } from "./run-layout-vwd4SwX_.js";
9
9
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalCandidateJson, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
10
10
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -680,7 +680,9 @@ async function serveCoordinationMcpForManager(opts, lifetime) {
680
680
  const audiences = /* @__PURE__ */ new Set();
681
681
  const paths = /* @__PURE__ */ new Set(["/mcp"]);
682
682
  const ownerReader = opts.spawnResourceReader ?? (opts.spawnResourceRoot === void 0 ? scopeRetainedOwnerResourceReader(opts.scope) : void 0);
683
+ let probeableByName;
683
684
  const coord = createCoordinationToolsForManager({
685
+ resolveProbeTool: (name) => probeableByName?.get(name),
684
686
  scope: opts.scope,
685
687
  blobs: opts.blobs,
686
688
  makeWorkerAgent: opts.makeWorkerAgent,
@@ -731,6 +733,7 @@ async function serveCoordinationMcpForManager(opts, lifetime) {
731
733
  if (tool === void 0) throw new ValidationError(`serveCoordinationMcp: requested tool ${JSON.stringify(name)} is unavailable`);
732
734
  return tool;
733
735
  });
736
+ probeableByName = new Map(servedTools.map((tool) => [tool.name, tool]));
734
737
  const mcp = createStdioToolServer({
735
738
  serverName: "coordination",
736
739
  serverVersion: "1",
@@ -1227,6 +1230,90 @@ function truncate(value) {
1227
1230
  return value.length > MAX_DETAIL_CHARS ? `${value.slice(0, MAX_DETAIL_CHARS)}…` : value;
1228
1231
  }
1229
1232
  //#endregion
1233
+ //#region src/runtime/supervise/reentry.ts
1234
+ /** Continuity when nothing is proven: compose the full state. */
1235
+ const UNPROVEN_CONTINUITY = Object.freeze({
1236
+ session: "new",
1237
+ environment: "unknown",
1238
+ workspace: "unknown"
1239
+ });
1240
+ /** Compose the task for one re-entered drive. */
1241
+ function composeReentryTask(input) {
1242
+ const { reentry, continuity, state } = input;
1243
+ if (reentry.reason === "unmet-contract" && continuity.session === "continued") {
1244
+ const changes = stateLines(state, false);
1245
+ return [reentry.steer, ...changes.length > 0 ? ["", ...changes] : []].join("\n");
1246
+ }
1247
+ return [
1248
+ `You are re-entering a run that is already in progress (driver attempt ${input.attempt}). This is the same run and the same objective, not a new one.`,
1249
+ whyLine(reentry),
1250
+ environmentLine(continuity),
1251
+ "",
1252
+ "## Objective",
1253
+ "",
1254
+ "This is the original task of the run, unchanged:",
1255
+ "",
1256
+ taskText(input.originalTask),
1257
+ "",
1258
+ "## Completion check",
1259
+ "",
1260
+ input.contract === void 0 || input.contract.trim().length === 0 ? "The run ends when submit_result passes the independent check." : `The run ends when submit_result passes the independent check. It expects: ${input.contract.trim()}`,
1261
+ ...reentry.reason === "unmet-contract" ? [
1262
+ "",
1263
+ "What is still unmet:",
1264
+ "",
1265
+ reentry.steer
1266
+ ] : [],
1267
+ "",
1268
+ "## Run state, from the coordinator",
1269
+ "",
1270
+ ...stateLines(state, true),
1271
+ "",
1272
+ "## What to do now",
1273
+ "",
1274
+ "Continue the run from this state.",
1275
+ "Receive the waiting events with await_event, and read the output of every settled worker before you spawn anything new.",
1276
+ "Do not spawn a replacement for a worker that is running or has settled.",
1277
+ "Your coordination tools are served by the same coordinator as before, and the state above comes from it."
1278
+ ].join("\n");
1279
+ }
1280
+ /**
1281
+ * Why the driver is back, in one clause. The failure's own text stays in the attempt records and
1282
+ * never reaches the driver: measured 2026-09-11, a continuation told the details of a provider
1283
+ * failure spent two of its first four children probing the infrastructure, while its peer, told
1284
+ * only what to continue, spent all forty-five on the research.
1285
+ */
1286
+ function whyLine(reentry) {
1287
+ return reentry.reason === "unmet-contract" ? `Your previous turn ended with the completion check unmet (re-prompt ${reentry.reprompt}).` : `Your previous turn ended before it finished (retry ${reentry.retry}); the run itself is intact.`;
1288
+ }
1289
+ function environmentLine(continuity) {
1290
+ if (continuity.environment === "same") return `You run in the same environment as before${continuity.environmentId === void 0 ? "" : ` (${continuity.environmentId})`}, and your files are where you left them.`;
1291
+ if (continuity.environment === "replaced") return `Your previous environment${continuity.previousEnvironmentId === void 0 ? "" : ` (${continuity.previousEnvironmentId})`} is gone, and you run in a new one. ` + (continuity.workspace === "kept" ? "Its files were carried over." : "Files you wrote there are not here. The coordinator and the knowledge store kept everything below.");
1292
+ return "You may be in a new environment. Check for files before you rely on them; the coordinator kept everything below.";
1293
+ }
1294
+ function stateLines(state, full) {
1295
+ const lines = [];
1296
+ if (full || state.journalRows > state.journalReadTo) lines.push(`Journal: ${state.journalRows} rows. You last read up to row ${state.journalReadTo}; call read_journal with sinceRow ${state.journalReadTo} to read what happened since, or sinceRow 0 to read the whole run.`);
1297
+ if (state.live.length > 0) lines.push(`Workers running: ${state.live.map((worker) => `${worker.id} (${worker.label}, ${worker.status})`).join("; ")}.`);
1298
+ else if (full) lines.push("Workers running: none.");
1299
+ const settled = full ? state.settled : state.settled.filter((worker) => !worker.delivered);
1300
+ if (settled.length > 0) lines.push(`Workers settled${full ? "" : " that you have not received"}: ${settled.map((worker) => `${worker.id} (${worker.status}${worker.valid === void 0 ? "" : worker.valid ? ", passed its check" : ", did not pass its check"}${worker.delivered ? "" : ", not yet received"})`).join("; ")}. Read an output with observe_agent and the worker id.`);
1301
+ else if (full) lines.push("Workers settled: none.");
1302
+ if (state.waiting.length > 0) lines.push(`Events waiting for you in await_event: ${state.waiting.length} (${state.waiting.map((event) => event.worker === void 0 ? event.type : `${event.type} from ${event.worker}`).join("; ")}).`);
1303
+ else if (full) lines.push("Events waiting for you in await_event: none.");
1304
+ if (state.unacknowledged.length > 0) lines.push(`Events delivered to a turn that did not finish, so treat them as unread: ${state.unacknowledged.map((event) => `#${event.seq} ${event.type}${event.worker === void 0 ? "" : ` from ${event.worker}`}`).join("; ")}. Pass their numbers in await_event's acknowledge once you have processed them.`);
1305
+ if (state.lastRejection !== void 0) lines.push(`Your last submit_result was refused: ${state.lastRejection.reason}`);
1306
+ return lines;
1307
+ }
1308
+ function taskText(task) {
1309
+ if (typeof task === "string") return task;
1310
+ try {
1311
+ return JSON.stringify(task, null, 2) ?? String(task);
1312
+ } catch {
1313
+ return String(task);
1314
+ }
1315
+ }
1316
+ //#endregion
1230
1317
  //#region src/runtime/supervise/root-stream.ts
1231
1318
  /**
1232
1319
  * The root manager's own provider stream, retained where Runtime owns it.
@@ -1870,49 +1957,89 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1870
1957
  contract: !contractDeclared ? "none" : submitted || candidate !== void 0 ? "met" : "unmet"
1871
1958
  };
1872
1959
  };
1873
- await runDriverWithRetry({
1874
- drive: async (attempt, reentry) => {
1875
- candidate = void 0;
1876
- if (deps.controlDir !== void 0 && deps.abortRun !== void 0) applyRunCancellation(deps.controlDir, deps.abortRun, () => (/* @__PURE__ */ new Date()).toISOString());
1877
- scope.signal.throwIfAborted();
1878
- beginScopeOwnerAttempt(scope, attempt);
1879
- harnessInvocationActive = true;
1880
- try {
1881
- await driveHarness({
1882
- profile: providerProfile,
1883
- authoredProfile: stableProfile,
1884
- ...profilePrompt !== void 0 ? { systemPrompt: profilePrompt } : {},
1885
- task: reentry === void 0 ? task : reentry.steer,
1886
- scope,
1887
- coordinationMcpUrl: mcp.url,
1888
- coordinationMcpHeaders: mcp.headers,
1889
- stopSignal: stopController.signal,
1890
- coordinationTools
1960
+ const loopRecords = [];
1961
+ let environmentReplacements = 0;
1962
+ const describe = deps.deliverable?.describe;
1963
+ const settleLoop = () => {
1964
+ const stopReason = controls.stopReason() ?? progressStopReason;
1965
+ const closedBy = mcp.submittedResult() ? "result-accepted" : controls.blocked() !== void 0 ? "blocked" : mcp.isStopped() ? "stop" : progressStopReason !== void 0 ? "stop-rule" : void 0;
1966
+ deps.onDriverLoopSettled?.({
1967
+ ...summarizeDriverAttempts(loopRecords),
1968
+ environmentReplacements,
1969
+ ...closedBy === void 0 ? {} : { closedBy },
1970
+ ...stopReason === void 0 ? {} : { stopReason }
1971
+ });
1972
+ };
1973
+ try {
1974
+ await runDriverWithRetry({
1975
+ drive: async (attempt, reentry) => {
1976
+ candidate = void 0;
1977
+ if (deps.controlDir !== void 0 && deps.abortRun !== void 0) applyRunCancellation(deps.controlDir, deps.abortRun, () => (/* @__PURE__ */ new Date()).toISOString());
1978
+ scope.signal.throwIfAborted();
1979
+ beginScopeOwnerAttempt(scope, attempt);
1980
+ controls.beginDriverAttempt(attempt);
1981
+ const compose = reentry === void 0 ? void 0 : (continuity) => composeReentryTask({
1982
+ originalTask: task,
1983
+ ...describe === void 0 ? {} : { contract: describe },
1984
+ reentry,
1985
+ continuity,
1986
+ state: controls.reentryState(),
1987
+ attempt
1891
1988
  });
1892
- } catch (error) {
1893
- if (!mcp.submittedResult() && !mcp.isStopped()) throw error;
1894
- } finally {
1895
- harnessInvocationActive = false;
1896
- }
1897
- if (contractDeclared && !mcp.submittedResult()) {
1898
- await mcp.drainResolved();
1899
- candidate = await finalize();
1989
+ harnessInvocationActive = true;
1990
+ let completed = false;
1991
+ try {
1992
+ await driveHarness({
1993
+ profile: providerProfile,
1994
+ authoredProfile: stableProfile,
1995
+ ...profilePrompt !== void 0 ? { systemPrompt: profilePrompt } : {},
1996
+ task: compose === void 0 ? task : compose(UNPROVEN_CONTINUITY),
1997
+ ...compose === void 0 ? {} : { reentry: {
1998
+ compose,
1999
+ onContinuity: (continuity) => {
2000
+ if (continuity.environment === "replaced") environmentReplacements += 1;
2001
+ }
2002
+ } },
2003
+ scope,
2004
+ coordinationMcpUrl: mcp.url,
2005
+ coordinationMcpHeaders: mcp.headers,
2006
+ stopSignal: stopController.signal,
2007
+ coordinationTools
2008
+ });
2009
+ completed = true;
2010
+ } catch (error) {
2011
+ if (!mcp.submittedResult() && !mcp.isStopped()) throw error;
2012
+ completed = true;
2013
+ } finally {
2014
+ harnessInvocationActive = false;
2015
+ if (completed) await controls.endDriverAttempt("completed");
2016
+ else await controls.endDriverAttempt("failed").catch(() => void 0);
2017
+ }
2018
+ if (contractDeclared && !mcp.submittedResult()) {
2019
+ await mcp.drainResolved();
2020
+ candidate = await finalize();
2021
+ }
2022
+ },
2023
+ progress: readProgress,
2024
+ budget: () => scope.budget,
2025
+ signal: scope.signal,
2026
+ ...deps.driverRetry ? { policy: deps.driverRetry } : {},
2027
+ ...repromptEnabled ? { reprompt: {
2028
+ maxReprompts,
2029
+ ...deps.deliverable?.describe === void 0 ? {} : { describe: deps.deliverable.describe },
2030
+ onUnmetContract: async (context) => {
2031
+ if (mcp.isStopped() || progressStopReason !== void 0) return "stop";
2032
+ return await deps.onUnmetContract?.(context) ?? { steer: defaultUnmetContractSteer(context) };
2033
+ }
2034
+ } } : {},
2035
+ onAttempt: async (record) => {
2036
+ loopRecords.push(record);
2037
+ await deps.onDriverAttempt?.(record);
1900
2038
  }
1901
- },
1902
- progress: readProgress,
1903
- budget: () => scope.budget,
1904
- signal: scope.signal,
1905
- ...deps.driverRetry ? { policy: deps.driverRetry } : {},
1906
- ...repromptEnabled ? { reprompt: {
1907
- maxReprompts,
1908
- ...deps.deliverable?.describe === void 0 ? {} : { describe: deps.deliverable.describe },
1909
- onUnmetContract: async (context) => {
1910
- if (mcp.isStopped()) return "stop";
1911
- return await deps.onUnmetContract?.(context) ?? { steer: defaultUnmetContractSteer(context) };
1912
- }
1913
- } } : {},
1914
- ...deps.onDriverAttempt ? { onAttempt: deps.onDriverAttempt } : {}
1915
- });
2039
+ });
2040
+ } finally {
2041
+ settleLoop();
2042
+ }
1916
2043
  if (!contractDeclared) await mcp.drainResolved();
1917
2044
  const submitted = mcp.submittedResult();
1918
2045
  if (submitted) {
@@ -2637,7 +2764,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
2637
2764
  const baseFactory = createExecutor(boundBackend);
2638
2765
  const ownerRuntime = boundBackend.backend === "provider" ? boundBackend.runtime ?? resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry).name : "cli";
2639
2766
  let activeExecutor;
2640
- const drive = async ({ profile, authoredProfile, task, scope, coordinationMcpUrl, coordinationMcpHeaders, stopSignal, coordinationTools }) => {
2767
+ const drive = async ({ profile, authoredProfile, task, scope, coordinationMcpUrl, coordinationMcpHeaders, stopSignal, coordinationTools, reentry }) => {
2641
2768
  const retainedOwner = boundBackend.backend === "provider" ? scopeRetainedOwnerContext(scope) : void 0;
2642
2769
  if (retainedOwner && boundBackend.backend === "provider") {
2643
2770
  bindScopeRetainedOwnerProvider(scope, resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry));
@@ -2647,7 +2774,13 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
2647
2774
  return execution?.kind === "environment" ? execution.id : void 0;
2648
2775
  });
2649
2776
  }
2650
- const originalTask = retainedOwner ? await prepareScopeRetainedOwnerTask(scope, task) : task;
2777
+ let driveTask = task;
2778
+ if (reentry !== void 0) {
2779
+ const continuity = await reentryContinuity(boundBackend, scope, retainedOwner !== void 0);
2780
+ reentry.onContinuity?.(continuity);
2781
+ driveTask = reentry.compose(continuity);
2782
+ }
2783
+ const originalTask = retainedOwner ? await prepareScopeRetainedOwnerTask(scope, driveTask) : driveTask;
2651
2784
  const acceptedOwner = retainedOwner ? await scopeRetainedOwnerResult(scope) : void 0;
2652
2785
  if (acceptedOwner) {
2653
2786
  await restoreScopeOwnerAcceptedExecution(scope);
@@ -3009,6 +3142,41 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3009
3142
  drive.progress = () => activeExecutor?.progress?.();
3010
3143
  return attestRuntimeOwnedScopeOwner(drive, ownerRuntime);
3011
3144
  }
3145
+ /**
3146
+ * What the next drive of a harness-brained manager continues, as far as its backend proves it.
3147
+ *
3148
+ * A bridge reattaches the harness session by its durable execution id. A retained provider owner
3149
+ * continues in the environment it last used while the provider still holds it, and a deliberate
3150
+ * later invocation there continues the same harness session. A provider without retained control
3151
+ * creates a new environment for every drive and releases the old one. Anything else is unproven.
3152
+ */
3153
+ async function reentryContinuity(backend, scope, retainedOwner) {
3154
+ if (backend.backend === "bridge") return {
3155
+ session: "continued",
3156
+ environment: "same",
3157
+ workspace: "kept"
3158
+ };
3159
+ if (backend.backend !== "provider" || !retainedOwner) return UNPROVEN_CONTINUITY;
3160
+ if ((await resolveAgentEnvironmentProvider(backend.provider, backend.registry).capabilities()).retainedControl === void 0) return {
3161
+ session: "new",
3162
+ environment: "replaced",
3163
+ workspace: "lost"
3164
+ };
3165
+ const environment = await reconcileScopeRetainedOwnerEnvironment(scope);
3166
+ if (environment.state === "live") return {
3167
+ session: "continued",
3168
+ environment: "same",
3169
+ environmentId: environment.environmentId,
3170
+ workspace: "kept"
3171
+ };
3172
+ if (environment.state === "lost") return {
3173
+ session: "new",
3174
+ environment: "replaced",
3175
+ previousEnvironmentId: environment.environmentId,
3176
+ workspace: "lost"
3177
+ };
3178
+ return UNPROVEN_CONTINUITY;
3179
+ }
3012
3180
  function isAsyncIterable(value) {
3013
3181
  return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
3014
3182
  }
@@ -3775,6 +3943,7 @@ function superviseInternal(profile, task, opts, testBrain) {
3775
3943
  durableCancellation.abort(request === void 0 ? new Error(reason) : new RunCancellationReason(request.source, reason, request.operationId));
3776
3944
  };
3777
3945
  const workerFactory = makeWorkerAgent;
3946
+ let rootContinuation;
3778
3947
  const start = async () => {
3779
3948
  await verifyProfilePromotions(profileTable);
3780
3949
  const priorCoordination = log ? await log.load(runId, rootOwnerId) : void 0;
@@ -3790,6 +3959,9 @@ function superviseInternal(profile, task, opts, testBrain) {
3790
3959
  onProviderModel(model) {
3791
3960
  rootProviderModels.push(model);
3792
3961
  },
3962
+ onDriverLoopSettled(record) {
3963
+ rootContinuation = record;
3964
+ },
3793
3965
  ...priorCoordination && (priorCoordination.questions.length > 0 || priorCoordination.findings.length > 0 || priorCoordination.continuations.length > 0 || priorCoordination.deliveryEvidence.length > 0 || priorCoordination.records.some((record) => record.event.type === "submission")) ? { priorCoordination } : {},
3794
3966
  ...finalizer ? { finalizer } : {},
3795
3967
  ...options.coordination && isExternalSupervisor(canonicalProfile) ? { coordination: options.coordination } : {},
@@ -3904,7 +4076,8 @@ function superviseInternal(profile, task, opts, testBrain) {
3904
4076
  return {
3905
4077
  ...result,
3906
4078
  rootProviderModel,
3907
- ...rootStream === void 0 ? {} : { rootStream }
4079
+ ...rootStream === void 0 ? {} : { rootStream },
4080
+ ...rootContinuation === void 0 ? {} : { continuation: rootContinuation }
3908
4081
  };
3909
4082
  };
3910
4083
  if (!recorder) return settle();
@@ -3951,6 +4124,6 @@ function rootProviderModelEvidenceFromExecution(evidence) {
3951
4124
  return evidence ?? rootProviderModelEvidence([]);
3952
4125
  }
3953
4126
  //#endregion
3954
- export { mapExecutorResult as S, readRootStream as _, superviseWithTestBrain as a, serveCoordinationMcp as b, resolveWorkerSpawnRetry as c, assertCoordinationBinding as d, coordinationProfileToolPrefix as f, ROOT_STREAM_FILE as g, supervisorAgentWithTestBrain as h, superviseRootProfile as i, retryPreSpawnRefusals as l, supervisorAgent as m, profileGuidanceComposer as n, workerFromBackend as o, resolveSupervisorProfile as p, supervise as r, isPreSpawnExecutorFailure as s, DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY as t, withWorkerSpawnRetry as u, readRootStreamReceipt as v, gateOnDeliverable as x, createSupervisorSpanRecorder as y };
4127
+ export { gateOnDeliverable as C, serveCoordinationMcp as S, readRootStream as _, superviseWithTestBrain as a, composeReentryTask as b, resolveWorkerSpawnRetry as c, assertCoordinationBinding as d, coordinationProfileToolPrefix as f, ROOT_STREAM_FILE as g, supervisorAgentWithTestBrain as h, superviseRootProfile as i, retryPreSpawnRefusals as l, supervisorAgent as m, profileGuidanceComposer as n, workerFromBackend as o, resolveSupervisorProfile as p, supervise as r, isPreSpawnExecutorFailure as s, DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY as t, withWorkerSpawnRetry as u, readRootStreamReceipt as v, mapExecutorResult as w, createSupervisorSpanRecorder as x, UNPROVEN_CONTINUITY as y };
3955
4128
 
3956
- //# sourceMappingURL=supervise-1QzYAyS2.js.map
4129
+ //# sourceMappingURL=supervise-BeAI8-On.js.map