@cotal-ai/manager 0.168.0 → 0.169.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.
package/dist/manager.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { UserProvision } from "./user-provision.js";
2
+ import { TurnRelay, goalKey, caughtEnvelope, TURN_ANSWER_RETENTION_MS, onceTurnNote, turnHoldToken } from "./turn-relay.js";
1
3
  import { createHash, randomBytes } from "node:crypto";
2
4
  import { checkEventStartup, EventStateConflictError, isPermissionDenied, chatStream, drainAndClose, requestSafeReconnect } from "@cotal-ai/core";
3
5
  import { hostname, homedir } from "node:os";
@@ -7,8 +9,9 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSy
7
9
  import { isAbsolute, join, resolve, sep } from "node:path";
8
10
  import { parse as parseYaml } from "yaml";
9
11
  import Headless from "@xterm/headless";
10
- import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, MANAGED_HANDOFF_KIND, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, assertValidChannel, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, provisionAgentDurables, registry, resolveAuthProvider, resolveReadAcl, runAgentBearer, runDriverCaller, saveAgentFile, eventChannel, eventChannelPrincipal, digestIdToken, capabilityWithin, grantOverreach, grantParts, isIssuedCaller, issuedSpawnerStanding, withIssuerSession, renderOnceTask, shownSpawner, } from "@cotal-ai/core";
12
+ import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, assertValidChannel, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, registry, resolveAuthProvider, resolveReadAcl, runDriverCaller, saveAgentFile, eventChannel, eventChannelPrincipal, digestIdToken, capabilityWithin, grantOverreach, grantParts, isIssuedCaller, issuedSpawnerStanding, withIssuerSession, renderOnceTask, shownSpawner, } from "@cotal-ai/core";
11
13
  import { loadLaunchPersonaFile, PersonaSourceError, retainConnectorSeat } from "@cotal-ai/workspace";
14
+ import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
12
15
  import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, remintDaemonCreds, resolveAgentType, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, SEAT_CAP_UNLIMITED, spaceKey, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
13
16
  import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
14
17
  import { Retirement } from "./retirement.js";
@@ -30,13 +33,12 @@ import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
30
33
  import { controlShutdown } from "./control-shutdown.js";
31
34
  import { RunHosting, servedRequestSubject } from "./run-hosting.js";
32
35
  import { enrolledAcl } from "./remote-authority.js";
33
- import { pendingEnrollment } from "./pending-enrollment.js";
34
36
  import { rejectionText, attemptCleanup, describeCleanupFailures } from "@cotal-ai/core";
35
37
  import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, supervisePolicy, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
36
38
  import { TranscriptReceiver } from "./transcript-receive.js";
37
39
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
38
40
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
39
- import { jetstream, jetstreamManager } from "@nats-io/jetstream";
41
+ import { jetstreamManager } from "@nats-io/jetstream";
40
42
  import { Kvm } from "@nats-io/kv";
41
43
  import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts, credentialIdOf, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC, REMOTE_MANAGER_IDENTITY_NAMES } from "@cotal-ai/core";
