@tangle-network/agent-runtime 0.299.3 → 0.301.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 (62) hide show
  1. package/dist/{activation-Bhp8dYV5.d.ts → activation-CRgEJutr.d.ts} +3 -3
  2. package/dist/{activation-DqWmWTyB.js → activation-V6aaOlZV.js} +2 -2
  3. package/dist/{activation-DqWmWTyB.js.map → activation-V6aaOlZV.js.map} +1 -1
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-DzTvehd6.js → coordination-driver-vNrdQBSH.js} +317 -211
  7. package/dist/coordination-driver-vNrdQBSH.js.map +1 -0
  8. package/dist/{delegate-qNq_wnQo.js → delegate-B-jFJcbW.js} +5 -5
  9. package/dist/delegate-B-jFJcbW.js.map +1 -0
  10. package/dist/durable.d.ts +3 -3
  11. package/dist/durable.js +116 -4
  12. package/dist/durable.js.map +1 -1
  13. package/dist/{graph-DN0lm24q.js → graph-Dwv_hQB_.js} +5 -5
  14. package/dist/graph-Dwv_hQB_.js.map +1 -0
  15. package/dist/{improvement-cycle-D6cPLi6k.js → improvement-cycle-Cf37Kexd.js} +3 -3
  16. package/dist/{improvement-cycle-D6cPLi6k.js.map → improvement-cycle-Cf37Kexd.js.map} +1 -1
  17. package/dist/{index-DonXCBsy.d.ts → index-CxBVmgqL.d.ts} +207 -74
  18. package/dist/index.d.ts +6 -6
  19. package/dist/index.js +7 -7
  20. package/dist/intelligence.d.ts +3 -3
  21. package/dist/intelligence.js +4 -4
  22. package/dist/kernel.d.ts +4 -4
  23. package/dist/kernel.js +9 -9
  24. package/dist/{loop-runner-bin-DKfdYEK-.js → loop-runner-bin-C8MI8N1A.js} +3 -3
  25. package/dist/{loop-runner-bin-DKfdYEK-.js.map → loop-runner-bin-C8MI8N1A.js.map} +1 -1
  26. package/dist/{loop-runner-bin-63H4stv1.d.ts → loop-runner-bin-DiTNiJNs.d.ts} +3 -3
  27. package/dist/loop-runner-bin.d.ts +1 -1
  28. package/dist/loop-runner-bin.js +1 -1
  29. package/dist/mcp/bin.js +3 -3
  30. package/dist/mcp/index.d.ts +6 -6
  31. package/dist/mcp/index.js +5 -5
  32. package/dist/{openai-tools-DvR82zEo.d.ts → openai-tools-BeogJ6V8.d.ts} +2 -2
  33. package/dist/profiles.d.ts +2 -2
  34. package/dist/{provision-supervisor-IXBlLHE0.js → provision-supervisor-CS0fBIhp.js} +13 -24
  35. package/dist/provision-supervisor-CS0fBIhp.js.map +1 -0
  36. package/dist/{runtime-CZR5n7Zy.js → runtime-6VPSJVeg.js} +28 -36
  37. package/dist/runtime-6VPSJVeg.js.map +1 -0
  38. package/dist/{search-method-DvU-fc-f.js → search-method-wTTS7mGG.js} +2 -2
  39. package/dist/{search-method-DvU-fc-f.js.map → search-method-wTTS7mGG.js.map} +1 -1
  40. package/dist/{server-CSSopQyk.js → server-BfHD5iLD.js} +3 -3
  41. package/dist/{server-CSSopQyk.js.map → server-BfHD5iLD.js.map} +1 -1
  42. package/dist/{stream-agent-turn-I3bb0eqF.d.ts → stream-agent-turn-B1ipFtOc.d.ts} +4 -2
  43. package/dist/{substrate-UjsxukjZ.d.ts → substrate-DKBMd0Dl.d.ts} +2 -2
  44. package/dist/{supervise-Bu2rNYsK.js → supervise-BJrEC2Mh.js} +202 -64
  45. package/dist/supervise-BJrEC2Mh.js.map +1 -0
  46. package/dist/{supervisor-CQSu5XGl.js → supervisor-DA_nvF-h.js} +563 -181
  47. package/dist/supervisor-DA_nvF-h.js.map +1 -0
  48. package/dist/testing.d.ts +2 -2
  49. package/dist/testing.js +12 -12
  50. package/dist/tui/index.d.ts +1 -1
  51. package/dist/tui/index.js +1 -1
  52. package/dist/{types-C73caP0U.d.ts → types-jD9mNnJM.d.ts} +61 -11
  53. package/package.json +1 -1
  54. package/skills/profile-authoring/SKILL.md +3 -3
  55. package/skills/supervise/SKILL.md +2 -2
  56. package/dist/coordination-driver-DzTvehd6.js.map +0 -1
  57. package/dist/delegate-qNq_wnQo.js.map +0 -1
  58. package/dist/graph-DN0lm24q.js.map +0 -1
  59. package/dist/provision-supervisor-IXBlLHE0.js.map +0 -1
  60. package/dist/runtime-CZR5n7Zy.js.map +0 -1
  61. package/dist/supervise-Bu2rNYsK.js.map +0 -1
  62. package/dist/supervisor-CQSu5XGl.js.map +0 -1
