@tangle-network/agent-runtime 0.229.0 → 0.231.1

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 (61) hide show
  1. package/dist/{activation-o9SrkJqs.js → activation-DVqSBfe1.js} +2 -2
  2. package/dist/{activation-o9SrkJqs.js.map → activation-DVqSBfe1.js.map} +1 -1
  3. package/dist/{activation-DFSQ90A8.d.ts → activation-Dltkq5S8.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-CUdEC2Qh.js} +4 -3
  7. package/dist/{coordination-driver-C6rde-Rv.js.map → coordination-driver-CUdEC2Qh.js.map} +1 -1
  8. package/dist/{delegate-Cmd-qlWH.js → delegate-BN0cSSUT.js} +2 -2
  9. package/dist/{delegate-Cmd-qlWH.js.map → delegate-BN0cSSUT.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-BK05MhFv.js → graph-D4wgK3ns.js} +3 -3
  13. package/dist/{graph-BK05MhFv.js.map → graph-D4wgK3ns.js.map} +1 -1
  14. package/dist/{improvement-cycle-DHl4SxbQ.js → improvement-cycle-CjIeWuyB.js} +3 -3
  15. package/dist/{improvement-cycle-DHl4SxbQ.js.map → improvement-cycle-CjIeWuyB.js.map} +1 -1
  16. package/dist/{index-B6xSpuPo.d.ts → index-BW6lJXnH.d.ts} +11 -6
  17. package/dist/index.d.ts +6 -6
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +3 -3
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +3 -3
  22. package/dist/kernel.js +8 -8
  23. package/dist/{loop-runner-bin-D5hutINM.d.ts → loop-runner-bin-BcqlGNW-.d.ts} +3 -3
  24. package/dist/{loop-runner-bin-CU2bdlr1.js → loop-runner-bin-BodmUPOf.js} +3 -3
  25. package/dist/{loop-runner-bin-CU2bdlr1.js.map → loop-runner-bin-BodmUPOf.js.map} +1 -1
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +3 -3
  29. package/dist/mcp/index.d.ts +5 -5
  30. package/dist/mcp/index.js +6 -6
  31. package/dist/mcp/memory-bin.js +1 -1
  32. package/dist/{memory-server-BR310Weg.js → memory-server-Cn8LbAxO.js} +2 -2
  33. package/dist/{memory-server-BR310Weg.js.map → memory-server-Cn8LbAxO.js.map} +1 -1
  34. package/dist/{openai-tools-HhRT1L1W.d.ts → openai-tools-avHT8eq3.d.ts} +2 -2
  35. package/dist/profiles.d.ts +2 -2
  36. package/dist/{provision-supervisor-C2rRWXG6.js → provision-supervisor-DyNDlA2I.js} +3 -3
  37. package/dist/{provision-supervisor-C2rRWXG6.js.map → provision-supervisor-DyNDlA2I.js.map} +1 -1
  38. package/dist/{runtime-BBcrtrkj.js → runtime-BxZHapmG.js} +8 -8
  39. package/dist/{runtime-BBcrtrkj.js.map → runtime-BxZHapmG.js.map} +1 -1
  40. package/dist/{server-CWIl-a3C.js → server-C9pa2tSq.js} +4 -4
  41. package/dist/{server-CWIl-a3C.js.map → server-C9pa2tSq.js.map} +1 -1
  42. package/dist/stream-agent-turn-hiU4vgGX.d.ts +2058 -0
  43. package/dist/{structural-rollout-zl02ztZ4.js → structural-rollout-DQoLyth9.js} +2 -2
  44. package/dist/{structural-rollout-zl02ztZ4.js.map → structural-rollout-DQoLyth9.js.map} +1 -1
  45. package/dist/{substrate-sWW5cDIe.d.ts → substrate-CBo6TWOl.d.ts} +2 -2
  46. package/dist/{supervise-DbNMYx7z.js → supervise-Cl_-IsVc.js} +134 -21
  47. package/dist/supervise-Cl_-IsVc.js.map +1 -0
  48. package/dist/{supervisor-DAHG98Rs.js → supervisor-DFsXULnE.js} +232 -96
  49. package/dist/supervisor-DFsXULnE.js.map +1 -0
  50. package/dist/testing.d.ts +2 -2
  51. package/dist/testing.js +12 -12
  52. package/dist/{tool-server-BJbCPhoW.js → tool-server-x9NEhvHZ.js} +2 -2
  53. package/dist/tool-server-x9NEhvHZ.js.map +1 -0
  54. package/dist/tui/index.d.ts +1 -1
  55. package/dist/tui/index.js +1 -1
  56. package/dist/{stream-agent-turn-jPdnzI_5.d.ts → types-DBovefLD.d.ts} +4015 -4770
  57. package/package.json +4 -4
  58. package/dist/supervise-DbNMYx7z.js.map +0 -1
  59. package/dist/supervisor-DAHG98Rs.js.map +0 -1
  60. package/dist/tool-server-BJbCPhoW.js.map +0 -1
  61. 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 { Qr as OutputAdapter, jr as Driver, kr as AgentRunSpec, ri as Validator } from "./types-DBovefLD.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-CBo6TWOl.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";