42
44
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
@@ -46,21 +48,13 @@ import { ManagerSessionPlane } from "./session/index.js";
46
48
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
47
49
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
48
50
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
49
- import { serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, requestGoalCancel, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, mintCheckpoint, MAX_SCHEDULE_MS, resumeCheckpoint, readCheckpointSettle, readCheckpointSpec, expireCheckpoint, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, seatCapRefused, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
51
+ import { serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, MAX_SCHEDULE_MS, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, seatCapRefused, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
50
52
  import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
51
53
  import { measureManagerVitals } from "./vitals.js";
52
54
  import { staticLifecycleTransport, activateStaticLifecycle, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, observeStaticSlot, listStaticSlotObservations, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
53
55
  import { CHAT_ALIAS_PREFIX, } from "./chat-session.js";
54
56
  // Capture the loaded package version before an installation can replace its files.
55
57
  const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
56
- /** Cadence of the turn-deadline sweep while turns are pending: the poll that turns an elapsed
57
- * hold's fire into its expired settle and commits the deadline terminal. Deadlines are
58
- * minutes-scale; a few seconds of lateness on the commit is invisible to the run. */
59
- const TURN_SWEEP_MS = 5_000;
60
- /** How long a settled turn's answer is kept so a RETRIED yield hears it instead of `not-found`.
61
- * The window a lost reply is retried in is seconds; five minutes is generous for that and short
62
- * enough that the map drains between bursts rather than growing for the process lifetime. */
63
- const TURN_ANSWER_RETENTION_MS = 5 * 60_000;
64
58
  /** A `once` spawn's task deadline when the caller names none: one hour from the spawn's accept. */
65
59
  const ONCE_DEFAULT_DEADLINE_MS = 60 * 60_000;
66
60
  /** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
@@ -82,10 +76,6 @@ export const READINESS_TIMEOUT_MS = 30_000;
82
76
  * from its launch: the watch's 15s for the confirm prompt and 15s for its notice, plus 5s for the
83
77
  * last read. The readiness window applies when it is longer. */
84
78
  const STARTUP_OUTCOME_MS = 35_000;
85
- /** The cancel reason of an inherited once task whose spawn has no succeeded terminal. */
86
- const NEVER_SERVED = "never served: the manager restarted before the spawn's readiness verdict";
87
- /** Said by every settle of an inherited once task whose seat this manager does not hold. */
88
- const UNHELD_SEAT = "the manager does not hold the seat; it may still be running";
89
79
  /** How often the readiness race asks a runtime that streams no exit whether its child has exited, and
90
80
  * how long it waits past the window for the proof of its last read. An operator waits on this reply,
91
81
  * so it asks more often than the exit watch that outlives readiness. */
@@ -175,16 +165,6 @@ function resumeOwner(entry) {
175
165
  * dash) — what {@link Manager.psOwnerFilter} returns for an unparseable caller so a malformed
176
166
  * principal fail-closes to an empty `ps` instead of an unbounded one. */
177
167
  const NO_OWNER_MATCHES = "-no-owner-";
178
- /** A caught value as a lifecycle envelope, or undefined when it is not one. A thrown Proxy can throw
179
- * from `instanceof` itself, so the test runs inside the guard. */
180
- function caughtEnvelope(e) {
181
- try {
182
- return e instanceof EpEnvelopeError ? e : undefined;
183
- }
184
- catch {
185
- return undefined;
186
- }
187
- }
188
168
  /** Why a frozen manager gate stays frozen on an open mesh. Reconciliation must prove the holder
189
169
  * gone, and an open mesh runs no delivery daemon to prove it, so neither boot self-heal nor
190
170
  * `cotal manager reconcile` can reopen the gate there. */
@@ -386,70 +366,6 @@ const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
386
366
  function participantKey(owner, actor, uid) {
387
367
  return `${owner}.${actor}.${uid}`;
388
368
  }
389
- function parseTurnNote(raw) {
390
- let o;
391
- try {
392
- o = JSON.parse(raw);
393
- }
394
- catch {
395
- return undefined;
396
- }
397
- if (o === null || typeof o !== "object")
398
- return undefined;
399
- const n = o;
400
- if (n.once !== undefined && n.once !== true)
401
- return undefined;
402
- if (typeof n.payload !== "string" || typeof n.holdEpoch !== "number")
403
- return undefined;
404
- if (typeof n.deadlineAt !== "number" && !(n.once === true && n.deadlineAt === undefined))
405
- return undefined;
406
- if (n.holdToken !== undefined && typeof n.holdToken !== "string")
407
- return undefined;
408
- if (n.handoffFrom !== undefined && typeof n.handoffFrom !== "string")
409
- return undefined;
410
- if (n.retire !== undefined && (n.once !== true || typeof n.retire !== "string"))
411
- return undefined;
412
- if (n.spawn !== undefined && (n.once !== true || typeof n.spawn !== "string"))
413
- return undefined;
414
- return {
415
- payload: n.payload, holdEpoch: n.holdEpoch,
416
- ...(typeof n.deadlineAt === "number" ? { deadlineAt: n.deadlineAt } : {}),
417
- ...(typeof n.holdToken === "string" ? { holdToken: n.holdToken } : {}),
418
- ...(typeof n.handoffFrom === "string" ? { handoffFrom: n.handoffFrom } : {}),
419
- ...(n.once === true ? { once: true } : {}),
420
- ...(typeof n.retire === "string" ? { retire: n.retire } : {}),
421
- ...(typeof n.spawn === "string" ? { spawn: n.spawn } : {}),
422
- };
423
- }
424
- function retireOf(d) {
425
- return d.retire === undefined ? undefined : { connector: d.retire, name: d.seat.name, uid: d.seat.uid };
426
- }
427
- /** The relay record of a `once` task. The prompt is only ever the string value of `context`, so a
428
- * prompt shaped like a run payload stays text and cannot add an `ask` or a `checkpoint`; the
429
- * `once` block is the manager's, rendered by the seat beside the prompt. */
430
- function onceTurnNote(o) {
431
- const payload = JSON.stringify({ context: o.prompt, once: { spawner: o.spawner, ...(o.deadlineAt !== undefined ? { deadlineAt: o.deadlineAt } : {}) } });
432
- const note = JSON.stringify({
433
- payload, holdEpoch: o.holdEpoch,
434
- ...(o.deadlineAt !== undefined ? { deadlineAt: o.deadlineAt } : {}),
435
- ...(o.holdToken !== undefined ? { holdToken: o.holdToken } : {}),
436
- once: true,
437
- ...(o.retire !== undefined ? { retire: o.retire } : {}),
438
- spawn: o.spawn,
439
- });
440
- return { payload, note };
441
- }
442
- /** A goal's key in the manager's maps: the caller triple and goal id the goal plane stores the
443
- * goal under, because a goal id is the caller's own (SPEC 13.6 item 1) and two callers may pick
444
- * the same one. Every part is a subject token, so the dotted join is unambiguous. */
445
- function goalKey(ref) {
446
- return `${ref.caller.owner}.${ref.caller.actor}.${ref.caller.uid}.${ref.goalId}`;
447
- }
448
- /** A turn hold's token, DERIVED from the relay key, so two callers' turns under one goal id never
449
- * share a hold. */
450
- function turnHoldToken(key) {
451
- return digestIdToken(`${key}:turn-deadline`);
452
- }
453
369
  /**
454
370
  * Event channels in `channels` that do NOT belong to `{owner, actor}`.
455
371
  *
@@ -531,6 +447,7 @@ export class Manager {
531
447
  /** See {@link ManagerOptions.installedExtensions}. */
532
448
  installedExtensions;
533
449
  expectedConnectorGeneration;
450
+ machineSetupCommand;
534
451
  executionState;
535
452
  /** One backend per kind a seat has asked for, beside {@link runtime}. The manager's own runtime
536
453
  * stays the default and is never replaced by a later seat's choice. */
@@ -632,59 +549,40 @@ export class Manager {
632
549
  /** The live spawn goal ref for each managed agent name, so a despawn MID-GOAL
633
550
  * drives the cancel path (transition -> cancel terminal). Cleared when the goal terminalizes. */
634
551
  agentGoals = new Map();
635
- /**
636
- * The turn relay's same-incarnation idempotency map ({@link goalAcceptances}'s twin), by
637
- * {@link goalKey}: a same-goal retry serves the identical acceptance; cross-incarnation retries
638
- * rebuild from the goal-index entry (its acceptance floor + note).
639
- *
640
- * One entry per turn this incarnation accepted: the acceptance a duplicate submission is served
641
- * from, and — once the turn settles — the answer a RETRIED yield is served from.
642
- *
643
- * A yield's reply can be lost, and the retry used to find the pending turn already deleted and
644
- * hear `not-found`, which a seat reads as "drop it": failure reported for work that committed.
645
- * The settled answer lives here for a bounded window instead, and the sweep drops it after,
646
- * which is also what keeps this map from being one entry per turn for the process lifetime.
647
- *
648
- * `ref` is the goal coordinates the durable terminal is published under. A late yield that
649
- * arrives after pendingTurns is gone and before `settled` is remembered (or after a concurrent
650
- * sweep dropped the settled field) still has to name that terminal, never `not-found`. The
651
- * index entry is not that answer: it is cleared at commit, and the yield path never consults it.
652
- *
653
- * `leftoverSince` is when the pending latch dropped. An unsettled leftover ages off that stamp,
654
- * never off `acceptance.deadlineAt`: a turn that expired after a long outage would otherwise be
655
- * pruned on the first sweep tick, taking the GoalRef with it, and a late yield in the retry
656
- * window would hear `not-found` again.
657
- */
658
- turnAcceptances = new Map();
552
+ turnRelayInstance;
553
+ get turnRelay() {
554
+ return this.turnRelayInstance ??= new TurnRelay({
555
+ goalWriter: () => this.goalWriter,
556
+ serviceServe: () => this.serviceServe,
557
+ space: this.space,
558
+ managerInstanceId: () => this.managerInstanceId,
559
+ execution: this.execution,
560
+ executionRefusal: this.executionRefusal(),
561
+ goalReconcileDone: () => this.goalReconcileDone,
562
+ readinessTimeoutMs: () => this.readinessTimeoutMs,
563
+ adoptsSeats: () => this.auth !== undefined && !this.userMode,
564
+ onceSeatReconciling: (uid) => this.staticLifecycle.pendingLifecycle(uid),
565
+ assertGoalWriterEpochCurrent: (epoch) => this.assertGoalWriterEpochCurrent(epoch),
566
+ emitGoalProgress: (ref, epoch, event) => this.emitGoalProgress(ref, epoch, event),
567
+ noticeSeatTurns: (seat) => this.noticeSeatTurns(seat),
568
+ turnExecutorEpoch: (name, owner, actor, uid) => this.turnExecutorEpoch(name, owner, actor, uid),
569
+ endOnceSeat: (pending, reason) => this.endOnceSeat(pending, reason),
570
+ findManagedByTarget: (target) => this.findManagedByTarget(target),
571
+ stopOnceSeat: (agent, reason) => this.stopOnceSeat(agent, reason),
572
+ watchOnceExit: (agent) => this.watchOnceExit(agent),
573
+ retireOnceSeat: (seat) => this.retireOnceSeat(seat),
574
+ forgetOnceWatch: (key) => { this.onceWatched.delete(key); },
575
+ });
576
+ }
659
577
  participants = new Map();
660
- /** Every relayed turn awaiting its seat's yield, by {@link goalKey}. The seat's `turn-pending` pull
661
- * scans it; the deadline sweep drives expiry; a seat reap stamps its entries `seatDiedAt`, which
662
- * the deadline terminal carries as `agentDownAt` so the run reads that death as L4002.
663
- * Rebuilt at boot from goal-index entries carrying a turn note. */
664
- pendingTurns = new Map();
665
- /** The deadline sweep behind {@link pendingTurns}: takes the hold's fire into an expired
666
- * settle and commits the deadline terminal. Unref'd; idle when no turn is pending. */
667
- turnSweepTimer;
668
- /** Once tasks whose ending is owed, by {@link goalKey}: the task can no longer run (its seat's
669
- * exit is proved, or it was never served), so it is cancelled if it has no terminal and its index
670
- * entry is dropped. A settle that fails stays here and the turn sweep retries it. */
671
- onceSettles = new Map();
672
578
  /** Once tasks whose seat's exit is watched: that exit, not the spawn's outcome, settles the debt. */
673
579
  onceWatched = new Set();
674
- /** Once tasks a predecessor accepted, by seat uid, until this incarnation binds the seat or
675
- * proves it gone. `readinessMs` bounds how long a seat no reconcile here can account for is
676
- * waited for. */
677
- onceInherited = new Map();
678
- /** Inherited once seats this manager does not hold whose task has a terminal, by lifecycle uid.
679
- * Every pull from one is answered `stop`, and its notice repeats until a pull has carried it. */
680
- onceStops = new Map();
681
- /** When the goal reconcile finished: the start of an inherited once task's wait for its seat. */
682
- goalReconcileDoneAt = 0;
683
580
  /** Process start, for the served `status` uptime. */
684
581
  startedAtMs = Date.now();
685
- /** Connector harness paths resolved ONCE at boot. Missing binaries do not stop unrelated manager
686
- * work, but they are named before the manager reports ready and remain visible in manager status. */
582
+ /** Connector harness inventory. Available paths stay pinned; missing binaries are retried when
583
+ * launch, model lookup or status asks, without stopping unrelated Manager work. */
687
584
  connectorStatuses = [];
585
+ connectorRequirements = new Map();
688
586
  /** The boot inventory's warnings, printed once start completes, so a refused start prints none. */
689
587
  bootNotes = [];
690
588
  /** The complete boot task. stop() joins it after fencing static reconciliation, so a registration
@@ -760,7 +658,7 @@ export class Manager {
760
658
  setSessionPlane: (value) => { this.sessionPlane = value; },
761
659
  sessionKeyRenewTimer: () => this.sessionKeyRenewTimer,
762
660
  setSessionKeyRenewTimer: (value) => { this.sessionKeyRenewTimer = value; },
763
- connectorStatuses: () => this.connectorStatuses,
661
+ connectorStatuses: () => { this.refreshUnavailableConnectors(); return this.connectorStatuses; },
764
662
  setGoalWriterIdentity: (value) => { this.goalWriterIdentity = value; },
765
663
  setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
766
664
  remoteStandingBudgetMs: REMOTE_STANDING_BUDGET_MS,
@@ -849,6 +747,7 @@ export class Manager {
849
747
  * does not re-acquire: a manager that is stopping never puts its own key back. It also closes the
850
748
  * lifecycle fence ({@link beginLifecycle}), so no spawn can launch a seat the stop never sees. */
851
749
  leaseStopping = false;
750
+ shutdownReadiness = new AbortController();
852
751
  /** The class-2 renewal owner's half-TTL schedule; armed only on auth meshes. */
853
752
  credRenewTimer;
854
753
  resumeCredRenewal;
@@ -1015,6 +914,19 @@ export class Manager {
1015
914
  adoptSeat: (row, record) => this.adoptSeat(row, record),
1016
915
  dropSeatRecord: (a) => this.dropSeatRecord(a),
1017
916
  });
917
+ /** User-mode provisioning owns no manager state: each dependency reads through at its use. */
918
+ userProvision = new UserProvision({
919
+ space: () => this.space,
920
+ workspaceRoot: () => this.workspaceRoot,
921
+ secrets: () => this.secrets,
922
+ managerInstanceId: () => this.managerInstanceId,
923
+ runHosting: () => this.runHosting,
924
+ remoteAuthority: () => this.remoteAuthority,
925
+ deprovision: (target) => this.deprovision(target),
926
+ withProvisioner: (fn) => this.withProvisioner(fn),
927
+ shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
928
+ bearerEntryArgv,
929
+ });
1018
930
  constructor(opts) {
1019
931
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
1020
932
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -1055,6 +967,7 @@ export class Manager {
1055
967
  this.secretStoreIdentity = injectedSecretStoreIdentity(opts.secretStore);
1056
968
  this.installedExtensions = opts.installedExtensions ?? false;
1057
969
  this.expectedConnectorGeneration = MANAGER_VERSION;
970
+ this.machineSetupCommand = opts.machineSetupCommand;
1058
971
  this.pooled = opts.pooled === true;
1059
972
  this.executionState = opts.execution === "none" ? { kind: "none" } : { kind: "runtime" };
1060
973
  if (!this.remoteAuthority) {
@@ -3026,6 +2939,7 @@ export class Manager {
3026
2939
  }
3027
2940
  async stopOnce(withAgents) {
3028
2941
  this.leaseStopping = true;
2942
+ this.shutdownReadiness.abort();
3029
2943
  clearTimeout(this.credentialPushRetry);
3030
2944
  this.credentialPushRetry = undefined;
3031
2945
  this.transcripts?.stop();
@@ -3523,9 +3437,7 @@ export class Manager {
3523
3437
  const agent = [...this.agents.values()].find((a) => this.managedPrincipal(a) === caller && a.lifecycleUid === ctx.subject.caller.uid);
3524
3438
  if (agent === undefined || agent.launch.capabilities?.includes("run"))
3525
3439
  return;
3526
- const pending = [...this.pendingTurns.values()].find((p) => p.seat.owner === ctx.subject.caller.owner
3527
- && p.seat.actor === ctx.subject.caller.actor
3528
- && p.seat.uid === ctx.subject.caller.uid);
3440
+ const pending = this.turnRelay.pendingForSeat(ctx.subject.caller);
3529
3441
  if (pending === undefined)
3530
3442
  throw new EpEnvelopeError("permission-denied", `run-answer is allowed to this baseline seat only for a pending ask or escalation addressed to its own incarnation; none is pending for ${agent.name}`);
3531
3443
  let payload;
@@ -3730,7 +3642,7 @@ export class Manager {
3730
3642
  if (observed !== undefined && observed.slotPhase !== "retired")
3731
3643
  throw new EpEnvelopeError("failed-precondition", `no live agent "${name}"; durable state contradicts absence ${renderStaticSlotObservation(observed)}`, [observed]);
3732
3644
  }
3733
- throw new EpEnvelopeError("not-found", `no agent "${name}"`);
3645
+ throw new EpEnvelopeError("not-found", `no agent "${name}"`, undefined, "not-executed");
3734
3646
  }
3735
3647
  return row;
3736
3648
  }),
@@ -4191,277 +4103,8 @@ export class Manager {
4191
4103
  })
4192
4104
  .finally(() => this.releaseLifecycle());
4193
4105
  }
4194
- /** The served spawn a hosted enrollment forwards. A run's spawn also names its run, so the host
4195
- * bounds the helper by what the run's starter held when the run was admitted (SPEC 14.8). */
4196
- servedSpawnRequest(served, caller) {
4197
- const run = caller !== undefined ? this.runHosting?.runAdmission(caller) : undefined;
4198
- return { served, ...(run !== undefined ? { runId: run.runId } : {}) };
4199
- }
4200
- /** USER-MODE spawn provisioning (the gate-1 counterpart to the static mint block): resolve the
4201
- * OWNER (ctl caller's principal, or the manifest's stamped owner — never a payload field),
4202
- * pre-create the principal-keyed durables + ACL row on the ephemeral provisioner, author the
4203
- * ledger grant (the upsert ROTATES the per-agent secret on every start — a non-running agent
4204
- * never holds a standing mint secret), materialize the 0600 secret/sentinel files, and
4205
- * PREFLIGHT the bearer chain once — the spawned agent must never be the first to discover a
4206
- * dead auth plane. Every failure is returned as the refusal sentence, with the grant + files
4207
- * rolled back. */
4208
- async provisionUserAgent(name, opts) {
4209
- if (opts.delegatedIntent) {
4210
- // startAgentActive refused a delegated launch on a manager without this callback.
4211
- const execute = this.remoteAuthority.executeDelegatedUserIntent;
4212
- const { intentId, owner } = opts.delegatedIntent;
4213
- // The hosted arm with the intent's execution in place of the holder's own enrollment: the
4214
- // spawning owner is the intent's, so its existing owner check refuses any other.
4215
- return this.enrollUserAgent(name, { ...opts, specOwner: owner }, async ({ target }) => {
4216
- const result = await execute({ intentId, operation: "launch", target: { actor: target.actor, tokenHash: target.tokenHash } });
4217
- if (result.operation !== "launch" || result.intentId !== intentId)
4218
- throw new Error(`the host answered delegated intent ${intentId} with another execution`);
4219
- return result.material;
4220
- });
4221
- }
4222
- if (this.remoteAuthority?.enrollManagedAgent)
4223
- return this.enrollUserAgent(name, opts, this.remoteAuthority.enrollManagedAgent);
4224
- const spawnerPr = opts.spawner ? parsePrincipalKey(opts.spawner) : null;
4225
- const owner = opts.specOwner ?? (spawnerPr && spawnerPr.owner.startsWith("u_") ? spawnerPr.owner : undefined);
4226
- if (!owner)
4227
- return {
4228
- error: `user-auth space "${this.space}": no owner for this spawn - call it from a user-mode session (\`cotal login\` then \`cotal spawn\`), or apply a manifest as a logged-in operator`,
4229
- };
4230
- let provider;
4231
- try {
4232
- provider = resolveAuthProvider();
4233
- }
4234
- catch (e) {
4235
- return { error: rejectionText(e) };
4236
- }
4237
- const dir = userAuthStateDir(this.workspaceRoot, this.space);
4238
- // The agent's capability scope rides its ledger row (act.scope in every bearer) — same
4239
- // vocabulary as static capabilities; the broker maps them to the ctl tiers. `role:<r>` tokens
4240
- // pass through too (a persona may hold delegable roles) — the ledger's envelope walk still
4241
- // attenuates every one of these against the spawner chain.
4242
- const scope = (opts.capabilities ?? []).filter((c) => c === "spawn" || c === "run" || c === "admin" || /^role:[A-Za-z0-9_-]+$/.test(c));
4243
- // The manager's ONE store (injected for a hosted composition, workstation FS locally). A hosted
4244
- // user-mode spawn reads the callout material from it — the same store the auth-store kinds
4245
- // (callout/issuer/…) were migrated onto — so this is no longer a local-only path.
4246
- const secrets = this.secrets;
4247
- // LIFECYCLE-KEYED family (SPEC 13.1 name-disjointness on the FS): this incarnation's files
4248
- // embed its uid, so no teardown addressed to another incarnation can ever reach them.
4249
- const files = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, opts.lifecycleUid);
4250
- const { actorToken: tokenPath, sentinelCreds: sentinelPath, health: healthPath } = files;
4251
- try {
4252
- // The GRANT first — it is the envelope-rule enforcement point (a delegation must sit within
4253
- // the spawner's own grant), so a refused delegation exits here having touched nothing beyond
4254
- // the ledger: no durables, no broker footprint, nothing for a corrected respawn to race.
4255
- const grant = await provider.grantAgent({
4256
- store: secrets,
4257
- dir,
4258
- space: this.space,
4259
- owner,
4260
- actor: name,
4261
- scope,
4262
- allowSubscribe: opts.allowSubscribe,
4263
- allowPublish: opts.allowPublish ?? [],
4264
- ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
4265
- role: opts.role,
4266
- parent: spawnerPr ? opts.spawner : undefined,
4267
- label: opts.label,
4268
- lifecycleUid: opts.lifecycleUid,
4269
- // This manager attests its own persisted logical instance id: the same id a static slot
4270
- // records as its owner. Recovery binds a managed row to a manager only through this.
4271
- custody: { kind: "local-manager", instanceId: this.managerInstanceId },
4272
- });
4273
- // Durables + ACL row, LIFECYCLE-keyed (SPEC 13.1) — the same onboarding as static agents minus
4274
- // the mint (a user agent's credential is its bearer, minted by the callout per connect from the
4275
- // ledger row's recorded lifecycleUid — the same value provisioned here).
4276
- await this.withProvisioner((prov) => provisionAgentDurables(prov, { owner, actor: name, lifecycleUid: opts.lifecycleUid }, {
4277
- subscribe: opts.subscribe,
4278
- allowSubscribe: opts.allowSubscribe,
4279
- role: opts.role,
4280
- }));
4281
- // The store holds the source of truth; the bearer re-exec (`--token-file`) and the launch's
4282
- // sentinel handoff read FILES, so materialize both at the canonical paths (under the local
4283
- // FS composition, a byte-identical rewrite of the keys' own locations).
4284
- await secrets.put(agentSecretKeyForFile(tokenPath, this.space), grant.actorToken);
4285
- await secrets.put(agentSecretKeyForFile(sentinelPath, this.space), grant.sentinelCreds);
4286
- await materializeSecretToFile(secrets, agentSecretKeyForFile(tokenPath, this.space), tokenPath);
4287
- await materializeSecretToFile(secrets, agentSecretKeyForFile(sentinelPath, this.space), sentinelPath);
4288
- rmSync(healthPath, { force: true }); // a fresh start opens a fresh health window
4289
- const bearerCmd = [
4290
- // The manager's own invocation prefix (node + loader flags + the cotal entry) — the agent
4291
- // process execs this argv for every bearer, so it must resolve from ANY cwd. Correct
4292
- // whenever the manager runs under a real `cotal` entry (supervise/up); a test constructing
4293
- // Manager directly never reaches this branch (user meshes boot through the CLI).
4294
- ...bearerEntryArgv(),
4295
- provider.agentBearerCommand,
4296
- "--dir", dir,
4297
- "--space", this.space,
4298
- "--owner", owner,
4299
- "--actor", name,
4300
- "--token-file", tokenPath,
4301
- "--health-file", healthPath,
4302
- ];
4303
- // One bearer run before the launch is the end-to-end auth preflight (state dir, daemon, ledger
4304
- // row, secret); its failure sentence is the spawn refusal.
4305
- await runAgentBearer(bearerCmd);
4306
- return { owner, lifecycleUid: opts.lifecycleUid, files, launch: { owner, actor: name, sentinelCredsPath: sentinelPath, bearerCmd } };
4307
- }
4308
- catch (e) {
4309
- // Roll back everything this attempt materialized — a refused spawn must leave no standing
4310
- // secret, no ledger row, no durable footprint — and AWAIT the broker teardown: the caller
4311
- // may respawn the moment it reads the refusal, and a detached teardown would race (and
4312
- // delete) that fresh spawn's just-provisioned durables. deprovision shreds the secret family
4313
- // and revokes the grant, but only logs a failed revoke, so the revoke is attempted here first.
4314
- // Each failure joins the refusal, so the caller learns what this spawn left behind.
4315
- const failed = [];
4316
- await attemptCleanup(failed, "revoke agent grant", () => provider.revokeAgent({ dir, owner, actor: name }));
4317
- await attemptCleanup(failed, "deprovision", () => this.deprovision({ id: principalKey(owner, name).key, name, lifecycleUid: opts.lifecycleUid, userOwner: owner, secretPaths: files }));
4318
- const leftover = failed.length ? `; cleanup failed: ${describeCleanupFailures(failed)}` : "";
4319
- return { error: `agent auth preflight failed for "${name}": ${rejectionText(e)}${leftover}` };
4320
- }
4321
- }
4322
- /**
4323
- * HOSTED user-mode spawn provisioning (#1972): the participant arm of host-owned enrollment.
4324
- *
4325
- * A registered participant holds no ledger writer, no JetStream provisioner, and no signing seed,
4326
- * so every step the local arm above performs itself is the HOST's here. What stays local is the
4327
- * one thing that must: the standing `actorToken`. This method generates it, writes it at 0600
4328
- * BEFORE the request, and sends only its SHA-256 digest — so the plaintext never crosses the
4329
- * network and a host compromise cannot replay an agent's exchange secret.
4330
- *
4331
- * The HOST picks the lifecycle UID. It alone can see the retirement tombstones that make a UID
4332
- * permanently unusable (a retired uid is refused forever by the retirement frontier), so a
4333
- * participant-chosen uid could aim a fresh grant at a dead incarnation. The uid the host returns
4334
- * is the one the spawn records and the one the child's durables are keyed by.
4335
- *
4336
- * The bearer argv selects `--exchange-url`: the local `--dir` arm reads a state directory this
4337
- * machine does not have, and a signerless participant must never appear to hold one.
4338
- */
4339
- async enrollUserAgent(name, opts, enroll) {
4340
- let provider;
4341
- try {
4342
- provider = resolveAuthProvider();
4343
- }
4344
- catch (e) {
4345
- return { error: rejectionText(e) };
4346
- }
4347
- const secrets = this.secrets;
4348
- const input = {
4349
- target: {
4350
- actor: name,
4351
- ...(opts.role !== undefined ? { role: opts.role } : {}),
4352
- label: opts.label,
4353
- ...(opts.capabilities !== undefined ? { capabilities: opts.capabilities } : {}),
4354
- ...(opts.subscribe !== undefined ? { subscribe: opts.subscribe } : {}),
4355
- allowSubscribe: opts.allowSubscribe,
4356
- ...(opts.allowPublish !== undefined ? { allowPublish: opts.allowPublish } : {}),
4357
- ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
4358
- },
4359
- ...(opts.spawnRequest !== undefined ? { spawn: opts.spawnRequest } : {}),
4360
- };
4361
- // An unanswered enrollment may already hold the host's alias. Keep its request and standing
4362
- // token together until preflight succeeds, rather than minting a conflicting successor.
4363
- let pending;
4364
- if (!opts.delegatedIntent) {
4365
- try {
4366
- pending = await pendingEnrollment({ store: secrets, space: this.space,
4367
- instanceId: this.managerInstanceId, actor: name, input,
4368
- authority: { target: input.target, owner: this.remoteAuthority.owner,
4369
- managerLifecycleUid: this.remoteAuthority.lifecycleUid, specOwner: opts.specOwner, spawner: opts.spawner,
4370
- caller: opts.enrollmentCaller, runId: opts.spawnRequest?.runId } });
4371
- }
4372
- catch (e) {
4373
- return { error: `agent auth preflight failed for "${name}": ${rejectionText(e)}` };
4374
- }
4375
- }
4376
- const actorToken = pending?.record.actorToken ?? randomBytes(32).toString("base64url");
4377
- const tokenHash = createHash("sha256").update(actorToken, "utf8").digest("hex");
4378
- // Provisional paths under the participant's OWN uid: the token has to be on disk before the
4379
- // request (a host that granted against a digest whose plaintext was lost would leave an agent
4380
- // that can never exchange), and the host's uid is not known until the request answers. The
4381
- // family is re-keyed to the host's uid below.
4382
- const staged = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, pending?.record.lifecycleUid ?? opts.lifecycleUid);
4383
- let files = staged;
4384
- let material;
4385
- let sent = false;
4386
- try {
4387
- await secrets.put(agentSecretKeyForFile(staged.actorToken, this.space), actorToken);
4388
- await materializeSecretToFile(secrets, agentSecretKeyForFile(staged.actorToken, this.space), staged.actorToken);
4389
- const saved = pending?.record.input ?? input;
4390
- if (canonicalJson(saved.target) !== canonicalJson(input.target))
4391
- throw new Error(`pending enrollment for "${name}" names different target authority`);
4392
- sent = true;
4393
- // The original observation may have expired, or vanished on a host restart before commit.
4394
- // Same-authority retries keep the enrollment identity but carry this freshly served spawn.
4395
- material = await enroll({ ...input, target: { ...saved.target, tokenHash },
4396
- ...(pending ? { requestId: pending.record.requestId } : {}) });
4397
- if (material.actor !== name)
4398
- throw new Error(`the host enrolled actor "${material.actor}", not the requested "${name}"`);
4399
- const specOwner = opts.specOwner ?? (opts.spawner ? parsePrincipalKey(opts.spawner)?.owner : undefined);
4400
- if (specOwner !== undefined && specOwner.startsWith("u_") && material.owner !== specOwner)
4401
- throw new Error(`the host enrolled the agent under owner ${material.owner}, not the spawning owner ${specOwner}`);
4402
- assertLifecycleToken(material.lifecycleUid, "host-enrolled managed agent lifecycleUid");
4403
- // Re-key the family onto the HOST's uid (SPEC 13.1 name-disjointness on the FS): the child's
4404
- // credential paths must embed the uid its broker footprint carries, never the provisional one.
4405
- files = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, material.lifecycleUid);
4406
- // From here the host holds a grant at that uid.
4407
- opts.onEnrolled?.({ owner: material.owner, lifecycleUid: material.lifecycleUid, files });
4408
- if (files.actorToken !== staged.actorToken) {
4409
- await secrets.put(agentSecretKeyForFile(files.actorToken, this.space), actorToken);
4410
- await materializeSecretToFile(secrets, agentSecretKeyForFile(files.actorToken, this.space), files.actorToken);
4411
- await secrets.delete(agentSecretKeyForFile(staged.actorToken, this.space));
4412
- rmSync(staged.actorToken, { force: true });
4413
- }
4414
- await secrets.put(agentSecretKeyForFile(files.sentinelCreds, this.space), material.sentinelCreds);
4415
- await materializeSecretToFile(secrets, agentSecretKeyForFile(files.sentinelCreds, this.space), files.sentinelCreds);
4416
- rmSync(files.health, { force: true }); // a fresh start opens a fresh health window
4417
- const bearerCmd = [
4418
- ...bearerEntryArgv(),
4419
- provider.agentBearerCommand,
4420
- // The signerless arm: the pinned public exchange, never a local state dir.
4421
- "--exchange-url", material.agentBearerExchangeUrl,
4422
- "--space", this.space,
4423
- "--owner", material.owner,
4424
- "--actor", name,
4425
- "--token-file", files.actorToken,
4426
- "--health-file", files.health,
4427
- ];
4428
- await runAgentBearer(bearerCmd);
4429
- if (pending)
4430
- await secrets.delete(pending.key);
4431
- return {
4432
- owner: material.owner,
4433
- lifecycleUid: material.lifecycleUid,
4434
- files,
4435
- launch: { owner: material.owner, actor: name, sentinelCredsPath: files.sentinelCreds, bearerCmd },
4436
- enrolled: { material, actorToken },
4437
- };
4438
- }
4439
- catch (e) {
4440
- // Remove launch-file materializations, but retain the pending token and request when the
4441
- // host may have committed. The next same-authority spawn replays that enrollment.
4442
- // A failed removal joins the refusal instead of throwing, so every removal is attempted and
4443
- // the refusal still reaches the caller.
4444
- const unshredded = [];
4445
- for (const family of files.actorToken === staged.actorToken ? [staged] : [staged, files])
4446
- await this.shredUserSecrets(unshredded, family);
4447
- const rejected = material === undefined ? caughtEnvelope(e) : undefined;
4448
- // Only a first, definitively refused request proves there was no earlier commit. A refusal
4449
- // during replay cannot prove that an earlier unanswered attempt enrolled nothing.
4450
- const discard = pending?.created && (!sent || rejected?.outcome === "not-executed");
4451
- if (discard && pending) {
4452
- const key = pending.key;
4453
- await attemptCleanup(unshredded, "pending enrollment", () => secrets.delete(key));
4454
- }
4455
- const retained = pending && !discard;
4456
- const leftover = unshredded.length ? `; cleanup failed: ${describeCleanupFailures(unshredded)}` : "";
4457
- const remedy = retained ? `; the name "${name}" is held by this manager's earlier enrollment. Retry this persona with the same caller to replay it. Once it launches, stop it before changing its authority` : "";
4458
- const refusal = !retained && material === undefined && !unshredded.length ? rejected : undefined;
4459
- return {
4460
- error: `agent auth preflight failed for "${name}": ${rejectionText(e)}${leftover}${remedy}`,
4461
- ...(refusal?.outcome === "not-executed" ? { refused: refusal.code, ...(refusal.details ? { details: refusal.details } : {}) } : {}),
4462
- };
4463
- }
4464
- }
4106
+ servedSpawnRequest(served, caller) { return this.userProvision.servedSpawnRequest(served, caller); }
4107
+ provisionUserAgent(name, opts) { return this.userProvision.provisionUserAgent(name, opts); }
4465
4108
  /** Shred a user agent's secret family from the store and from disk. Every removal is attempted,
4466
4109
  * and each failure joins `unshredded`, so one fault cannot leave the rest of the family behind. */
