@tangle-network/agent-runtime 0.199.0 → 0.201.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 (72) hide show
  1. package/dist/{activation-c3um4SY1.d.ts → activation-BPxs-Iu2.d.ts} +2 -2
  2. package/dist/{activation-zQWmiiPg.js → activation-C_FN2aqK.js} +2 -2
  3. package/dist/{activation-zQWmiiPg.js.map → activation-C_FN2aqK.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -3
  6. package/dist/agent.js.map +1 -1
  7. package/dist/analyst-loop-DZw5QWT9.js +176 -0
  8. package/dist/analyst-loop-DZw5QWT9.js.map +1 -0
  9. package/dist/analyst-loop.d.ts +1 -11
  10. package/dist/analyst-loop.js +2 -2
  11. package/dist/candidate-execution/index.d.ts +2 -2
  12. package/dist/candidate-execution/index.js +3 -3
  13. package/dist/{coordination-driver-vWb7kViA.js → coordination-driver-qdAwriPV.js} +8 -5
  14. package/dist/{coordination-driver-vWb7kViA.js.map → coordination-driver-qdAwriPV.js.map} +1 -1
  15. package/dist/{delegate-Ch93bpH5.js → delegate-BWHG-zZW.js} +2 -2
  16. package/dist/{delegate-Ch93bpH5.js.map → delegate-BWHG-zZW.js.map} +1 -1
  17. package/dist/durable.d.ts +2 -2
  18. package/dist/durable.js +2 -2
  19. package/dist/{graph-C6pT08K-.js → graph-cCqKhLqz.js} +3 -3
  20. package/dist/{graph-C6pT08K-.js.map → graph-cCqKhLqz.js.map} +1 -1
  21. package/dist/{improvement-cycle-CxZKIbLD.js → improvement-cycle-VH_ZGcIj.js} +5 -5
  22. package/dist/{improvement-cycle-CxZKIbLD.js.map → improvement-cycle-VH_ZGcIj.js.map} +1 -1
  23. package/dist/{index-CMTUgh-T.d.ts → index-Br191WbE.d.ts} +190 -142
  24. package/dist/index.d.ts +6 -5
  25. package/dist/index.js +28 -49
  26. package/dist/index.js.map +1 -1
  27. package/dist/intelligence.d.ts +15 -106
  28. package/dist/intelligence.js +9 -408
  29. package/dist/intelligence.js.map +1 -1
  30. package/dist/kernel.d.ts +3 -3
  31. package/dist/kernel.js +8 -9
  32. package/dist/{loop-runner-bin-CAf1OQot.d.ts → loop-runner-bin-BNRdsDOn.d.ts} +3 -3
  33. package/dist/{loop-runner-bin-SNrh585k.js → loop-runner-bin-jQ8hXO9J.js} +4 -4
  34. package/dist/{loop-runner-bin-SNrh585k.js.map → loop-runner-bin-jQ8hXO9J.js.map} +1 -1
  35. package/dist/loop-runner-bin.d.ts +1 -1
  36. package/dist/loop-runner-bin.js +1 -1
  37. package/dist/mcp/bin.js +3 -3
  38. package/dist/mcp/index.d.ts +2 -2
  39. package/dist/mcp/index.js +4 -4
  40. package/dist/{prepare-CAO1yXov.js → prepare-Dc30WRB0.js} +6 -3
  41. package/dist/prepare-Dc30WRB0.js.map +1 -0
  42. package/dist/{protected-model-port-BtXp2dUY.d.ts → protected-model-port-BlLP8ja6.d.ts} +2 -2
  43. package/dist/{protected-model-port-B5avcRiQ.js → protected-model-port-D5gDcnrH.js} +2 -2
  44. package/dist/{protected-model-port-B5avcRiQ.js.map → protected-model-port-D5gDcnrH.js.map} +1 -1
  45. package/dist/{provision-supervisor-D5YSCDVD.js → provision-supervisor-BA2-GPth.js} +3 -3
  46. package/dist/{provision-supervisor-D5YSCDVD.js.map → provision-supervisor-BA2-GPth.js.map} +1 -1
  47. package/dist/{redact-Dv8WcCKy.js → redact-h-oaw11Q.js} +13093 -11221
  48. package/dist/redact-h-oaw11Q.js.map +1 -0
  49. package/dist/{runtime-BN16GbTA.js → runtime-DeqdBVeC.js} +8 -9
  50. package/dist/{runtime-BN16GbTA.js.map → runtime-DeqdBVeC.js.map} +1 -1
  51. package/dist/{server-CbNb_N1x.js → server-U_k9NUbk.js} +3 -3
  52. package/dist/{server-CbNb_N1x.js.map → server-U_k9NUbk.js.map} +1 -1
  53. package/dist/{stream-agent-turn-CLOQr497.d.ts → stream-agent-turn-CJWthifS.d.ts} +42 -13
  54. package/dist/{structural-rollout-DANCelu6.js → structural-rollout-BcMmrpv4.js} +2 -3
  55. package/dist/{structural-rollout-DANCelu6.js.map → structural-rollout-BcMmrpv4.js.map} +1 -1
  56. package/dist/{supervise-BGNXB8No.js → supervise-DmFO50N6.js} +497 -90
  57. package/dist/supervise-DmFO50N6.js.map +1 -0
  58. package/dist/testing.d.ts +2 -2
  59. package/dist/testing.js +13 -13
  60. package/dist/tui/index.d.ts +1 -1
  61. package/dist/tui/index.js +1 -1
  62. package/dist/{types-1s_29INY.d.ts → types-CuXu5zuS.d.ts} +3 -2
  63. package/dist/{workspace-archive-BMOnloFf.js → workspace-archive-CBX0hwL_.js} +2 -2
  64. package/dist/{workspace-archive-BMOnloFf.js.map → workspace-archive-CBX0hwL_.js.map} +1 -1
  65. package/package.json +6 -6
  66. package/dist/analyst-loop-BknOQUW5.js +0 -546
  67. package/dist/analyst-loop-BknOQUW5.js.map +0 -1
  68. package/dist/prepare-CAO1yXov.js.map +0 -1
  69. package/dist/redact-Dv8WcCKy.js.map +0 -1
  70. package/dist/sandbox-events-DbC2WKKS.js +0 -929
  71. package/dist/sandbox-events-DbC2WKKS.js.map +0 -1
  72. package/dist/supervise-BGNXB8No.js.map +0 -1
@@ -1,12 +1,12 @@
1
- import { $ as bridgeAdmissionRefusal, Ar as worktreeCliProfileMaterialization, Ct as createInbox, Er as renderUnsupported, Gn as createOtelExporter, Gr as runtimeOwnedDriveHarnessProviderEvidence, Ir as attestRuntimeOwnedScopeOwner, J as teardownExecutor, Jn as generateSpanId, Jr as runtimeOwnedExecutorProviderEvidence, Kr as runtimeOwnedExecutorExecutionBinding, On as unmeteredSpend, Or as unsupportedProfileDimensions, Q as bindReusableExecutorExecutionId, Qn as toOtelAttributes, Sr as promptModelProfileMaterialization, Ur as providerAttemptEvidence, Wr as recordRuntimeOwnedDriveHarnessProviderEvidence, Xr as runtimeOwnedScopeOwnerRuntime, Xt as contentAddress, Y as assertValidBudget, Yr as runtimeOwnedPendingExecutorMaterialization, Z as spendFromUsageEvents, _ as meterRuntimeOwnedProviderAttempt, _r as controlProfileMaterialization, a as createSupervisor, br as profileMaterializationAxes$1, ct as snapshotExecutorConfig, d as driverChild, et as bridgeModelRouteRefusal, g as meterRuntimeOwnedAccounting, gr as assertProfileMaterialization, h as deriveNodeExecutionIdentity, i as createRootHandle, kn as zeroSpend, l as runFinalizer, ni as detachedSnapshot, nt as bridgeStopSignalKey, o as bestDelivered, ot as createExecutor, p as beginScopeOwnerAttempt, q as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, qr as runtimeOwnedExecutorMaterialization, rt as captureReusableExecutorConfig, sn as routerBrain, tt as bridgeRuntimeAttachmentsKey, u as runTree, ut as WORKER_TRACE_PROPAGATION, v as recordScopeOwnerMaterialization, vr as defineProfileMaterializationContract, xr as promptControlProfileMaterialization, y as scopeOwnerExecutorNodeContext, yr as fullProfileMaterialization, zr as inheritRuntimeOwnedExecutorAttestation } from "./redact-Dv8WcCKy.js";
1
+ import { $ as bridgeAdmissionRefusal, $r as providerAttemptEvidence, $t as spendFromUsageEvents, A as consumeScopeRetainedOwnerResult, Ar as profileMaterializationAxes$1, Br as worktreeCliProfileMaterialization, Ct as createInbox, Dr as controlProfileMaterialization, Er as assertProfileMaterialization, Ir as renderUnsupported, Kr as attestRuntimeOwnedScopeOwner, M as scopeRetainedOwnerContext, Mn as zeroSpend, Mr as promptModelProfileMaterialization, N as scopeRetainedOwnerPriorSpend, Nn as registerRetainedExecutorPreparation, Or as defineProfileMaterializationContract, P as scopeRetainedOwnerResult, Pn as retainedExecutorSeamKey, Q as bindReusableExecutorExecutionId, Rr as unsupportedProfileDimensions, S as scopeOwnerExecutorNodeContext, X as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, Xt as contentAddress, Yr as inheritRuntimeOwnedExecutorAttestation, Z as teardownExecutor, Zt as assertValidBudget, _ as deriveNodeExecutionIdentity, _n as resolveAgentEnvironmentProvider, a as createSupervisor, ai as runtimeOwnedPendingExecutorMaterialization, b as recordScopeOwnerMaterialization, cr as toOtelAttributes, ct as snapshotExecutorConfig, d as driverChild, ei as recordRuntimeOwnedDriveHarnessProviderEvidence, et as bridgeModelRouteRefusal, f as driverExecutorFactory, fi as detachedSnapshot, h as beginScopeOwnerAttempt, i as createRootHandle, ii as runtimeOwnedExecutorProviderEvidence, ir as generateSpanId, j as prepareScopeRetainedOwnerTask, jn as unmeteredSpend, jr as promptControlProfileMaterialization, kr as fullProfileMaterialization, l as runFinalizer, ni as runtimeOwnedExecutorExecutionBinding, nt as bridgeStopSignalKey, o as bestDelivered, oi as runtimeOwnedScopeOwnerRuntime, ot as createExecutor, p as isDriverSpec, ri as runtimeOwnedExecutorMaterialization, rt as captureReusableExecutorConfig, ti as runtimeOwnedDriveHarnessProviderEvidence, tr as createOtelExporter, tt as bridgeRuntimeAttachmentsKey, u as runTree, un as routerBrain, ut as WORKER_TRACE_PROPAGATION, v as meterRuntimeOwnedAccounting, x as restoreScopeOwnerAcceptedExecution, y as meterRuntimeOwnedProviderAttempt, yn as addSpend } from "./redact-h-oaw11Q.js";
2
2
  import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError, r as BackendTransportError, t as AgentEvalError } 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-DKDyr-fc.js";