1
+ import { $ as captureReusableExecutorConfig, $r as runtimeOwnedExecutorMaterialization, An as RunCancellationReason, At as spendFromUsageTotals, Bi as withBudgetResources, Bt as createInbox, C as scopeOwnerExecutorNodeContext, Ci as addSpend, Cn as resolveAgentEnvironmentProvider, Cr as controlProfileMaterialization, Ct as contentAddress, Dr as promptControlProfileMaterialization, Dt as meterUsageEvent, Er as profileMaterializationAxes$1, F as scopeRetainedOwnerPriorSpend, Fi as unmeteredSpend, Gr as inheritRuntimeOwnedExecutorAttestation, Hr as attestRuntimeOwnedScopeOwner, I as scopeRetainedOwnerResult, Ii as withTimeout, Ir as worktreeCliProfileMaterialization, Ki as teardownExecutor, Li as zeroSpend, Lr as isNoEntError, M as consumeScopeRetainedOwnerResult, Mn as linkAbort, Mr as renderUnsupported, N as prepareScopeRetainedOwnerTask, Nn as runAbortable, On as registerRetainedExecutorPreparation, Or as promptModelProfileMaterialization, Ot as newUsageTotals, P as scopeRetainedOwnerContext, Pr as unsupportedProfileDimensions, Q as bindReusableExecutorExecutionId, Qr as runtimeOwnedExecutorExecutionBinding, Qt as bridgeModelRouteRefusal, Ri as addResourceSpend, Rr as parseCommittedJsonLines, S as restoreScopeOwnerAcceptedExecution, Sr as assertProfileMaterialization, Tr as fullProfileMaterialization, Tt as assertValidBudget, Wi as DEFAULT_SUCCESSFUL_SHUTDOWN_MS, Xr as recordRuntimeOwnedDriveHarnessProviderEvidence, Yr as providerAttemptEvidence, Zn as createOtelExporter, Zr as runtimeOwnedDriveHarnessProviderEvidence, Zt as bridgeAdmissionRefusal, b as meterRuntimeOwnedProviderAttempt, ci as detachedSnapshot, d as runDriverWithRetry, ei as runtimeOwnedExecutorProviderEvidence, er as generateSpanId, f as driverChild, g as beginScopeOwnerAttempt, hn as routerBrain, in as bridgeStopSignalKey, ir as toOtelAttributes, it as snapshotExecutorConfig, j as bindScopeRetainedOwnerProvider, ji as sleep, jt as WORKER_TRACE_PROPAGATION, kn as retainedExecutorSeamKey, m as isDriverSpec, n as createSupervisor, ni as runtimeOwnedScopeOwnerRuntime, nt as createExecutor, o as runFinalizer, p as driverExecutorFactory, r as bestDelivered, rn as bridgeRuntimeAttachmentsKey, s as runTree, t as createRootHandle, ti as runtimeOwnedPendingExecutorMaterialization, u as defaultUnmetContractSteer, v as deriveNodeExecutionIdentity, wr as defineProfileMaterializationContract, x as recordScopeOwnerMaterialization, y as meterRuntimeOwnedAccounting, zi as resourceTelemetry, zr as prepareJsonlAppend } from "./supervisor-DFsXULnE.js";
2
2
  import { 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-CUdEC2Qh.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";
@@ -345,6 +345,97 @@ function coordinationHttpHandler(input) {
345
345
  };
346
346
  }
347
347
  //#endregion