4467
4110
  async shredUserSecrets(unshredded, family) {
@@ -4472,43 +4115,8 @@ export class Manager {
4472
4115
  if (path)
4473
4116
  await attemptCleanup(unshredded, `file ${path}`, () => rmSync(path, { force: true }));
4474
4117
  }
4475
- /** This manager's registry record for its space, which pins the broker and IdP a delegated seat's
4476
- * handoff carries. It must pin the exchange the host enrolls against, or the child would register
4477
- * a mesh whose bearers come from somewhere else. */
4478
- delegatedMeshRecord() {
4479
- const record = loadMeshes().find((m) => m.space === this.space);
4480
- if (!record?.userAuth)
4481
- throw new Error(`a delegated seat needs this manager's user-mode registry record for space "${this.space}", and there is none`);
4482
- if (record.userAuth.endpoints?.url !== this.remoteAuthority?.agentBearerExchangeUrl)
4483
- throw new Error(`the registry record for space "${this.space}" pins a different exchange than the host's agentBearerExchangeUrl`);
4484
- return record;
4485
- }
4486
- /** The one handoff a delegated seat receives, built from values this manager holds: the
4487
- * enrollment result, the token it generated, and its own registry record. No path crosses. */
4488
- composeManagedHandoff(enrolled, actorToken) {
4489
- const record = this.delegatedMeshRecord();
4490
- if (enrolled.agentBearerExchangeUrl !== record.userAuth.endpoints?.url)
4491
- throw new Error(`the host enrolled "${enrolled.actor}" against a different exchange than this manager's registry record pins`);
4492
- const { url, issuer, audience } = record.userAuth.idp;
4493
- return {
4494
- kind: MANAGED_HANDOFF_KIND,
4495
- space: this.space,
4496
- owner: enrolled.owner,
4497
- actor: enrolled.actor,
4498
- lifecycleUid: enrolled.lifecycleUid,
4499
- server: record.server,
4500
- tlsRequired: record.tlsRequired === true,
4501
- authProvider: record.userAuth.provider,
4502
- idp: { url, issuer, audience },
4503
- exchangeUrl: enrolled.agentBearerExchangeUrl,
4504
- sentinelCreds: enrolled.sentinelCreds,
4505
- actorToken,
4506
- subscribe: enrolled.subscribe,
4507
- allowSubscribe: enrolled.allowSubscribe,
4508
- allowPublish: enrolled.allowPublish,
4509
- ...(record.policy ? { policy: record.policy } : {}),
4510
- };
4511
- }
4118
+ delegatedMeshRecord() { return this.userProvision.delegatedMeshRecord(); }
4119
+ composeManagedHandoff(enrolled, actorToken) { return this.userProvision.composeManagedHandoff(enrolled, actorToken); }
4512
4120
  /**
4513
4121
  * WHY A SEAT LEFT — one line, at the one place every free path passes through.
4514
4122
  *
@@ -4952,7 +4560,7 @@ export class Manager {
4952
4560
  let declared;
4953
4561
  if (this.installedExtensions) {
4954
4562
  try {
4955
- declared = loadExtensionsManifest().extensions.flatMap((ext) => extensionConnectors(ext));
4563
+ declared = loadExtensionsManifest().extensions.flatMap((ext) => extensionConnectors(ext).map((connector) => ({ ...connector, pkg: ext.pkg })));
4956
4564
  }
4957
4565
  catch (error) {
4958
4566
  const reason = rejectionText(error);
@@ -4969,8 +4577,27 @@ export class Manager {
4969
4577
  eventPlane: connector.eventChannel !== undefined,
4970
4578
  }));
4971
4579
  }
4972
- for (const { name, requires, eventPlane } of declared) {
4973
- const { binaries, reason } = resolveHarness(name, requires);
4580
+ this.connectorRequirements = new Map(declared.map(({ name, requires }) => [name, requires]));
4581
+ for (const { name, requires, eventPlane, pkg } of declared) {
4582
+ const { binaries, reason: missing } = resolveHarness(name, requires);
4583
+ let reason = missing;
4584
+ if (!reason && this.machineSetupCommand && name === "claude" && pkg === OFFICIAL_CONNECTORS.claude) {
4585
+ try {
4586
+ const connector = await this.resolveConnector(name);
4587
+ if (!connector.setup)
4588
+ throw new Error("Claude connector has no setup provider");
4589
+ const provider = await materializeFromManifest(connector.setup, { expectedGeneration: this.expectedConnectorGeneration });
4590
+ if (!provider.connector)
4591
+ throw new Error("Claude connector has no install action");
4592
+ const cotal = bearerEntryArgv();
4593
+ cotal[cotal.length - 1] = logicalExecutionEntry() ?? cotal.at(-1);
4594
+ await provider.connector.run({ cotal, machineHost: true });
4595
+ }
4596
+ catch (error) {
4597
+ const detail = oneLine(rejectionText(error).replace(/eyJ[A-Za-z0-9_.-]*/g, "<redacted>").slice(0, 800));
4598
+ reason = `Claude wake channel setup failed: ${detail}. Correct the cause and run \`${this.machineSetupCommand}\` on this computer.`;
4599
+ }
4600
+ }
4974
4601
  if (reason) {
4975
4602
  rows.push({ agent: name, state: "unavailable", binaries, eventPlane, reason });
4976
4603
  this.bootNotes.push(`! manager boot: connector ${name} unavailable - ${reason}`);
@@ -4983,6 +4610,27 @@ export class Manager {
4983
4610
  if (!this.classSpawnEnabled())
4984
4611
  this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
4985
4612
  }
4613
+ /** Retry missing applications on the Manager's PATH without changing resolved available rows. */
4614
+ refreshUnavailableConnectors(name) {
4615
+ const wasEnabled = this.classSpawnEnabled();
4616
+ for (const row of this.connectorStatuses) {
4617
+ if (row.state !== "unavailable" || (name !== undefined && row.agent !== name))
4618
+ continue;
4619
+ const requires = this.connectorRequirements.get(row.agent);
4620
+ if (!requires)
4621
+ continue;
4622
+ const { binaries, reason } = resolveHarness(row.agent, requires);
4623
+ row.binaries = binaries;
4624
+ if (reason)
4625
+ row.reason = reason;
4626
+ else {
4627
+ row.state = "available";
4628
+ delete row.reason;
4629
+ }
4630
+ }
4631
+ if (!wasEnabled && this.classSpawnEnabled())
4632
+ this.servePlane.enableClassSpawn();
4633
+ }
4986
4634
  /** True when at least one declared connector is available. Empty inventory (or a failed
4987
4635
  * inventory load) skips the class `one` subscribe for spawn/launch so this member cannot
4988
4636
  * consume an unpinned request a sibling could serve. */
@@ -5007,8 +4655,10 @@ export class Manager {
5007
4655
  /** The harness binaries a managed launch runs, as boot resolved them, or the refusal naming what is
5008
4656
  * missing. Spawn, resume and the model catalog all take it, so a seat launches from the same files
5009
4657
  * whichever path starts it and the catalog never disagrees with a launch about whether the harness
5010
- * is there. A connector registered after boot has no inventory row and is checked on PATH now. */
4658
+ * is there. Unavailable rows are checked again on PATH; available rows retain their resolved files.
4659
+ * A connector registered after boot has no inventory row and is checked on PATH now. */
5011
4660
  launchHarness(connector) {
4661
+ this.refreshUnavailableConnectors(connector.name);
5012
4662
  const row = this.connectorStatuses.find((status) => status.agent === connector.name);
5013
4663
  if (row?.state === "unavailable")
5014
4664
  return { refusal: row.reason ?? `${connector.name} harness is unavailable` };
@@ -5097,14 +4747,14 @@ export class Manager {
5097
4747
  }
5098
4748
  /** The refusal for an event-plane choice the registration policy or the connector cannot meet.
5099
4749
  * Spawn and resume both ask before a seat's launch is built, so a seat retained without the
5100
- * plane cannot come back on a space that now requires it. An absent choice arms the plane. */
4750
+ * plane cannot come back on a space that now requires it. An absent choice arms supported planes. */
5101
4751
  eventsRefusal(connector, events) {
5102
4752
  if (this.eventsRequired && events === false)
5103
4753
  return `space "${this.space}" requires the event plane by registration policy; --no-events (events: false on the start op) is not allowed`;
5104
- if (events !== false && !connector.eventChannel)
4754
+ if ((this.eventsRequired || events === true) && !connector.eventChannel)
5105
4755
  return this.eventsRequired
5106
4756
  ? `space "${this.space}" requires the event plane by registration policy, but connector "${connector.name}" does not publish one`
5107
- : `connector "${connector.name}" does not publish an AG-UI event plane; pass --no-events (events: false on the start op) to launch it without one`;
4757
+ : `connector "${connector.name}" does not publish an AG-UI event plane; omit --events to launch it without one`;
5108
4758
  return undefined;
5109
4759
  }
5110
4760
  /** Return connector-provided model catalogs for selector UIs. Optional by connector: a host with no
@@ -5116,9 +4766,9 @@ export class Manager {
5116
4766
  const requested = String(args.agent ?? "").trim();
5117
4767
  const refresh = args.refresh === true;
5118
4768
  const one = async (connector) => {
4769
+ const harness = this.launchHarness(connector);
5119
4770
  if (!connector.listModels)
5120
4771
  return { agent: connector.name, supported: false, models: [] };
5121
- const harness = this.launchHarness(connector);
5122
4772
  if ("refusal" in harness)
5123
4773
  return { agent: connector.name, supported: true, models: [], error: harness.refusal };
5124
4774
  try {
@@ -5813,9 +5463,8 @@ export class Manager {
5813
5463
  catch (e) {
5814
5464
  return { ok: false, error: opts.resolved ? `launch agent: ${rejectionText(e)}` : `persona ${where}: ${rejectionText(e)}` };
5815
5465
  }
5816
- // The AG-UI event plane is on unless the launch explicitly opted out. A connector that cannot
5817
- // emit one is refused further down, before anything is minted.
5818
- const events = this.eventsRequired || opts.events !== false;
5466
+ // Default events on where the connector supports them, unless the launch explicitly opts out.
5467
+ const events = this.eventsRequired || opts.events === true || (opts.events !== false && !!connector.eventChannel);
5819
5468
  if (this.eventPayloadsWithheld && opts.eventPayloads === true)
5820
5469
  return { ok: false, error: "space policy withholds event payloads" };
5821
5470
  const eventPayloads = !this.eventPayloadsWithheld && (opts.eventPayloads ?? def?.eventPayloads) !== false;
@@ -6512,7 +6161,7 @@ export class Manager {
6512
6161
  // task, never served, cancelled with the verdict.
6513
6162
  if (onceTask && connector.onceNeedsConfirmed !== undefined) {
6514
6163
  const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
6515
- if (managed.terminalizing) {
6164
+ if (managed.terminalizing || this.leaseStopping) {
6516
6165
  hooks?.onTerminalDeferred?.();
6517
6166
  return { ok: false, error: `${name} was stopped before its startup ended` };
6518
6167
  }
@@ -6532,7 +6181,7 @@ export class Manager {
6532
6181
  // starting it silently without push (#5737).
6533
6182
  if (!onceTask && connector.idleWakeNeedsConfirmed !== undefined && runtime.reportsStartupOutcome) {
6534
6183
  const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
6535
- if (managed.terminalizing) {
6184
+ if (managed.terminalizing || this.leaseStopping) {
6536
6185
  hooks?.onTerminalDeferred?.();
6537
6186
  return { ok: false, error: `${name} was stopped before its startup ended` };
6538
6187
  }
@@ -7462,6 +7111,7 @@ export class Manager {
7462
7111
  if (joinedPoll !== undefined)
7463
7112
  clearInterval(joinedPoll);
7464
7113
  this.ep.off("presence", onPresence);
7114
+ this.shutdownReadiness.signal.removeEventListener("abort", onShutdown);
7465
7115
  unsubExit();
7466
7116
  resolve(r);
7467
7117
  };
@@ -7469,6 +7119,9 @@ export class Manager {
7469
7119
  if (joined())
7470
7120
  finish({ ok: true });
7471
7121
  };
7122
+ // Shutdown owns the seat's stop and retirement after the lifecycle ticket drains. Do not
7123
+ // keep that ticket waiting on a connector's readiness window while shutdown waits on it.
7124
+ const onShutdown = () => finish({ ok: false, deliberate: true, detail: `${a.name} was stopped before it reported ready` });
7472
7125
  if (opts.joinedAfter !== undefined) {
7473
7126
  // Heartbeats bump roster.ts without emitting "presence" (same status/uid/activity).
7474
7127
  // A supervised restart needs that bump, so poll joined() rather than waiting on the event.
@@ -7557,8 +7210,11 @@ export class Manager {
7557
7210
  else
7558
7211
  pollProvedExit(a.handle, onExit, () => !done, READINESS_EXIT_POLL_MS);
7559
7212
  this.ep.on("presence", onPresence);
7213
+ this.shutdownReadiness.signal.addEventListener("abort", onShutdown, { once: true });
7560
7214
  // Subscribe-then-check (TOCTOU): a join or an exit that already landed before we subscribed.
7561
- if (s && a.handle.status() === "exited")
7215
+ if (this.shutdownReadiness.signal.aborted)
7216
+ onShutdown();
7217
+ else if (s && a.handle.status() === "exited")
7562
7218
  onExit();
7563
7219
  else
7564
7220
  onPresence();
@@ -7908,6 +7564,7 @@ export class Manager {
7908
7564
  * seats, as `ps` lists them ({@link psOwnerFilter}), so a person reading a shared Manager does not
7909
7565
  * learn how many seats other owners hold on it. */
7910
7566
  managerStatusData(ownerFilter) {
7567
+ this.refreshUnavailableConnectors();
7911
7568
  return {
7912
7569
  instanceId: this.managerInstanceId,
7913
7570
  lifecycleUid: this.managerLifecycleUid,
@@ -8182,7 +7839,7 @@ export class Manager {
8182
7839
  // filters on (skip a goal whose accepting `iid` is a still-LIVE sibling — never settle its goal).
8183
7840
  for (const entry of entries) {
8184
7841
  const key = goalKey(entry.ref);
8185
- if (this.goalAcceptances.has(key) || this.turnAcceptances.has(key))
7842
+ if (this.goalAcceptances.has(key) || this.turnRelay.hasAcceptance(key))
8186
7843
  continue; // never settle a goal THIS incarnation drives
8187
7844
  try {
8188
7845
  // A note marks a TURN entry: its relay is rebuilt (the hold is its bounded ending), never
@@ -8204,11 +7861,11 @@ export class Manager {
8204
7861
  }
8205
7862
  finally {
8206
7863
  this.goalReconcileDone = true;
8207
- this.goalReconcileDoneAt = Date.now();
7864
+ this.turnRelay.markReconciled(Date.now());
8208
7865
  // A seat that pulled during the window was refused, and a predecessor may have died before
8209
7866
  // its notice went out, so every seat holding a rebuilt turn is told once.
8210
- const seats = new Map([...this.pendingTurns.values()].map((p) => [`${p.seat.owner}.${p.seat.actor}.${p.seat.uid}`, p.seat]));
8211
- for (const seat of seats.values())
7867
+ const seats = this.turnRelay.pendingSeats();
7868
+ for (const seat of seats)
8212
7869
  this.noticeSeatTurns(seat);
8213
7870
  }
8214
7871
  }
@@ -8633,178 +8290,10 @@ export class Manager {
8633
8290
  * path (idempotent retry map, index-CAS-before-bind, create-only bindGoal) but runs it INLINE:
8634
8291
  * there is no launch to hand off, so the accept either completes durably or unwinds its own
8635
8292
  * bound goal with a `failed` terminal before refusing. */
8636
- async serveTurnGoal(ctx, target) {
8637
- const gw = this.goalWriter;
8638
- if (!gw)
8639
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; turn-as-action cannot accept (SPEC 13.6)");
8640
- const serve = this.serviceServe;
8641
- if (!serve)
8642
- throw new EpEnvelopeError("unavailable", "the manager service endpoint is not serving; a turn's deadline hold is armed over its connection (SPEC 13.9)");
8643
- if (!this.goalReconcileDone)
8644
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; retry shortly (SPEC 13.6)");
8645
- const t = ctx.request.target; // targeted command: the serve boundary enforced presence + currency
8646
- const name = target.name;
8647
- const goalId = ctx.request.id;
8648
- const { fingerprint } = submissionFingerprint(ctx.request, ctx.subject);
8649
- const ref = goalRefOf(ctx.subject, goalId);
8650
- const key = goalKey(ref);
8651
- const executor = { lifecycleUid: this.managerInstanceId, epoch: this.serviceServe?.grant.epoch ?? 0 };
8652
- const acceptedAt = Date.now();
8653
- const prior = this.turnAcceptances.get(key)?.acceptance;
8654
- if (prior !== undefined) {
8655
- if (prior.fingerprint !== fingerprint)
8656
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted under a different submission; one goalId never carries two specs (SPEC 13.6)`);
8657
- return prior;
8658
- }
8659
- // Refused here, before anything durable, so the caller's goal id stays free for another seat.
8660
- this.assertSeatTurnFree(name, t, goalId);
8661
- if (target.kind === "managed" && target.agent.once)
8662
- throw new EpEnvelopeError("failed-precondition", `seat "${name}" is a once seat; it takes only the task it was spawned with`, undefined, "not-executed");
8663
- const raw = (ctx.request.args ?? {});
8664
- const payload = String(raw.payload);
8665
- const deadlineAt = raw.deadlineAt === undefined ? acceptedAt + Number(raw.deadlineMs) : Number(raw.deadlineAt);
8666
- if (deadlineAt <= acceptedAt)
8667
- throw new EpEnvelopeError("deadline-exceeded", `goal "${goalId}" names a deadline already past (${new Date(deadlineAt).toISOString()}); a turn with no time left to serve it is never accepted (SPEC 13.6)`);
8668
- const deadlineMs = deadlineAt - acceptedAt;
8669
- const handoffFrom = raw.handoffFrom === undefined ? undefined : String(raw.handoffFrom);
8670
- const holdToken = turnHoldToken(key);
8671
- const note = JSON.stringify({ payload, deadlineAt, holdEpoch: executor.epoch, holdToken, ...(handoffFrom !== undefined ? { handoffFrom } : {}) });
8672
- // A goal that already ENDED is never accepted again, whatever the retry carries: the bind is
8673
- // create-only and outlives an unwind (the failed terminal, the cleared index), so a retry of an
8674
- // unwound accept would otherwise re-record an index entry over a tombstone and, before that
8675
- // check existed, be served an acceptance rebuilt from it — a live deadline on a turn no seat
8676
- // would ever be shown. The terminal is the durable answer, and it is read before anything is
8677
- // written.
8678
- const ended = await readGoalResult(gw.ctx, ref);
8679
- if (ended !== undefined)
8680
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" already ended ${ended.state}; a bound goal is never accepted again (SPEC 13.6)`);
8681
- // Index-CAS-before-bind, exactly as spawn: the entry (floor + note) is the durable relay
8682
- // record a successor rebuilds from, so it must exist before the acceptance is servable.
8683
- const idx = await recordGoalIndex(gw.ctx, ref, executor.lifecycleUid, { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid, readinessDeadlineMs: deadlineMs }, note);
8684
- if (!idx.recorded && idx.existing.iid !== executor.lifecycleUid)
8685
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted by instance "${idx.existing.iid}"; that instance owns its relay and this attempt provisions nothing (SPEC 13.6)`);
8686
- const b = await bindGoal(gw.ctx, ref, fingerprint);
8687
- if (!b.bound) {
8688
- if (b.existing.fingerprint !== fingerprint)
8689
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" is already bound to a different submission; one goalId never carries two specs (SPEC 13.6)`);
8690
- // Same submission, bound, not ended, and not in the acceptance map. Every relay this
8691
- // incarnation holds is in that map (the accept path and the boot sweep both write it), so
8692
- // this is a goal nobody is relaying: an earlier attempt bound it and could not finish its
8693
- // unwind, or a predecessor's relay was left unadopted. Nothing here can rebuild a relay a
8694
- // seat will be shown, so the caller is refused rather than served an acceptance no pending
8695
- // entry backs; the index entry this attempt recorded is withdrawn with it.
8696
- if (idx.recorded)
8697
- await clearGoalIndex(gw.ctx, ref);
8698
- throw new EpEnvelopeError("unavailable", `goal "${goalId}" is bound but no relay of it is pending on this instance; retry (SPEC 13.6)`);
8699
- }
8700
- try {
8701
- await createGoal(gw.ctx, ref, {
8702
- fingerprint,
8703
- command: ctx.subject.command,
8704
- caller: { id: `${ctx.subject.caller.owner}.${ctx.subject.caller.actor}`, lifecycleUid: ctx.subject.caller.uid },
8705
- acceptedEpoch: executor.epoch,
8706
- requestId: goalId,
8707
- sourceSeq: 0,
8708
- acceptedAt,
8709
- readinessDeadlineMs: deadlineMs,
8710
- // The §13.6 target pin: the seat INCARNATION this payload is addressed to. A successor
8711
- // under the same name is a different addressee; its uid differs and the pin holds that.
8712
- target: { owner: t.owner, actor: t.actor, lifecycleUid: t.lifecycleUid, mappingRevision: 0 },
8713
- });
8714
- // The deadline, as a goal-bound hold on the plane: its EXPIRED settle is the one predicate
8715
- // `commitGoalResult` accepts for the deny. The record rides the goal-writer's KV; the
8716
- // `.schedule` request rides the SERVE connection, because the timer row is the serving
8717
- // instance's own (`ept.<e>.<iid>.<epoch>.*.schedule`, SPEC 13.9) and the goal-writer holds
8718
- // none. Measured on an auth mesh: minted over the goal-writer, the schedule publish was
8719
- // broker-denied and every accept unwound.
8720
- await mintCheckpoint(gw.ctx.kv, jetstream(serve.nc), this.space, {
8721
- ref: { endpoint: ref.endpoint, token: holdToken },
8722
- instanceId: this.managerInstanceId,
8723
- epoch: executor.epoch,
8724
- goal: { caller: { owner: ctx.subject.caller.owner, actor: ctx.subject.caller.actor, uid: ctx.subject.caller.uid }, goalId },
8725
- holder: { id: MANAGER_ENDPOINT, lifecycleUid: this.managerInstanceId },
8726
- deadline: deadlineAt,
8727
- now: acceptedAt,
8728
- });
8729
- // Again after the awaits, with no await before the maps are written: another caller's
8730
- // accept of this id to this seat may have finished meanwhile, and this unwinds the loser.
8731
- this.assertSeatTurnFree(name, t, goalId);
8732
- }
8733
- catch (e) {
8734
- // The accept is inline (no launch closure to fail later), so a post-bind throw unwinds HERE:
8735
- // commit the failed terminal this attempt owns, clear the index, and refuse the accept — an
8736
- // accepted-but-unanswered goal must never be left for the boot sweep to find (H1's rule).
8737
- const msg = rejectionText(e);
8738
- try {
8739
- await this.assertGoalWriterEpochCurrent(executor.epoch);
8740
- // The goal is TARGET-PINNED, so its completion proves the seat's currency exactly as the
8741
- // yield's does (managed-seat epochs are 0 within an incarnation; the resolver answers from
8742
- // the live agents map). Committed without it, core refused the terminal and the unwind
8743
- // left a bound goal with no ending for every retry to find.
8744
- await commitGoalResult(gw.ctx, {
8745
- ref, now: Date.now(), cause: "complete", state: "failed", data: { error: msg },
8746
- committer: { instanceId: this.managerInstanceId, epoch: executor.epoch },
8747
- executor: { lifecycleUid: t.lifecycleUid, epoch: 0 },
8748
- resolveCurrentEpoch: (current) => this.turnExecutorEpoch(name, t.owner, t.actor, current.lifecycleUid),
8749
- });
8750
- await clearGoalIndex(gw.ctx, ref);
8751
- }
8752
- catch (e2) {
8753
- console.error(`! turn accept unwind for ${goalId}: ${rejectionText(e2)}`);
8754
- }
8755
- throw caughtEnvelope(e) ?? new EpEnvelopeError("internal", `turn accept for ${goalId} failed: ${msg}`);
8756
- }
8757
- const pending = {
8758
- ref, goalId,
8759
- seat: { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid },
8760
- payload, acceptedAt, deadlineAt,
8761
- holdToken, holdEpoch: executor.epoch,
8762
- ...(handoffFrom !== undefined ? { handoffFrom } : {}),
8763
- };
8764
- this.pendingTurns.set(key, pending);
8765
- this.ensureTurnSweep();
8766
- this.noticeSeatTurns(pending.seat);
8767
- const acceptance = { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid, goalId, fingerprint, deadlineAt, executor };
8768
- this.turnAcceptances.set(key, { acceptance, ref });
8769
- this.emitGoalProgress(ref, executor.epoch, { phase: "relayed" });
8770
- return acceptance;
8771
- }
8293
+ serveTurnGoal(ctx, target) { return this.turnRelay.serveTurnGoal(ctx, target); }
8772
8294
  /** The seat's pull: every pending turn addressed to the CALLER's incarnation, oldest first.
8773
8295
  * The uid is part of the address — a successor seat never receives a predecessor's turn. */
8774
- turnPendingFor(c) {
8775
- // AN EMPTY LIST IS AN ANSWER, so it must not be given before the index is rebuilt. Between
8776
- // registration and `reconcileGoalIndex`, `pendingTurns` holds nothing a predecessor accepted,
8777
- // and a seat that pulls in that window is told authoritatively that it has no turn. The seat
8778
- // treats a refusal as "keep what you hold" and an empty list as "you hold nothing", so the
8779
- // window has to refuse, the same way `serveTurnGoal` does.
8780
- if (!this.goalReconcileDone)
8781
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; the pending-turn index is not rebuilt yet, retry (SPEC 13.6)");
8782
- // A once seat this manager does not hold, whose task has ended, is told to end itself. Nothing
8783
- // else rides that answer, and the settled task is never served again.
8784
- const stop = this.onceStops.get(c.uid);
8785
- if (stop !== undefined && stop.owner === c.owner && stop.actor === c.actor) {
8786
- stop.told = true;
8787
- return { turns: [], notices: true, stop: true };
8788
- }
8789
- // Two turns on one seat are serialized at the dispatch (cotal-lang 6.5): only the oldest
8790
- // unsettled one is served, and the next surfaces once it yields or its deadline denies, so a
8791
- // seat is never shown two turns at once.
8792
- // An ELAPSED turn is not servable: its hold is expirable and its run has already thrown from
8793
- // its own pause, so handing it to the seat buys work whose yield is refused. It also cannot be
8794
- // allowed to stay the head, or one expired turn dams every later turn for that seat. A once
8795
- // task is not served before its spawn's readiness verdict, and one with no deadline never
8796
- // elapses.
8797
- const now = Date.now();
8798
- const head = [...this.pendingTurns.values()]
8799
- .filter((p) => p.seat.owner === c.owner && p.seat.actor === c.actor && p.seat.uid === c.uid)
8800
- .filter((p) => (p.deadlineAt === undefined || now < p.deadlineAt) && p.once?.deliverable !== false)
8801
- .sort((x, y) => x.acceptedAt - y.acceptedAt)
8802
- .slice(0, 1);
8803
- for (const p of head)
8804
- p.pulledAt ??= now;
8805
- const turns = head.map((p) => ({ goalId: p.goalId, payload: p.payload, acceptedAt: p.acceptedAt, ...(p.deadlineAt !== undefined ? { deadlineAt: p.deadlineAt } : {}), ...(p.once ? { once: true } : {}) }));
8806
- return { turns, notices: true };
8807
- }
8296
+ turnPendingFor(c) { return this.turnRelay.turnPendingFor(c); }
8808
8297
  /** Tell a seat that its `turn-pending` answer changed (SPEC 14.3 turn notice), over the serve
8809
8298
  * connection that holds this instance's reply rows. The notice carries no turn and the seat
8810
8299
  * pulls on it, so a lost notice delays that seat until its next pull, and nothing else. */
@@ -8824,163 +8313,17 @@ export class Manager {
8824
8313
  console.error(`! turn notice for ${seat.actor} failed: ${rejectionText(e)}`);
8825
8314
  }
8826
8315
  }
8827
- /** A seat names a turn by goal id alone when it yields, so one incarnation holding two callers'
8828
- * turns under one id could not say which of the two it answered. */
8829
- assertSeatTurnFree(name, t, goalId) {
8830
- if (this.seatTurnKey({ owner: t.owner, actor: t.actor, uid: t.lifecycleUid }, goalId) !== undefined)
8831
- throw new EpEnvelopeError("failed-precondition", `seat "${name}" already holds another caller's turn "${goalId}"; a seat yields by goal id, so it is never handed two turns under one (SPEC 13.6)`);
8832
- }
8833
- /** The relay key of the turn addressed to seat incarnation `c` under `goalId`, pending or kept
8834
- * for a retried yield. The accept path never hands one incarnation two turns under one goal
8835
- * id, so at most one matches. */
8836
- seatTurnKey(c, goalId) {
8837
- for (const [key, { acceptance: a }] of this.turnAcceptances)
8838
- if (a.goalId === goalId && a.owner === c.owner && a.actor === c.actor && a.uid === c.uid)
8839
- return key;
8840
- return undefined;
8841
- }
8842
8316
  /** The seat's yield: claim the hold (one-use; expiry fails closed), then commit the goal
8843
8317
  * `succeeded` carrying the TurnResult. A yield AFTER the deadline drives the deadline terminal
8844
8318
  * instead and refuses — the expiry outcome stands, never a late success over it. */
8845
- async serveTurnYield(c, raw) {
8846
- if (this.execution === "none")
8847
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
8848
- // Same boot window as the pull, and checked first because it is the earlier boot phase: before
8849
- // the index is rebuilt a predecessor's accepted turn is not in `pendingTurns`, and `not-found`
8850
- // would tell the seat to drop work it is holding.
8851
- if (!this.goalReconcileDone)
8852
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; this yield's turn may not be indexed yet, retry (SPEC 13.6)");
8853
- const gw = this.goalWriter;
8854
- if (!gw)
8855
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
8856
- const goalId = String(raw.goalId);
8857
- const status = String(raw.status);
8858
- const to = raw.to === undefined ? undefined : String(raw.to);
8859
- const yieldNote = raw.note === undefined ? undefined : String(raw.note);
8860
- if (status === "handoff" && (to === undefined || to.length === 0))
8861
- throw new EpEnvelopeError("failed-precondition", `a handoff yield names its addressee ("to"); a handoff to nobody relays nothing`);
8862
- const key = this.seatTurnKey(c, goalId);
8863
- if (key === undefined)
8864
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
8865
- const p = this.pendingTurns.get(key);
8866
- if (!p)
8867
- return this.settledTurnAnswer(key, goalId);
8868
- await this.claimTurnHold(p);
8869
- const epoch = this.serviceServe?.grant.epoch ?? 0;
8870
- await this.assertGoalWriterEpochCurrent(epoch);
8871
- const at = Date.now();
8872
- const data = { status, ...(to !== undefined ? { to } : {}), ...(yieldNote !== undefined ? { note: yieldNote } : {}), ...(p.handoffFrom !== undefined ? { handoffFrom: p.handoffFrom } : {}), at };
8873
- // The goal is TARGET-PINNED, so this completion proves the EXECUTOR's (the seat's) fresh
8874
- // currency, not the manager's: managed-seat epochs are 0 within an incarnation (the same
8875
- // convention resolveTarget serves), and the resolver answers from the live agents map — a
8876
- // seat that died between its yield call and this commit refuses `expired` here.
8877
- const { fact } = await commitGoalResult(gw.ctx, {
8878
- ref: p.ref, now: at, cause: "complete", state: "succeeded", data,
8879
- committer: { instanceId: this.managerInstanceId, epoch },
8880
- executor: { lifecycleUid: p.seat.uid, epoch: 0 },
8881
- resolveCurrentEpoch: (target) => this.turnExecutorEpoch(p.seat.name, p.seat.owner, p.seat.actor, target.lifecycleUid),
8882
- });
8883
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
8884
- // A once task's index entry is its seat's debt, dropped at the seat's proved exit.
8885
- if (!p.once)
8886
- await clearGoalIndex(gw.ctx, p.ref);
8887
- this.pendingTurns.delete(key);
8888
- this.noticeSeatTurns(p.seat);
8889
- this.markTurnLatchDropped(key, at);
8890
- this.rememberSettledTurn(key, fact.state, at);
8891
- if (p.once)
8892
- this.endOnceSeat(p, `yielded ${status}`);
8893
- this.maybeStopTurnSweep();
8894
- return { goalId, state: fact.state };
8895
- }
8896
- /** A seat's answer for a turn no longer pending. A REPLY THAT WAS LOST IS NOT AN ANSWER THAT
8897
- * FAILED: the commit deleted the pending turn, so a retry found nothing and heard `not-found`,
8898
- * which a seat reads as "drop it", reporting failure for work the run already has. The answer
8899
- * the first reply carried is served again instead, to the addressee it was addressed to and
8900
- * nobody else. */
8901
- async settledTurnAnswer(key, goalId) {
8902
- const settled = this.turnAcceptances.get(key);
8903
- if (settled !== undefined) {
8904
- if (settled.settled !== undefined)
8905
- return { goalId, state: settled.settled.state };
8906
- // The in-memory answer is not yet remembered (pending deleted before the terminal CAS,
8907
- // or a concurrent sweep dropped `settled` while the commit was still in flight). The
8908
- // durable terminal is the one the run already has; name it, never `not-found`.
8909
- if (settled.ref !== undefined && this.goalWriter) {
8910
- const ended = await readGoalResult(this.goalWriter.ctx, settled.ref);
8911
- if (ended !== undefined) {
8912
- this.rememberSettledTurn(key, ended.state, ended.ts);
8913
- return { goalId, state: ended.state };
8914
- }
8915
- }
8916
- }
8917
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
8918
- }
8919
- /** Claim a pending turn's deadline hold before the seat's answer commits: one use, and a hold
8920
- * that already expired drives the deadline terminal instead and refuses the answer. A once task
8921
- * with no deadline has no hold. */
8922
- async claimTurnHold(p) {
8923
- if (p.holdToken === undefined)
8924
- return;
8925
- const gw = this.goalWriter;
8926
- const cpRef = { endpoint: p.ref.endpoint, token: p.holdToken };
8927
- try {
8928
- await resumeCheckpoint(gw.ctx.kv, gw.ctx.js, gw.ctx.jsm, this.space, { ref: cpRef, presenter: { id: MANAGER_ENDPOINT, lifecycleUid: this.managerInstanceId }, now: Date.now() });
8929
- }
8930
- catch (e) {
8931
- const settle = await readCheckpointSettle(gw.ctx.jsm, this.space, cpRef).catch(() => undefined);
8932
- if (settle?.settle === "expired") {
8933
- await this.commitTurnDeadline(p);
8934
- throw new EpEnvelopeError("failed-precondition", `turn "${p.goalId}" elapsed its deadline before the seat answered; the deadline terminal stands (SPEC 13.6)`);
8935
- }
8936
- // Already resumed BY THIS MANAGER (the hold is holder-bound): a prior attempt claimed it
8937
- // and then failed to commit. Fall through and commit; the claim is ours to finish.
8938
- if (settle?.settle !== "resumed")
8939
- throw e;
8940
- }
8941
- }
8319
+ serveTurnYield(c, raw) { return this.turnRelay.serveTurnYield(c, raw); }
8942
8320
  /** A once seat's report that its task's handoff to its harness was not confirmed. The seat sealed
8943
8321
  * the task before it reported, so nothing hands it over again; the task fails
8944
8322
  * `delivery-unconfirmed` and the seat is stopped. The commit proves the seat's live currency, as
8945
8323
  * a yield's does: a seat already gone commits nothing here, and its exit cancels the task. Only
8946
8324
  * the addressed seat may report, only for its once task; a repeat after the terminal is answered
8947
8325
  * with it. */
8948
- async serveTurnUnconfirmed(c, raw) {
8949
- if (this.execution === "none")
8950
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
8951
- if (!this.goalReconcileDone)
8952
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; this report's turn may not be indexed yet, retry (SPEC 13.6)");
8953
- const gw = this.goalWriter;
8954
- if (!gw)
8955
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
8956
- const goalId = String(raw.goalId);
8957
- const key = this.seatTurnKey(c, goalId);
8958
- if (key === undefined)
8959
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
8960
- const p = this.pendingTurns.get(key);
8961
- if (!p)
8962
- return this.settledTurnAnswer(key, goalId);
8963
- if (!p.once)
8964
- throw new EpEnvelopeError("failed-precondition", `turn "${goalId}" is a run's turn; turn-unconfirmed reports only a once task, and a run's turn is offered again`);
8965
- await this.claimTurnHold(p);
8966
- const epoch = this.serviceServe?.grant.epoch ?? 0;
8967
- await this.assertGoalWriterEpochCurrent(epoch);
8968
- const at = Date.now();
8969
- const { fact } = await commitGoalResult(gw.ctx, {
8970
- ref: p.ref, now: at, cause: "complete", state: "failed", data: { reason: "delivery-unconfirmed", at },
8971
- committer: { instanceId: this.managerInstanceId, epoch },
8972
- executor: { lifecycleUid: p.seat.uid, epoch: 0 },
8973
- resolveCurrentEpoch: (target) => this.turnExecutorEpoch(p.seat.name, p.seat.owner, p.seat.actor, target.lifecycleUid),
8974
- });
8975
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
8976
- this.pendingTurns.delete(key);
8977
- this.noticeSeatTurns(p.seat);
8978
- this.markTurnLatchDropped(key, at);
8979
- this.rememberSettledTurn(key, fact.state, at);
8980
- this.endOnceSeat(p, "delivery-unconfirmed");
8981
- this.maybeStopTurnSweep();
8982
- return { goalId, state: fact.state };
8983
- }
8326
+ serveTurnUnconfirmed(c, raw) { return this.turnRelay.serveTurnUnconfirmed(c, raw); }
8984
8327
  /** The caller withdraws a turn it submitted (the reserved `cancel`, SPEC 13.6 item 4), so the
8985
8328
  * seat is not shown it again and a late yield is answered from the cancelled terminal. Only a
8986
8329
  * relay this incarnation holds is moved to `cancelling`, because only its holder can commit the
@@ -8991,317 +8334,20 @@ export class Manager {
8991
8334
  * held: a yield that read the entry first, or this commit with only its reply lost. An entry
8992
8335
  * whose outcome cannot be read back stays out and converges through the goal index at the
8993
8336
  * next boot, as a failed deadline commit does. */
8994
- async serveTurnCancel(ctx) {
8995
- if (this.execution === "none")
8996
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
8997
- if (!this.goalReconcileDone)
8998
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; the pending-turn index is not rebuilt yet, retry (SPEC 13.6)");
8999
- const gw = this.goalWriter;
9000
- if (!gw)
9001
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
9002
- const raw = (ctx.request.args ?? {});
9003
- const goalId = String(raw.goalId);
9004
- const ref = goalRefOf(ctx.subject, goalId);
9005
- const key = goalKey(ref);
9006
- const p = this.pendingTurns.get(key);
9007
- if (p === undefined) {
9008
- const ended = await readGoalResult(gw.ctx, ref);
9009
- if (ended !== undefined)
9010
- throw goalAlreadyTerminal(goalId, ended);
9011
- throw new EpEnvelopeError("failed-precondition", `no turn "${goalId}" of this caller is pending on this manager; cancel withdraws a relayed turn (SPEC 13.6)`);
9012
- }
9013
- this.pendingTurns.delete(key);
9014
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9015
- let fact;
9016
- try {
9017
- await requestGoalCancel(gw.ctx, { request: ctx.subject, goalId, mode: (raw.mode ?? "graceful") });
9018
- await this.assertGoalWriterEpochCurrent(epoch);
9019
- ({ fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "caller" }, committer: { instanceId: this.managerInstanceId, epoch } }));
9020
- }
9021
- catch (e) {
9022
- // The remembered answer is read after the durable one, with no await before the put back:
9023
- // a yield that has dropped the entry remembered its answer, and one still committing drops
9024
- // the entry it finds. An ended relay is stamped so its acceptance still ages off.
9025
- if ((await readGoalResult(gw.ctx, ref)) !== undefined)
9026
- this.markTurnLatchDropped(key);
9027
- else if (this.turnAcceptances.get(key)?.settled === undefined)
9028
- this.pendingTurns.set(key, p);
9029
- throw e;
9030
- }
9031
- this.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9032
- this.noticeSeatTurns(p.seat);
9033
- this.markTurnLatchDropped(key);
9034
- this.rememberSettledTurn(key, fact.state, Date.now());
9035
- if (p.once)
9036
- this.endOnceSeat(p, "cancelled");
9037
- else
9038
- await clearGoalIndex(gw.ctx, ref);
9039
- this.maybeStopTurnSweep();
9040
- return { goalId, state: fact.state };
9041
- }
9042
- /** Commit the deadline terminal for one pending turn whose hold settled EXPIRED: the deny's
9043
- * predicate is that recorded settle, verified by core against the spec's goal binding. The map
9044
- * delete is the idempotency latch (yield-loss and sweep race here); a commit failure after it
9045
- * converges through the goal index at the next boot, the same narrow leg spawn leaves open. */
9046
- async commitTurnDeadline(p) {
9047
- const gw = this.goalWriter;
9048
- if (!gw)
9049
- return;
9050
- const key = goalKey(p.ref);
9051
- if (!this.pendingTurns.delete(key))
9052
- return;
9053
- this.noticeSeatTurns(p.seat);
9054
- this.markTurnLatchDropped(key);
9055
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9056
- try {
9057
- await this.assertGoalWriterEpochCurrent(epoch);
9058
- const { fact } = await commitGoalResult(gw.ctx, { ref: p.ref, now: Date.now(), cause: "deny", denial: { kind: "hold-expired", token: p.holdToken }, data: { reason: "turn-deadline", ...(p.seatDiedAt !== undefined ? { agentDownAt: p.seatDiedAt } : {}), ...(p.handoffFrom !== undefined ? { handoffFrom: p.handoffFrom } : {}), ...(this.onceSeatUnheld(p) ? { seat: UNHELD_SEAT } : {}) }, committer: { instanceId: this.managerInstanceId, epoch } });
9059
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9060
- // Remember BEFORE the index clear: a late yield that arrives after the pending latch
9061
- // (the delete at the top of this function) and after this CAS has to name this terminal.
9062
- // Clearing first, then remembering, left a window where maybeStopTurnSweep saw no pending
9063
- // turn and no settled answer, wiped the acceptance, and rememberSettledTurn no-op'd.
9064
- this.rememberSettledTurn(key, fact.state, Date.now());
9065
- if (p.once)
9066
- this.endOnceSeat(p, "turn-deadline");
9067
- else
9068
- await clearGoalIndex(gw.ctx, p.ref);
9069
- }
9070
- catch (e) {
9071
- console.error(`! turn deadline terminal for ${p.goalId}: ${rejectionText(e)}`);
9072
- // A once seat stops at its deadline whether or not the terminal landed, and the task stays
9073
- // pending so the turn sweep writes the terminal again while this manager runs.
9074
- if (p.once) {
9075
- this.pendingTurns.set(key, p);
9076
- this.endOnceSeat(p, "turn-deadline");
9077
- this.ensureTurnSweep();
9078
- }
9079
- }
9080
- this.maybeStopTurnSweep();
9081
- }
8337
+ serveTurnCancel(ctx) { return this.turnRelay.serveTurnCancel(ctx); }
9082
8338
  /** The reap hook: a pending turn addressed to the reaped INCARNATION is MARKED dead, never
9083
8339
  * settled early — no honest terminal exists for it (a completion must prove the executor's
9084
8340
  * live currency, and the hold is only expirable once due), so the entry rides to its deadline
9085
8341
  * and the deny then records both facts. The addressee's own client observes the death from
9086
8342
  * presence long before that, which is the run's L4002. */
9087
- failSeatTurns(name, uid) {
9088
- for (const p of this.pendingTurns.values()) {
9089
- if (p.seat.name !== name || p.seat.uid !== uid || p.seatDiedAt !== undefined)
9090
- continue;
9091
- p.seatDiedAt = Date.now();
9092
- console.error(`turn ${p.goalId}: addressed seat ${name}/${uid} died before yielding; the deadline terminal will record it`);
9093
- }
9094
- }
9095
- /** Settle one DUE hold as its owner: the manager minted it, so once the deadline has passed it
9096
- * expires the pause itself ({@link expireCheckpoint}, the guard-hold precedent) rather than
9097
- * waiting on the broker's fire — which it holds no grant to read, and which a hold minted under
9098
- * a predecessor's epoch would carry on a subject this incarnation never subscribes. Idempotent
9099
- * by the plane: a yield that claimed the hold first is observed as `resumed` and left to its
9100
- * own commit, and an already-expired hold returns its recorded settle. */
9101
- async expireTurnHold(p) {
9102
- const gw = this.goalWriter;
9103
- if (!gw)
9104
- return undefined;
9105
- return expireCheckpoint(gw.ctx.kv, gw.ctx.js, gw.ctx.jsm, this.space, { ref: { endpoint: p.ref.endpoint, token: p.holdToken }, now: Date.now() });
9106
- }
9107
- ensureTurnSweep() {
9108
- if (this.turnSweepTimer !== undefined)
9109
- return;
9110
- const t = setInterval(() => { void this.sweepTurnDeadlines().catch((e) => console.error(`! turn deadline sweep: ${rejectionText(e)}`)); }, TURN_SWEEP_MS);
9111
- t.unref?.();
9112
- this.turnSweepTimer = t;
9113
- }
9114
- /** The answer a retried yield is served, held for {@link TURN_ANSWER_RETENTION_MS}. Only for a
9115
- * turn this incarnation accepted: an entry it has no acceptance for is one it cannot vouch for. */
9116
- rememberSettledTurn(key, state, at) {
9117
- const entry = this.turnAcceptances.get(key);
9118
- if (entry === undefined)
9119
- return;
9120
- entry.settled = { state, at };
9121
- }
9122
- /** Stamp when the pending latch dropped, so an unsettled leftover ages off that instant rather
9123
- * than the original deadline. Idempotent: the first drop is the one the retry window starts at. */
9124
- markTurnLatchDropped(key, at = Date.now()) {
9125
- const entry = this.turnAcceptances.get(key);
9126
- if (entry === undefined || entry.leftoverSince !== undefined)
9127
- return;
9128
- entry.leftoverSince = at;
9129
- }
9130
- /** Stop the sweep only when it has nothing left to do. It drives elapsed turns to their deadline
9131
- * terminals AND drops settled answers once their retry window has passed, so a stop while the
9132
- * second is still owed would leave one entry per turn for the process lifetime. */
9133
- maybeStopTurnSweep() {
9134
- if (this.pendingTurns.size > 0 || this.onceSettles.size > 0 || this.onceInherited.size > 0 || [...this.onceStops.values()].some((s) => !s.told))
9135
- return;
9136
- // An acceptance with no `settled` yet is the in-flight deadline commit: pending was the
9137
- // latch and is already gone, the terminal CAS has not returned, and a concurrent sweep
9138
- // tick used to clear the map here, so rememberSettledTurn no-op'd and a late yield heard
9139
- // `not-found` for a deny the run already has. Prune is the only deleter; stop only when
9140
- // it has left nothing.
9141
- if (this.turnAcceptances.size > 0)
9142
- return;
9143
- this.stopTurnSweep();
9144
- }
9145
- stopTurnSweep() {
9146
- if (this.turnSweepTimer === undefined)
9147
- return;
9148
- clearInterval(this.turnSweepTimer);
9149
- this.turnSweepTimer = undefined;
9150
- }
9151
- /** Drive every elapsed pending turn to its deadline terminal. Only entries at/past their own
9152
- * `deadlineAt` are read at all; a `resumed` settle is a yield mid-commit and is left alone. */
9153
- async sweepTurnDeadlines() {
9154
- const now = Date.now();
9155
- // A settled answer is kept only as long as a lost reply could still be retried under it.
9156
- // An UNSETTLED acceptance whose pending latch is already gone is the in-flight (or failed)
9157
- // deadline commit: keep it for the same window so a late yield can still read the durable
9158
- // terminal, then drop it so a commit that never remembered cannot pin the sweep forever.
9159
- for (const [key, e] of [...this.turnAcceptances.entries()]) {
9160
- if (this.pendingTurns.has(key))
9161
- continue;
9162
- // Unsettled leftovers age off the latch-drop stamp, never `deadlineAt`.
9163
- const at = e.settled?.at ?? e.leftoverSince;
9164
- if (at !== undefined && now - at >= TURN_ANSWER_RETENTION_MS)
9165
- this.turnAcceptances.delete(key);
9166
- }
9167
- // The prune above is the one event after which the sweep may have nothing left to do, and
9168
- // the settle-time callers cannot see it: they run when an answer has just been remembered.
9169
- this.maybeStopTurnSweep();
9170
- // A notice is at-most-once, so a seat offline when it went out has not pulled its head turn.
9171
- // Repeat the notice until it does; a seat that pulled is not told again for that turn.
9172
- const heads = new Map();
9173
- for (const p of this.pendingTurns.values()) {
9174
- if ((p.deadlineAt !== undefined && now >= p.deadlineAt) || p.once?.deliverable === false)
9175
- continue;
9176
- const k = `${p.seat.owner}.${p.seat.actor}.${p.seat.uid}`;
9177
- const h = heads.get(k);
9178
- if (h === undefined || p.acceptedAt < h.acceptedAt)
9179
- heads.set(k, p);
9180
- }
9181
- for (const p of heads.values())
9182
- if (p.pulledAt === undefined)
9183
- this.noticeSeatTurns(p.seat);
9184
- for (const stop of this.onceStops.values())
9185
- if (!stop.told)
9186
- this.noticeSeatTurns(stop);
9187
- for (const owed of [...this.onceSettles.values()])
9188
- if (!owed.flight)
9189
- void this.settleOnceTurn(owed.ref, owed.reason);
9190
- if (this.onceInherited.size > 0)
9191
- await this.settleInheritedOnce().catch((e) => console.error(`! inherited once tasks: ${rejectionText(e)}`));
9192
- for (const p of [...this.pendingTurns.values()]) {
9193
- if (p.deadlineAt === undefined || now < p.deadlineAt)
9194
- continue;
9195
- try {
9196
- const settle = await this.expireTurnHold(p);
9197
- if (settle?.settle === "expired")
9198
- await this.commitTurnDeadline(p);
9199
- }
9200
- catch (e) {
9201
- console.error(`! turn deadline sweep for ${p.goalId}: ${rejectionText(e)}`);
9202
- }
9203
- }
9204
- }
8343
+ failSeatTurns(name, uid) { return this.turnRelay.failSeatTurns(name, uid); }
9205
8344
  /** Adopt one inherited TURN goal at boot (the reconcile sweep's turn branch): a non-terminal
9206
8345
  * entry carrying a parseable note rebuilds its pending relay — never an `uncertain` settle,
9207
8346
  * because the deadline hold IS this goal's bounded ending and it survived the restart. No
9208
8347
  * liveness verdict is made here (the agents map is empty during reconcile, so absence means
9209
8348
  * "not yet re-registered", never "dead"); a garbled note or a floor that does not name the
9210
8349
  * seat's owner is logged and left, the dead-pointer honesty rule. */
9211
- async adoptTurnGoal(entry) {
9212
- const gw = this.goalWriter;
9213
- if (!gw)
9214
- return;
9215
- const status = await readGoalStatus(gw.ctx, entry.ref);
9216
- if (status === undefined)
9217
- return; // index points at no goal record: a dead pointer, left for honesty
9218
- const parsed = entry.note !== undefined ? parseTurnNote(entry.note) : undefined;
9219
- const ownOnce = parsed?.once === true && entry.iid === this.managerInstanceId && entry.allocated?.owner !== undefined;
9220
- if (GOAL_TERMINAL_STATES.includes(status.value.state)) {
9221
- // A once task's entry is its seat's debt until that seat's exit is proved, so it outlives
9222
- // the terminal: the stop the predecessor owed may never have landed.
9223
- if (ownOnce)
9224
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9225
- else
9226
- await clearGoalIndex(gw.ctx, entry.ref);
9227
- return;
9228
- }
9229
- if (entry.iid !== this.managerInstanceId) {
9230
- console.error(`turn reconcile ${entry.ref.goalId}: accepted by instance "${entry.iid}", not this incarnation "${this.managerInstanceId}"; left for its owner (never a cross-instance settle)`);
9231
- return;
9232
- }
9233
- if (entry.allocated?.owner === undefined || parsed === undefined) {
9234
- console.error(`turn reconcile ${entry.ref.goalId}: the relay record is garbled (no floor naming the seat's owner, or an unparseable note); left unsettled`);
9235
- return;
9236
- }
9237
- const spec = await readGoalSpec(gw.ctx, entry.ref);
9238
- if (spec === undefined) {
9239
- // NOW IS NOT WHEN THIS WAS ACCEPTED. `acceptedAt` is what orders a seat's queue, and a turn
9240
- // stamped with the boot instant sorts BEHIND every turn accepted since — a predecessor's
9241
- // oldest turn served last, which is the one thing the ordering exists to prevent. A goal
9242
- // with an index entry and no spec is a relay record that is not readable, and this is the
9243
- // same verdict the garbled-note branch above reaches: left unsettled, said out loud.
9244
- console.error(`turn reconcile ${entry.ref.goalId}: the goal spec is unreadable, so its acceptance time is unknown; left unsettled rather than re-stamped with the boot instant`);
9245
- return;
9246
- }
9247
- const p = {
9248
- ref: entry.ref, goalId: entry.ref.goalId,
9249
- seat: { name: entry.allocated.name, owner: entry.allocated.owner, actor: entry.allocated.actor, uid: entry.allocated.uid },
9250
- payload: parsed.payload,
9251
- acceptedAt: spec.value.acceptedAt,
9252
- holdEpoch: parsed.holdEpoch,
9253
- ...(parsed.deadlineAt !== undefined ? { deadlineAt: parsed.deadlineAt, holdToken: parsed.holdToken ?? turnHoldToken(entry.ref.goalId) } : {}),
9254
- ...(parsed.handoffFrom !== undefined ? { handoffFrom: parsed.handoffFrom } : {}),
9255
- // An inherited once task is served again only once its seat is bound to this incarnation.
9256
- ...(parsed.once ? { once: { deliverable: false } } : {}),
9257
- };
9258
- // The hold is the relay's bounded ending, minted AFTER the index entry and the goal record,
9259
- // so a crash between them leaves a goal with no hold: nothing could ever settle it, and the
9260
- // sweep would report the same missing pause every tick. Left unsettled, said once.
9261
- if (p.holdToken !== undefined && (await readCheckpointSpec(gw.ctx.kv, { endpoint: p.ref.endpoint, token: p.holdToken })) === undefined) {
9262
- // A once task's hold is minted before its seat launches, so without one no seat ever ran it:
9263
- // the task is cancelled and its entry dropped, with nothing launched to prove gone.
9264
- if (parsed.once) {
9265
- await this.settleOnceTurn(p.ref, "launch-failed");
9266
- return;
9267
- }
9268
- console.error(`turn reconcile ${p.goalId}: its deadline hold was never minted (the accept crashed before it); left unsettled`);
9269
- return;
9270
- }
9271
- // A once task whose spawn has no succeeded terminal was never served, whatever seat exists:
9272
- // it is cancelled, its row is not rebuilt so a later pull finds nothing, and its seat is
9273
- // settled as an inherited debt.
9274
- if (parsed.once && !(await this.onceServed(entry.ref, parsed))) {
9275
- await this.commitOnceCancel(entry.ref, NEVER_SERVED);
9276
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9277
- return;
9278
- }
9279
- const key = goalKey(p.ref);
9280
- this.pendingTurns.set(key, p);
9281
- // THE ACCEPTANCE TOO, or the adopted turn's answer is never remembered: `rememberSettledTurn`
9282
- // writes only against an acceptance this incarnation holds, and adoption rebuilt the pending
9283
- // relay without one, so a yield whose reply was lost after a restart still heard `not-found`
9284
- // on the very path adoption exists for. The acceptance is rebuilt from the same records the
9285
- // relay was: the spec holds the fingerprint, the index holds the seat, the note the deadline.
9286
- this.turnAcceptances.set(key, {
9287
- acceptance: {
9288
- name: p.seat.name, owner: p.seat.owner, actor: p.seat.actor, uid: p.seat.uid, goalId: p.goalId,
9289
- fingerprint: spec.value.fingerprint, deadlineAt: p.deadlineAt,
9290
- executor: { lifecycleUid: this.managerInstanceId, epoch: p.holdEpoch },
9291
- },
9292
- ref: p.ref,
9293
- });
9294
- // NO LIVENESS VERDICT AT BOOT. The agents map is empty here: seats are re-registered later,
9295
- // by the resume path, so `not in the map` at this moment means "not yet re-registered", never
9296
- // "dead". Stamping death from it marked EVERY adopted turn as a dead seat, and its deadline
9297
- // terminal then carried `agentDownAt`, so the run raised L4002 for a seat that was alive the
9298
- // whole time where the reference says L4003. The reap hook is the only honest writer of that
9299
- // fact: it fires when a managed seat actually dies.
9300
- console.error(`turn reconcile ${p.goalId}: pending relay to ${p.seat.name}/${p.seat.uid} adopted (deadline ${p.deadlineAt ?? "none"})`);
9301
- if (parsed.once)
9302
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9303
- this.ensureTurnSweep();
9304
- }
8350
+ adoptTurnGoal(entry) { return this.turnRelay.adoptTurnGoal(entry); }
9305
8351
  // ---- once (a spawn whose prompt is its one relayed task) ----------------------------------------
9306
8352
  //
9307
8353
  // A once spawn's prompt is not a kickoff: the manager accepts it as one turn addressed to the
@@ -9315,77 +8361,7 @@ export class Manager {
9315
8361
  * the goal ref and the seat given rather than read off a request. A task with no deadline mints
9316
8362
  * no hold; its goal still records the spawn's readiness budget, which a successor needs to settle
9317
8363
  * it. */
9318
- async acceptOnceTurn(o) {
9319
- const gw = this.goalWriter;
9320
- if (!gw)
9321
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; a once task cannot be accepted (SPEC 13.6)");
9322
- const serve = this.serviceServe;
9323
- if (o.deadlineMs !== undefined && !serve)
9324
- throw new EpEnvelopeError("unavailable", "the manager service endpoint is not serving; a once task's deadline hold is armed over its connection (SPEC 13.9)");
9325
- const ref = { endpoint: o.spawnRef.endpoint, caller: { ...o.spawnRef.caller }, goalId: digestIdToken(`${o.spawnRef.goalId}:once`) };
9326
- const key = goalKey(ref);
9327
- const deadlineAt = o.deadlineMs === undefined ? undefined : o.acceptedAt + o.deadlineMs;
9328
- if (deadlineAt !== undefined && deadlineAt > MAX_SCHEDULE_MS)
9329
- throw new EpEnvelopeError("failed-precondition", `once: the deadline ends after the deadline scheduler's last instant (the end of year 9999)`);
9330
- const holdToken = deadlineAt === undefined ? undefined : turnHoldToken(key);
9331
- const { payload, note } = onceTurnNote({ prompt: o.prompt, spawner: o.spawner, holdEpoch: o.executor.epoch, ...(deadlineAt !== undefined ? { deadlineAt, holdToken } : {}), ...(o.retire !== undefined ? { retire: o.retire } : {}), spawn: o.spawnRef.goalId });
9332
- const { seat } = o;
9333
- const idx = await recordGoalIndex(gw.ctx, ref, o.executor.lifecycleUid, { name: seat.name, owner: seat.owner, actor: seat.actor, uid: seat.uid, readinessDeadlineMs: o.readinessDeadlineMs }, note);
9334
- if (!idx.recorded)
9335
- throw new EpEnvelopeError("failed-precondition", `once: the task goal "${ref.goalId}" is already recorded; a spawn accepts its task once (SPEC 13.6)`);
9336
- const b = await bindGoal(gw.ctx, ref, o.fingerprint);
9337
- if (!b.bound) {
9338
- await clearGoalIndex(gw.ctx, ref);
9339
- throw new EpEnvelopeError("failed-precondition", `once: the task goal "${ref.goalId}" is already bound; a spawn accepts its task once (SPEC 13.6)`);
9340
- }
9341
- try {
9342
- await createGoal(gw.ctx, ref, {
9343
- fingerprint: o.fingerprint,
9344
- command: o.command,
9345
- caller: { id: `${ref.caller.owner}.${ref.caller.actor}`, lifecycleUid: ref.caller.uid },
9346
- acceptedEpoch: o.executor.epoch,
9347
- requestId: ref.goalId,
9348
- sourceSeq: 0,
9349
- acceptedAt: o.acceptedAt,
9350
- readinessDeadlineMs: o.readinessDeadlineMs,
9351
- target: { owner: seat.owner, actor: seat.actor, lifecycleUid: seat.uid, mappingRevision: 0 },
9352
- });
9353
- if (deadlineAt !== undefined)
9354
- await mintCheckpoint(gw.ctx.kv, jetstream(serve.nc), this.space, {
9355
- ref: { endpoint: ref.endpoint, token: holdToken },
9356
- instanceId: this.managerInstanceId,
9357
- epoch: o.executor.epoch,
9358
- goal: { caller: { ...ref.caller }, goalId: ref.goalId },
9359
- holder: { id: MANAGER_ENDPOINT, lifecycleUid: this.managerInstanceId },
9360
- deadline: deadlineAt,
9361
- now: o.acceptedAt,
9362
- });
9363
- }
9364
- catch (e) {
9365
- // Nothing launched and nothing was served, so the task is withdrawn with `cancel`.
9366
- try {
9367
- await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: "terminate" } });
9368
- await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "manager", reason: "accept-failed" }, committer: { instanceId: this.managerInstanceId, epoch: o.executor.epoch } });
9369
- await clearGoalIndex(gw.ctx, ref);
9370
- }
9371
- catch (e2) {
9372
- console.error(`! once task accept unwind for ${ref.goalId}: ${rejectionText(e2)}`);
9373
- }
9374
- throw e;
9375
- }
9376
- this.pendingTurns.set(key, {
9377
- ref, goalId: ref.goalId, seat: { ...seat }, payload, acceptedAt: o.acceptedAt, holdEpoch: o.executor.epoch,
9378
- ...(deadlineAt !== undefined ? { deadlineAt, holdToken } : {}),
9379
- once: { deliverable: false },
9380
- });
9381
- this.turnAcceptances.set(key, {
9382
- acceptance: { name: seat.name, owner: seat.owner, actor: seat.actor, uid: seat.uid, goalId: ref.goalId, fingerprint: o.fingerprint, ...(deadlineAt !== undefined ? { deadlineAt } : {}), executor: o.executor },
9383
- ref,
9384
- });
9385
- this.ensureTurnSweep();
9386
- this.emitGoalProgress(ref, o.executor.epoch, { phase: "relayed" });
9387
- return { ref, ...(deadlineAt !== undefined ? { deadlineAt } : {}) };
9388
- }
8364
+ acceptOnceTurn(o) { return this.turnRelay.acceptOnceTurn(o); }
9389
8365
  /** How a once seat's startup watch ended, waited for until {@link STARTUP_OUTCOME_MS} after its
9390
8366
  * launch or the readiness window, whichever is longer. A watch that has not ended by then, or a
9391
8367
  * seat being stopped, answers what the handle reports at that moment. */