4
4
  import { t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
5
- import { C as coordinationVerbNames, M as createFileRunContext, N as createInMemoryRunContext, c as createProgressTracker, d as progressStop, r as driverAgent, v as watchRunCancellation, w as createCoordinationTools } from "./coordination-driver-vWb7kViA.js";
5
+ import { C as coordinationVerbNames, M as createFileRunContext, N as createInMemoryRunContext, c as createProgressTracker, d as progressStop, r as driverAgent, v as watchRunCancellation, w as createCoordinationTools } from "./coordination-driver-qdAwriPV.js";
6
6
  import { k as writeRunCancellation, o as readRunCancelRequest, s as readRunCancellation } from "./run-layout-B8I_LXN-.js";
7
7
  import { t as createStdioToolServer } from "./tool-server-BJbCPhoW.js";
8
8
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
9
- import { randomUUID } from "node:crypto";
9
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
10
10
  import { resolve } from "node:path";
11
11
  import { isMaterializerHarness } from "@tangle-network/agent-profile-materialize";
12
12
  import { createServer } from "node:http";
@@ -468,6 +468,194 @@ function truncate(value) {
468
468
  return value.length > MAX_DETAIL_CHARS ? `${value.slice(0, MAX_DETAIL_CHARS)}…` : value;
469
469
  }
470
470
  //#endregion
471
+ //#region src/runtime/supervise/coordination-http.ts
472
+ function coordinationHttpLimits(options) {
473
+ const positive = (name, value, fallback) => {
474
+ const resolved = value ?? fallback;
475
+ if (!Number.isSafeInteger(resolved) || resolved <= 0) throw new ConfigError(`coordination ${name} must be a positive safe integer`);
476
+ return resolved;
477
+ };
478
+ const origins = new Set(options.allowedOrigins ?? []);
479
+ for (const origin of origins) {
480
+ const parsed = new URL(origin);
481
+ if (parsed.origin !== origin || !["http:", "https:"].includes(parsed.protocol)) throw new ConfigError("coordination allowedOrigins must contain canonical HTTP origins");
482
+ }
483
+ const requestTimeoutMs = positive("requestTimeoutMs", options.requestTimeoutMs, 3e4);
484
+ if (requestTimeoutMs > 2147483647) throw new ConfigError("coordination requestTimeoutMs exceeds the timer limit");
485
+ return {
486
+ maxRequestBytes: positive("maxRequestBytes", options.maxRequestBytes, 1024 * 1024),
487
+ requestTimeoutMs,
488
+ maxConcurrentRequests: positive("maxConcurrentRequests", options.maxConcurrentRequests, 32),
489
+ requestsPerMinute: positive("requestsPerMinute", options.requestsPerMinute, 600),
490
+ origins
491
+ };
492
+ }
493
+ /** One bounded HTTP adapter around the existing JSON-RPC handler; it owns no run commands. */
494
+ function coordinationHttpHandler(input) {
495
+ const limits = coordinationHttpLimits(input.options);
496
+ let active = 0;
497
+ let controlActive = 0;
498
+ let controlRequests = 0;
499
+ let windowStart = Date.now();
500
+ let requests = 0;
501
+ const audit = async (outcome, status, action) => {
502
+ await input.options.onAudit?.({
503
+ ...input.identity,
504
+ outcome,
505
+ status,
506
+ ...action ? { action } : {}
507
+ });
508
+ };
509
+ return (req, res) => {
510
+ let finished = false;
511
+ let executing = false;
512
+ let timedOut = false;
513
+ let admitted = false;
514
+ let controlAdmission = false;
515
+ let action;
516
+ let timer;
517
+ const release = () => {
518
+ if (admitted) {
519
+ admitted = false;
520
+ if (controlAdmission) controlActive--;
521
+ else active--;
522
+ }
523
+ if (timer) clearTimeout(timer);
524
+ };
525
+ const respond = (status, value) => {
526
+ if (finished) return;
527
+ finished = true;
528
+ if (timer) clearTimeout(timer);
529
+ res.writeHead(status, {
530
+ "content-type": "application/json",
531
+ "cache-control": "no-store",
532
+ ...status === 405 ? { allow: "POST" } : {}
533
+ });
534
+ res.end(value === void 0 ? void 0 : JSON.stringify(value));
535
+ if (!executing) release();
536
+ };
537
+ const reject = (status) => {
538
+ respond(status);
539
+ audit("rejected", status, action).catch(() => void 0);
540
+ req.resume();
541
+ };
542
+ req.on("error", () => reject(400));
543
+ req.on("aborted", () => {
544
+ finished = true;
545
+ if (!executing) release();
546
+ });
547
+ res.on("close", () => {
548
+ finished = true;
549
+ if (!executing) release();
550
+ });
551
+ if (req.method !== "POST") {
552
+ reject(405);
553
+ return;
554
+ }
555
+ const authorization = input.authorize(req);
556
+ if (authorization !== void 0) {
557
+ reject(authorization);
558
+ return;
559
+ }
560
+ const origin = req.headers.origin;
561
+ if (origin !== void 0 && !limits.origins.has(origin)) {
562
+ reject(403);
563
+ return;
564
+ }
565
+ if (req.headers["content-type"]?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") {
566
+ reject(415);
567
+ return;
568
+ }
569
+ const length = req.headers["content-length"];
570
+ if (length !== void 0 && (!/^\d+$/.test(length) || Number(length) > limits.maxRequestBytes)) {
571
+ reject(413);
572
+ return;
573
+ }
574
+ const now = Date.now();
575
+ if (now - windowStart >= 6e4) {
576
+ windowStart = now;
577
+ requests = 0;
578
+ controlRequests = 0;
579
+ }
580
+ controlAdmission = active >= limits.maxConcurrentRequests || requests >= limits.requestsPerMinute;
581
+ if (controlAdmission) {
582
+ if (controlActive >= 2 || controlRequests >= 60) {
583
+ reject(429);
584
+ return;
585
+ }
586
+ controlActive++;
587
+ } else {
588
+ requests++;
589
+ active++;
590
+ }
591
+ admitted = true;
592
+ timer = setTimeout(() => {
593
+ timedOut = true;
594
+ reject(executing ? 504 : 408);
595
+ }, limits.requestTimeoutMs);
596
+ timer.unref();
597
+ let size = 0;
598
+ const chunks = [];
599
+ req.on("data", (chunk) => {
600
+ if (finished) return;
601
+ size += chunk.length;
602
+ if (size > limits.maxRequestBytes) {
603
+ reject(413);
604
+ return;
605
+ }
606
+ chunks.push(chunk);
607
+ });
608
+ req.on("end", () => {
609
+ if (finished) return;
610
+ let message;
611
+ try {
612
+ const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
613
+ if (!value || typeof value !== "object" || Array.isArray(value) || !("jsonrpc" in value) || value.jsonrpc !== "2.0" || !("method" in value) || typeof value.method !== "string" || "id" in value && value.id !== null && typeof value.id !== "string" && (typeof value.id !== "number" || !Number.isFinite(value.id))) {
614
+ reject(400);
615
+ return;
616
+ }
617
+ message = value;
618
+ } catch {
619
+ reject(400);
620
+ return;
621
+ }
622
+ const authorization = input.authorize(req);
623
+ if (authorization !== void 0) {
624
+ reject(authorization);
625
+ return;
626
+ }
627
+ if (message.method === "tools/call" && message.params && typeof message.params === "object" && "name" in message.params && typeof message.params.name === "string" && input.toolNames.has(message.params.name)) action = message.params.name;
628
+ if (controlAdmission) {
629
+ if (!(message.method === "initialize" || message.method === "tools/list" || action === "stop" || action === "observe_agent" || action === "read_journal")) {
630
+ reject(429);
631
+ return;
632
+ }
633
+ controlRequests++;
634
+ }
635
+ executing = true;
636
+ (async () => {
637
+ try {
638
+ await audit("accepted", 200, action);
639
+ if (finished) return;
640
+ const authorization = input.authorize(req);
641
+ if (authorization !== void 0) {
642
+ reject(authorization);
643
+ return;
644
+ }
645
+ const response = await input.handle(message);
646
+ if (!finished) respond(response === null ? 202 : 200, response ?? void 0);
647
+ await audit(timedOut ? "completed-after-deadline" : "completed", timedOut ? 504 : response === null ? 202 : 200, action);
648
+ } catch {
649
+ respond(500);
650
+ } finally {
651
+ executing = false;
652
+ release();
653
+ }
654
+ })();
655
+ });
656
+ };
657
+ }
658
+ //#endregion
471
659
  //#region src/runtime/supervise/coordination-mcp.ts
472
660
  /**
473
661
  *
@@ -498,12 +686,84 @@ function isLoopbackHost(host) {
498
686
  if (h === "localhost" || h === "::1" || h === "0:0:0:0:0:0:0:1" || h === "::ffff:127.0.0.1") return true;
499
687
  return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
500
688
  }
501
- /** Stand up the coordination MCP over a live scope. The HOST address is `127.0.0.1` (the bridge runs
502
- * opencode locally, same host); pass `host` to bind elsewhere when the harness is remote a
503
- * non-loopback host additionally requires `allowUnauthenticatedRemote`. */
689
+ function assertCoordinationTransport(options) {
690
+ if (!isLoopbackHost(options.host ?? "127.0.0.1") && !options.authentication) throw new ConfigError("coordination non-loopback address requires authentication; allowUnauthenticatedRemote is no longer supported");
691
+ if (options.authentication !== void 0 && options.authentication !== true && (typeof options.authentication !== "object" || options.authentication === null || Array.isArray(options.authentication))) throw new ConfigError("coordination authentication must be true or a credential lifetime configuration");
692
+ const ttl = typeof options.authentication === "object" ? options.authentication.ttlMs : void 0;
693
+ if (ttl !== void 0 && (!Number.isSafeInteger(ttl) || ttl <= 0 || ttl > 864e5)) throw new ConfigError("coordination credential ttlMs must be a positive integer no greater than 24 hours");
694
+ if (options.publicUrl !== void 0 && !options.authentication) throw new ConfigError("coordination publicUrl requires authentication");
695
+ const signingKeys = typeof options.authentication === "object" ? options.authentication.signingKeys : void 0;
696
+ if (signingKeys !== void 0) {
697
+ if (!options.publicUrl) throw new ConfigError("coordination signingKeys requires a stable publicUrl");
698
+ if (!signingKeys.activeKeyId || !Object.hasOwn(signingKeys.keys, signingKeys.activeKeyId)) throw new ConfigError("coordination signingKeys must contain the active key");
699
+ for (const [id, key] of Object.entries(signingKeys.keys)) if (!/^[A-Za-z0-9_-]{1,64}$/.test(id) || typeof key !== "string" || Buffer.byteLength(key) < 32) throw new ConfigError("coordination signing keys require bounded key IDs and at least 32 secret bytes");
700
+ }
701
+ coordinationHttpLimits(options);
702
+ }
703
+ /** Stand up the existing coordination tools with bounded HTTP access over one live scope. */
504
704
  async function serveCoordinationMcp(opts) {
505
705
  const host = opts.host ?? "127.0.0.1";
506
- if (!isLoopbackHost(host) && opts.allowUnauthenticatedRemote !== true) throw new ConfigError(`coordination host=${JSON.stringify(host)} is not a loopback address and the coordination MCP has no authentication: any client that can reach the port could call spawn_worker/steer_agent and spend this run's budget. Bind a loopback host ("127.0.0.1", "localhost", "::1"), or set allowUnauthenticatedRemote: true to accept that exposure explicitly.`);
706
+ assertCoordinationTransport(opts);
707
+ if (opts.peerMail && (!isLoopbackHost(host) || opts.publicUrl)) throw new ConfigError("remote peer mail requires a separate reachable capability transport; coordination authentication does not authorize the peer listener");
708
+ const identity = Object.freeze({ ...opts.identity ?? {
709
+ runId: opts.scope.view?.root ?? "",
710
+ actorId: opts.scope.view?.root ?? ""
711
+ } });
712
+ if ((opts.authentication || opts.onAudit) && (!identity.runId.trim() || !identity.actorId.trim())) throw new ConfigError("authenticated coordination requires a trusted run and actor identity");
713
+ const auth = typeof opts.authentication === "object" ? opts.authentication : void 0;
714
+ const signingKeys = auth?.signingKeys ? {
715
+ activeKeyId: auth.signingKeys.activeKeyId,
716
+ keys: { ...auth.signingKeys.keys }
717
+ } : void 0;
718
+ let token;
719
+ let credentialExpiresAt;
720
+ let headers = Object.freeze({});
721
+ let credentialAudience = "";
722
+ let closed = false;
723
+ const revoked = /* @__PURE__ */ new Map();
724
+ const grantDigest = createHash("sha256").update(JSON.stringify([...opts.toolNames].sort())).digest("hex");
725
+ const rotateCredential = () => {
726
+ if (!opts.authentication) throw new ConfigError("coordination authentication is not configured");
727
+ if (closed) throw new ConfigError("coordination server is closed");
728
+ for (const [credential, expiry] of revoked) if (expiry <= Date.now()) revoked.delete(credential);
729
+ if (token) revoked.set(token.toString(), credentialExpiresAt);
730
+ credentialExpiresAt = Date.now() + (auth?.ttlMs ?? 9e5);
731
+ const nonce = randomBytes(32).toString("base64url");
732
+ let text = nonce;
733
+ if (signingKeys) {
734
+ const payload = Buffer.from(JSON.stringify({
735
+ key: signingKeys.activeKeyId,
736
+ run: identity.runId,
737
+ actor: identity.actorId,
738
+ audience: credentialAudience,
739
+ grants: grantDigest,
740
+ expires: credentialExpiresAt,
741
+ nonce
742
+ })).toString("base64url");
743
+ text = `${payload}.${createHmac("sha256", signingKeys.keys[signingKeys.activeKeyId]).update(payload).digest("base64url")}`;
744
+ }
745
+ token = Buffer.from(text);
746
+ headers = Object.freeze({ Authorization: `Bearer ${text}` });
747
+ };
748
+ const validCredential = (supplied) => {
749
+ if (closed || revoked.has(supplied.toString())) return false;
750
+ if (!signingKeys) return token !== void 0 && Date.now() < credentialExpiresAt && supplied.length === token.length && timingSafeEqual(supplied, token);
751
+ if (supplied.length > 8192) return false;
752
+ try {
753
+ const parts = supplied.toString().split(".");
754
+ if (parts.length !== 2) return false;
755
+ const payload = parts[0];
756
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
757
+ if (!claims || typeof claims.key !== "string" || !Object.hasOwn(signingKeys.keys, claims.key)) return false;
758
+ const expected = createHmac("sha256", signingKeys.keys[claims.key]).update(payload).digest();
759
+ const signature = Buffer.from(parts[1], "base64url");
760
+ return signature.length === expected.length && timingSafeEqual(signature, expected) && claims.run === identity.runId && claims.actor === identity.actorId && claims.audience === credentialAudience && claims.grants === grantDigest && Number.isSafeInteger(claims.expires) && claims.expires > Date.now();
761
+ } catch {
762
+ return false;
763
+ }
764
+ };
765
+ const audiences = /* @__PURE__ */ new Set();
766
+ const paths = /* @__PURE__ */ new Set(["/mcp"]);
507
767
  const coord = createCoordinationTools({
508
768
  scope: opts.scope,
509
769
  blobs: opts.blobs,
@@ -542,51 +802,35 @@ async function serveCoordinationMcp(opts) {
542
802
  if (!Array.isArray(opts.toolNames)) throw new ValidationError("serveCoordinationMcp: toolNames must name every granted tool explicitly");
543
803
  const selectedNames = opts.toolNames;
544
804
  if (new Set(selectedNames).size !== selectedNames.length) throw new ValidationError("serveCoordinationMcp: toolNames contains a duplicate name");
805
+ const servedTools = selectedNames.map((name) => {
806
+ const tool = availableByName.get(name);
807
+ if (tool === void 0) throw new ValidationError(`serveCoordinationMcp: requested tool ${JSON.stringify(name)} is unavailable`);
808
+ return tool;
809
+ });
545
810
  const mcp = createStdioToolServer({
546
811
  serverName: "coordination",
547
812
  serverVersion: "1",
548
- tools: selectedNames.map((name) => {
549
- const tool = availableByName.get(name);
550
- if (tool === void 0) throw new ValidationError(`serveCoordinationMcp: requested tool ${JSON.stringify(name)} is unavailable`);
551
- return tool;
552
- })
813
+ tools: servedTools
553
814
  });
554
815
  opts.onCoordinationTools?.([...mcp.tools.values()]);
555
- const server = createServer((req, res) => {
556
- if (req.method !== "POST") {
557
- res.writeHead(405, { allow: "POST" });
558
- res.end();
559
- return;
816
+ const server = createServer(coordinationHttpHandler({
817
+ options: opts,
818
+ identity,
819
+ toolNames: new Set(servedTools.map((tool) => tool.name)),
820
+ handle: (message) => mcp.handle(message),
821
+ authorize: (req) => {
822
+ if (!paths.has(req.url ?? "")) return 404;
823
+ if (!audiences.has(req.headers.host ?? "")) return 403;
824
+ if (closed) return 401;
825
+ if (!opts.authentication) return void 0;
826
+ const authorization = req.headers.authorization;
827
+ const supplied = typeof authorization === "string" && authorization.startsWith("Bearer ") ? Buffer.from(authorization.slice(7)) : Buffer.alloc(0);
828
+ if (!validCredential(supplied)) return 401;
560
829
  }
561
- let body = "";
562
- req.on("data", (c) => {
563
- body += c;
564
- });
565
- req.on("end", () => {
566
- (async () => {
567
- try {
568
- const message = JSON.parse(body);
569
- const response = await mcp.handle(message);
570
- if (response === null) {
571
- res.writeHead(202).end();
572
- return;
573
- }
574
- res.writeHead(200, { "content-type": "application/json" });
575
- res.end(JSON.stringify(response));
576
- } catch (e) {
577
- res.writeHead(200, { "content-type": "application/json" });
578
- res.end(JSON.stringify({
579
- jsonrpc: "2.0",
580
- id: null,
581
- error: {
582
- code: -32700,
583
- message: e instanceof Error ? e.message : "parse error"
584
- }
585
- }));
586
- }
587
- })();
588
- });
589
- });
830
+ }));
831
+ const requestTimeoutMs = coordinationHttpLimits(opts).requestTimeoutMs;
832
+ server.requestTimeout = requestTimeoutMs;
833
+ server.headersTimeout = requestTimeoutMs;
590
834
  const port = await new Promise((resolve, reject) => {
591
835
  server.once("error", reject);
592
836
  server.listen(opts.port ?? 0, host, () => {
@@ -594,11 +838,40 @@ async function serveCoordinationMcp(opts) {
594
838
  resolve(typeof addr === "object" && addr ? addr.port : opts.port ?? 0);
595
839
  });
596
840
  });
841
+ const localUrl = `http://${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}:${port}/mcp`;
842
+ let url;
843
+ try {
844
+ const configured = typeof opts.publicUrl === "function" ? opts.publicUrl({
845
+ host,
846
+ port,
847
+ ...identity
848
+ }) : opts.publicUrl;
849
+ const publicAddress = new URL(configured ?? localUrl);
850
+ if (!["http:", "https:"].includes(publicAddress.protocol) || publicAddress.username || publicAddress.password || publicAddress.search || publicAddress.hash) throw new ConfigError("coordination publicUrl must be an HTTP endpoint without credentials, query, or fragment");
851
+ if (configured !== void 0 && publicAddress.protocol !== "https:" && !isLoopbackHost(publicAddress.hostname)) throw new ConfigError("remote coordination publicUrl must use HTTPS");
852
+ url = publicAddress.href;
853
+ credentialAudience = url;
854
+ if (opts.authentication) rotateCredential();
855
+ audiences.add(new URL(localUrl).host);
856
+ audiences.add(publicAddress.host);
857
+ if (host === "0.0.0.0" || host === "::") audiences.add(`127.0.0.1:${port}`);
858
+ paths.add(publicAddress.pathname);
859
+ } catch (error) {
860
+ await new Promise((resolve) => server.close(() => resolve()));
861
+ throw error;
862
+ }
597
863
  const mailbox = coord.peerMail;
598
864
  const mailListener = mailbox === void 0 ? void 0 : await servePeerMail(mailbox, host);
599
865
  return {
600
- url: `http://${host}:${port}/mcp`,
866
+ url,
601
867
  port,
868
+ get headers() {
869
+ return headers;
870
+ },
871
+ get credentialExpiresAt() {
872
+ return credentialExpiresAt;
873
+ },
874
+ rotateCredential,
602
875
  settled: () => coord.settled(),
603
876
  submittedResult: () => coord.submittedResult(),
604
877
  drainResolved: () => coord.drainResolved(),
@@ -609,6 +882,7 @@ async function serveCoordinationMcp(opts) {
609
882
  mailHistory: () => mailbox?.history() ?? [],
610
883
  stopMailThread: (threadId) => mailbox?.stopThread(threadId) ?? false,
611
884
  close: async () => {
885
+ closed = true;
612
886
  await new Promise((resolve) => {
613
887
  server.close(() => resolve());
614
888
  });
@@ -1105,18 +1379,9 @@ function resolveSupervisorProfile(profile) {
1105
1379
  ...systemPrompt !== void 0 ? { systemPrompt } : {}
1106
1380
  };
1107
1381
  }
1108
- /**
1109
- * Fail closed on a non-loopback coordination bind. `serveCoordinationMcp` mounts spawn_worker /
1110
- * steer_agent / stop with NO authentication of any kind (it is a bare JSON-RPC-over-HTTP handler),
1111
- * so a non-loopback bind lets anyone who can reach the port spawn agents and spend the run's
1112
- * conserved budget. There is no token to require yet, so the only honest options are loopback or an
1113
- * explicit, recorded acknowledgment — never a silent bind.
1114
- */
1382
+ /** Validate a manager's coordination authentication and request limits before execution. */
1115
1383
  function assertCoordinationBinding(binding) {
1116
- const host = binding?.host;
1117
- if (host === void 0 || isLoopbackHost(host)) return;
1118
- if (binding?.allowUnauthenticatedRemote === true) return;
1119
- throw new ConfigError(`supervisorAgent: coordination.host=${JSON.stringify(host)} is not a loopback address and the coordination MCP has no authentication: any client that can reach the port could call spawn_worker/steer_agent and spend this run's budget. Bind a loopback host ("127.0.0.1", "localhost", "::1"), or set coordination.allowUnauthenticatedRemote: true to accept that exposure explicitly.`);
1384
+ assertCoordinationTransport(binding ?? {});
1120
1385
  }
1121
1386
  function createVerbSlot() {
1122
1387
  let bound;
@@ -1302,9 +1567,11 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1302
1567
  makeWorkerAgent: deps.makeWorkerAgent,
1303
1568
  ...deps.authorizeDownMessage ? { authorizeDownMessage: deps.authorizeDownMessage } : {},
1304
1569
  perWorker: deps.perWorker,
1305
- ...coordination?.host !== void 0 ? { host: coordination.host } : {},
1306
- ...coordination?.port !== void 0 ? { port: coordination.port } : {},
1307
- ...coordination?.allowUnauthenticatedRemote === true ? { allowUnauthenticatedRemote: true } : {},
1570
+ ...coordination ?? {},
1571
+ ...context ? { identity: {
1572
+ runId: context.runNamespace,
1573
+ actorId: context.ownerId
1574
+ } } : {},
1308
1575
  ...deps.deliverable ? { deliverable: deps.deliverable } : {},
1309
1576
  onStop: (reason) => {
1310
1577
  if (!stopController.signal.aborted) stopController.abort(reason ?? "coordination stop");
@@ -1368,6 +1635,7 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1368
1635
  task: reentry === void 0 ? task : reentry.steer,
1369
1636
  scope,
1370
1637
  coordinationMcpUrl: mcp.url,
1638
+ coordinationMcpHeaders: mcp.headers,
1371
1639
  stopSignal: stopController.signal,
1372
1640
  coordinationTools
1373
1641
  });
@@ -1995,6 +2263,8 @@ const routerSupervisorProfileMaterialization = defineProfileMaterializationContr
1995
2263
  "modelDefault",
1996
2264
  "modelProvider",
1997
2265
  "modelReasoningEffort",
2266
+ "modelMaxVisibleOutputTokens",
2267
+ "modelMaxTotalOutputTokens",
1998
2268
  "modelMetadata",
1999
2269
  "harness",
2000
2270
  "metadata"
@@ -2054,9 +2324,18 @@ function profileToolSpawnPreflight(runtimeOwnsManager, canResolveProductTools) {
2054
2324
  * environment nor a reservation exists yet. A router-brained child holds the same tools in-process
2055
2325
  * and needs no channel.
2056
2326
  */
2057
- function coordinationChannelSpawnPreflight(runtimeOwnsManager, hasCustomDriveHarness, managerBackend) {
2327
+ function coordinationChannelSpawnPreflight(runtimeOwnsManager, hasCustomDriveHarness, managerBackend, coordination) {
2058
2328
  if (!runtimeOwnsManager || hasCustomDriveHarness) return void 0;
2059
- if (managerBackend !== void 0 && automaticDriverBackendSupported(managerBackend)) return;
2329
+ if (managerBackend !== void 0 && automaticDriverBackendSupported(managerBackend, coordination)) {
2330
+ if (managerBackend.backend !== "provider") return void 0;
2331
+ return async (profile) => {
2332
+ if (!isExternalSupervisor(profile) || declaredRuntimeToolNames(profile).length === 0) return void 0;
2333
+ return await providerAcceptsCoordinationAttachments(managerBackend) ? void 0 : {
2334
+ cause: "unmountable-tool",
2335
+ detail: "the 'provider' backend does not advertise create.runtimeAttachments.mcp; Runtime cannot mount this manager's coordination tools before dispatch"
2336
+ };
2337
+ };
2338
+ }
2060
2339
  const missingChannel = managerBackend === void 0 ? "this run has no driverBackend" : `the '${managerBackend.backend}' backend has no coordination channel`;
2061
2340
  return async (profile) => {
2062
2341
  if (!isExternalSupervisor(profile)) return void 0;
@@ -2064,7 +2343,7 @@ function coordinationChannelSpawnPreflight(runtimeOwnsManager, hasCustomDriveHar
2064
2343
  if (declared.length === 0) return void 0;
2065
2344
  return {
2066
2345
  cause: "unmountable-tool",
2067
- detail: `the profile declares ${declared.map((name) => JSON.stringify(`${coordinationProfileToolPrefix}${name}`)).join(", ")} with harness ${JSON.stringify(profile.harness)}, but ${missingChannel}: Runtime's coordination MCP binds host loopback and reaches a harness only through the 'bridge' backend's runtime-attachments seam. Drive managers through a bridge driverBackend, or supply driveHarness/resolveDriveHarness with a relay this child can reach`
2346
+ detail: `the profile declares ${declared.map((name) => JSON.stringify(`${coordinationProfileToolPrefix}${name}`)).join(", ")} with harness ${JSON.stringify(profile.harness)}, but ${missingChannel}: Use a local bridge, or a provider with runtime MCP attachments and an authenticated coordination.publicUrl this child can reach; an explicit driveHarness may supply its own channel`
2068
2347
  };
2069
2348
  };
2070
2349
  }
@@ -2091,8 +2370,14 @@ const DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY = Object.freeze({
2091
2370
  function isExternalSupervisor(profile) {
2092
2371
  return harnessRunsAgent(profile.harness);
2093
2372
  }
2094
- function automaticDriverBackendSupported(backend) {
2095
- return backend.backend === "bridge";
2373
+ function automaticDriverBackendSupported(backend, coordination) {
2374
+ return backend.backend === "bridge" || backend.backend === "provider" && !backend.steering && coordination?.authentication !== void 0 && coordination.publicUrl !== void 0;
2375
+ }
2376
+ async function providerAcceptsCoordinationAttachments(backend) {
2377
+ const create = (await resolveAgentEnvironmentProvider(backend.provider, backend.registry).capabilities()).create;
2378
+ if (!create || !("runtimeAttachments" in create)) return false;
2379
+ const attachments = create.runtimeAttachments;
2380
+ return Boolean(attachments && typeof attachments === "object" && "mcp" in attachments && attachments.mcp === true);
2096
2381
  }
2097
2382
  /** Run a harness-brained manager through the same executor factory as its children. The manager's
2098
2383
  * full profile is preserved, the live coordination server is added under one reserved alias, and
@@ -2103,7 +2388,14 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2103
2388
  const boundBackend = bindReusableExecutorExecutionId(captureReusableExecutorConfig(backend, "driveHarnessFromBackend"), executionId);
2104
2389
  const baseFactory = createExecutor(boundBackend);
2105
2390
  let activeExecutor;
2106
- const drive = async ({ profile, authoredProfile, task, scope, coordinationMcpUrl, stopSignal, coordinationTools }) => {
2391
+ const drive = async ({ profile, authoredProfile, task, scope, coordinationMcpUrl, coordinationMcpHeaders, stopSignal, coordinationTools }) => {
2392
+ const retainedOwner = boundBackend.backend === "provider" ? scopeRetainedOwnerContext(scope) : void 0;
2393
+ const originalTask = retainedOwner ? await prepareScopeRetainedOwnerTask(scope, task) : task;
2394
+ if (retainedOwner ? await scopeRetainedOwnerResult(scope) : void 0) {
2395
+ await restoreScopeOwnerAcceptedExecution(scope);
2396
+ consumeScopeRetainedOwnerResult(scope);
2397
+ return;
2398
+ }
2107
2399
  const initialBudget = scope.budget;
2108
2400
  if (!(scope.view.inFlight > 0 || scope.view.waiting > 0) && (initialBudget.tokensLeft <= 0 || initialBudget.iterationsLeft <= 0 || initialBudget.usdCapped && initialBudget.usdLeft <= 0 || initialBudget.deadlineMs > 0 && now() >= initialBudget.deadlineMs)) throw new ValidationError("driveHarnessFromBackend: supervisor budget exhausted");
2109
2401
  const canonicalDriverProfile = agentProfileSchema.parse(authoredProfile);
@@ -2118,15 +2410,52 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2118
2410
  };
2119
2411
  const turnStop = turnCap > 0 ? new AbortController() : void 0;
2120
2412
  const effectiveStopSignal = turnStop === void 0 ? stopSignal : stopSignal === void 0 ? turnStop.signal : AbortSignal.any([stopSignal, turnStop.signal]);
2121
- const executor = baseFactory(spec, {
2413
+ const attachment = {
2414
+ transport: "http",
2415
+ url: coordinationMcpUrl,
2416
+ ...coordinationMcpHeaders ? { headers: coordinationMcpHeaders } : {}
2417
+ };
2418
+ let factory = baseFactory;
2419
+ if (boundBackend.backend === "provider") {
2420
+ const credentialName = "AGENT_RUNTIME_COORDINATION_TOKEN";
2421
+ const authorization = coordinationMcpHeaders?.Authorization;
2422
+ if (!authorization?.startsWith("Bearer ")) throw new ValidationError("driveHarnessFromBackend: provider coordination requires a bearer credential");
2423
+ if (Object.hasOwn(boundBackend.defaults?.env ?? {}, credentialName)) throw new ValidationError("driveHarnessFromBackend: provider defaults contain the reserved coordination credential name");
2424
+ if (Object.hasOwn(boundBackend.defaults?.runtimeAttachments?.mcp ?? {}, "agent-runtime-coordination")) throw new ValidationError("driveHarnessFromBackend: provider defaults contain the reserved coordination attachment alias");
2425
+ if (!await providerAcceptsCoordinationAttachments(boundBackend)) throw new ValidationError("driveHarnessFromBackend: provider does not advertise create.runtimeAttachments.mcp; no environment was created");
2426
+ factory = createExecutor({
2427
+ ...boundBackend,
2428
+ defaults: {
2429
+ ...boundBackend.defaults ?? {},
2430
+ env: {
2431
+ ...boundBackend.defaults?.env ?? {},
2432
+ [credentialName]: authorization.slice(7)
2433
+ },
2434
+ runtimeAttachments: { mcp: {
2435
+ ...boundBackend.defaults?.runtimeAttachments?.mcp ?? {},
2436
+ [coordinationMcpAlias]: {
2437
+ transport: "http",
2438
+ url: coordinationMcpUrl,
2439
+ headers: { Authorization: {
2440
+ kind: "secret-ref",
2441
+ key: credentialName,
2442
+ format: "bearer"
2443
+ } }
2444
+ }
2445
+ } }
2446
+ }
2447
+ });
2448
+ }
2449
+ const executor = factory(spec, {
2122
2450
  signal: scope.signal,
2123
2451
  node: scopeOwnerExecutorNodeContext(scope),
2124
2452
  seams: {
2453
+ ...retainedOwner ? { [retainedExecutorSeamKey]: {
2454
+ ...retainedOwner,
2455
+ onResult: async (result) => commitOwnerResult(result)
2456
+ } } : {},
2125
2457
  ...effectiveStopSignal === void 0 ? {} : { [bridgeStopSignalKey]: effectiveStopSignal },
2126
- [bridgeRuntimeAttachmentsKey]: { [coordinationMcpAlias]: {
2127
- transport: "http",
2128
- url: coordinationMcpUrl
2129
- } }
2458
+ [bridgeRuntimeAttachmentsKey]: { [coordinationMcpAlias]: attachment }
2130
2459
  }
2131
2460
  });
2132
2461
  activeExecutor = executor;
@@ -2134,6 +2463,19 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2134
2463
  let started = false;
2135
2464
  let terminalAccountingCaptured = false;
2136
2465
  let pendingUsage = [];
2466
+ let observedOwnerSpend = zeroSpend();
2467
+ let committedOwnerSpend = retainedOwner ? await scopeRetainedOwnerPriorSpend(scope) : zeroSpend();
2468
+ const ownerDelta = (total) => ({
2469
+ iterations: Math.max(0, total.iterations - committedOwnerSpend.iterations),
2470
+ tokens: {
2471
+ input: Math.max(0, total.tokens.input - committedOwnerSpend.tokens.input),
2472
+ output: Math.max(0, total.tokens.output - committedOwnerSpend.tokens.output)
2473
+ },
2474
+ usd: Math.max(0, total.usd - committedOwnerSpend.usd),
2475
+ ms: Math.max(0, total.ms - committedOwnerSpend.ms),
2476
+ ...total.tokensKnown === false ? { tokensKnown: false } : {},
2477
+ ...total.usdKnown === false ? { usdKnown: false } : {}
2478
+ });
2137
2479
  let meteredProviderAttempts = 0;
2138
2480
  const providerEvidenceForNextMeter = () => {
2139
2481
  const attempt = runtimeOwnedExecutorProviderEvidence(executor)?.attempts[meteredProviderAttempts++];
@@ -2176,14 +2518,17 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2176
2518
  const batch = pendingUsage;
2177
2519
  pendingUsage = [];
2178
2520
  const measured = spendFromUsageEvents(batch);
2521
+ observedOwnerSpend = addSpend(observedOwnerSpend, measured);
2522
+ const charge = retainedOwner ? ownerDelta(observedOwnerSpend) : measured;
2179
2523
  await meterRuntimeOwnedProviderAttempt(scope, forceUnknown ? {
2180
- ...measured,
2524
+ ...charge,
2181
2525
  tokensKnown: false,
2182
2526
  usdKnown: false
2183
- } : measured, providerEvidenceForNextMeter(), {
2527
+ } : charge, providerEvidenceForNextMeter(), {
2184
2528
  role: "driver",
2185
2529
  runtime: executor.runtime
2186
2530
  });
2531
+ if (retainedOwner) committedOwnerSpend = addSpend(committedOwnerSpend, charge);
2187
2532
  const budget = scope.budget;
2188
2533
  if (budget.tokensLeft <= 0 || budget.usdCapped && budget.usdLeft <= 0 || budget.deadlineMs > 0 && now() >= budget.deadlineMs) throw new ValidationError("driveHarnessFromBackend: supervisor budget exhausted");
2189
2534
  };
@@ -2217,6 +2562,28 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2217
2562
  }
2218
2563
  });
2219
2564
  };
2565
+ const commitOwnerResult = async (result) => {
2566
+ const declaration = runtimeOwnedExecutorMaterialization(executor);
2567
+ const binding = runtimeOwnedExecutorExecutionBinding(executor);
2568
+ if (!declaration || !binding) throw new ValidationError("retained owner result requires terminal materialization before release");
2569
+ if (!ownerMaterializationPublished) {
2570
+ await publishMaterialization(declaration, binding);
2571
+ ownerMaterializationPublished = true;
2572
+ }
2573
+ await meterPending();
2574
+ const total = {
2575
+ ...result.spent,
2576
+ iterations: 0
2577
+ };
2578
+ const delta = ownerDelta(total);
2579
+ await meterRuntimeOwnedAccounting(scope, delta, {
2580
+ role: "driver",
2581
+ runtime: executor.runtime
2582
+ });
2583
+ committedOwnerSpend = addSpend(committedOwnerSpend, delta);
2584
+ await retainedOwner.onResult(result);
2585
+ terminalAccountingCaptured = true;
2586
+ };
2220
2587
  try {
2221
2588
  const declaration = runtimeOwnedExecutorMaterialization(executor);
2222
2589
  const executionBinding = runtimeOwnedExecutorExecutionBinding(executor);
@@ -2224,10 +2591,14 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2224
2591
  if (pending !== void 0) {
2225
2592
  if (pending.runtime !== executor.runtime || pending.binding.attemptId !== scopeOwnerExecutorNodeContext(scope).attemptId) throw new ValidationError("driveHarnessFromBackend: pending executor did not bind the kernel-minted attempt");
2226
2593
  if (canonicalAgentProfileDigest(pending.declaration.effectiveProfile) !== canonicalAgentProfileDigest(providerDriverProfile)) throw new ValidationError("driveHarnessFromBackend: pending executor changed the provider-visible AgentProfile before execution");
2227
- } else await publishMaterialization(declaration, executionBinding);
2594
+ } else {
2595
+ await publishMaterialization(declaration, executionBinding);
2596
+ ownerMaterializationPublished = true;
2597
+ }
2228
2598
  if (executor.budgetExempt) throw new ValidationError(`driveHarnessFromBackend: runtime ${JSON.stringify(executor.runtime)} does not report usage and cannot drive a budgeted supervisor`);
2229
2599
  started = true;
2230
- const run = executor.execute(task, scope.signal);
2600
+ if (retainedOwner?.admissions.length && !executor.recover) throw new ValidationError("retained owner executor does not support recovery");
2601
+ const run = retainedOwner?.admissions.length ? executor.recover(originalTask, scope.signal) : executor.execute(originalTask, scope.signal);
2231
2602
  if (isAsyncIterable(run)) {
2232
2603
  let turns = 0;
2233
2604
  for await (const event of run) if (event.kind === "iteration") {
@@ -2238,7 +2609,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2238
2609
  await meterPending();
2239
2610
  const artifact = executor.resultArtifact();
2240
2611
  terminalAccountingCaptured = true;
2241
- if (artifact.spent.tokensKnown === false || artifact.spent.usdKnown === false) await meterRuntimeOwnedAccounting(scope, {
2612
+ if (!retainedOwner && (artifact.spent.tokensKnown === false || artifact.spent.usdKnown === false)) await meterRuntimeOwnedAccounting(scope, {
2242
2613
  iterations: 0,
2243
2614
  tokens: {
2244
2615
  input: 0,
@@ -2264,7 +2635,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2264
2635
  runtime: executor.runtime
2265
2636
  });
2266
2637
  }
2267
- if (pending !== void 0) {
2638
+ if (pending !== void 0 && !ownerMaterializationPublished) {
2268
2639
  const acknowledged = runtimeOwnedExecutorMaterialization(executor);
2269
2640
  const acknowledgedBinding = runtimeOwnedExecutorExecutionBinding(executor);
2270
2641
  if (acknowledged === void 0 || acknowledgedBinding === void 0) throw new ValidationError("driveHarnessFromBackend: external executor completed without a terminal materialization acknowledgement");
@@ -2335,7 +2706,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns)
2335
2706
  if (!deliver) return false;
2336
2707
  return deliver.call(activeExecutor, message) !== false;
2337
2708
  };
2338
- return attestRuntimeOwnedScopeOwner(drive, "cli");
2709
+ return attestRuntimeOwnedScopeOwner(drive, boundBackend.backend === "provider" ? boundBackend.runtime ?? resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry).name : "cli");
2339
2710
  }
2340
2711
  function isAsyncIterable(value) {
2341
2712
  return value !== null && typeof value === "object" && Symbol.asyncIterator in value && typeof value[Symbol.asyncIterator] === "function";
@@ -2470,9 +2841,17 @@ function assertNoUncapturedExecutableOption(decisionData) {
2470
2841
  * mutable options object can no longer change an in-flight run. */
2471
2842
  function captureSuperviseOptions(opts) {
2472
2843
  assertSuperviseOptionKeys(opts, "supervise");
2473
- const { backend, driverBackend, deliverable, resolveDeliverable, router, compaction, watchWorkers, analysts, makeWorkerAgent, makeLeafAgent, resolveSpawnProfile, blobs, journal, probes, registry, hooks, otel, authorizeSpawn, authorizeMessage, driveHarness, resolveDriveHarness, resolveSupervisorTools, escalateQuestion, onCoordinationEvent, executeExtraTool, stopRule, onProgressStop, onDriverAttempt, onUnmetContract, workerRetry, onWorkerRetry, finalizer, now, signal, rootHandle, ...decisionData } = opts;
2844
+ const { backend, coordination, driverBackend, deliverable, resolveDeliverable, router, compaction, watchWorkers, analysts, makeWorkerAgent, makeLeafAgent, resolveSpawnProfile, blobs, journal, probes, registry, hooks, otel, authorizeSpawn, authorizeMessage, driveHarness, resolveDriveHarness, resolveSupervisorTools, escalateQuestion, onCoordinationEvent, executeExtraTool, stopRule, onProgressStop, onDriverAttempt, onUnmetContract, workerRetry, onWorkerRetry, finalizer, now, signal, rootHandle, ...decisionData } = opts;
2474
2845
  assertNoUncapturedExecutableOption(decisionData);
2475
2846
  const capturedData = detachedSnapshot(decisionData, "supervise options");
2847
+ const capturedCoordination = coordination === void 0 ? void 0 : (() => {
2848
+ const { publicUrl, onAudit, ...configuration } = coordination;
2849
+ return Object.freeze({
2850
+ ...detachedSnapshot(configuration, "supervise coordination configuration"),
2851
+ ...publicUrl === void 0 ? {} : { publicUrl },
2852
+ ...onAudit === void 0 ? {} : { onAudit }
2853
+ });
2854
+ })();
2476
2855
  const capturedBackend = backend === void 0 ? void 0 : snapshotExecutorConfig(backend);
2477
2856
  const capturedDriverBackend = driverBackend === void 0 ? void 0 : snapshotExecutorConfig(driverBackend);
2478
2857
  const capturedDeliverable = deliverable === void 0 || typeof deliverable === "string" ? deliverable : captureDeliverable(deliverable, "supervise deliverable");
@@ -2512,6 +2891,7 @@ function captureSuperviseOptions(opts) {
2512
2891
  });
2513
2892
  return Object.freeze({
2514
2893
  ...capturedData,
2894
+ ...capturedCoordination === void 0 ? {} : { coordination: capturedCoordination },
2515
2895
  ...capturedBackend === void 0 ? {} : { backend: capturedBackend },
2516
2896
  ...capturedDriverBackend === void 0 ? {} : { driverBackend: capturedDriverBackend },
2517
2897
  ...capturedDeliverable === void 0 ? {} : { deliverable: capturedDeliverable },
@@ -2753,9 +3133,9 @@ function superviseInternal(profile, task, opts, testBrain) {
2753
3133
  const managerBackend = options.driverBackend ?? (options.rootDriverFromBackend === false ? void 0 : options.backend);
2754
3134
  if (options.driveHarness && options.resolveDriveHarness) throw new ValidationError("supervise: provide driveHarness or resolveDriveHarness, not both");
2755
3135
  const hasCustomDriveHarness = Boolean(options.driveHarness || options.resolveDriveHarness);
2756
- const spawnPreflight = composeSpawnPreflights(profileToolSpawnPreflight(options.makeWorkerAgent === void 0, options.resolveSupervisorTools !== void 0), coordinationChannelSpawnPreflight(options.makeWorkerAgent === void 0, hasCustomDriveHarness, managerBackend), options.backend?.backend === "bridge" ? bridgeSpawnPreflight(options.backend) : void 0);
2757
- const driverMaterialization = hasCustomDriveHarness ? options.driveHarnessMaterialization ?? fullProfileMaterialization : managerBackend && automaticDriverBackendSupported(managerBackend) ? backendProfileMaterialization(managerBackend) : void 0;
2758
- if (isExternalSupervisor(canonicalProfile) && !options.driveHarness && !options.resolveDriveHarness && (!managerBackend || !automaticDriverBackendSupported(managerBackend))) throw new ValidationError(`supervise: external supervisor profile.harness=${JSON.stringify(canonicalProfile.harness)} requires a local bridge driverBackend, an explicit driveHarness, or resolveDriveHarness with reachable coordination transport`);
3136
+ const spawnPreflight = composeSpawnPreflights(profileToolSpawnPreflight(options.makeWorkerAgent === void 0, options.resolveSupervisorTools !== void 0), coordinationChannelSpawnPreflight(options.makeWorkerAgent === void 0, hasCustomDriveHarness, managerBackend, options.coordination), options.backend?.backend === "bridge" ? bridgeSpawnPreflight(options.backend) : void 0);
3137
+ const driverMaterialization = hasCustomDriveHarness ? options.driveHarnessMaterialization ?? fullProfileMaterialization : managerBackend && automaticDriverBackendSupported(managerBackend, options.coordination) ? backendProfileMaterialization(managerBackend) : void 0;
3138
+ if (isExternalSupervisor(canonicalProfile) && !options.driveHarness && !options.resolveDriveHarness && (!managerBackend || !automaticDriverBackendSupported(managerBackend, options.coordination))) throw new ValidationError(`supervise: external supervisor profile.harness=${JSON.stringify(canonicalProfile.harness)} requires a local bridge, a provider with authenticated coordination.publicUrl and runtime MCP attachments, or an explicit driveHarness with reachable coordination transport`);
2759
3139
  const harnessClaims = /* @__PURE__ */ new WeakMap();
2760
3140
  const claimDriveHarness = (rawHarness, ownerId) => {
2761
3141
  if (typeof rawHarness !== "function") throw new ValidationError("supervise: resolveDriveHarness must return a DriveHarness function");
@@ -2778,7 +3158,7 @@ function superviseInternal(profile, task, opts, testBrain) {
2778
3158
  const driveHarnessForOwner = (context) => {
2779
3159
  if (options.resolveDriveHarness) return claimDriveHarness(options.resolveDriveHarness(context), context.ownerId);
2780
3160
  if (options.driveHarness) return claimDriveHarness(options.driveHarness, context.ownerId);
2781
- return managerBackend && automaticDriverBackendSupported(managerBackend) ? driveHarnessFromBackend(managerBackend, externalExecutionId("supervised-manager", {
3161
+ return managerBackend && automaticDriverBackendSupported(managerBackend, options.coordination) ? driveHarnessFromBackend(managerBackend, externalExecutionId("supervised-manager", {
2782
3162
  runNamespace,
2783
3163
  ownerId: context.ownerId
2784
3164
  }), options.now ?? Date.now, options.maxTurns) : void 0;
@@ -2797,6 +3177,7 @@ function superviseInternal(profile, task, opts, testBrain) {
2797
3177
  const now = options.now ?? Date.now;
2798
3178
  let spans;
2799
3179
  const traceUnpropagated = options.backend ? workerTraceUnpropagatedDeclaration(options.backend.backend) : void 0;
3180
+ const recoveryFactories = /* @__PURE__ */ new WeakMap();
2800
3181
  let makeWorkerAgent = options.makeWorkerAgent;
2801
3182
  if (!makeWorkerAgent) {
2802
3183
  if (!options.backend && !options.makeLeafAgent) throw new ValidationError("supervise: provide opts.backend (where workers run), opts.makeLeafAgent, or opts.makeWorkerAgent");
@@ -2804,7 +3185,7 @@ function superviseInternal(profile, task, opts, testBrain) {
2804
3185
  const makeLeaf = withRetry(options.makeLeafAgent ?? workerFromBackend(options.backend, deliverable));
2805
3186
  const securityPolicy = options.profileSecurity ?? DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY;
2806
3187
  const makeRecursiveWorkerFor = (parent, parentIdentity, depth, parentOwnerId) => {
2807
- const makeRecursiveWorker = (authoredProfile, spawnContext) => {
3188
+ const makeRecursiveWorker = (authoredProfile, spawnContext, recovering = false) => {
2808
3189
  if (!spawnContext) throw new ValidationError("supervise: backend-derived workers require spawn context");
2809
3190
  const input = freezeDetachedProfile(authoredProfile);
2810
3191
  const authorizationInput = Object.freeze({
@@ -2821,7 +3202,7 @@ function superviseInternal(profile, task, opts, testBrain) {
2821
3202
  ...spawnContext.analyst !== void 0 ? { analyst: spawnContext.analyst } : {},
2822
3203
  ...spawnContext.continuity !== void 0 ? { continuity: spawnContext.continuity } : {}
2823
3204
  });
2824
- const decision = options.authorizeSpawn ? freezeDetached(options.authorizeSpawn(authorizationInput)) : Object.freeze({
3205
+ const decision = !recovering && options.authorizeSpawn ? freezeDetached(options.authorizeSpawn(authorizationInput)) : Object.freeze({
2825
3206
  profile: input,
2826
3207
  ...spawnContext.execution ? { execution: spawnContext.execution } : {}
2827
3208
  });
@@ -2868,7 +3249,7 @@ function superviseInternal(profile, task, opts, testBrain) {
2868
3249
  profile: authorized,
2869
3250
  task: spawnContext.task
2870
3251
  })) : void 0;
2871
- if (isExternalSupervisor(authorized) && !nestedDriveHarness) throw new ValidationError(`supervise: authored external supervisor profile.harness=${JSON.stringify(authorized.harness)} requires a local bridge driverBackend, an explicit driveHarness, or resolveDriveHarness with reachable coordination transport`);
3252
+ if (isExternalSupervisor(authorized) && !nestedDriveHarness) throw new ValidationError(`supervise: authored external supervisor profile.harness=${JSON.stringify(authorized.harness)} requires a local bridge, a provider with authenticated coordination.publicUrl and runtime MCP attachments, or an explicit driveHarness with reachable coordination transport`);
2872
3253
  assertProfileContract(authorized, isExternalSupervisor(authorized) ? driverMaterialization : promptModelProfileMaterialization, `supervise driver ${JSON.stringify(spawnContext.label)}`, true);
2873
3254
  if (managerBackend) assertBridgeProfileMaterializes(profileWithoutDeclaredRuntimeCoordinationTools(authorized), managerBackend, `supervise driver ${JSON.stringify(spawnContext.label)}`);
2874
3255
  const childFactory = makeRecursiveWorkerFor(authorized, childExecution.identity, depth + 1, ownerId);
@@ -2882,6 +3263,7 @@ function superviseInternal(profile, task, opts, testBrain) {
2882
3263
  perWorker: nestedPerWorker,
2883
3264
  ...options.router ? { router: options.router } : {},
2884
3265
  ...nestedDriveHarness ? { driveHarness: nestedDriveHarness } : {},
3266
+ ...options.coordination && isExternalSupervisor(authorized) ? { coordination: options.coordination } : {},
2885
3267
  nodeContext: {
2886
3268
  runId,
2887
3269
  runNamespace,
@@ -2924,8 +3306,32 @@ function superviseInternal(profile, task, opts, testBrain) {
2924
3306
  controlDir: resolve(options.runDir),
2925
3307
  controlScope: "subtree"
2926
3308
  }
2927
- }), journal, childExecution.ref, () => acceptedSubmission);
3309
+ }), journal, childExecution.ref, () => acceptedSubmission, recoveryFactories.get(childFactory));
2928
3310
  };
3311
+ if (options.makeLeafAgent === void 0 && options.backend?.backend === "provider" && !options.backend.steering) {
3312
+ const factory = registerRetainedExecutorPreparation(createExecutor(options.backend), ({ spawned, profile, task }) => {
3313
+ if (!spawned.ownedTreeRoot || !spawned.parent || !spawned.assignmentId || !spawned.identity) return void 0;
3314
+ const execution = {
3315
+ ...spawned.identity.candidateDigest ? { candidateDigest: spawned.identity.candidateDigest } : {},
3316
+ ...spawned.identity.correlation ? { correlation: spawned.identity.correlation } : {}
3317
+ };
3318
+ const spec = makeRecursiveWorker(profile, {
3319
+ assignmentId: spawned.assignmentId,
3320
+ parentNodeId: spawned.parent,
3321
+ budget: spawned.budget,
3322
+ task,
3323
+ label: spawned.label,
3324
+ ...spawned.key === void 0 ? {} : { key: spawned.key },
3325
+ execution
3326
+ }, true).executorSpec;
3327
+ if (!spec || !isDriverSpec(spec)) return void 0;
3328
+ return {
3329
+ spec,
3330
+ factory: driverExecutorFactory
3331
+ };
3332
+ });
3333
+ recoveryFactories.set(makeRecursiveWorker, factory);
3334
+ }
2929
3335
  return makeRecursiveWorker;
2930
3336
  };
2931
3337
  makeWorkerAgent = makeRecursiveWorkerFor(canonicalProfile, rootExecution.identity, 1, rootOwnerId);
@@ -2947,7 +3353,7 @@ function superviseInternal(profile, task, opts, testBrain) {
2947
3353
  },
2948
3354
  ...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 } : {},
2949
3355
  ...finalizer ? { finalizer } : {},
2950
- ...options.coordination ? { coordination: options.coordination } : {},
3356
+ ...options.coordination && isExternalSupervisor(canonicalProfile) ? { coordination: options.coordination } : {},
2951
3357
  ...spawnPreflight ? { preflightSpawn: spawnPreflight } : {},
2952
3358
  ...options.resolveSpawnProfile ? { resolveSpawnProfile: options.resolveSpawnProfile } : {},
2953
3359
  ...options.peerMail ? { peerMail: options.peerMail } : {},
@@ -3005,6 +3411,7 @@ function superviseInternal(profile, task, opts, testBrain) {
3005
3411
  journal,
3006
3412
  blobs,
3007
3413
  executors: ctx.executors,
3414
+ ...recoveryFactories.get(workerFactory) ? { recoverExecutor: recoveryFactories.get(workerFactory) } : {},
3008
3415
  rootIdentity: rootExecution.identity,
3009
3416
  ...rootOwnerRuntime === void 0 ? {} : { rootMaterialization: {
3010
3417
  runtime: rootOwnerRuntime,
@@ -3065,4 +3472,4 @@ function rootProviderModelEvidenceFromExecution(evidence) {
3065
3472
  //#endregion
3066
3473
  export { serveCoordinationMcp as _, isPreSpawnExecutorFailure as a, mapExecutorResult as b, withWorkerSpawnRetry as c, resolveSupervisorProfile as d, supervisorAgent as f, defaultUnmetContractSteer as g, classifyDriverFailure as h, workerFromBackend as i, assertCoordinationBinding as l, DriverAttemptsExhaustedError as m, supervise as n, resolveWorkerSpawnRetry as o, supervisorAgentWithTestBrain as p, superviseWithTestBrain as r, retryPreSpawnRefusals as s, DEFAULT_AUTHORED_PROFILE_SECURITY_POLICY as t, coordinationProfileToolPrefix as u, createSupervisorSpanRecorder as v, gateOnDeliverable as y };
3067
3474
 
3068
- //# sourceMappingURL=supervise-BGNXB8No.js.map
3475
+ //# sourceMappingURL=supervise-DmFO50N6.js.map