348
+ //#region src/runtime/supervise/coordination-preflight.ts
349
+ const MAX_RESPONSE_BYTES = 1024 * 1024;
350
+ var CoordinationPreflightError = class extends ConfigError {
351
+ constructor(reason) {
352
+ super(`coordination public endpoint preflight failed: ${reason}`);
353
+ }
354
+ };
355
+ function record$1(value) {
356
+ return typeof value === "object" && value !== null && !Array.isArray(value);
357
+ }
358
+ /** Check the operator's route before it becomes a provider attachment. This does not prove cloud egress. */
359
+ async function preflightPublicCoordination(input) {
360
+ const deadline = new AbortController();
361
+ const linked = linkAbort(input.signal, deadline.signal);
362
+ const timer = setTimeout(() => deadline.abort(), Math.min(input.requestTimeoutMs, 1e4));
363
+ timer.unref();
364
+ const rpc = async (method, params) => {
365
+ const response = await fetch(input.url, {
366
+ method: "POST",
367
+ headers: {
368
+ ...input.headers,
369
+ "content-type": "application/json",
370
+ accept: "application/json"
371
+ },
372
+ body: JSON.stringify({
373
+ jsonrpc: "2.0",
374
+ id: method,
375
+ method,
376
+ ...params ? { params } : {}
377
+ }),
378
+ redirect: "manual",
379
+ signal: linked.signal
380
+ });
381
+ if (response.status !== 200) {
382
+ response.body?.cancel().catch(() => void 0);
383
+ throw new CoordinationPreflightError(`HTTP ${response.status}`);
384
+ }
385
+ const reader = response.body?.getReader();
386
+ if (!reader) throw new CoordinationPreflightError("invalid MCP response");
387
+ let size = 0;
388
+ const chunks = [];
389
+ try {
390
+ for (;;) {
391
+ const part = await reader.read();
392
+ if (part.done) break;
393
+ size += part.value.byteLength;
394
+ if (size > MAX_RESPONSE_BYTES) {
395
+ reader.cancel().catch(() => void 0);
396
+ throw new CoordinationPreflightError("response too large");
397
+ }
398
+ chunks.push(part.value);
399
+ }
400
+ } finally {
401
+ reader.releaseLock();
402
+ }
403
+ let body;
404
+ try {
405
+ body = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
406
+ } catch {
407
+ throw new CoordinationPreflightError("invalid MCP response");
408
+ }
409
+ if (!record$1(body) || body.jsonrpc !== "2.0" || body.id !== method || body.error || !record$1(body.result)) throw new CoordinationPreflightError("invalid MCP response");
410
+ return body.result;
411
+ };
412
+ try {
413
+ await runAbortable(async () => {
414
+ const initialized = await rpc("initialize", {
415
+ protocolVersion: PROTOCOL_VERSION,
416
+ capabilities: {},
417
+ clientInfo: {
418
+ name: "agent-runtime-coordination-preflight",
419
+ version: "1"
420
+ }
421
+ });
422
+ 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");
423
+ const listing = await rpc("tools/list");
424
+ if (!Array.isArray(listing.tools) || listing.tools.some((tool) => !record$1(tool) || typeof tool.name !== "string")) throw new CoordinationPreflightError("invalid MCP tool list");
425
+ const names = listing.tools.map((tool) => tool.name).sort();
426
+ if (JSON.stringify(names) !== JSON.stringify([...input.toolNames].sort())) throw new CoordinationPreflightError("coordination tool grants differ");
427
+ }, linked.signal, "coordination public endpoint preflight cancelled");
428
+ } catch (error) {
429
+ if (input.signal.aborted) throw new CoordinationPreflightError("cancelled");
430
+ if (deadline.signal.aborted) throw new CoordinationPreflightError("timed out");
431
+ if (error instanceof CoordinationPreflightError) throw error;
432
+ throw new CoordinationPreflightError("transport unavailable");
433
+ } finally {
434
+ clearTimeout(timer);
435
+ linked.release();
436
+ }
437
+ }
438
+ //#endregion
348
439
  //#region src/runtime/supervise/single-flight-tools.ts