@@ -9393,19 +8369,13 @@ export class Manager {
9393
8369
  const until = launchedAt + Math.max(readinessTimeoutMs, STARTUP_OUTCOME_MS);
9394
8370
  for (;;) {
9395
8371
  const outcome = a.handle.startupOutcome?.() ?? "pending";
9396
- if (outcome !== "pending" || a.terminalizing || Date.now() >= until)
8372
+ if (outcome !== "pending" || a.terminalizing || this.leaseStopping || Date.now() >= until)
9397
8373
  return outcome;
9398
8374
  await new Promise((resolve) => setTimeout(resolve, 250));
9399
8375
  }
9400
8376
  }
9401
8377
  /** Serve a once task from now on: its spawn's succeeded terminal is written. */
9402
- openOnceDelivery(ref) {
9403
- const p = this.pendingTurns.get(goalKey(ref));
9404
- if (p?.once === undefined || p.once.deliverable)
9405
- return;
9406
- p.once.deliverable = true;
9407
- this.noticeSeatTurns(p.seat);
9408
- }
8378
+ openOnceDelivery(ref) { return this.turnRelay.openOnceDelivery(ref); }
9409
8379
  /** Stop the seat of a once task that just ended, found by its incarnation and never by its name.
9410
8380
  * After the readiness verdict the spawn goal's outcome belongs to that verdict, so the stop lets
9411
8381
  * go of the spawn goal first and never cancels it. Before the verdict it is a deliberate stop,
@@ -9441,62 +8411,9 @@ export class Manager {
9441
8411
  * the seat's launched processes gone, cancel the task with `reason` if it has no terminal yet,
9442
8412
  * then drop its index entry. One flight per task; a failure keeps it in {@link onceSettles} and
9443
8413
  * the turn sweep retries it. */