@@ -1,9 +1,9 @@
1
- import { $ as bindScopeRetainedOwnerProvider, $n as parseWorkerToolTraceArtifact, A as driverExecutorFactory, Aa as addResourceSpend, Ai as prepareJsonlAppend, An as resolveAgentEnvironmentProvider, Ar as contentAddress, At as createExecutor, B as recordScopeOwnerDriverAttempt, C as createContinuationKeeper, Ca as sleep, Cr as runAbortable, Da as unmeteredSpend, Dr as readHarnessTranscript, Dt as captureReusableExecutorConfig, Ei as unsupportedProfileDimensions, Er as persistHarnessTranscript, Et as bindReusableExecutorExecutionId, F as beginScopeOwnerAttempt, Gi as runtimeOwnedExecutorMaterialization, H as recordScopeOwnerPause, Hi as recordRuntimeOwnedDriveHarnessProviderEvidence, Hr as createOtelExporter, Ia as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, In as registerRetainedExecutorPreparation, It as createRouterTranscript, Ji as runtimeOwnedScopeOwnerRuntime, Jr as toOtelAttributes, Ki as runtimeOwnedExecutorProviderEvidence, L as deriveNodeExecutionIdentity, Li as inheritRuntimeOwnedExecutorAttestation, Ln as retainedExecutorSeamKey, Ma as withBudgetResources, Mt as snapshotExecutorConfig, Oa as withTimeout, Oi as worktreeCliProfileMaterialization, P as assertRecursiveReservationPolicy, Pi as attestRuntimeOwnedScopeOwner, Q as bindScopeRetainedOwnerEnvironmentId, R as meterRuntimeOwnedAccounting, Ra as teardownExecutor, Rt as WORKER_TRACE_PROPAGATION, Sr as linkAbort, U as restoreScopeOwnerAcceptedExecution, Ui as runtimeOwnedDriveHarnessProviderEvidence, V as recordScopeOwnerMaterialization, Vi as providerAttemptEvidence, W as scopeOwnerExecutorNodeContext, Wi as runtimeOwnedExecutorExecutionBinding, Wr as generateSpanId, _ as CheckUnavailableError, _i as fullProfileMaterialization, an as bridgeModelRouteRefusal, at as scopeRetainedOwnerPriorSpend, b as bestComposite, bi as promptModelProfileMaterialization, br as RunCancellationReason, c as runTree, ct as scopeRetainedOwnerResult, dn as bridgeStopSignalKey, ea as detachedSnapshot, et as consumeScopeRetainedOwnerResult, f as runDriverWithRetry, gi as defineProfileMaterializationContract, h as CONTINUATIONS_DIR, ha as addSpend, hi as controlProfileMaterialization, i as bestDelivered, in as bridgeAdmissionRefusal, ir as assertValidBudget, it as scopeRetainedOwnerContext, j as isDriverSpec, ja as resourceTelemetry, ji as readCommittedJsonLines, k as driverChild, ka as zeroSpend, ki as isNoEntError, lr as spendFromUsageTotals, mi as assertProfileMaterialization, n as createRootHandle, nt as prepareScopeRetainedOwnerTask, or as meterUsageEvent, ot as scopeRetainedOwnerResourceReader, p as summarizeDriverAttempts, qi as runtimeOwnedPendingExecutorMaterialization, qt as createInbox, r as createSupervisor, rt as reconcileScopeRetainedOwnerEnvironment, s as runFinalizer, sr as newUsageTotals, st as scopeRetainedOwnerRestorePoint, tr as executorFailure, tt as noteScopeRetainedOwnerCoordination, u as HarnessTurnFailedError, un as bridgeRuntimeAttachmentsKey, ur as errMessage, v as admitContinuationPolicy, vi as profileMaterializationAxes$1, wi as renderUnsupported, wn as routerBrain, x as checkVerdictOf, yi as promptControlProfileMaterialization, z as meterRuntimeOwnedProviderAttempt, za as teardownSurfaces } from "./supervisor-CQSu5XGl.js";
1
+ import { $ as bindScopeRetainedOwnerEnvironmentId, $n as parseWorkerToolTraceArtifact, A as driverExecutorFactory, Aa as withTimeout, Ai as worktreeCliProfileMaterialization, An as resolveAgentEnvironmentProvider, B as recordScopeOwnerDriverAttempt, Ba as teardownExecutor, Bt as WORKER_TRACE_PROPAGATION, C as createContinuationKeeper, Ei as renderUnsupported, F as beginScopeOwnerAttempt, Gi as runtimeOwnedDriveHarnessProviderEvidence, H as recordScopeOwnerPause, Ii as attestRuntimeOwnedScopeOwner, In as registerRetainedExecutorPreparation, Ji as runtimeOwnedExecutorProviderEvidence, Ki as runtimeOwnedExecutorExecutionBinding, Kr as generateSpanId, L as deriveNodeExecutionIdentity, Ln as retainedExecutorSeamKey, Ma as addResourceSpend, Mi as prepareJsonlAppend, Mr as contentAddress, Mt as createExecutor, Na as resourceTelemetry, Ni as readCommittedJsonLines, Oi as unsupportedProfileDimensions, Or as persistHarnessTranscript, Ot as bindReusableExecutorExecutionId, P as assertRecursiveReservationPolicy, Pa as withBudgetResources, Pt as snapshotExecutorConfig, Q as beginScopeRetainedOwnerDrive, R as meterRuntimeOwnedAccounting, Ra as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, Rt as createRouterTranscript, Si as promptModelProfileMaterialization, Sr as RunCancellationReason, Ta as sleep, Tr as runAbortable, U as restoreScopeOwnerAcceptedExecution, Ui as providerAttemptEvidence, V as recordScopeOwnerMaterialization, Va as teardownSurfaces, W as scopeOwnerExecutorNodeContext, Wi as recordRuntimeOwnedDriveHarnessProviderEvidence, Wr as createOtelExporter, Xi as runtimeOwnedScopeOwnerRuntime, Xr as toOtelAttributes, Yi as runtimeOwnedPendingExecutorMaterialization, Yt as createInbox, _ as CheckUnavailableError, _a as addSpend, _i as controlProfileMaterialization, at as scopeRetainedOwnerContext, b as bestComposite, bi as profileMaterializationAxes$1, c as runTree, ct as scopeRetainedOwnerRestorePoint, dr as bridgeStopSignalKey, et as bindScopeRetainedOwnerProvider, f as runDriverWithRetry, fr as errMessage, gi as assertProfileMaterialization, h as CONTINUATIONS_DIR, i as bestDelivered, in as isLiveNodeStatus, ir as assertValidBudget, it as reconcileScopeRetainedOwnerEnvironment, j as isDriverSpec, ja as zeroSpend, ji as isNoEntError, k as driverChild, ka as unmeteredSpend, kr as readHarnessTranscript, kt as captureReusableExecutorConfig, lr as spendFromUsageTotals, lt as scopeRetainedOwnerResult, n as createRootHandle, na as detachedSnapshot, nt as noteScopeRetainedOwnerCoordination, on as bridgeAdmissionRefusal, or as meterUsageEvent, ot as scopeRetainedOwnerPriorSpend, p as summarizeDriverAttempts, qi as runtimeOwnedExecutorMaterialization, qt as createActivityLog, r as createSupervisor, rt as prepareScopeRetainedOwnerTask, s as runFinalizer, sn as bridgeModelRouteRefusal, sr as newUsageTotals, st as scopeRetainedOwnerResourceReader, tr as executorFailure, tt as consumeScopeRetainedOwnerResult, u as HarnessTurnFailedError, ur as bridgeRuntimeAttachmentsKey, ut as scopeRetainedOwnerTurnEnded, v as admitContinuationPolicy, vi as defineProfileMaterializationContract, wn as routerBrain, wr as linkAbort, x as checkVerdictOf, xi as promptControlProfileMaterialization, yi as fullProfileMaterialization, z as meterRuntimeOwnedProviderAttempt, zi as inheritRuntimeOwnedExecutorAttestation } from "./supervisor-DA_nvF-h.js";
2
2
  import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError } from "./errors-DodWX-cb.js";
3
3
  import { _ as agentHarness, a as concreteProfileModel, c as profileModelExecutionSettings, n as assertModelAllowed, o as enforceTokenLimits, r as assertProfileModelsAllowed, s as profileBridgeWireModel, t as assertExecutableAgentProfile, v as harnessRunsAgent } from "./model-policy-DydyWTQg.js";
4
4
  import { n as assertNoSymlinkDescendant } from "./durable-file-DWQA4ooo.js";