349
440
  /**
350
441
  * Serve method-supplied supervisor tools on the coordination MCP as single-flight, fenced calls.
@@ -529,10 +620,11 @@ async function serveCoordinationMcp(opts) {
529
620
  const rotateCredential = () => {
530
621
  if (!opts.authentication) throw new ConfigError("coordination authentication is not configured");
531
622
  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");
623
+ const deadline = opts.scope.budget.deadlineMs;
624
+ const expiresAt = auth?.ttlMs === void 0 ? deadline > 0 ? deadline : void 0 : Date.now() + auth.ttlMs;
625
+ if (expiresAt !== void 0 && !Number.isSafeInteger(expiresAt)) throw new ConfigError("coordination credential expiry must remain a safe integer");
534
626
  for (const [credential, expiry] of revoked) if (expiry <= Date.now()) revoked.delete(credential);
535
- if (token) revoked.set(token.toString(), credentialExpiresAt);
627
+ if (token) revoked.set(token.toString(), credentialExpiresAt ?? Number.POSITIVE_INFINITY);
536
628
  credentialExpiresAt = expiresAt;
537
629
  const nonce = randomBytes(32).toString("base64url");
538
630
  let text = nonce;
@@ -543,7 +635,7 @@ async function serveCoordinationMcp(opts) {
543
635
  actor: identity.actorId,
544
636
  audience: credentialAudience,
545
637
  grants: grantDigest,
546
- expires: credentialExpiresAt,
638
+ expires: credentialExpiresAt ?? null,
547
639
  nonce
548
640
  })).toString("base64url");
549
641
  text = `${payload}.${createHmac("sha256", signingKeys.keys[signingKeys.activeKeyId]).update(payload).digest("base64url")}`;
@@ -552,8 +644,9 @@ async function serveCoordinationMcp(opts) {
552
644
  headers = Object.freeze({ Authorization: `Bearer ${text}` });
553
645
  };
554
646
  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);
647
+ const deadline = opts.scope.budget.deadlineMs;
648
+ if (closed || opts.scope.signal.aborted || deadline > 0 && Date.now() >= deadline || revoked.has(supplied.toString())) return false;
649
+ if (!signingKeys) return token !== void 0 && (credentialExpiresAt === void 0 || Date.now() < credentialExpiresAt) && supplied.length === token.length && timingSafeEqual(supplied, token);
557
650
  if (supplied.length > 8192) return false;
558
651
  try {
559
652
  const parts = supplied.toString().split(".");
@@ -563,7 +656,7 @@ async function serveCoordinationMcp(opts) {
563
656
  if (!claims || typeof claims.key !== "string" || !Object.hasOwn(signingKeys.keys, claims.key)) return false;
564
657
  const expected = createHmac("sha256", signingKeys.keys[claims.key]).update(payload).digest();
565
658
  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();
659
+ 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
660
  } catch {
568
661
  return false;
569
662
  }
@@ -669,8 +762,19 @@ async function serveCoordinationMcp(opts) {
669
762
  audiences.add(publicAddress.host);
670
763
  if (host === "0.0.0.0" || host === "::") audiences.add(`127.0.0.1:${port}`);
671
764
  paths.add(publicAddress.pathname);
765
+ if (configured !== void 0) await preflightPublicCoordination({
766
+ url,
767
+ headers,
768
+ signal: opts.scope.signal,
769
+ requestTimeoutMs,
770
+ toolNames: selectedNames
771
+ });
672
772
  } catch (error) {
673
- await new Promise((resolve) => server.close(() => resolve()));
773
+ closed = true;
774
+ await new Promise((resolve) => {
775
+ server.close(() => resolve());
776
+ server.closeAllConnections();
777
+ });
674
778
  throw error;
675
779
  }
676
780
  const mailbox = coord.peerMail;
@@ -1594,6 +1698,14 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1594
1698
  const baseTokensLeft = scope.budget.tokensLeft;
1595
1699
  const contractDeclared = deps.deliverable !== void 0;
1596
1700
  const maxReprompts = deps.repromptOnUnmet ?? 0;
1701
+ let candidate;
1702
+ const finalize = () => runFinalizer(deps.finalizer ?? bestDelivered, {
1703
+ settled: mcp.settled(),
1704
+ blobs: deps.blobs,
1705
+ tree: runTree(scope),
1706
+ budget: scope.budget,
1707
+ ...deps.deliverable ? { deliverable: deps.deliverable } : {}
1708
+ });
1597
1709
  const readProgress = () => {
1598
1710
  const settled = mcp.settled();
1599
1711
  const deliveredCount = settled.filter((w) => w.status === "done" && w.valid === true).length;
@@ -1603,11 +1715,12 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1603
1715
  settledCount: settled.length,
1604
1716
  submitted,
1605
1717
  deliveredCount,
1606
- contract: !contractDeclared ? "none" : submitted || deliveredCount > 0 ? "met" : "unmet"
1718
+ contract: !contractDeclared ? "none" : submitted || candidate !== void 0 ? "met" : "unmet"
1607
1719
  };
1608
1720
  };
1609
1721
  await runDriverWithRetry({
1610
1722
  drive: async (attempt, reentry) => {
1723
+ candidate = void 0;
1611
1724
  if (deps.controlDir !== void 0 && deps.abortRun !== void 0) applyRunCancellation(deps.controlDir, deps.abortRun, () => (/* @__PURE__ */ new Date()).toISOString());