9444
- settleOnceTurn(ref, reason, retire) {
9445
- const key = goalKey(ref);
9446
- const owed = this.onceSettles.get(key) ?? { ref, reason, ...(retire !== undefined ? { retire } : {}) };
9447
- if (owed.flight)
9448
- return owed.flight;
9449
- this.onceSettles.set(key, owed);
9450
- const flight = this.runOnceSettle(key, owed).finally(() => { owed.flight = undefined; });
9451
- owed.flight = flight;
9452
- return flight;
9453
- }
9454
- async runOnceSettle(key, owed) {
9455
- const gw = this.goalWriter;
9456
- if (!gw)
9457
- return;
9458
- // The pending entry is the latch the yield and the deadline race on; a task settled here is
9459
- // served to no one again.
9460
- const p = this.pendingTurns.get(key);
9461
- // A task past its deadline owes the deadline terminal, which the turn sweep writes again until
9462
- // it lands; the settle waits for it rather than record a cancel in its place.
9463
- const denyOwed = p?.deadlineAt !== undefined && p.deadlineAt <= Date.now();
9464
- if (p && !denyOwed) {
9465
- this.pendingTurns.delete(key);
9466
- this.markTurnLatchDropped(key);
9467
- this.noticeSeatTurns(p.seat);
9468
- }
9469
- try {
9470
- if (denyOwed)
9471
- throw new Error("its deadline terminal is not written yet");
9472
- // A seat whose exit is proved may have left processes of its own running the task: the task
9473
- // is not recorded as ended, nor its debt cleared, before they are proved gone.
9474
- const retired = owed.retire === undefined ? undefined : await this.retireOnceSeat(owed.retire);
9475
- await this.commitOnceCancel(owed.ref, owed.reason);
9476
- await clearGoalIndex(gw.ctx, owed.ref);
9477
- this.onceSettles.delete(key);
9478
- this.onceWatched.delete(key);
9479
- await retired?.discard().catch((e) => console.error(`! once task ${owed.ref.goalId}: its retirement receipt was not discarded (${rejectionText(e)})`));
9480
- }
9481
- catch (e) {
9482
- console.error(`! once task ${owed.ref.goalId} (${owed.reason}): ${rejectionText(e)}; retried by the turn sweep`);
9483
- this.ensureTurnSweep();
9484
- }
9485
- this.maybeStopTurnSweep();
9486
- }
8414
+ settleOnceTurn(ref, reason, retire) { return this.turnRelay.settleOnceTurn(ref, reason, retire); }
9487
8415
  /** Cancel a once task with `reason` unless it already has a terminal. */