5
5
  import { t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
6
- import { B as withCoordinationAwaitFence, C as applyRunCancellation, E as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, I as COORDINATION_CLIENT_TOOL_TIMEOUT_MS, L as MCP_TOOL_TIMEOUT_HEADER, R as declaredAwaitFenceMs, b as withRunContext, c as createProgressTracker, d as progressStop, j as createCoordinationToolsForManager, k as coordinationVerbNames, n as createSteerAcknowledger, r as driverAgent, t as createCancelAcknowledger, u as plateau, v as createFileRunContext, w as watchRunCancellation, y as createInMemoryRunContext, z as declaredToolTimeoutMs } from "./coordination-driver-DzTvehd6.js";
6
+ import { A as watchRunCancellation, E as withRunContext, I as createCoordinationToolsForManager, P as coordinationVerbNames, T as createInMemoryRunContext, _ as progressStop, c as composeWakeInput, g as plateau, k as applyRunCancellation, l as deadlineWarningAt, m as createProgressTracker, n as createSteerAcknowledger, r as driverAgent, t as createCancelAcknowledger, u as resolveWakePolicy, w as createFileRunContext } from "./coordination-driver-vNrdQBSH.js";
7
7
  import { r as createStdioToolServer, t as PROTOCOL_VERSION } from "./tool-server-Dqer2M4_.js";
8
8
  import { k as writeRunCancellation, o as readRunCancelRequest, s as readRunCancellation } from "./run-layout-DSCWdbX2.js";
9
9
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalCandidateJson, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
@@ -16,6 +16,13 @@ import { isMaterializerHarness } from "@tangle-network/agent-profile-materialize
16
16
  import { ATTR } from "@tangle-network/agent-trace-contract";
17
17
  import { createServer } from "node:http";
18
18
  import { withProfileKb } from "@tangle-network/agent-interface/profile-kb";
19
+ //#region src/mcp/tools/coordination-request-context.ts
20
+ /** The tool-call timeout Runtime asks harnesses to give its coordination server. The Tangle
21
+ * profile materializer writes it as `MCP_TOOL_TIMEOUT` (Claude Code) and `tool_timeout_sec`
22
+ * (Codex) when an attachment declares `metadata.toolTimeoutMs`, so a fenced coordination call
23
+ * that holds its response for its whole fence is never cut off at the 60 s harness default. */
24
+ const COORDINATION_CLIENT_TOOL_TIMEOUT_MS = 3e5;
25
+ //#endregion
19
26
  //#region src/runtime/supervise/completion-gate.ts
20
27
  /**
21
28
  *
@@ -287,12 +294,10 @@ function coordinationHttpHandler(input) {
287
294
  active++;
288
295
  }
289
296
  admitted = true;
290
- const declaredTimeoutMs = declaredToolTimeoutMs(req.headers[MCP_TOOL_TIMEOUT_HEADER]);
291
- const declaredFenceMs = declaredTimeoutMs === void 0 ? void 0 : declaredAwaitFenceMs(declaredTimeoutMs);
292
297
  timer = setTimeout(() => {
293
298
  timedOut = true;
294
299
  reject(executing ? 504 : 408);
295
- }, Math.max(limits.requestTimeoutMs, declaredTimeoutMs ?? 0));
300
+ }, limits.requestTimeoutMs);
296
301
  timer.unref();
297
302
  let size = 0;
298
303
  const chunks = [];
@@ -342,7 +347,7 @@ function coordinationHttpHandler(input) {
342
347
  reject(authorization);
343
348
  return;
344
349
  }
345
- const response = await withCoordinationAwaitFence(declaredFenceMs, () => input.handle(message));
350
+ const response = await input.handle(message);
346
351
  if (!finished) respond(response === null ? 202 : 200, response ?? void 0);
347
352
  await audit(timedOut ? "completed-after-deadline" : "completed", timedOut ? 504 : response === null ? 202 : 200, action);
348
353
  } catch {
@@ -459,25 +464,23 @@ async function preflightPublicCoordination(input) {
459
464
  *
460
465
  * Two rules close that failure:
461
466
  * - Identity. A call joins an existing invocation when its tool name and its RFC 8785 canonical
462
- * arguments match, and that invocation has not yet returned its outcome to a caller. The handler
463
- * is not invoked again. Key order does not matter: the observed retry reordered every key.
464
- * - Fence. A call waits at most `fenceMs` for the outcome. If the handler is still running, the call
465
- * returns a non-error pending result. A later identical call keeps waiting, then returns the value
466
- * or throws the handler's error once the handler settles.
467
+ * arguments match, and that invocation has not yet settled. The handler is not invoked again.
468
+ * Key order does not matter: the observed retry reordered every key.
469
+ * - Fence. A call waits at most `fenceMs` for the outcome. If the handler is still running, the
470
+ * call returns a receipt. The handler keeps running, and its outcome is published to the
471
+ * manager's inbox, where its next wake delivers it. Nothing has to call again to collect it.
467
472
  *
468
- * An invocation's identity ends when a call returns its outcome. The next identical call is a fresh
469
- * run, because equal arguments do not make a call a replay. Code mode's `execute` and Knowledge's
473
+ * An invocation's identity ends when its handler settles. The next identical call is a fresh run,
474
+ * because equal arguments do not make a call a replay: code mode's `execute` and Knowledge's
470
475
  * `knowledge_search` read live state, so their callers repeat identical arguments to get a current
471
476
  * answer. A handler that finishes within the fence therefore behaves exactly as it did unwrapped.
472
- * No escape hatch is needed: the only calls this absorbs are ones whose caller could not have seen
473
- * the outcome.
474
477
  */
475
478
  function singleFlightTools(tools, options) {
476
- const { fenceMs } = options;
479
+ const { fenceMs, receipts } = options;
477
480
  if (!Number.isSafeInteger(fenceMs) || fenceMs <= 0) throw new ValidationError("singleFlightTools: fenceMs must be a positive safe integer");
478
481
  const now = options.now ?? Date.now;
479
482
  const invocations = /* @__PURE__ */ new Map();
480
- const start = (tool, raw) => {
483
+ const start = (tool, raw, key) => {
481
484
  const invocation = {
482
485
  startedAt: now(),
483
486
  settled: (async () => tool.handler(raw))().then((value) => {
@@ -494,8 +497,19 @@ function singleFlightTools(tools, options) {
494
497
  return invocation.outcome;
495
498
  }),
496
499
  outcome: void 0,
497
- waiting: 0
500
+ waiting: 0,
501
+ receipt: void 0
498
502
  };
503
+ invocation.settled.then(async (outcome) => {
504
+ if (invocations.get(key) === invocation) invocations.delete(key);
505
+ if (invocation.receipt !== void 0) await receipts.settleToolReceipt(invocation.receipt, outcome).catch((error) => {
506
+ console.error("Runtime could not publish a receipted tool outcome", {
507
+ tool: tool.name,
508
+ receipt: invocation.receipt,
509
+ error: error instanceof Error ? error.message : String(error)
510
+ });
511
+ });
512
+ });
499
513
  return invocation;
500
514
  };
501
515
  const wrap = (tool) => Object.freeze({
@@ -504,7 +518,7 @@ function singleFlightTools(tools, options) {
504
518
  const key = invocationKey(tool.name, raw);
505
519
  let invocation = invocations.get(key);
506
520
  if (invocation === void 0) {
507
- invocation = start(tool, raw);
521
+ invocation = start(tool, raw, key);
508
522
  invocations.set(key, invocation);
509
523
  }
510
524
  if (invocation.outcome === void 0) {
@@ -516,8 +530,10 @@ function singleFlightTools(tools, options) {
516
530
  }
517
531
  }
518
532
  const outcome = invocation.outcome;
519
- if (outcome === void 0) return pendingToolCall(tool.name, now() - invocation.startedAt);
520
- if (invocations.get(key) === invocation) invocations.delete(key);
533
+ if (outcome === void 0) {
534
+ invocation.receipt ??= receipts.openToolReceipt(tool.name);
535
+ return toolCallReceipt(tool.name, invocation.receipt, now() - invocation.startedAt);
536
+ }
521
537
  if (outcome.ok) return outcome.value;
522
538
  throw outcome.error;
523
539
  }
@@ -538,19 +554,20 @@ function invocationKey(name, raw) {
538
554
  throw new ValidationError(`${name}: arguments must be finite JSON so a repeated call can join its earlier run`, { cause: error });
539
555
  }
540
556
  }
541
- function pendingToolCall(tool, elapsedMs) {
557
+ function toolCallReceipt(tool, receipt, elapsedMs) {
542
558
  return {
543
- pending: true,
559
+ running: true,
560
+ receipt,
544
561
  tool,
545
562
  elapsedMs,
546
- instruction: `${tool} is still running; nothing failed. Call ${tool} again with the same arguments to keep waiting. That call joins this run and returns its result, or its error, once it finishes. Different arguments start a separate run.`
563
+ instruction: `${tool} is still running; nothing failed. Do not call it again: its result arrives with receipt ${receipt} when you are next woken. Continue other work, or end your turn to wait.`
547
564
  };
548
565
  }
549
566
  //#endregion
550
567
  //#region src/runtime/supervise/coordination-mcp.ts
551
568
  /**
552
569
  *
553
- * Serve the coordination verbs (spawn_worker / await_event / observe_agent / steer_agent / stop)
570
+ * Serve the coordination verbs (spawn_worker / observe_agent / steer_agent / submit_result / stop)
554
571
  * as a real HTTP MCP server over a LIVE `Scope`. This is the keystone that lets a coding-harness
555
572
  * agent (opencode via the cli-bridge, claude-code, codex) BE the supervisor: it mounts this MCP
556
573
  * (`mcp.mcpServers.coordination`) and calls `spawn_worker` as a native tool, which lands on
@@ -597,20 +614,20 @@ function assertCoordinationTransport(options) {
597
614
  * exactly when a deliverable is injected.
598
615
  */
599
616
  const DELIVERABLE_VERB = "submit_result";
617
+ /** The longest any coordination call holds its response, whatever the request timeout: under the
618
+ * 60 s MCP tool-call timeout Claude Code and Codex apply by default. */
619
+ const RESPONSE_FENCE_CAP_MS = 45e3;
600
620
  /**
601
- * The longest one coordination call holds its HTTP response before it answers with a re-pollable
602
- * pending result instead: `await_event` by default, and `submit_result` and every method-supplied
603
- * node tool always.
621
+ * The longest a fenced coordination call (`submit_result` and every method-supplied node tool)
622
+ * holds its HTTP response before it answers with a receipt instead. The call keeps running, and
623
+ * its outcome reaches the manager in its next wake.
604
624
  *
605
625
  * It is half of `requestTimeoutMs`, so the answer leaves before the transport's own 504 at
606
- * `requestTimeoutMs`, with the other half left for body transfer, admission, and serialization.
607
- * Deriving it here means a configured request timeout moves both fences with it. It is capped at
608
- * {@link DEFAULT_AWAIT_EVENT_TIMEOUT_MS} so a long request timeout does not lengthen each wait; at
609
- * the default 90 s request timeout both values are 45 s, under the 60 s MCP tool-call timeout that
610
- * Claude Code and Codex apply by default.
626
+ * `requestTimeoutMs`, with the other half left for body transfer, admission, and serialization,
627
+ * and at most {@link RESPONSE_FENCE_CAP_MS}.
611
628
  */
612
629
  function coordinationResponseFenceMs(requestTimeoutMs) {
613
- return Math.max(1, Math.min(DEFAULT_AWAIT_EVENT_TIMEOUT_MS, Math.floor(requestTimeoutMs / 2)));
630
+ return Math.max(1, Math.min(RESPONSE_FENCE_CAP_MS, Math.floor(requestTimeoutMs / 2)));
614
631
  }
615
632
  /** Stand up the existing coordination tools with bounded HTTP access over one live scope. */
616
633
  async function serveCoordinationMcp(opts) {
@@ -698,7 +715,6 @@ async function serveCoordinationMcpForManager(opts, lifetime) {
698
715
  ...opts.deliverable ? { deliverable: opts.deliverable } : {},
699
716
  ...opts.readContinuation ? { readContinuation: opts.readContinuation } : {},
700
717
  ...opts.onStop ? { onStop: opts.onStop } : {},
701
- awaitTimeoutMs: opts.awaitTimeoutMs ?? responseFenceMs,
702
718
  ...opts.analysts ? { analysts: opts.analysts } : {},
703
719
  ...opts.analyzeOnSettle ? { analyzeOnSettle: opts.analyzeOnSettle } : {},
704
720
  ...opts.sourceEvidenceRefs ? { sourceEvidenceRefs: opts.sourceEvidenceRefs } : {},
@@ -727,8 +743,14 @@ async function serveCoordinationMcpForManager(opts, lifetime) {
727
743
  if (reservedNames.has(tool.name)) throw new ValidationError(`serveCoordinationMcp: node tool ${JSON.stringify(tool.name)} shadows a coordination verb or another node tool`);
728
744
  reservedNames.add(tool.name);
729
745
  }
730
- const nodeTools = singleFlightTools(opts.nodeTools ?? [], { fenceMs: responseFenceMs });
731
- const fencedVerbs = singleFlightTools(coord.tools.filter((tool) => tool.name === DELIVERABLE_VERB), { fenceMs: responseFenceMs });
746
+ const nodeTools = singleFlightTools(opts.nodeTools ?? [], {
747
+ fenceMs: responseFenceMs,
748
+ receipts: coord
749
+ });
750
+ const fencedVerbs = singleFlightTools(coord.tools.filter((tool) => tool.name === DELIVERABLE_VERB), {
751
+ fenceMs: responseFenceMs,
752
+ receipts: coord
753
+ });
732
754
  if (opts.deliverable && fencedVerbs.tools.length !== 1) throw new ValidationError(`serveCoordinationMcp: a deliverable is injected but the coordination verbs lack ${DELIVERABLE_VERB}, so its check would run unfenced`);
733
755
  const fencedByName = new Map(fencedVerbs.tools.map((tool) => [tool.name, tool]));
734
756
  const availableTools = [...coord.tools.map((tool) => fencedByName.get(tool.name) ?? tool), ...nodeTools.tools];
@@ -747,7 +769,7 @@ async function serveCoordinationMcpForManager(opts, lifetime) {
747
769
  serverVersion: "1",
748
770
  tools: servedTools
749
771
  });
750
- opts.onCoordinationTools?.([...mcp.tools.values()]);
772
+ opts.onCoordinationTools?.([...mcp.tools.values()], coord);
751
773
  const server = createServer(coordinationHttpHandler({
752
774
  options: opts,
753
775
  identity,
@@ -978,7 +1000,7 @@ function createSupervisorSpanRecorder(opts) {
978
1000
  if (!exporter) return void 0;
979
1001
  const ownsExporter = opts.exporter === void 0;
980
1002
  const now = opts.now ?? Date.now;
981
- const traceId = normalizeTraceId(opts.traceId, opts.runId);
1003
+ const traceId = normalizeTraceId(opts.traceId, opts.runId, opts.namespace);
982
1004
  const rootSpanId = generateSpanId();
983
1005
  const rootStartMs = now();
984
1006
  const base = {
@@ -1258,12 +1280,13 @@ function assignBudget(attrs, value) {
1258
1280
  }
1259
1281
  /**
1260
1282
  * A trace id must be 32 hex characters. A caller-supplied one is used verbatim when it already is;
1261
- * anything else (and the default) is DERIVED from the run id by content address — deterministic, so
1262
- * a resumed run rejoins the trace its first process opened rather than forking a new one.
1283
+ * anything else (and the default) is DERIVED by content address — deterministic, so a resumed run
1284
+ * rejoins the trace its first process opened rather than forking a new one. The default covers the
1285
+ * namespace as well as the run id, because run ids repeat across copies of a run.
1263
1286
  */
1264
- function normalizeTraceId(traceId, runId) {
1287
+ function normalizeTraceId(traceId, runId, namespace) {
1265
1288
  if (traceId && /^[0-9a-f]{32}$/i.test(traceId)) return traceId.toLowerCase();
1266
- return contentAddress(traceId ?? runId).slice(7, 39);
1289
+ return contentAddress(traceId ?? (namespace === void 0 ? runId : `${namespace}\u0000${runId}`)).slice(7, 39);
1267
1290
  }
1268
1291
  function msToNano(ms) {
1269
1292
  return (BigInt(Number.isFinite(ms) ? Math.floor(ms) : 0) * 1000000n).toString();
@@ -1295,6 +1318,7 @@ function composeReentryTask(input) {
1295
1318
  const changes = stateLines(state, false, input.tools);
1296
1319
  return [reentry.steer, ...changes.length > 0 ? ["", ...changes] : []].join("\n");
1297
1320
  }
1321
+ if (reentry.reason === "wake" && continuity.session === "continued") return reentry.input;
1298
1322
  return [
1299
1323
  `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.`,
1300
1324
  whyLine(reentry),
@@ -1316,6 +1340,12 @@ function composeReentryTask(input) {
1316
1340
  "",
1317
1341
  reentry.steer
1318
1342
  ] : [],
1343
+ ...reentry.reason === "wake" ? [
1344
+ "",
1345
+ "## What woke you",
1346
+ "",
1347
+ reentry.input
1348
+ ] : [],
1319
1349
  "",
1320
1350
  "## Run state, from the coordinator",
1321
1351
  "",
@@ -1325,7 +1355,6 @@ function composeReentryTask(input) {
1325
1355
  "",
1326
1356
  "Continue the run from this state.",
1327
1357
  ...continuity.workspace === "kept" || continuity.workspace === "restored" ? ["Read the files you already wrote before you repeat any step of the task. A step whose file is there is done, and its content stands."] : [],
1328
- ...input.tools?.includes("await_event") === true ? ["Receive the waiting events with await_event before starting new work."] : [],
1329
1358
  ...input.tools?.includes("observe_agent") === true ? ["Read the output of every settled worker with observe_agent before you spawn anything new."] : [],
1330
1359
  "Do not spawn a replacement for a worker that is running or has settled.",
1331
1360
  "Your coordination tools are served by the same coordinator as before, and the state above comes from it."
@@ -1339,6 +1368,7 @@ function composeReentryTask(input) {
1339
1368
  */
1340
1369
  function whyLine(reentry) {
1341
1370
  if (reentry.reason === "unmet-contract") return `Your previous turn ended with the completion check unmet (continuation ${reentry.continuation}).`;
1371
+ if (reentry.reason === "wake") return "Your previous turn ended while your workers ran, and Runtime woke you with what happened.";
1342
1372
  return reentry.reason === "upstream-unavailable" ? "Your previous turn was interrupted before it finished; the run itself is intact." : `Your previous turn ended before it finished (retry ${reentry.retry}); the run itself is intact.`;
1343
1373
  }
1344
1374
  function environmentLine(continuity) {
@@ -1356,7 +1386,7 @@ function stateLines(state, full, tools) {
1356
1386
  else if (full) lines.push("Workers settled: none.");
1357
1387
  if (state.waiting.length > 0) lines.push(`Events waiting for you: ${state.waiting.length} (${state.waiting.map((event) => event.worker === void 0 ? event.type : `${event.type} from ${event.worker}`).join("; ")}).`);
1358
1388
  else if (full) lines.push("Events waiting for you: none.");
1359
- 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("; ")}.` + (tools?.includes("await_event") === true ? " Pass their numbers in await_event's acknowledge once you have processed them." : ""));
1389
+ if (state.unacknowledged.length > 0) lines.push(`Events delivered to a turn that has not finished, so treat them as unread: ${state.unacknowledged.map((event) => `#${event.seq} ${event.type}${event.worker === void 0 ? "" : ` from ${event.worker}`}`).join("; ")}.`);
1360
1390
  if (state.lastRejection !== void 0) lines.push(`Your last submit_result was refused: ${state.lastRejection.reason}`);
1361
1391
  return lines;
1362
1392
  }
@@ -1768,6 +1798,7 @@ function declaredRuntimeToolNames(profile) {
1768
1798
  /** Describe Runtime declarations that cannot resolve without a product tool provider. */
1769
1799
  function runtimeToolDeclarationError(profile, hasProductToolResolver, mountedStaticToolNames = []) {
1770
1800
  const mountedStaticToolNameSet = new Set(mountedStaticToolNames);
1801
+ if (declaredRuntimeToolNames(profile).includes("await_event")) return `the profile declares ${JSON.stringify(`${coordinationProfileToolPrefix}await_event`)}, which no longer exists: a manager ends its turn to wait, and Runtime wakes it with what happened. Remove the grant`;
1771
1802
  const unresolved = declaredRuntimeToolNames(profile).filter((name) => !coordinationVerbNameSet$1.has(name) && !hasProductToolResolver && !mountedStaticToolNameSet.has(name));
1772
1803
  if (unresolved.length === 0) return void 0;
1773
1804
  return `the profile declares ${unresolved.map((name) => JSON.stringify(`${coordinationProfileToolPrefix}${name}`)).join(", ")}, but this run has no resolveSupervisorTools provider or router-mounted static tool for those tools`;
@@ -1859,6 +1890,7 @@ function assertCoordinationBinding(binding) {
1859
1890
  }
1860
1891
  function createVerbSlot() {
1861
1892
  let bound;
1893
+ let waits;
1862
1894
  const verb = (name) => async (args) => {
1863
1895
  if (bound === void 0) throw new ValidationError(`supervisorAgent: coordination verb "${name}" was called before this manager's coordination tools were bound`);
1864
1896
  const tool = bound.find((descriptor) => descriptor.name === name);
@@ -1868,7 +1900,12 @@ function createVerbSlot() {
1868
1900
  return {
1869
1901
  verbs: Object.freeze({
1870
1902
  spawnAgent: verb("spawn_worker"),
1871
- awaitEvent: verb("await_event"),
1903
+ awaitSettlement: async (args) => {
1904
+ if (waits === void 0) throw new ValidationError("supervisorAgent: coordination verb \"awaitSettlement\" was called before this manager's coordination tools were bound");
1905
+ const ids = args?.workerIds;
1906
+ if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string" && id.length > 0)) throw new ValidationError("awaitSettlement: workerIds must be an array of worker ids");
1907
+ return { settled: await waits.awaitSettlement(ids) };
1908
+ },
1872
1909
  steerAgent: verb("steer_agent"),
1873
1910
  observeAgent: verb("observe_agent"),
1874
1911
  listQuestions: verb("list_questions"),
@@ -1885,8 +1922,9 @@ function createVerbSlot() {
1885
1922
  inputSchema
1886
1923
  })));
1887
1924
  },
1888
- bind(tools) {
1925
+ bind(tools, coordination) {
1889
1926
  bound = tools;
1927
+ waits = coordination;
1890
1928
  }
1891
1929
  };
1892
1930
  }
@@ -1977,7 +2015,7 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1977
2015
  ...deps.escalateQuestion ? { escalateQuestion: deps.escalateQuestion } : {},
1978
2016
  ...deps.watchWorkers ? { watchWorkers: deps.watchWorkers } : {},
1979
2017
  ...deps.stallAfterMs !== void 0 ? { stallAfterMs: deps.stallAfterMs } : {},
1980
- ...deps.awaitTimeoutMs !== void 0 ? { awaitTimeoutMs: deps.awaitTimeoutMs } : {},
2018
+ ...deps.wake !== void 0 ? { wake: deps.wake } : {},
1981
2019
  ...deps.continuityByProfile ? { continuityByProfile: deps.continuityByProfile } : {},
1982
2020
  ...deps.preflightSpawn ? { preflightSpawn: deps.preflightSpawn } : {},
1983
2021
  ...deps.resolveSpawnProfile ? { resolveSpawnProfile: deps.resolveSpawnProfile } : {},
@@ -1993,7 +2031,7 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1993
2031
  ...deps.replaySettlements ? { replaySettlements: true } : {},
1994
2032
  ...priorCoordination ? { priorCoordination } : {},
1995
2033
  ...deps.finalizer ? { finalizer: deps.finalizer } : {},
1996
- ...slot ? { onCoordinationTools: (tools) => slot.bind(tools) } : {},
2034
+ ...slot ? { onCoordinationTools: (tools, coordination) => slot.bind(tools, coordination) } : {},
1997
2035
  ...deps.controlDir === void 0 ? {} : { controlDir: deps.controlDir },
1998
2036
  ...deps.steerDir === void 0 ? {} : { steerDir: deps.steerDir },
1999
2037
  ...deps.controlScope === void 0 ? {} : { controlScope: deps.controlScope },
@@ -2023,13 +2061,25 @@ function buildSupervisorAgent(profile, deps, testBrain) {
2023
2061
  const rawDeliverReady = driveHarness.deliverReady;
2024
2062
  if (rawDeliverReady !== void 0 && typeof rawDeliverReady !== "function") throw new ValidationError("supervisorAgent: driveHarness.deliverReady must be a function when provided");
2025
2063
  const deliverReady = rawDeliverReady?.bind(driveHarness);
2064
+ const wakePolicy = resolveWakePolicy(deps.wake);
2065
+ let managerInbox;
2066
+ let waitingOn;
2067
+ let liveCoordinator;
2026
2068
  const externalAgent = {
2027
2069
  name,
2028
- ...deliver ? { deliver(message) {
2029
- return deliver(message);
2030
- } } : {},
2070
+ deliver(message) {
2071
+ return managerInbox?.(message) ?? false;
2072
+ },
2073
+ resultAccepted: () => Boolean(liveCoordinator?.submittedResult()),
2031
2074
  traceSource: () => driveHarness.traceSource?.(),
2032
- progress: () => driveHarness.progress?.(),
2075
+ progress: () => {
2076
+ const harnessProgress = driveHarness.progress?.();
2077
+ if (waitingOn === void 0) return harnessProgress;
2078
+ return {
2079
+ ...harnessProgress,
2080
+ note: `waiting for ${waitingOn} worker${waitingOn === 1 ? "" : "s"}; Runtime wakes it when one reports`
2081
+ };
2082
+ },
2033
2083
  ...driveHarness.harnessTranscript ? { harnessTranscript: () => driveHarness.harnessTranscript?.() } : {},
2034
2084
  ...driveHarness.harnessTranscriptSettled ? { harnessTranscriptSettled: () => driveHarness.harnessTranscriptSettled?.() ?? Promise.resolve() } : {},
2035
2085
  async act(task, scope) {
@@ -2101,12 +2151,17 @@ function buildSupervisorAgent(profile, deps, testBrain) {
2101
2151
  ...priorCoordination?.analystDefinitions?.length ? { priorAnalystDefinitions: priorCoordination.analystDefinitions } : {},
2102
2152
  ...nodeTools?.length ? { nodeTools } : {},
2103
2153
  toolNames: runtimeToolNames,
2104
- onCoordinationTools: (tools) => slot.bind(tools)
2154
+ onCoordinationTools: (tools, coordination) => slot.bind(tools, coordination)
2105
2155
  }, coordinationLifetime.signal).catch((error) => {
2106
2156
  coordinationLifetime.abort(error);
2107
2157
  throw error;
2108
2158
  });
2109
2159
  ledger = mcp;
2160
+ liveCoordinator = mcp;
2161
+ managerInbox = (message) => {
2162
+ if (deliver !== void 0 && harnessInvocationActive && (deliverReady === void 0 || deliverReady()) && deliver(message)) return true;
2163
+ return controls.receiveLeadMessage(message);
2164
+ };
2110
2165
  const coordinationTools = slot.descriptors();
2111
2166
  const providerProfile = detachedSnapshot(providerVisibleProfile(stableProfile), "supervisorAgent provider-visible profile");
2112
2167
  let controlObserver;
@@ -2119,8 +2174,8 @@ function buildSupervisorAgent(profile, deps, testBrain) {
2119
2174
  signal: coordinationLifetime.signal,
2120
2175
  controlScope: deps.controlScope ?? "run",
2121
2176
  ...deps.controlScope === "subtree" ? {} : {
2122
- deliverRoot: (message) => deliver?.(message) ?? false,
2123
- deliverRootReady: () => deliver === void 0 || harnessInvocationActive && (deliverReady === void 0 || deliverReady())
2177
+ deliverRoot: (message) => managerInbox?.(message) ?? false,
2178
+ deliverRootReady: () => true
2124
2179
  },
2125
2180
  onError: (error) => {
2126
2181
  coordinationLifetime.abort(error);
@@ -2233,6 +2288,8 @@ function buildSupervisorAgent(profile, deps, testBrain) {
2233
2288
  if (last?.unavailable !== void 0) throw new CheckUnavailableError(`the completion check could not run: ${last.unavailable}`);
2234
2289
  };
2235
2290
  const loopRecords = [];
2291
+ let deadlineWarned = false;
2292
+ const managerStartedAt = Date.now();
2236
2293
  let environmentReplacements = 0;
2237
2294
  let workspaceRestores = 0;
2238
2295
  const describe = deps.deliverable?.describe;
@@ -2295,7 +2352,7 @@ function buildSupervisorAgent(profile, deps, testBrain) {
2295
2352
  if (completed) await controls.endDriverAttempt("completed");
2296
2353
  else await controls.endDriverAttempt("failed").catch(() => void 0);
2297
2354
  }
2298
- if (contractDeclared && !mcp.submittedResult()) {
2355
+ if (contractDeclared && !mcp.submittedResult() && !controls.hasOpenWork()) {
2299
2356
  await mcp.drainResolved();
2300
2357
  candidate = await finalize();
2301
2358
  if (candidate === void 0 && !mcp.isStopped()) await readCheckAtTurnEnd(attempt);
@@ -2304,6 +2361,35 @@ function buildSupervisorAgent(profile, deps, testBrain) {
2304
2361
  progress: readProgress,
2305
2362
  budget: () => scope.budget,
2306
2363
  signal: scope.signal,
2364
+ wait: {
2365
+ open: () => !mcp.submittedResult() && !mcp.isStopped() && progressStopReason === void 0 && controls.hasOpenWork(),
2366
+ wake: async (nextAttempt) => {
2367
+ const deadlineMs = scope.budget.deadlineMs;
2368
+ const warnAt = deadlineWarningAt(deadlineMs, wakePolicy, deadlineWarned, managerStartedAt);
2369
+ waitingOn = scope.view.nodes.filter((node) => node.id !== scope.view.root && isLiveNodeStatus(node.status)).length;
2370
+ try {
2371
+ const wake = await controls.awaitWake({
2372
+ attempt: nextAttempt,
2373
+ signal: AbortSignal.any([scope.signal, stopController.signal]),
2374
+ heartbeatMs: wakePolicy.heartbeatMs,
2375
+ debounceMs: wakePolicy.debounceMs,
2376
+ ...warnAt === void 0 ? {} : { deadlineAt: warnAt }
2377
+ });
2378
+ if (wake === void 0 || stopController.signal.aborted) return void 0;
2379
+ if (wake.reason === "deadline") deadlineWarned = true;
2380
+ return {
2381
+ input: composeWakeInput(wake, {
2382
+ tools: runtimeToolNames,
2383
+ deadlineMs,
2384
+ now: Date.now()
2385
+ }),
2386
+ idleMs: wake.idleMs
2387
+ };
2388
+ } finally {
2389
+ waitingOn = void 0;
2390
+ }
2391
+ }
2392
+ },
2307
2393
  ...deps.driverRetry ? { policy: deps.driverRetry } : {},
2308
2394
  ...continuation !== void 0 && keeper !== void 0 && continuationDeadlineMs ? { continuation: {
2309
2395
  maxBarren: continuation.maxBarren,
@@ -2371,6 +2457,7 @@ function buildSupervisorAgent(profile, deps, testBrain) {
2371
2457
  });
2372
2458
  throw error;
2373
2459
  } finally {
2460
+ managerInbox = void 0;
2374
2461
  coordinationLifetime.abort(/* @__PURE__ */ new Error("supervisor manager stopped"));
2375
2462
  try {
2376
2463
  await controlObserver?.close();
@@ -3115,6 +3202,15 @@ async function providerAcceptsCoordinationAttachments(backend) {
3115
3202
  const attachments = create.runtimeAttachments;
3116
3203
  return Boolean(attachments && typeof attachments === "object" && "mcp" in attachments && attachments.mcp === true);
3117
3204
  }
3205
+ /**
3206
+ * A manager waits between turns, and a wake can come much later than five minutes after its last
3207
+ * turn. Claude Code 2.1.289 writes its prompt cache with a five-minute lifetime unless this variable
3208
+ * is set; a wake after the cache expired re-writes the manager's whole context, about 140K tokens
3209
+ * per turn on a Discovery root measured 2026-10-05. That root ran on a subscription and already
3210
+ * wrote one-hour entries; the variable makes the hour hold for every claude-code manager, whatever
3211
+ * its credential. A value the caller set wins.
3212
+ */
3213
+ const CLAUDE_CODE_ONE_HOUR_CACHE = "ENABLE_PROMPT_CACHING_1H";
3118
3214
  /** Run a harness-brained manager through the same executor factory as its children. The manager's
3119
3215
  * full profile is preserved, the live coordination server is added under one reserved alias, and
3120
3216
  * every streamed turn is charged to the manager's scope before it may continue. */
@@ -3125,6 +3221,30 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3125
3221
  const baseFactory = createExecutor(boundBackend);
3126
3222
  const ownerRuntime = boundBackend.backend === "provider" ? boundBackend.runtime ?? resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry).name : "cli";
3127
3223
  let activeExecutor;
3224
+ const driveActivity = createActivityLog();
3225
+ let driveTurns = 0;
3226
+ const noteDriveProgress = (event) => {
3227
+ const at = Date.now();
3228
+ if (event.kind === "tool_call") driveActivity.push({
3229
+ at,
3230
+ kind: "tool",
3231
+ label: event.toolName
3232
+ });
3233
+ else if (event.kind === "tool_result") driveActivity.push({
3234
+ at,
3235
+ kind: "tool",
3236
+ label: event.toolName,
3237
+ status: "ok"
3238
+ });
3239
+ else if (event.kind === "text_delta" || event.kind === "reasoning_delta") {
3240
+ const last = driveActivity.last();
3241
+ if (last === void 0 || last.kind !== "turn" || at - last.at > 3e4) driveActivity.push({
3242
+ at,
3243
+ kind: "turn",
3244
+ label: "model output"
3245
+ });
3246
+ }
3247
+ };
3128
3248
  let managerTranscript;
3129
3249
  let managerArtifact;
3130
3250
  const drive = async ({ profile, authoredProfile, task, scope, coordinationMcpUrl, coordinationMcpHeaders, stopSignal, coordinationTools, reentry }) => {
@@ -3137,6 +3257,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3137
3257
  const execution = runtimeOwnedExecutorMaterialization(activeExecutor)?.execution;
3138
3258
  return execution?.kind === "environment" ? execution.id : void 0;
3139
3259
  });
3260
+ await scopeRetainedOwnerTurnEnded(scope);
3140
3261
  }
3141
3262
  let driveTask = task;
3142
3263
  if (reentry !== void 0) {
@@ -3187,6 +3308,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3187
3308
  defaults: {
3188
3309
  ...boundBackend.defaults ?? {},
3189
3310
  env: {
3311
+ ...providerDriverProfile.harness === "claude-code" ? { [CLAUDE_CODE_ONE_HOUR_CACHE]: "1" } : {},
3190
3312
  ...boundBackend.defaults?.env ?? {},
3191
3313
  [credentialName]: authorization.slice(7)
3192
3314
  },
@@ -3303,6 +3425,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3303
3425
  runtime: executor.runtime
3304
3426
  });
3305
3427
  if (retainedOwner) committedOwnerSpend = addSpend(committedOwnerSpend, charge);
3428
+ if (effectiveStopSignal?.aborted === true) return;
3306
3429
  const budget = scope.budget;
3307
3430
  if (budget.tokensLeft <= 0 || budget.usdCapped && budget.usdLeft <= 0 || Object.values(budget.resources ?? {}).some((resource) => !resource.known || resource.remaining <= 0) || budget.deadlineMs > 0 && now() >= budget.deadlineMs) throw new ValidationError("driveHarnessFromBackend: supervisor budget exhausted");
3308
3431
  };
@@ -3361,6 +3484,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3361
3484
  await retainedOwner.onResult(result);
3362
3485
  terminalAccountingCaptured = true;
3363
3486
  };
3487
+ const endDrive = retainedOwner ? beginScopeRetainedOwnerDrive(scope) : () => {};
3364
3488
  try {
3365
3489
  const declaration = runtimeOwnedExecutorMaterialization(executor);
3366
3490
  const executionBinding = runtimeOwnedExecutorExecutionBinding(executor);
@@ -3382,9 +3506,12 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3382
3506
  for await (const event of run) if (event.kind === "iteration") {
3383
3507
  await meterPending();
3384
3508
  turns += 1;
3509
+ driveTurns += 1;
3385
3510
  if (turnStop !== void 0 && turns >= turnCap && !turnStop.signal.aborted) turnStop.abort(`supervise: maxTurns ${turnCap} reached`);
3386
- } else if (event.kind === "progress") rootStream?.append(event.progress);
3387
- else pendingUsage.push(event);
3511
+ } else if (event.kind === "progress") {
3512
+ rootStream?.append(event.progress);
3513
+ noteDriveProgress(event.progress);
3514
+ } else pendingUsage.push(event);
3388
3515
  await meterPending();
3389
3516
  const artifact = executor.resultArtifact();
3390
3517
  terminalArtifact = artifact;
@@ -3500,6 +3627,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3500
3627
  const capture = executor.harnessTranscript?.();
3501
3628
  if (capture !== void 0 && (capture.status !== "unavailable" || managerTranscript?.status === "unavailable" || managerTranscript === void 0)) managerTranscript = capture;
3502
3629
  if (activeExecutor === executor) activeExecutor = void 0;
3630
+ endDrive();
3503
3631
  }
3504
3632
  if (failed) throw failure;
3505
3633
  if (turnFailure !== void 0) throw turnFailure;
@@ -3513,7 +3641,16 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
3513
3641
  };
3514
3642
  drive.deliverReady = () => activeExecutor !== void 0;
3515
3643
  drive.traceSource = () => activeExecutor?.traceSource?.();
3516
- drive.progress = () => activeExecutor?.progress?.();
3644
+ drive.progress = () => {
3645
+ const fromExecutor = activeExecutor?.progress?.();
3646
+ const own = driveActivity.read();
3647
+ const recentActivity = [...fromExecutor?.recentActivity ?? [], ...own].sort((a, b) => a.at - b.at).slice(-12);
3648
+ return {
3649
+ ...fromExecutor,
3650
+ turns: Math.max(fromExecutor?.turns ?? 0, driveTurns),
3651
+ ...recentActivity.length > 0 ? { recentActivity } : {}
3652
+ };
3653
+ };
3517
3654
  if (boundBackend.backend === "provider") {
3518
3655
  drive.harnessTranscript = () => managerTranscript ?? activeExecutor?.harnessTranscript?.();
3519
3656
  drive.harnessTranscriptSettled = () => activeExecutor?.harnessTranscriptSettled?.() ?? Promise.resolve();
@@ -3678,7 +3815,7 @@ const superviseOptionKeySet = /* @__PURE__ */ new Set([
3678
3815
  "runId",
3679
3816
  "signal",
3680
3817
  "stallAfterMs",
3681
- "awaitTimeoutMs",
3818
+ "wake",
3682
3819
  "steerDir",
3683
3820
  "stopRule",
3684
3821
  "watchWorkers",
@@ -4323,7 +4460,7 @@ function superviseInternal(profile, task, opts, testBrain) {
4323
4460
  ...!analystLineage && spawnContext.analyst === void 0 && !spawnContext.assignmentId.startsWith("analyst:") && options.analyzeOnSettle ? { analyzeOnSettle: options.analyzeOnSettle } : {},
4324
4461
  ...options.watchWorkers ? { watchWorkers: options.watchWorkers } : {},
4325
4462
  ...options.stallAfterMs !== void 0 ? { stallAfterMs: options.stallAfterMs } : {},
4326
- ...options.awaitTimeoutMs !== void 0 ? { awaitTimeoutMs: options.awaitTimeoutMs } : {},
4463
+ ...options.wake !== void 0 ? { wake: options.wake } : {},
4327
4464
  ...options.continuityByProfile ? { continuityByProfile: options.continuityByProfile } : {},
4328
4465
  ...spawnPreflight ? { preflightSpawn: spawnPreflight } : {},
4329
4466
  ...options.resolveSpawnProfile ? { resolveSpawnProfile: options.resolveSpawnProfile } : {},
@@ -4446,7 +4583,7 @@ function superviseInternal(profile, task, opts, testBrain) {
4446
4583
  ...options.analyzeOnSettle ? { analyzeOnSettle: options.analyzeOnSettle } : {},
4447
4584
  ...options.watchWorkers ? { watchWorkers: options.watchWorkers } : {},
4448
4585
  ...options.stallAfterMs !== void 0 ? { stallAfterMs: options.stallAfterMs } : {},
4449
- ...options.awaitTimeoutMs !== void 0 ? { awaitTimeoutMs: options.awaitTimeoutMs } : {},
4586
+ ...options.wake !== void 0 ? { wake: options.wake } : {},
4450
4587
  ...options.continuityByProfile ? { continuityByProfile: options.continuityByProfile } : {},
4451
4588
  ...options.stopRule ? { stopRule: stopRuleOf(options.stopRule) } : {},
4452
4589
  ...options.onProgressStop ? { onProgressStop: options.onProgressStop } : {},
@@ -4473,6 +4610,7 @@ function superviseInternal(profile, task, opts, testBrain) {
4473
4610
  });
4474
4611
  spans = options.otel ? createSupervisorSpanRecorder({
4475
4612
  runId,
4613
+ namespace: runNamespace,
4476
4614
  ...options.otel,
4477
4615
  now
4478
4616
  }) : void 0;
@@ -4586,4 +4724,4 @@ function rootProviderModelEvidenceFromExecution(evidence) {
4586
4724
  //#endregion
4587
4725
  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 };
4588
4726
 
4589
- //# sourceMappingURL=supervise-Bu2rNYsK.js.map
4727
+ //# sourceMappingURL=supervise-BJrEC2Mh.js.map