@tangle-network/agent-runtime 0.229.0 → 0.232.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-o9SrkJqs.js → activation-BXjgjus6.js} +2 -2
  2. package/dist/{activation-o9SrkJqs.js.map → activation-BXjgjus6.js.map} +1 -1
  3. package/dist/{activation-DFSQ90A8.d.ts → activation-LJ33ygpS.d.ts} +2 -2
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-C6rde-Rv.js → coordination-driver-hXWuo-1n.js} +16 -14
  7. package/dist/{coordination-driver-C6rde-Rv.js.map → coordination-driver-hXWuo-1n.js.map} +1 -1
  8. package/dist/{delegate-Cmd-qlWH.js → delegate-B8b6oHnj.js} +2 -2
  9. package/dist/{delegate-Cmd-qlWH.js.map → delegate-B8b6oHnj.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +9 -3
  12. package/dist/durable.js.map +1 -1
  13. package/dist/{graph-BK05MhFv.js → graph-Ce7g744w.js} +3 -3
  14. package/dist/{graph-BK05MhFv.js.map → graph-Ce7g744w.js.map} +1 -1
  15. package/dist/{improvement-cycle-DHl4SxbQ.js → improvement-cycle-CGAPVMst.js} +3 -3
  16. package/dist/{improvement-cycle-DHl4SxbQ.js.map → improvement-cycle-CGAPVMst.js.map} +1 -1
  17. package/dist/{index-B6xSpuPo.d.ts → index-BnEWL76W.d.ts} +33 -22
  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 +3 -3
  22. package/dist/kernel.d.ts +4 -4
  23. package/dist/kernel.js +9 -9
  24. package/dist/{loop-runner-bin-D5hutINM.d.ts → loop-runner-bin-BdobVmHx.d.ts} +3 -3
  25. package/dist/{loop-runner-bin-CU2bdlr1.js → loop-runner-bin-Q47flacp.js} +3 -3
  26. package/dist/{loop-runner-bin-CU2bdlr1.js.map → loop-runner-bin-Q47flacp.js.map} +1 -1
  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 +5 -5
  31. package/dist/mcp/index.js +6 -6
  32. package/dist/mcp/memory-bin.js +1 -1
  33. package/dist/{memory-server-BR310Weg.js → memory-server-Cn8LbAxO.js} +2 -2
  34. package/dist/{memory-server-BR310Weg.js.map → memory-server-Cn8LbAxO.js.map} +1 -1
  35. package/dist/{openai-tools-HhRT1L1W.d.ts → openai-tools-Dl5AKEtq.d.ts} +2 -2
  36. package/dist/profiles.d.ts +2 -2
  37. package/dist/{provision-supervisor-C2rRWXG6.js → provision-supervisor-BXnC4uwd.js} +3 -3
  38. package/dist/{provision-supervisor-C2rRWXG6.js.map → provision-supervisor-BXnC4uwd.js.map} +1 -1
  39. package/dist/{runtime-BBcrtrkj.js → runtime-CcMvprwa.js} +8 -8
  40. package/dist/{runtime-BBcrtrkj.js.map → runtime-CcMvprwa.js.map} +1 -1
  41. package/dist/{server-CWIl-a3C.js → server-ClTO4X79.js} +4 -4
  42. package/dist/{server-CWIl-a3C.js.map → server-ClTO4X79.js.map} +1 -1
  43. package/dist/stream-agent-turn-nAvemLZR.d.ts +2049 -0
  44. package/dist/{structural-rollout-zl02ztZ4.js → structural-rollout-C9z5pjxN.js} +2 -2
  45. package/dist/{structural-rollout-zl02ztZ4.js.map → structural-rollout-C9z5pjxN.js.map} +1 -1
  46. package/dist/{substrate-sWW5cDIe.d.ts → substrate-ijm9h_79.d.ts} +2 -2
  47. package/dist/{supervise-DbNMYx7z.js → supervise-CLkM45VY.js} +144 -28
  48. package/dist/supervise-CLkM45VY.js.map +1 -0
  49. package/dist/{supervisor-DAHG98Rs.js → supervisor-BVAM5glY.js} +609 -262
  50. package/dist/supervisor-BVAM5glY.js.map +1 -0
  51. package/dist/testing.d.ts +2 -2
  52. package/dist/testing.js +12 -12
  53. package/dist/{tool-server-BJbCPhoW.js → tool-server-x9NEhvHZ.js} +2 -2
  54. package/dist/tool-server-x9NEhvHZ.js.map +1 -0
  55. package/dist/tui/index.d.ts +1 -1
  56. package/dist/tui/index.js +1 -1
  57. package/dist/{stream-agent-turn-jPdnzI_5.d.ts → types-C8Fj6hNL.d.ts} +4103 -4746
  58. package/package.json +4 -4
  59. package/dist/supervise-DbNMYx7z.js.map +0 -1
  60. package/dist/supervisor-DAHG98Rs.js.map +0 -1
  61. package/dist/tool-server-BJbCPhoW.js.map +0 -1
  62. package/dist/types-Ba5mJkyd.d.ts +0 -1293
@@ -1,4 +1,4 @@
1
- import { k as Validator, r as Driver, t as AgentRunSpec, w as OutputAdapter } from "./types-Ba5mJkyd.js";
1
+ import { Ir as AgentRunSpec, Rr as Driver, ai as OutputAdapter, ui as Validator } from "./types-C8Fj6hNL.js";
2
2
  import { AgentProfile } from "@tangle-network/agent-interface";
3
3
  //#region src/profiles/coder.d.ts
4
4
  /**
@@ -281,4 +281,4 @@ interface UiFinding {
281
281
  }
282
282
  //#endregion
283
283
  export { CoderTask as _, UiFindingSeverity as a, KnowledgeUpdate as c, ResearchSource as d, ResearchTask as f, researcherProfile as g, multiHarnessResearcherFanout as h, UiFindingScreenshot as i, MultiHarnessResearcherFanoutOptions as l, createResearcherValidator as m, UI_LENSES as n, UiLens as o, ResearcherProfileOptions as p, UiFinding as r, KnowledgeItem as s, UI_FINDING_SEVERITIES as t, ResearchOutput as u, coderTaskToPrompt as v };
284
- //# sourceMappingURL=substrate-sWW5cDIe.d.ts.map
284
+ //# sourceMappingURL=substrate-ijm9h_79.d.ts.map
@@ -1,10 +1,10 @@
1
- import { $n as generateSpanId, $r as runtimeOwnedExecutorProviderEvidence, Ai as sleep, At as WORKER_TRACE_PROPAGATION, C as scopeOwnerExecutorNodeContext, Cr as defineProfileMaterializationContract, Dn as registerRetainedExecutorPreparation, Dr as promptModelProfileMaterialization, Dt as newUsageTotals, Er as promptControlProfileMaterialization, Et as meterUsageEvent, F as scopeRetainedOwnerResult, Fi as withTimeout, Fr as worktreeCliProfileMaterialization, Gi as teardownExecutor, Ii as zeroSpend, Ir as isNoEntError, Jr as providerAttemptEvidence, Li as addResourceSpend, Lr as parseCommittedJsonLines, M as prepareScopeRetainedOwnerTask, Mn as runAbortable, N as scopeRetainedOwnerContext, Nr as unsupportedProfileDimensions, On as retainedExecutorSeamKey, P as scopeRetainedOwnerPriorSpend, Pi as unmeteredSpend, Q as captureReusableExecutorConfig, Qr as runtimeOwnedExecutorMaterialization, Ri as resourceTelemetry, Rr as prepareJsonlAppend, S as restoreScopeOwnerAcceptedExecution, Si as addSpend, Sn as resolveAgentEnvironmentProvider, Sr as controlProfileMaterialization, St as contentAddress, Tr as profileMaterializationAxes$1, Ui as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, Vr as attestRuntimeOwnedScopeOwner, Wr as inheritRuntimeOwnedExecutorAttestation, Xn as createOtelExporter, Xr as runtimeOwnedDriveHarnessProviderEvidence, Xt as bridgeAdmissionRefusal, Yr as recordRuntimeOwnedDriveHarnessProviderEvidence, Z as bindReusableExecutorExecutionId, Zr as runtimeOwnedExecutorExecutionBinding, Zt as bridgeModelRouteRefusal, b as meterRuntimeOwnedProviderAttempt, d as runDriverWithRetry, ei as runtimeOwnedPendingExecutorMaterialization, f as driverChild, g as beginScopeOwnerAttempt, j as consumeScopeRetainedOwnerResult, jr as renderUnsupported, kn as RunCancellationReason, kt as spendFromUsageTotals, m as isDriverSpec, mn as routerBrain, n as createSupervisor, nn as bridgeRuntimeAttachmentsKey, o as runFinalizer, p as driverExecutorFactory, r as bestDelivered, rn as bridgeStopSignalKey, rr as toOtelAttributes, rt as snapshotExecutorConfig, s as runTree, si as detachedSnapshot, t as createRootHandle, ti as runtimeOwnedScopeOwnerRuntime, tt as createExecutor, u as defaultUnmetContractSteer, v as deriveNodeExecutionIdentity, wr as fullProfileMaterialization, wt as assertValidBudget, x as recordScopeOwnerMaterialization, xr as assertProfileMaterialization, y as meterRuntimeOwnedAccounting, zi as withBudgetResources, zt as createInbox } from "./supervisor-DAHG98Rs.js";
2
- import { i as ConfigError, m as ValidationError } from "./errors-DodWX-cb.js";
1
+ import { $ as bindReusableExecutorExecutionId, $r as providerAttemptEvidence, An as RunCancellationReason, Ar as profileMaterializationAxes$1, At as spendFromUsageTotals, Bi as withTimeout, Br as worktreeCliProfileMaterialization, Bt as createInbox, C as scopeOwnerExecutorNodeContext, Cn as resolveAgentEnvironmentProvider, Di as addSpend, Dr as controlProfileMaterialization, Dt as meterUsageEvent, Er as assertProfileMaterialization, F as scopeRetainedOwnerPriorSpend, Fi as sleep, Gn as contentAddress, Hi as addResourceSpend, Hr as parseCommittedJsonLines, I as scopeRetainedOwnerResult, Ir as renderUnsupported, J as errMessage, Ji as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, Kr as attestRuntimeOwnedScopeOwner, M as consumeScopeRetainedOwnerResult, Mn as linkAbort, Mr as promptModelProfileMaterialization, N as prepareScopeRetainedOwnerTask, Nn as runAbortable, On as registerRetainedExecutorPreparation, Or as defineProfileMaterializationContract, Ot as newUsageTotals, P as scopeRetainedOwnerContext, Qt as bridgeModelRouteRefusal, Rr as unsupportedProfileDimensions, S as restoreScopeOwnerAcceptedExecution, Tt as assertValidBudget, Ui as resourceTelemetry, Ur as prepareJsonlAppend, Vi as zeroSpend, Vr as isNoEntError, Wi as withBudgetResources, Xi as teardownExecutor, Yr as inheritRuntimeOwnedExecutorAttestation, Zt as bridgeAdmissionRefusal, ai as runtimeOwnedPendingExecutorMaterialization, at as snapshotExecutorConfig, b as meterRuntimeOwnedProviderAttempt, cr as toOtelAttributes, d as runDriverWithRetry, ei as recordRuntimeOwnedDriveHarnessProviderEvidence, et as captureReusableExecutorConfig, f as driverChild, fi as detachedSnapshot, g as beginScopeOwnerAttempt, hn as routerBrain, ii as runtimeOwnedExecutorProviderEvidence, in as bridgeStopSignalKey, ir as generateSpanId, j as bindScopeRetainedOwnerProvider, jr as promptControlProfileMaterialization, jt as WORKER_TRACE_PROPAGATION, kn as retainedExecutorSeamKey, kr as fullProfileMaterialization, m as isDriverSpec, n as createSupervisor, ni as runtimeOwnedExecutorExecutionBinding, o as runFinalizer, oi as runtimeOwnedScopeOwnerRuntime, p as driverExecutorFactory, r as bestDelivered, ri as runtimeOwnedExecutorMaterialization, rn as bridgeRuntimeAttachmentsKey, rt as createExecutor, s as runTree, t as createRootHandle, ti as runtimeOwnedDriveHarnessProviderEvidence, tr as createOtelExporter, u as defaultUnmetContractSteer, v as deriveNodeExecutionIdentity, x as recordScopeOwnerMaterialization, y as meterRuntimeOwnedAccounting, zi as unmeteredSpend } from "./supervisor-BVAM5glY.js";
2
+ import { f as RuntimeRunStateError, i as ConfigError, m as ValidationError } from "./errors-DodWX-cb.js";
3
3
  import { a as concreteProfileModel, c as profileModelExecutionSettings, d as agentHarness, f as harnessRunsAgent, n as assertModelAllowed, o as enforceTokenLimits, r as assertProfileModelsAllowed, s as profileBridgeWireModel, t as assertExecutableAgentProfile } from "./model-policy-BbSCSak0.js";
4
4
  import { t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
5
5
  import { n as assertNoSymlinkDescendant } from "./durable-file-D24y9zg7.js";
6
- import { t as createStdioToolServer } from "./tool-server-BJbCPhoW.js";
7
- import { D as coordinationVerbNames, O as createCoordinationTools, S as watchRunCancellation, c as createProgressTracker, d as progressStop, r as driverAgent, v as createFileRunContext, w as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, x as applyRunCancellation, y as createInMemoryRunContext } from "./coordination-driver-C6rde-Rv.js";
6
+ import { n as createStdioToolServer, t as PROTOCOL_VERSION } from "./tool-server-x9NEhvHZ.js";
7
+ import { D as coordinationVerbNames, O as createCoordinationTools, S as watchRunCancellation, c as createProgressTracker, d as progressStop, r as driverAgent, v as createFileRunContext, w as DEFAULT_AWAIT_EVENT_TIMEOUT_MS, x as applyRunCancellation, y as createInMemoryRunContext } from "./coordination-driver-hXWuo-1n.js";
8
8
  import { k as writeRunCancellation, o as readRunCancelRequest, s as readRunCancellation } from "./run-layout-hZREkcfu.js";
9
9
  import { agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, canonicalCandidateJson, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
10
10
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -78,6 +78,7 @@ function gateOnDeliverable(inner, deliverable) {
78
78
  ...inner.progress ? { progress: () => inner.progress?.() } : {},
79
79
  ...inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {},
80
80
  ...inner.metered ? { metered: () => inner.metered?.() } : {},
81
+ ...inner.harnessTranscript ? { harnessTranscript: () => inner.harnessTranscript?.() } : {},
81
82
  execute(task, signal) {
82
83
  const r = inner.execute(task, signal);
83
84
  if (isAsyncIterable$2(r)) return (async function* () {
@@ -138,6 +139,7 @@ function mapExecutorResult(inner, map) {
138
139
  ...inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {},
139
140
  ...inner.accounting ? { accounting: () => inner.accounting?.() } : {},
140
141
  ...inner.metered ? { metered: () => inner.metered?.() } : {},
142
+ ...inner.harnessTranscript ? { harnessTranscript: () => inner.harnessTranscript?.() } : {},
141
143
  execute(task, signal) {
142
144
  const execution = inner.execute(task, signal);
143
145
  if (isAsyncIterable$2(execution)) return (async function* () {
@@ -345,6 +347,97 @@ function coordinationHttpHandler(input) {
345
347
  };
346
348
  }
347
349
  //#endregion
350
+ //#region src/runtime/supervise/coordination-preflight.ts
351
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
352
+ var CoordinationPreflightError = class extends ConfigError {
353
+ constructor(reason) {
354
+ super(`coordination public endpoint preflight failed: ${reason}`);
355
+ }
356
+ };
357
+ function record$1(value) {
358
+ return typeof value === "object" && value !== null && !Array.isArray(value);
359
+ }
360
+ /** Check the operator's route before it becomes a provider attachment. This does not prove cloud egress. */
361
+ async function preflightPublicCoordination(input) {
362
+ const deadline = new AbortController();
363
+ const linked = linkAbort(input.signal, deadline.signal);
364
+ const timer = setTimeout(() => deadline.abort(), Math.min(input.requestTimeoutMs, 1e4));
365
+ timer.unref();
366
+ const rpc = async (method, params) => {
367
+ const response = await fetch(input.url, {
368
+ method: "POST",
369
+ headers: {
370
+ ...input.headers,
371
+ "content-type": "application/json",
372
+ accept: "application/json"
373
+ },
374
+ body: JSON.stringify({
375
+ jsonrpc: "2.0",
376
+ id: method,
377
+ method,
378
+ ...params ? { params } : {}
379
+ }),
380
+ redirect: "manual",
381
+ signal: linked.signal
382
+ });
383
+ if (response.status !== 200) {
384
+ response.body?.cancel().catch(() => void 0);
385
+ throw new CoordinationPreflightError(`HTTP ${response.status}`);
386
+ }
387
+ const reader = response.body?.getReader();
388
+ if (!reader) throw new CoordinationPreflightError("invalid MCP response");
389
+ let size = 0;
390
+ const chunks = [];
391
+ try {
392
+ for (;;) {
393
+ const part = await reader.read();
394
+ if (part.done) break;
395
+ size += part.value.byteLength;
396
+ if (size > MAX_RESPONSE_BYTES) {
397
+ reader.cancel().catch(() => void 0);
398
+ throw new CoordinationPreflightError("response too large");
399
+ }
400
+ chunks.push(part.value);
401
+ }
402
+ } finally {
403
+ reader.releaseLock();
404
+ }
405
+ let body;
406
+ try {
407
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
408
+ } catch {
409
+ throw new CoordinationPreflightError("invalid MCP response");
410
+ }
411
+ if (!record$1(body) || body.jsonrpc !== "2.0" || body.id !== method || body.error || !record$1(body.result)) throw new CoordinationPreflightError("invalid MCP response");
412
+ return body.result;
413
+ };
414
+ try {
415
+ await runAbortable(async () => {
416
+ const initialized = await rpc("initialize", {
417
+ protocolVersion: PROTOCOL_VERSION,
418
+ capabilities: {},
419
+ clientInfo: {
420
+ name: "agent-runtime-coordination-preflight",
421
+ version: "1"
422
+ }
423
+ });
424
+ if (initialized.protocolVersion !== "2024-11-05" || !record$1(initialized.serverInfo) || initialized.serverInfo.name !== "coordination" || !record$1(initialized.capabilities) || !record$1(initialized.capabilities.tools)) throw new CoordinationPreflightError("invalid MCP initialization");
425
+ const listing = await rpc("tools/list");
426
+ if (!Array.isArray(listing.tools) || listing.tools.some((tool) => !record$1(tool) || typeof tool.name !== "string")) throw new CoordinationPreflightError("invalid MCP tool list");
427
+ const names = listing.tools.map((tool) => tool.name).sort();
428
+ if (JSON.stringify(names) !== JSON.stringify([...input.toolNames].sort())) throw new CoordinationPreflightError("coordination tool grants differ");
429
+ }, linked.signal, "coordination public endpoint preflight cancelled");
430
+ } catch (error) {
431
+ if (input.signal.aborted) throw new CoordinationPreflightError("cancelled");
432
+ if (deadline.signal.aborted) throw new CoordinationPreflightError("timed out");
433
+ if (error instanceof CoordinationPreflightError) throw error;
434
+ throw new CoordinationPreflightError("transport unavailable");
435
+ } finally {
436
+ clearTimeout(timer);
437
+ linked.release();
438
+ }
439
+ }
440
+ //#endregion
348
441
  //#region src/runtime/supervise/single-flight-tools.ts
349
442
  /**
350
443
  * Serve method-supplied supervisor tools on the coordination MCP as single-flight, fenced calls.
@@ -529,10 +622,11 @@ async function serveCoordinationMcp(opts) {
529
622
  const rotateCredential = () => {
530
623
  if (!opts.authentication) throw new ConfigError("coordination authentication is not configured");
531
624
  if (closed) throw new ConfigError("coordination server is closed");
532
- const expiresAt = Date.now() + (auth?.ttlMs ?? 9e5);
533
- if (!Number.isSafeInteger(expiresAt)) throw new ConfigError("coordination credential expiry must remain a safe integer");
625
+ const deadline = opts.scope.budget.deadlineMs;
626
+ const expiresAt = auth?.ttlMs === void 0 ? deadline > 0 ? deadline : void 0 : Date.now() + auth.ttlMs;
627
+ if (expiresAt !== void 0 && !Number.isSafeInteger(expiresAt)) throw new ConfigError("coordination credential expiry must remain a safe integer");
534
628
  for (const [credential, expiry] of revoked) if (expiry <= Date.now()) revoked.delete(credential);
535
- if (token) revoked.set(token.toString(), credentialExpiresAt);
629
+ if (token) revoked.set(token.toString(), credentialExpiresAt ?? Number.POSITIVE_INFINITY);
536
630
  credentialExpiresAt = expiresAt;
537
631
  const nonce = randomBytes(32).toString("base64url");
538
632
  let text = nonce;
@@ -543,7 +637,7 @@ async function serveCoordinationMcp(opts) {
543
637
  actor: identity.actorId,
544
638
  audience: credentialAudience,
545
639
  grants: grantDigest,
546
- expires: credentialExpiresAt,
640
+ expires: credentialExpiresAt ?? null,
547
641
  nonce
548
642
  })).toString("base64url");
549
643
  text = `${payload}.${createHmac("sha256", signingKeys.keys[signingKeys.activeKeyId]).update(payload).digest("base64url")}`;
@@ -552,8 +646,9 @@ async function serveCoordinationMcp(opts) {
552
646
  headers = Object.freeze({ Authorization: `Bearer ${text}` });
553
647
  };
554
648
  const validCredential = (supplied) => {
555
- if (closed || revoked.has(supplied.toString())) return false;
556
- if (!signingKeys) return token !== void 0 && Date.now() < credentialExpiresAt && supplied.length === token.length && timingSafeEqual(supplied, token);
649
+ const deadline = opts.scope.budget.deadlineMs;
650
+ if (closed || opts.scope.signal.aborted || deadline > 0 && Date.now() >= deadline || revoked.has(supplied.toString())) return false;
651
+ if (!signingKeys) return token !== void 0 && (credentialExpiresAt === void 0 || Date.now() < credentialExpiresAt) && supplied.length === token.length && timingSafeEqual(supplied, token);
557
652
  if (supplied.length > 8192) return false;
558
653
  try {
559
654
  const parts = supplied.toString().split(".");
@@ -563,7 +658,7 @@ async function serveCoordinationMcp(opts) {
563
658
  if (!claims || typeof claims.key !== "string" || !Object.hasOwn(signingKeys.keys, claims.key)) return false;
564
659
  const expected = createHmac("sha256", signingKeys.keys[claims.key]).update(payload).digest();
565
660
  const signature = Buffer.from(parts[1], "base64url");
566
- 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();
661
+ return signature.toString("base64url") === parts[1] && signature.length === expected.length && timingSafeEqual(signature, expected) && claims.run === identity.runId && claims.actor === identity.actorId && claims.audience === credentialAudience && claims.grants === grantDigest && (claims.expires === null && auth?.ttlMs === void 0 || Number.isSafeInteger(claims.expires) && claims.expires > Date.now());
567
662
  } catch {
568
663
  return false;
569
664
  }
@@ -669,8 +764,19 @@ async function serveCoordinationMcp(opts) {
669
764
  audiences.add(publicAddress.host);
670
765
  if (host === "0.0.0.0" || host === "::") audiences.add(`127.0.0.1:${port}`);
671
766
  paths.add(publicAddress.pathname);
767
+ if (configured !== void 0) await preflightPublicCoordination({
768
+ url,
769
+ headers,
770
+ signal: opts.scope.signal,
771
+ requestTimeoutMs,
772
+ toolNames: selectedNames
773
+ });
672
774
  } catch (error) {
673
- await new Promise((resolve) => server.close(() => resolve()));
775
+ closed = true;
776
+ await new Promise((resolve) => {
777
+ server.close(() => resolve());
778
+ server.closeAllConnections();
779
+ });
674
780
  throw error;
675
781
  }
676
782
  const mailbox = coord.peerMail;
@@ -1452,9 +1558,10 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1452
1558
  if (harness === null && deps.peerMail) throw new ValidationError("supervisorAgent: peerMail is only served by a harness-brained supervisor (profile.harness set). A router-brained supervisor serves no coordination MCP listener, so there is no peer-mail post office to mint worker capabilities from.");
1453
1559
  if (harness !== null && deps.compaction) throw new ValidationError("supervisorAgent: compaction is only supported for router-brained supervisors (profile.harness omitted or cli-base)");
1454
1560
  if (harness === null && (deps.repromptOnUnmet !== void 0 || deps.onUnmetContract !== void 0)) throw new ValidationError("supervisorAgent: repromptOnUnmet/onUnmetContract apply to an EXTERNAL-harness supervisor only (profile.harness set). A router-brained supervisor runs its own turn loop in process, so this option would be silently ignored.");
1455
- if (deps.repromptOnUnmet !== void 0 && (!Number.isInteger(deps.repromptOnUnmet) || deps.repromptOnUnmet < 0)) throw new ValidationError("supervisorAgent: repromptOnUnmet must be a non-negative integer (0 = never re-prompt)");
1456
- if (deps.onUnmetContract !== void 0 && (deps.repromptOnUnmet ?? 0) <= 0) throw new ValidationError("supervisorAgent: onUnmetContract needs repromptOnUnmet >= 1 — without a cap the hook is never consulted");
1457
- if ((deps.repromptOnUnmet ?? 0) > 0 && deps.deliverable === void 0) throw new ValidationError("supervisorAgent: repromptOnUnmet needs a `deliverable` completion check — with no check there is no contract that can be unmet, and every run would re-prompt");
1561
+ if (deps.repromptOnUnmet !== void 0 && deps.repromptOnUnmet !== "until-complete" && (!Number.isInteger(deps.repromptOnUnmet) || deps.repromptOnUnmet < 0)) throw new ValidationError("supervisorAgent: repromptOnUnmet must be a non-negative integer or 'until-complete' (0 = never re-prompt)");
1562
+ const repromptEnabled = deps.repromptOnUnmet === "until-complete" || (deps.repromptOnUnmet ?? 0) > 0;
1563
+ if (deps.onUnmetContract !== void 0 && !repromptEnabled) throw new ValidationError("supervisorAgent: onUnmetContract needs repromptOnUnmet >= 1 or 'until-complete'");
1564
+ if (repromptEnabled && deps.deliverable === void 0) throw new ValidationError("supervisorAgent: repromptOnUnmet needs a `deliverable` completion check — with no check there is no contract that can be unmet, and every run would re-prompt");
1458
1565
  if (harness === null) {
1459
1566
  assertRouterArmResourcePolicy(stableProfile);
1460
1567
  const brain = testBrain ?? routerBrainFromProfile(stableProfile, stableRouter);
@@ -1594,6 +1701,14 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1594
1701
  const baseTokensLeft = scope.budget.tokensLeft;
1595
1702
  const contractDeclared = deps.deliverable !== void 0;
1596
1703
  const maxReprompts = deps.repromptOnUnmet ?? 0;
1704
+ let candidate;
1705
+ const finalize = () => runFinalizer(deps.finalizer ?? bestDelivered, {
1706
+ settled: mcp.settled(),
1707
+ blobs: deps.blobs,
1708
+ tree: runTree(scope),
1709
+ budget: scope.budget,
1710
+ ...deps.deliverable ? { deliverable: deps.deliverable } : {}
1711
+ });
1597
1712
  const readProgress = () => {
1598
1713
  const settled = mcp.settled();
1599
1714
  const deliveredCount = settled.filter((w) => w.status === "done" && w.valid === true).length;
@@ -1603,11 +1718,12 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1603
1718
  settledCount: settled.length,
1604
1719
  submitted,
1605
1720
  deliveredCount,
1606
- contract: !contractDeclared ? "none" : submitted || deliveredCount > 0 ? "met" : "unmet"
1721
+ contract: !contractDeclared ? "none" : submitted || candidate !== void 0 ? "met" : "unmet"
1607
1722
  };
1608
1723
  };
1609
1724
  await runDriverWithRetry({
1610
1725
  drive: async (attempt, reentry) => {
1726
+ candidate = void 0;
1611
1727
  if (deps.controlDir !== void 0 && deps.abortRun !== void 0) applyRunCancellation(deps.controlDir, deps.abortRun, () => (/* @__PURE__ */ new Date()).toISOString());