9488
- async commitOnceCancel(ref, reason) {
9489
- const gw = this.goalWriter;
9490
- if ((await readGoalResult(gw.ctx, ref)) !== undefined)
9491
- return;
9492
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9493
- await this.assertGoalWriterEpochCurrent(epoch);
9494
- if ((await readGoalStatus(gw.ctx, ref))?.value.state !== "cancelling")
9495
- await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: "terminate" } });
9496
- const { fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "manager", reason }, committer: { instanceId: this.managerInstanceId, epoch } });
9497
- this.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9498
- this.rememberSettledTurn(goalKey(ref), fact.state, Date.now());
9499
- }
8416
+ commitOnceCancel(ref, reason) { return this.turnRelay.commitOnceCancel(ref, reason); }
9500
8417
  /** Ask the seat's connector to prove its launched processes gone, within {@link ONCE_RETIRE_MS}.
9501
8418
  * Throws without that proof. */
9502
8419
  async retireOnceSeat(r) {
@@ -9505,106 +8422,9 @@ export class Manager {
9505
8422
  throw new Error(`the ${r.connector} connector cannot prove seat ${r.name}'s launched processes gone`);
9506
8423
  return withTimeout(connector.retireAfterExit({ space: this.space, name: r.name, lifecycleUid: r.uid, workspaceRoot: this.workspaceRoot }), ONCE_RETIRE_MS, `seat ${r.name}'s launched processes were not proved gone within ${ONCE_RETIRE_MS}ms`);
9507
8424
  }
9508
- /** Record a once task a predecessor accepted, and bind its seat if this incarnation already
9509
- * adopted it. The static adoption and the goal reconcile run in either order, so each side
9510
- * binds what the other has already found. */
9511
- async inheritOnce(ref, allocated, note) {
9512
- this.onceInherited.set(allocated.uid, {
9513
- ref, seat: { name: allocated.name, owner: allocated.owner, actor: allocated.actor, uid: allocated.uid },
9514
- ...(note.deadlineAt !== undefined ? { deadlineAt: note.deadlineAt } : {}),
9515
- readinessMs: allocated.readinessDeadlineMs ?? this.readinessTimeoutMs,
9516
- ...(note.retire !== undefined ? { retire: note.retire } : {}),
9517
- });
9518
- const a = this.findManagedByTarget({ owner: allocated.owner, actor: allocated.actor, lifecycleUid: allocated.uid });
9519
- if (a !== undefined)
9520
- await this.bindOnceSeat(a);
9521
- this.ensureTurnSweep();
9522
- }
9523
- /** An inherited once task whose seat this manager cannot hold: it adopts no seats (an open or
9524
- * user-mode mesh) and the seat is not bound here. */
9525
- onceSeatUnheld(p) {
9526
- return p.once !== undefined && this.onceInherited.has(p.seat.uid) && !(this.auth !== undefined && !this.userMode);
9527
- }
9528
- /** Whether a once task was served: its spawn's succeeded terminal is written. */
9529
- async onceServed(ref, note) {
9530
- if (note.spawn === undefined)
9531
- return false;
9532
- const spawn = await readGoalResult(this.goalWriter.ctx, { endpoint: ref.endpoint, caller: ref.caller, goalId: note.spawn });
9533
- return spawn?.state === "succeeded";
9534
- }
9535
8425
  /** Make an adopted seat a once seat again: its exit settles its task, and the task is served to
9536
8426
  * it. A task that ended before the restart owes the stop the predecessor may not have made. */
9537
- async bindOnceSeat(a) {
9538
- const inherited = this.onceInherited.get(a.lifecycleUid);
9539
- if (inherited === undefined || a.once !== undefined)
9540
- return;
9541
- this.onceInherited.delete(a.lifecycleUid);
9542
- a.once = { ref: inherited.ref, ...(inherited.retire !== undefined ? { retire: inherited.retire } : {}) };
9543
- this.watchOnceExit(a);
9544
- const p = this.pendingTurns.get(goalKey(inherited.ref));
9545
- if (p?.once) {
9546
- p.once.deliverable = true;
9547
- this.noticeSeatTurns(p.seat);
9548
- return;
9549
- }
9550
- const ended = this.goalWriter ? await readGoalResult(this.goalWriter.ctx, inherited.ref) : undefined;
9551
- if (ended !== undefined)
9552
- this.stopOnceSeat(a, "turn-ended");
9553
- }
9554
- /** Inherited once tasks whose seat is not bound here. On a static mesh the boot reconcile adopts
9555
- * every seat it can and reaps the rest by their custody reference, so once it has finished with
9556
- * a seat's slot, an unbound seat is proved gone. A manager that adopts no seats cannot reach the
9557
- * old seat or prove its exit: it does not serve the task to it, a task with a deadline ends at
9558
- * that deadline, and one without is settled `uncertain` after one readiness window. Its debt is
9559
- * never cleared here, since nothing proves that seat gone. */
9560
- async settleInheritedOnce() {
9561
- const gw = this.goalWriter;
9562
- if (!gw || !this.goalReconcileDone)
9563
- return;
9564
- const adopts = this.auth !== undefined && !this.userMode;
9565
- for (const [uid, d] of [...this.onceInherited]) {
9566
- const live = this.findManagedByTarget({ owner: d.seat.owner, actor: d.seat.actor, lifecycleUid: uid });
9567
- if (live !== undefined) {
9568
- await this.bindOnceSeat(live);
9569
- continue;
9570
- }
9571
- if (adopts) {
9572
- const reconciling = this.staticLifecycle.pendingLifecycle(uid);
9573
- if (reconciling)
9574
- continue;
9575
- this.onceInherited.delete(uid);
9576
- void this.settleOnceTurn(d.ref, "seat-exited", retireOf(d));
9577
- continue;
9578
- }
9579
- if ((await readGoalResult(gw.ctx, d.ref)) !== undefined) {
9580
- this.onceInherited.delete(uid);
9581
- this.keepUnprovedOnceDebt(d);
9582
- continue;
9583
- }
9584
- if (d.deadlineAt !== undefined || Date.now() - this.goalReconcileDoneAt < d.readinessMs)
9585
- continue;
9586
- this.onceInherited.delete(uid);
9587
- const key = goalKey(d.ref);
9588
- this.pendingTurns.delete(key);
9589
- this.markTurnLatchDropped(key);
9590
- try {
9591
- await settleGoalUncertain(gw.ctx, { ref: d.ref, now: Date.now(), committer: { instanceId: this.managerInstanceId, epoch: this.serviceServe?.grant.epoch ?? 0 }, reason: `the manager restarted and could not reach the seat; ${UNHELD_SEAT}, and the task may have run in part or in full` });
9592
- this.keepUnprovedOnceDebt(d);
9593
- }
9594
- catch (e) {
9595
- console.error(`! inherited once task ${d.ref.goalId}: ${rejectionText(e)}`);
9596
- }
9597
- }
9598
- }
9599
- /** An inherited task's seat this manager cannot reach: its terminal stands, and its index entry,
9600
- * the seat's debt, stays recorded, because nothing here can prove that seat gone. The seat is
9601
- * told to end itself on its next pull, and its notice repeats until a pull carries that. */
9602
- keepUnprovedOnceDebt(d) {
9603
- console.error(`! once task ${d.ref.goalId}: this manager cannot reach seat ${d.seat.name}/${d.seat.uid} to prove it gone; its debt stays in the goal index, and the seat is told to end itself`);
9604
- this.onceStops.set(d.seat.uid, { ...d.seat });
9605
- this.noticeSeatTurns(d.seat);
9606
- this.ensureTurnSweep();
9607
- }
8427
+ bindOnceSeat(a) { return this.turnRelay.bindOnceSeat(a); }
9608
8428
  /** Settle race: a despawn MID-GOAL drives the goal's cancel terminal - transition to
9609
8429
  * `cancelling`, then commit the `cancel` cause on the goal-writer connection. First-terminal-fact
9610
8430
  * wins: if the readiness outcome already committed (succeeded/failed/uncertain) the transition or