1612
1725
  scope.signal.throwIfAborted();
1613
1726
  beginScopeOwnerAttempt(scope, attempt);
@@ -1626,6 +1739,10 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1626
1739
  } catch (error) {
1627
1740
  if (!mcp.submittedResult() && !mcp.isStopped()) throw error;
1628
1741
  }
1742
+ if (contractDeclared && !mcp.submittedResult()) {
1743
+ await mcp.drainResolved();
1744
+ candidate = await finalize();
1745
+ }
1629
1746
  },
1630
1747
  progress: readProgress,
1631
1748
  budget: () => scope.budget,
@@ -1641,18 +1758,13 @@ function buildSupervisorAgent(profile, deps, testBrain) {
1641
1758
  } } : {},
1642
1759
  ...deps.onDriverAttempt ? { onAttempt: deps.onDriverAttempt } : {}
1643
1760
  });
1644
- await mcp.drainResolved();
1761
+ if (!contractDeclared) await mcp.drainResolved();
1645
1762
  const submitted = mcp.submittedResult();
1646
1763
  if (submitted) {
1647
1764
  deps.onAcceptedSubmission?.(submitted.result);
1648
1765
  return submitted.result;
1649
1766
  }
1650
- return await runFinalizer(deps.finalizer ?? bestDelivered, {
1651
- settled: mcp.settled(),
1652
- blobs: deps.blobs,
1653
- tree: runTree(scope),
1654
- budget: scope.budget
1655
- });
1767
+ return contractDeclared ? candidate : await finalize();
1656
1768
  } finally {
1657
1769
  await mcp.close();
1658
1770
  }
@@ -2364,6 +2476,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
2364
2476
  let activeExecutor;
2365
2477
  const drive = async ({ profile, authoredProfile, task, scope, coordinationMcpUrl, coordinationMcpHeaders, stopSignal, coordinationTools }) => {
2366
2478
  const retainedOwner = boundBackend.backend === "provider" ? scopeRetainedOwnerContext(scope) : void 0;
2479
+ if (retainedOwner && boundBackend.backend === "provider") bindScopeRetainedOwnerProvider(scope, resolveAgentEnvironmentProvider(boundBackend.provider, boundBackend.registry));
2367
2480
  const originalTask = retainedOwner ? await prepareScopeRetainedOwnerTask(scope, task) : task;
2368
2481
  if (retainedOwner ? await scopeRetainedOwnerResult(scope) : void 0) {
2369
2482
  await restoreScopeOwnerAcceptedExecution(scope);
@@ -2696,7 +2809,7 @@ function driveHarnessFromBackend(backend, executionId, now = Date.now, maxTurns,
2696
2809
  if (budget.tokensKnown !== false || budget.usdCapped && budget.usdKnown !== false) failure = error;
2697
2810
  }
2698
2811
  try {
2699
- await teardownOnce(completed ? DEFAULT_SUCCESSFUL_SHUTDOWN_MS : "brutalKill");
2812
+ if (!retainedOwner?.preserveEnvironment || retainedOwner.admissions.length === 0) await teardownOnce(completed ? DEFAULT_SUCCESSFUL_SHUTDOWN_MS : "brutalKill");
2700
2813
  } catch (error) {
2701
2814
  if (!failed) {
2702
2815
  failed = true;
@@ -3558,4 +3671,4 @@ function rootProviderModelEvidenceFromExecution(evidence) {
3558
3671
  //#endregion
3559
3672
  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
3673
 
3561
- //# sourceMappingURL=supervise-DbNMYx7z.js.map
3674
+ //# sourceMappingURL=supervise-Cl_-IsVc.js.map