1612
1728
  scope.signal.throwIfAborted();
1613
1729
  beginScopeOwnerAttempt(scope, attempt);
@@ -1626,12 +1742,16 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1626
1742
  } catch (error) {
1627
1743
  if (!mcp.submittedResult() && !mcp.isStopped()) throw error;
1628
1744
  }
1745
+ if (contractDeclared && !mcp.submittedResult()) {
1746
+ await mcp.drainResolved();
1747
+ candidate = await finalize();
1748
+ }
1629
1749
  },
1630
1750
  progress: readProgress,
1631
1751
  budget: () => scope.budget,
1632
1752
  signal: scope.signal,
1633
1753
  ...deps.driverRetry ? { policy: deps.driverRetry } : {},
1634
- ...maxReprompts > 0 ? { reprompt: {
1754
+ ...repromptEnabled ? { reprompt: {
1635
1755
  maxReprompts,
1636
1756
  ...deps.deliverable?.describe === void 0 ? {} : { describe: deps.deliverable.describe },
1637
1757
  onUnmetContract: async (context) => {
@@ -1641,18 +1761,13 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1641
1761
  } } : {},
1642
1762
  ...deps.onDriverAttempt ? { onAttempt: deps.onDriverAttempt } : {}
1643
1763
  });
1644
- await mcp.drainResolved();
1764
+ if (!contractDeclared) await mcp.drainResolved();
1645
1765
  const submitted = mcp.submittedResult();
1646
1766
  if (submitted) {
1647
1767
  deps.onAcceptedSubmission?.(submitted.result);
1648
1768
  return submitted.result;
1649
1769
  }
1650
- return await runFinalizer(deps.finalizer ?? bestDelivered, {
1651
- settled: mcp.settled(),
1652
- blobs: deps.blobs,
1653
- tree: runTree(scope),
1654
- budget: scope.budget
1655
- });
1770
+ return contractDeclared ? candidate : await finalize();
1656
1771
  } finally {
1657
1772
  await mcp.close();
1658
1773
  }
@@ -1890,6 +2005,7 @@ function retryPreSpawnRefusals(inner, policy, hooks = {}) {
1890
2005
  ...inner.progress ? { progress: () => inner.progress?.() } : {},
1891
2006
  ...inner.traceSource ? { traceSource: () => inner.traceSource?.() } : {},
1892
2007
  ...inner.metered ? { metered: () => inner.metered?.() } : {},
2008
+ ...inner.harnessTranscript ? { harnessTranscript: () => inner.harnessTranscript?.() } : {},
1893
2009
  ...inner.interactive === void 0 ? {} : { interactive: () => interactiveOf(inner) },
1894
2010
  execute(task, signal) {
1895
2011
  const first = inner.execute(task, signal);
@@ -2364,6 +2480,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
2364
2480
  let activeExecutor;
2365
2481
  const drive = async ({ profile, authoredProfile, task, scope, coordinationMcpUrl, coordinationMcpHeaders, stopSignal, coordinationTools }) => {
2366
2482
  const retainedOwner = boundBackend.backend === "provider" ? scopeRetainedOwnerContext(scope) : void 0;
2483
+ if (retainedOwner && boundBackend.backend === "provider") bindScopeRetainedOwnerProvider(scope, resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry));
2367
2484
  const originalTask = retainedOwner ? await prepareScopeRetainedOwnerTask(scope, task) : task;
2368
2485
  if (retainedOwner ? await scopeRetainedOwnerResult(scope) : void 0) {
2369
2486
  await restoreScopeOwnerAcceptedExecution(scope);
@@ -2692,11 +2809,10 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
2692
2809
  telemetry: "unknown-after-failure"
2693
2810
  });
2694
2811
  } catch (error) {
2695
- const budget = scope.budget;
2696
- if (budget.tokensKnown !== false || budget.usdCapped && budget.usdKnown !== false) failure = error;
2812
+ failure = new RuntimeRunStateError(`${errMessage(failure)}; accounting failed: ${errMessage(error)}`, { cause: failure });
2697
2813
  }
2698
2814
  try {
2699
- await teardownOnce(completed ? DEFAULT_SUCCESSFUL_SHUTDOWN_MS : "brutalKill");
2815
+ if (!retainedOwner?.preserveEnvironment || retainedOwner.admissions.length === 0) await teardownOnce(completed ? DEFAULT_SUCCESSFUL_SHUTDOWN_MS : "brutalKill");
2700
2816
  } catch (error) {
2701
2817
  if (!failed) {
2702
2818
  failed = true;
@@ -3558,4 +3674,4 @@ function rootProviderModelEvidenceFromExecution(evidence) {
3558
3674
  //#endregion
3559
3675
  export { createSupervisorSpanRecorder as _, isPreSpawnExecutorFailure as a, mapExecutorResult as b, withWorkerSpawnRetry as c, resolveSupervisorProfile as d, supervisorAgent as f, readRootStreamReceipt as g, readRootStream as h, workerFromBackend as i, assertCoordinationBinding as l, ROOT_STREAM_FILE 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, serveCoordinationMcp as v, gateOnDeliverable as y };
3560
3676
 
3561
- //# sourceMappingURL=supervise-DbNMYx7z.js.map
3677
+ //# sourceMappingURL=supervise-CLkM45VY.js.map