@cotal-ai/manager 0.167.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.
Files changed (51) hide show
  1. package/dist/attach-endpoint.d.ts.map +1 -1
  2. package/dist/attach-endpoint.js +2 -0
  3. package/dist/attach-endpoint.js.map +1 -1
  4. package/dist/commands.js +1 -0
  5. package/dist/commands.js.map +1 -1
  6. package/dist/console/app.js +12 -1
  7. package/dist/control-session.d.ts +5 -5
  8. package/dist/control-session.d.ts.map +1 -1
  9. package/dist/control-session.js +17 -65
  10. package/dist/control-session.js.map +1 -1
  11. package/dist/control-shutdown.d.ts +6 -7
  12. package/dist/control-shutdown.d.ts.map +1 -1
  13. package/dist/control-shutdown.js +9 -38
  14. package/dist/control-shutdown.js.map +1 -1
  15. package/dist/lease-keeper.d.ts +98 -0
  16. package/dist/lease-keeper.d.ts.map +1 -0
  17. package/dist/lease-keeper.js +257 -0
  18. package/dist/lease-keeper.js.map +1 -0
  19. package/dist/managed-static-lifecycle.d.ts +247 -0
  20. package/dist/managed-static-lifecycle.d.ts.map +1 -0
  21. package/dist/managed-static-lifecycle.js +926 -0
  22. package/dist/managed-static-lifecycle.js.map +1 -0
  23. package/dist/manager.d.ts +57 -417
  24. package/dist/manager.d.ts.map +1 -1
  25. package/dist/manager.js +270 -2680
  26. package/dist/manager.js.map +1 -1
  27. package/dist/names-capacity.d.ts +125 -0
  28. package/dist/names-capacity.d.ts.map +1 -0
  29. package/dist/names-capacity.js +236 -0
  30. package/dist/names-capacity.js.map +1 -0
  31. package/dist/run-hosting.d.ts.map +1 -1
  32. package/dist/run-hosting.js +8 -6
  33. package/dist/run-hosting.js.map +1 -1
  34. package/dist/serve-plane.d.ts +3 -0
  35. package/dist/serve-plane.d.ts.map +1 -1
  36. package/dist/serve-plane.js +18 -8
  37. package/dist/serve-plane.js.map +1 -1
  38. package/dist/service-child.js +2 -2
  39. package/dist/service-child.js.map +1 -1
  40. package/dist/session-recovery.d.ts +2 -4
  41. package/dist/session-recovery.d.ts.map +1 -1
  42. package/dist/session-recovery.js.map +1 -1
  43. package/dist/turn-relay.d.ts +397 -0
  44. package/dist/turn-relay.d.ts.map +1 -0
  45. package/dist/turn-relay.js +1068 -0
  46. package/dist/turn-relay.js.map +1 -0
  47. package/dist/user-provision.d.ts +152 -0
  48. package/dist/user-provision.d.ts.map +1 -0
  49. package/dist/user-provision.js +328 -0
  50. package/dist/user-provision.js.map +1 -0
  51. package/package.json +12 -12
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,15 +9,21 @@ 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, MANAGER_LEASE_TTL_MS, awaitLeaseExpiry, leaseRemainingMs, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, assertValidChannel, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, DeprovisionError, addDeprovisionAccounting, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, firstFreeName, spawnNameError, 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";
12
- 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, probeLiveness, remintDaemonCreds, resolveAgentType, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, SEAT_CAP_UNLIMITED, spaceKey, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
14
+ import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
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";
15
18
  import { ServePlane } from "./serve-plane.js";
19
+ import { NamesCapacity } from "./names-capacity.js";
16
20
  import { AttachEndpoint } from "./attach-endpoint.js";
17
- import { DELIVERY_ADMIN_BOOT_WAIT_MS, isUnansweredDeliveryAdmin, makeManagerEndpointEvictionEvidence, makeManagerEndpointHolderEvictor, untilDeliveryAdminAnswers, withScopedEndpoint } from "./endpoint-evict.js";
21
+ import { DELIVERY_ADMIN_BOOT_WAIT_MS, isUnansweredDeliveryAdmin, makeManagerEndpointHolderEvictor, untilDeliveryAdminAnswers, withScopedEndpoint } from "./endpoint-evict.js";
18
22
  import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
23
+ import { ManagedStaticLifecycle, STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
24
+ export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
25
+ import { LeaseKeeper } from "./lease-keeper.js";
26
+ export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
19
27
  import { SessionRecovery } from "./session-recovery.js";
20
28
  import { SeatCustody } from "./seat-custody.js";
21
29
  import { withTimeout } from "./manager-timeout.js";
@@ -25,15 +33,14 @@ import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
25
33
  import { controlShutdown } from "./control-shutdown.js";
26
34
  import { RunHosting, servedRequestSubject } from "./run-hosting.js";
27
35
  import { enrolledAcl } from "./remote-authority.js";
28
- import { pendingEnrollment } from "./pending-enrollment.js";
29
36
  import { rejectionText, attemptCleanup, describeCleanupFailures } from "@cotal-ai/core";
30
37
  import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, supervisePolicy, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
31
38
  import { TranscriptReceiver } from "./transcript-receive.js";
32
39
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
33
40
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
34
- import { jetstream, jetstreamManager } from "@nats-io/jetstream";
41
+ import { jetstreamManager } from "@nats-io/jetstream";
35
42
  import { Kvm } from "@nats-io/kv";
36
- import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts, credentialIdOf, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC, issuedHorizon, REMOTE_MANAGER_IDENTITY_NAMES } from "@cotal-ai/core";
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";
37
44
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
38
45
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
39
46
  // per-session credentials on their own short-lived connections).
@@ -41,25 +48,13 @@ import { ManagerSessionPlane } from "./session/index.js";
41
48
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
42
49
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
43
50
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
44
- import { provisionEndpointGateOpen, 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";
45
52
  import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
46
53
  import { measureManagerVitals } from "./vitals.js";
47
- import { staticLifecycleTransport, activateStaticLifecycle, runStaticTerminal, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, planStaticSlotResume, ownedBySibling, observeStaticSlot, listStaticSlotObservations, walkStaticSlots, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
48
- import { CHAT_ALIAS_PREFIX, CHAT_EXPIRY_CONCURRENCY, ChatSessionExpiry, chatOpenLists, chatRetireRefusal, drawChatAlias, isChatAlias, readChatOpenInput, readChatRetireInput, sealChatAdmission, } from "./chat-session.js";
54
+ import { staticLifecycleTransport, activateStaticLifecycle, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, observeStaticSlot, listStaticSlotObservations, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
55
+ import { CHAT_ALIAS_PREFIX, } from "./chat-session.js";
49
56
  // Capture the loaded package version before an installation can replace its files.
50
57
  const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
51
- /** Minimum slot lifetime for rate-flooring (P4c). A slot freed (by despawn OR natural exit/reap)
52
- * before living this long leaves a cooling stamp that still counts toward the ceiling until it
53
- * expires — so churn (spawn↔despawn or spawn↔fast-exit) can't outrun the concurrency bound. */
54
- const MIN_LIFETIME = 10_000;
55
- /** Cadence of the turn-deadline sweep while turns are pending: the poll that turns an elapsed
56
- * hold's fire into its expired settle and commits the deadline terminal. Deadlines are
57
- * minutes-scale; a few seconds of lateness on the commit is invisible to the run. */
58
- const TURN_SWEEP_MS = 5_000;
59
- /** How long a settled turn's answer is kept so a RETRIED yield hears it instead of `not-found`.
60
- * The window a lost reply is retried in is seconds; five minutes is generous for that and short
61
- * enough that the map drains between bursts rather than growing for the process lifetime. */
62
- const TURN_ANSWER_RETENTION_MS = 5 * 60_000;
63
58
  /** A `once` spawn's task deadline when the caller names none: one hour from the spawn's accept. */
64
59
  const ONCE_DEFAULT_DEADLINE_MS = 60 * 60_000;
65
60
  /** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
@@ -81,10 +76,6 @@ export const READINESS_TIMEOUT_MS = 30_000;
81
76
  * from its launch: the watch's 15s for the confirm prompt and 15s for its notice, plus 5s for the
82
77
  * last read. The readiness window applies when it is longer. */
83
78
  const STARTUP_OUTCOME_MS = 35_000;
84
- /** The cancel reason of an inherited once task whose spawn has no succeeded terminal. */
85
- const NEVER_SERVED = "never served: the manager restarted before the spawn's readiness verdict";
86
- /** Said by every settle of an inherited once task whose seat this manager does not hold. */
87
- const UNHELD_SEAT = "the manager does not hold the seat; it may still be running";
88
79
  /** How often the readiness race asks a runtime that streams no exit whether its child has exited, and
89
80
  * how long it waits past the window for the proof of its last read. An operator waits on this reply,
90
81
  * so it asks more often than the exit watch that outlives readiness. */
@@ -102,16 +93,6 @@ const OPERATOR_READINESS_MS = 3_000;
102
93
  * `.catch`. Generous over the helper's 5s connect timeout to allow the two consumer-deletes + ACL purge
103
94
  * + drain on a healthy-but-slow broker. */
104
95
  const DEPROVISION_TIMEOUT_MS = 15_000;
105
- /** How long a clean stop keeps trying to release its liveness lease when the broker does not answer
106
- * (#3916). The client redials a lost broker every 2 s, so a connection dropped by an outage of up to
107
- * about 3 s is back inside this budget. A longer outage is left to the row's TTL: the stop's other
108
- * steps also wait on the broker, and the whole stop must still finish inside the 15 s a CLI stop
109
- * waits before it sends SIGKILL. */
110
- const LEASE_RELEASE_BUDGET_MS = 5_000;
111
- /** The pause between lease release attempts that got no answer. An attempt that waits for its own
112
- * deadline already spaces the retries; this only keeps one that fails at once, on a closed
113
- * connection, from spinning. */
114
- const LEASE_RELEASE_RETRY_MS = 250;
115
96
  /** At most this many retirements run at once (#4965). A retirement dials up to four fresh broker
116
97
  * connections in turn and queues an eviction and an inventory on the delivery daemon's admin rail,
117
98
  * each against a fixed deadline. A stop that started all 50 seats' retirements together lost most of
@@ -173,13 +154,7 @@ export function credRenewIntervalMs(ttlSeconds) {
173
154
  * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
174
155
  * a reuse. */
175
156
  const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
176
- /** One initial terminal entry plus three re-drives. The short first retry absorbs a one-shot
177
- * broker/eviction blip; the wider later spacing avoids hammering a persistently unavailable
178
- * authority. The finite ~36s window is intentionally not a liveness inference: exhausting it
179
- * leaves the durable alias held and requires a later manager start. */
180
- export const STATIC_RECONCILE_RETRY_DELAYS_MS = [1_000, 5_000, 30_000];
181
157
  const REMOTE_STANDING_BUDGET_MS = 10_000;
182
- const STATIC_RECONCILE_MAX_ATTEMPTS = STATIC_RECONCILE_RETRY_DELAYS_MS.length + 1;
183
158
  /** The owner a retained seat resumes under: its inventory identity's, which is the same value the
184
159
  * adopted seat records as `userOwner`, so a resumed seat is counted against the owner that held
185
160
  * it before the restart ({@link Manager.ownerSeats}) and not against the mesh's default one. */
@@ -190,16 +165,6 @@ function resumeOwner(entry) {
190
165
  * dash) — what {@link Manager.psOwnerFilter} returns for an unparseable caller so a malformed
191
166
  * principal fail-closes to an empty `ps` instead of an unbounded one. */
192
167
  const NO_OWNER_MATCHES = "-no-owner-";
193
- /** A caught value as a lifecycle envelope, or undefined when it is not one. A thrown Proxy can throw
194
- * from `instanceof` itself, so the test runs inside the guard. */
195
- function caughtEnvelope(e) {
196
- try {
197
- return e instanceof EpEnvelopeError ? e : undefined;
198
- }
199
- catch {
200
- return undefined;
201
- }
202
- }
203
168
  /** Why a frozen manager gate stays frozen on an open mesh. Reconciliation must prove the holder
204
169
  * gone, and an open mesh runs no delivery daemon to prove it, so neither boot self-heal nor
205
170
  * `cotal manager reconcile` can reopen the gate there. */
@@ -286,25 +251,6 @@ function ownPersona(record) {
286
251
  });
287
252
  return owned;
288
253
  }
289
- /** `start()`'s refusal when this manager instance's lease is held (#3915): by another live process
290
- * on this workspace root, or by a holder on another root. A restart whose predecessor on this root
291
- * is dead, this process's own earlier start included, waits the key out instead (#4092). The
292
- * message is the operator copy; `held` and `sameRoot` are the data, so no caller parses it. A
293
- * lease that could not be read or written is a plain `Error`. */
294
- export class ManagerInstanceLeaseHeld extends Error {
295
- instanceId;
296
- space;
297
- held;
298
- sameRoot;
299
- name = "ManagerInstanceLeaseHeld";
300
- constructor(message, instanceId, space, held, sameRoot) {
301
- super(message);
302
- this.instanceId = instanceId;
303
- this.space = space;
304
- this.held = held;
305
- this.sameRoot = sameRoot;
306
- }
307
- }
308
254
  /** Operator-facing phrasing per cause. Kept beside the union so adding a member without a sentence
309
255
  * is a type error rather than a blank in the log. The stop family's sentences carry the principal
310
256
  * from the cause, so they render through {@link STOP_CAUSE_TEXT} under the same exhaustive-Record
@@ -322,23 +268,6 @@ const FREE_SLOT_CAUSE_TEXT = {
322
268
  "supervise-record-failed": "this manager stopped it: its supervise policy could not be recorded for a manager restart",
323
269
  "inline-snapshot-changed": "this manager retired it instead of restarting it: its inline persona snapshot changed after launch",
324
270
  };
325
- /** The SPEC 13.6 end reason a live attach session gets when this cause frees its seat. The causes
326
- * that free the slot in the same step that saw the seat's own process exit report `process-exit`.
327
- * A failed recovery frees it later, after its own stop, so it reports `target-despawn` with every
328
- * manager stop. */
329
- const FREE_SLOT_ATTACH_END = {
330
- "process-exit": "process-exit",
331
- "pi-crash-loop": "process-exit",
332
- "supervise-crash-loop": "process-exit",
333
- "inline-snapshot-changed": "process-exit",
334
- "pi-recovery-failed": "target-despawn",
335
- "supervise-recovery-failed": "target-despawn",
336
- "session-bind-failed": "target-despawn",
337
- "resume-session-rebind-failed": "target-despawn",
338
- "carried-fork-refused": "target-despawn",
339
- "resume-custody-unrecorded": "target-despawn",
340
- "supervise-record-failed": "target-despawn",
341
- };
342
271
  /** The stop family's sentences — the same job {@link FREE_SLOT_CAUSE_TEXT} does for the string
343
272
  * causes, beside it so both stay the single place a cause becomes a sentence. A requested stop's
344
273
  * sentence embeds the authenticated principal and a recursive reap's embeds the parent that
@@ -437,70 +366,6 @@ const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
437
366
  function participantKey(owner, actor, uid) {
438
367
  return `${owner}.${actor}.${uid}`;
439
368
  }
440
- function parseTurnNote(raw) {
441
- let o;
442
- try {
443
- o = JSON.parse(raw);
444
- }
445
- catch {
446
- return undefined;
447
- }
448
- if (o === null || typeof o !== "object")
449
- return undefined;
450
- const n = o;
451
- if (n.once !== undefined && n.once !== true)
452
- return undefined;
453
- if (typeof n.payload !== "string" || typeof n.holdEpoch !== "number")
454
- return undefined;
455
- if (typeof n.deadlineAt !== "number" && !(n.once === true && n.deadlineAt === undefined))
456
- return undefined;
457
- if (n.holdToken !== undefined && typeof n.holdToken !== "string")
458
- return undefined;
459
- if (n.handoffFrom !== undefined && typeof n.handoffFrom !== "string")
460
- return undefined;
461
- if (n.retire !== undefined && (n.once !== true || typeof n.retire !== "string"))
462
- return undefined;
463
- if (n.spawn !== undefined && (n.once !== true || typeof n.spawn !== "string"))
464
- return undefined;
465
- return {
466
- payload: n.payload, holdEpoch: n.holdEpoch,
467
- ...(typeof n.deadlineAt === "number" ? { deadlineAt: n.deadlineAt } : {}),
468
- ...(typeof n.holdToken === "string" ? { holdToken: n.holdToken } : {}),
469
- ...(typeof n.handoffFrom === "string" ? { handoffFrom: n.handoffFrom } : {}),
470
- ...(n.once === true ? { once: true } : {}),
471
- ...(typeof n.retire === "string" ? { retire: n.retire } : {}),
472
- ...(typeof n.spawn === "string" ? { spawn: n.spawn } : {}),
473
- };
474
- }
475
- function retireOf(d) {
476
- return d.retire === undefined ? undefined : { connector: d.retire, name: d.seat.name, uid: d.seat.uid };
477
- }
478
- /** The relay record of a `once` task. The prompt is only ever the string value of `context`, so a
479
- * prompt shaped like a run payload stays text and cannot add an `ask` or a `checkpoint`; the
480
- * `once` block is the manager's, rendered by the seat beside the prompt. */
481
- function onceTurnNote(o) {
482
- const payload = JSON.stringify({ context: o.prompt, once: { spawner: o.spawner, ...(o.deadlineAt !== undefined ? { deadlineAt: o.deadlineAt } : {}) } });
483
- const note = JSON.stringify({
484
- payload, holdEpoch: o.holdEpoch,
485
- ...(o.deadlineAt !== undefined ? { deadlineAt: o.deadlineAt } : {}),
486
- ...(o.holdToken !== undefined ? { holdToken: o.holdToken } : {}),
487
- once: true,
488
- ...(o.retire !== undefined ? { retire: o.retire } : {}),
489
- spawn: o.spawn,
490
- });
491
- return { payload, note };
492
- }
493
- /** A goal's key in the manager's maps: the caller triple and goal id the goal plane stores the
494
- * goal under, because a goal id is the caller's own (SPEC 13.6 item 1) and two callers may pick
495
- * the same one. Every part is a subject token, so the dotted join is unambiguous. */
496
- function goalKey(ref) {
497
- return `${ref.caller.owner}.${ref.caller.actor}.${ref.caller.uid}.${ref.goalId}`;
498
- }
499
- /** A turn hold's token, DERIVED from the relay key, so two callers' turns under one goal id never
500
- * share a hold. */
501
- function turnHoldToken(key) {
502
- return digestIdToken(`${key}:turn-deadline`);
503
- }
504
369
  /**
505
370
  * Event channels in `channels` that do NOT belong to `{owner, actor}`.
506
371
  *
@@ -582,6 +447,7 @@ export class Manager {
582
447
  /** See {@link ManagerOptions.installedExtensions}. */
583
448
  installedExtensions;
584
449
  expectedConnectorGeneration;
450
+ machineSetupCommand;
585
451
  executionState;
586
452
  /** One backend per kind a seat has asked for, beside {@link runtime}. The manager's own runtime
587
453
  * stays the default and is never replaced by a later seat's choice. */
@@ -594,28 +460,9 @@ export class Manager {
594
460
  preserveStopTimeoutMs;
595
461
  endpointServeExecutorExpiresInSeconds;
596
462
  agents = new Map();
597
- /** Names whose spawn is in flight (reserved synchronously before the provision await) — counted
598
- * toward the ceiling (once per name, see {@link Manager.occupancy}) so two concurrent same-name
599
- * spawns can't both pass the gate (P4a). Each name carries the OWNER its launch was admitted
600
- * for, so the per-owner ceiling ({@link Manager.ownerSeats}) counts a launch from the moment it
601
- * is reserved; a cap read only off `agents` would let a burst of concurrent spawns overshoot it,
602
- * because none of them has a seat yet when the next one checks. */
603
- reserved = new Map();
604
- /** Reserved names whose launch already put its seat in `agents`. The name stays reserved until
605
- * the launch settles, so no other spawn can take it, but the ceiling counts that seat through
606
- * `agents` and, if it frees young, its cooling stamp, never through the reservation (#906). */
607
- reservedLive = new Set();
608
- /** Every numbered name {@link uniqueName} has issued. A suffix carries nothing but arrival order,
609
- * so reissuing a freed one would give a later principal the name an earlier one posted under, and
610
- * a reader of that name could not tell the two apart (#382). Never pruned in-process: one string
611
- * per numbered spawn. */
612
- issuedNumberedNames = new Set();
613
463
  /** Lifecycle UIDs already handed to `Runtime.spawnDelegated`: a lifecycle is handed off at most
614
464
  * once, so a lost create acknowledgement can never become a second create. */
615
465
  delegatedLaunched = new Set();
616
- /** Expiry stamps (`startedAt + MIN_LIFETIME`) for slots that freed while still young — a
617
- * count-only, lazily-pruned recycle floor (P4c). Pruned + summed into the ceiling gate. */
618
- cooling = [];
619
466
  /** This manager process's own incarnation uid (SPEC 13.1; minted once per supervisor process,
620
467
  * never reused across restarts) — the endpoint's presence key AND the `managerInstance` audit
621
468
  * coordinate every static activation records. */
@@ -702,81 +549,42 @@ export class Manager {
702
549
  /** The live spawn goal ref for each managed agent name, so a despawn MID-GOAL
703
550
  * drives the cancel path (transition -> cancel terminal). Cleared when the goal terminalizes. */
704
551
  agentGoals = new Map();
705
- /**
706
- * The turn relay's same-incarnation idempotency map ({@link goalAcceptances}'s twin), by
707
- * {@link goalKey}: a same-goal retry serves the identical acceptance; cross-incarnation retries
708
- * rebuild from the goal-index entry (its acceptance floor + note).
709
- *
710
- * One entry per turn this incarnation accepted: the acceptance a duplicate submission is served
711
- * from, and — once the turn settles — the answer a RETRIED yield is served from.
712
- *
713
- * A yield's reply can be lost, and the retry used to find the pending turn already deleted and
714
- * hear `not-found`, which a seat reads as "drop it": failure reported for work that committed.
715
- * The settled answer lives here for a bounded window instead, and the sweep drops it after,
716
- * which is also what keeps this map from being one entry per turn for the process lifetime.
717
- *
718
- * `ref` is the goal coordinates the durable terminal is published under. A late yield that
719
- * arrives after pendingTurns is gone and before `settled` is remembered (or after a concurrent
720
- * sweep dropped the settled field) still has to name that terminal, never `not-found`. The
721
- * index entry is not that answer: it is cleared at commit, and the yield path never consults it.
722
- *
723
- * `leftoverSince` is when the pending latch dropped. An unsettled leftover ages off that stamp,
724
- * never off `acceptance.deadlineAt`: a turn that expired after a long outage would otherwise be
725
- * pruned on the first sweep tick, taking the GoalRef with it, and a late yield in the retry
726
- * window would hear `not-found` again.
727
- */
728
- 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
+ }
729
577
  participants = new Map();
730
- /** Every relayed turn awaiting its seat's yield, by {@link goalKey}. The seat's `turn-pending` pull
731
- * scans it; the deadline sweep drives expiry; a seat reap stamps its entries `seatDiedAt`, which
732
- * the deadline terminal carries as `agentDownAt` so the run reads that death as L4002.
733
- * Rebuilt at boot from goal-index entries carrying a turn note. */
734
- pendingTurns = new Map();
735
- /** The deadline sweep behind {@link pendingTurns}: takes the hold's fire into an expired
736
- * settle and commits the deadline terminal. Unref'd; idle when no turn is pending. */
737
- turnSweepTimer;
738
- /** Once tasks whose ending is owed, by {@link goalKey}: the task can no longer run (its seat's
739
- * exit is proved, or it was never served), so it is cancelled if it has no terminal and its index
740
- * entry is dropped. A settle that fails stays here and the turn sweep retries it. */
741
- onceSettles = new Map();
742
578
  /** Once tasks whose seat's exit is watched: that exit, not the spawn's outcome, settles the debt. */
743
579
  onceWatched = new Set();
744
- /** Once tasks a predecessor accepted, by seat uid, until this incarnation binds the seat or
745
- * proves it gone. `readinessMs` bounds how long a seat no reconcile here can account for is
746
- * waited for. */
747
- onceInherited = new Map();
748
- /** Inherited once seats this manager does not hold whose task has a terminal, by lifecycle uid.
749
- * Every pull from one is answered `stop`, and its notice repeats until a pull has carried it. */
750
- onceStops = new Map();
751
- /** When the goal reconcile finished: the start of an inherited once task's wait for its seat. */
752
- goalReconcileDoneAt = 0;
753
580
  /** Process start, for the served `status` uptime. */
754
581
  startedAtMs = Date.now();
755
- /** Connector harness paths resolved ONCE at boot. Missing binaries do not stop unrelated manager
756
- * 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. */
757
584
  connectorStatuses = [];
585
+ connectorRequirements = new Map();
758
586
  /** The boot inventory's warnings, printed once start completes, so a refused start prints none. */
759
587
  bootNotes = [];
760
- /** Static aliases whose startup exact-op terminal is still in flight. Scoped per alias: control
761
- * serves during the sweep, but no caller can reuse or attach an alias the sweep still owns. */
762
- reconcilingAliases = new Set();
763
- /** In-flight static chat-session terminals, by lifecycle UID, so every caller that retires one
764
- * session joins one terminal instead of racing its CAS sequence. */
765
- chatRetirements = new Map();
766
- /** The expiry side of every chat session this process admitted and nothing retired sooner. */
767
- chatExpiry = new ChatSessionExpiry((session) => this.expireStaticChatSession(session), {
768
- retryDelaysMs: STATIC_RECONCILE_RETRY_DELAYS_MS,
769
- concurrency: CHAT_EXPIRY_CONCURRENCY,
770
- log: (line) => console.error(line),
771
- });
772
- /** Current failed/recovered static reconciliation coordinates. This is an operator snapshot, not
773
- * lifecycle authority: every re-drive re-reads broker KV and re-runs planStaticSlotResume. */
774
- staticReconcileItems = new Map();
775
- staticReconcileLastSweep;
776
- staticReconcileLastSweepResources;
777
- staticReconcileSweepsInFlight = 0;
778
- staticReconcileDrainWaiters = [];
779
- staticReconcileStopping = false;
780
588
  /** The complete boot task. stop() joins it after fencing static reconciliation, so a registration
781
589
  * already past an earlier shutdown check cannot finish after stop() returns. */
782
590
  startTask;
@@ -805,6 +613,28 @@ export class Manager {
805
613
  /** True on a USER-AUTH space (the on-disk marker; cross-checked against the registry at start).
806
614
  * Gates the whole spawn path: user mode grants ledger actors + bearer plumbing, never static mints. */
807
615
  userMode = false;
616
+ namesCapacity = new NamesCapacity({
617
+ userMode: () => this.userMode,
618
+ authEnabled: () => this.auth !== undefined,
619
+ maintenanceActive: () => this.maintenanceState === "active",
620
+ roster: () => this.ep.getRoster(),
621
+ agentFor: (name) => this.agents.get(name),
622
+ hasAgent: (name) => this.agents.has(name),
623
+ removeAgent: (name) => { this.agents.delete(name); },
624
+ managedCount: () => this.agents.size,
625
+ predecessor: (name) => this.retirement.predecessor(name),
626
+ hasRetirementHold: (name) => this.retirement.hasHold(name),
627
+ holdRetirement: (name, hold) => this.retirement.hold(name, hold),
628
+ endSessionsForTarget: (...args) => { this.sessionPlane?.endForTarget(...args); },
629
+ logSeatReaped: (...args) => this.logSeatReaped(...args),
630
+ recordContinuityAtStop: (...args) => this.recordContinuityAtStop(...args),
631
+ releasedSeatPending: (...args) => this.releasedSeatPending(...args),
632
+ dropSeatRecord: (...args) => this.dropSeatRecord(...args),
633
+ failSeatTurns: (...args) => this.failSeatTurns(...args),
634
+ teardownTarget: (...args) => this.teardownTarget(...args),
635
+ dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
636
+ trackDeprovision: (...args) => this.trackDeprovision(...args),
637
+ });
808
638
  servePlane = new ServePlane({
809
639
  auth: () => this.auth,
810
640
  remoteAuthority: () => this.remoteAuthority,
@@ -828,7 +658,7 @@ export class Manager {
828
658
  setSessionPlane: (value) => { this.sessionPlane = value; },
829
659
  sessionKeyRenewTimer: () => this.sessionKeyRenewTimer,
830
660
  setSessionKeyRenewTimer: (value) => { this.sessionKeyRenewTimer = value; },
831
- connectorStatuses: () => this.connectorStatuses,
661
+ connectorStatuses: () => { this.refreshUnavailableConnectors(); return this.connectorStatuses; },
832
662
  setGoalWriterIdentity: (value) => { this.goalWriterIdentity = value; },
833
663
  setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
834
664
  remoteStandingBudgetMs: REMOTE_STANDING_BUDGET_MS,
@@ -897,23 +727,27 @@ export class Manager {
897
727
  brokerTeardown: (task, message) => withTimeout(task, DEPROVISION_TIMEOUT_MS, message),
898
728
  trackLifecycle: () => { this.lifecycleInFlight++; return () => this.releaseLifecycle(); },
899
729
  });
900
- leaseInfo;
901
- leaseRevision;
902
- leaseTimer;
903
- /** What the last renew tick learned about this instance's key. Only a CHANGE of state is printed
904
- * (see {@link noteLease}), so an outage of hours is one line going in and one line coming out. */
905
- leaseState = "held";
906
- /** A renew is in flight. The tick must not start a second one: both would read the same cached
907
- * revision, so whichever lands second CASes against a sequence the first already moved. */
908
- leaseRenewInFlight = false;
909
- /** The promise a currently in-flight `renewLease()` is running, so `stop()` can await it before
910
- * releasing the key instead of racing it: a renew that lands after the cached revision was read
911
- * for release would otherwise move the row out from under a same-cached-revision CAS delete. */
912
- leaseRenewTask;
730
+ lease = new LeaseKeeper({
731
+ endpoint: () => this.ep,
732
+ instanceId: () => this.managerInstanceId,
733
+ space: () => this.space,
734
+ stopping: () => this.leaseStopping,
735
+ });
736
+ get leaseInfo() { return this.lease.leaseInfo; }
737
+ set leaseInfo(info) { this.lease.leaseInfo = info; }
738
+ get leaseRevision() { return this.lease.leaseRevision; }
739
+ set leaseRevision(revision) { this.lease.leaseRevision = revision; }
740
+ get leaseTimer() { return this.lease.leaseTimer; }
741
+ set leaseTimer(timer) { this.lease.leaseTimer = timer; }
742
+ get leaseRenewTask() { return this.lease.leaseRenewTask; }
743
+ acquireInstanceLease(info) { return this.lease.acquireInstanceLease(info); }
744
+ renewLease() { return this.lease.renewLease(); }
745
+ releaseOwnManagerLease() { return this.lease.releaseOwnManagerLease(); }
913
746
  /** Set at the top of `stop()`. `renewLease` returns at once once this is set, and its `gone` arm
914
747
  * does not re-acquire: a manager that is stopping never puts its own key back. It also closes the
915
748
  * lifecycle fence ({@link beginLifecycle}), so no spawn can launch a seat the stop never sees. */
916
749
  leaseStopping = false;
750
+ shutdownReadiness = new AbortController();
917
751
  /** The class-2 renewal owner's half-TTL schedule; armed only on auth meshes. */
918
752
  credRenewTimer;
919
753
  resumeCredRenewal;
@@ -1041,6 +875,58 @@ export class Manager {
1041
875
  stopHandle: (agent, graceful, cause) => this.stopHandle(agent, graceful, cause),
1042
876
  trackStoppedHandle: (agent, floor, cause) => this.trackStoppedHandle(agent, floor, cause),
1043
877
  });
878
+ get staticReconcileLastSweepResources() { return this.staticLifecycle.resources(); }
879
+ set staticReconcileLastSweepResources(value) { this.staticLifecycle.setResources(value); }
880
+ staticLifecycle = new ManagedStaticLifecycle({
881
+ space: () => this.space,
882
+ servers: () => this.servers,
883
+ auth: () => this.auth,
884
+ secrets: () => this.secrets,
885
+ workspaceRoot: () => this.workspaceRoot,
886
+ instanceId: () => this.managerInstanceId,
887
+ processUid: () => this.managerLifecycleUid,
888
+ userMode: () => this.userMode,
889
+ eventPayloadsWithheld: () => this.eventPayloadsWithheld,
890
+ evictor: () => this.staticLifecycleEvict,
891
+ retryDelays: () => this.staticReconcileRetryDelaysMs,
892
+ resumeRequired: () => this.resumeRequired,
893
+ records: () => this.goalWriter?.ctx.kv,
894
+ agentFor: (name) => this.agents.get(name),
895
+ retirementFor: (name) => this.retirement.held(name),
896
+ recordStaticRetirement: (a) => this.retirement.recordStaticRetirement(a),
897
+ noteRetiredPrincipal: (principal) => { this.retirement.rememberRetired(principal); },
898
+ foreignEventChannels: (channels, owner, actor) => foreignEventChannels(channels, owner, actor),
899
+ withIssuer: (fn) => this.withIssuer(fn),
900
+ deprovisionBroker: (a) => this.deprovisionBroker(a),
901
+ reapOrphanSeat: (a) => this.reapOrphanSeat(a),
902
+ withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
903
+ readerRemedy: (owner, channel) => this.readerRemedy(owner, channel),
904
+ withProvisioner: (fn) => this.withProvisioner(fn),
905
+ beginLifecycle: (resumeOperation) => this.beginLifecycle(resumeOperation),
906
+ maintenanceError: () => this.maintenanceError(),
907
+ withRetirementSlot: (run) => this.withRetirementSlot(run),
908
+ managedStaticInstanceReads: (capabilities) => this.managedStaticInstanceReads(capabilities),
909
+ issuanceSeam: (i, mode, a, exp) => this.issuanceSeam(i, mode, a, exp),
910
+ refreshSeatRecord: (a) => this.refreshSeatRecord(a),
911
+ dial: (opts) => this.dial(opts),
912
+ seatRecordFor: (row) => this.seatRecordFor(row),
913
+ restartSupervisedSeat: (row, record) => this.restartSupervisedSeat(row, record),
914
+ adoptSeat: (row, record) => this.adoptSeat(row, record),
915
+ dropSeatRecord: (a) => this.dropSeatRecord(a),
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
+ });
1044
930
  constructor(opts) {
1045
931
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
1046
932
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -1081,6 +967,7 @@ export class Manager {
1081
967
  this.secretStoreIdentity = injectedSecretStoreIdentity(opts.secretStore);
1082
968
  this.installedExtensions = opts.installedExtensions ?? false;
1083
969
  this.expectedConnectorGeneration = MANAGER_VERSION;
970
+ this.machineSetupCommand = opts.machineSetupCommand;
1084
971
  this.pooled = opts.pooled === true;
1085
972
  this.executionState = opts.execution === "none" ? { kind: "none" } : { kind: "runtime" };
1086
973
  if (!this.remoteAuthority) {
@@ -1410,7 +1297,7 @@ export class Manager {
1410
1297
  }
1411
1298
  async runStart() {
1412
1299
  await this.admitExecutionState();
1413
- this.staticReconcileStopping = false;
1300
+ this.staticLifecycle.start();
1414
1301
  await this.inspectConnectorsAtBoot();
1415
1302
  await this.attach.start();
1416
1303
  // In auth mode the manager is just another user in the space's account — it mints
@@ -1670,7 +1557,7 @@ export class Manager {
1670
1557
  // stop() fences before it waits for an accepted startup reconciliation terminal. Once that
1671
1558
  // terminal drains, start() and stop() resume from the same await boundary; start must observe
1672
1559
  // the fence before it can publish a fresh service registration after shutdown.
1673
- if (this.staticReconcileStopping)
1560
+ if (this.staticLifecycle.stopping)
1674
1561
  return;
1675
1562
  // Register the manager as an ordinary v0.4 `service` endpoint (SPEC §13.7/§13.9)
1676
1563
  // and serve its typed command surface on the ep rails - the ONLY control door, in
@@ -1680,7 +1567,7 @@ export class Manager {
1680
1567
  // trust). Fail-loud: a manager that cannot register does not start half-registered.
1681
1568
  console.error("manager startup: binding the service endpoint");
1682
1569
  await this.registerManagerService();
1683
- if (this.staticReconcileStopping)
1570
+ if (this.staticLifecycle.stopping)
1684
1571
  return;
1685
1572
  // Stand up the standing goal-writer connection for spawn-as-action — AFTER
1686
1573
  // registration (it writes this endpoint's goal facts/records), disjoint from the serve cred.
@@ -3041,54 +2928,6 @@ export class Manager {
3041
2928
  if (failures.length)
3042
2929
  throw new Error(`manager preservation shutdown incomplete: ${failures.join("; ")}`);
3043
2930
  }
3044
- /** Create THIS instance's lease key, waiting out a dead predecessor's row first (#4092).
3045
- *
3046
- * A manager SIGKILLed on this host cannot release its key, so a restart inside the key's TTL
3047
- * loses the create. When the row names this workspace root and a pid that is not running here
3048
- * (or is this process's own pid, which a live predecessor cannot hold), the holder is dead and
3049
- * the restart waits for the bucket TTL to remove the row, then creates again. It never writes
3050
- * over the row: a live holder renews it inside the TTL, and the wait then refuses on that write.
3051
- * Any other conflict refuses at once, as before. */
3052
- async acquireInstanceLease(info) {
3053
- const refuse = (held, e) => {
3054
- if (!held)
3055
- return new Error(`could not acquire the manager lease for space "${this.space}": ${rejectionText(e)}`);
3056
- const sameRoot = held.root === info.root;
3057
- return new ManagerInstanceLeaseHeld(`manager instance ${this.managerInstanceId} already serves space "${this.space}" from ${sameRoot ? "this" : "another"} workspace root (${held.runtime}, pid ${held.pid}, root ${held.root}) - stop it first before restarting the same instance`, this.managerInstanceId, this.space, held, sameRoot);
3058
- };
3059
- try {
3060
- return await this.ep.acquireManagerLease(info);
3061
- }
3062
- catch (e) {
3063
- // Our OWN instance id already holds a live key ⇒ refuse. Anything else (e.g. a KV/JS error) is a
3064
- // real failure to surface, not a silent "held" — keep the cause so it isn't misread as a conflict.
3065
- const held = await this.ep.readOwnManagerLease(this.managerInstanceId).catch(() => undefined);
3066
- if (!held || held.info.root !== info.root || (held.info.pid !== process.pid && probeLiveness(held.info.pid) !== "dead"))
3067
- throw refuse(held?.info, e);
3068
- console.error(`• manager instance ${this.managerInstanceId}: its lease is still held by pid ${held.info.pid}, which is not running on this host; ` +
3069
- `waiting ${Math.ceil(leaseRemainingMs(held.created, MANAGER_LEASE_TTL_MS) / 1000)}s for the lease to expire`);
3070
- const waited = await awaitLeaseExpiry({
3071
- read: async () => {
3072
- const row = await this.ep.readOwnManagerLease(this.managerInstanceId);
3073
- return row && { revision: row.revision, created: row.created };
3074
- },
3075
- revision: held.revision,
3076
- created: held.created,
3077
- ttlMs: MANAGER_LEASE_TTL_MS,
3078
- aborted: () => this.leaseStopping,
3079
- });
3080
- if (waited === "rewritten")
3081
- throw new Error(`manager instance ${this.managerInstanceId}: its lease was written again while waiting for pid ${held.info.pid}'s lease to expire, so a live process holds it - stop it first before restarting the same instance`);
3082
- if (waited !== "expired")
3083
- throw refuse(held.info, e);
3084
- try {
3085
- return await this.ep.acquireManagerLease(info);
3086
- }
3087
- catch (again) {
3088
- throw refuse((await this.ep.readOwnManagerLease(this.managerInstanceId).catch(() => undefined))?.info, again);
3089
- }
3090
- }
3091
- }
3092
2931
  /** Every call joins the first stop and settles with it. A call that asks for a different
3093
2932
  * `withAgents` is refused, since the running stop has already applied its own policy. */
3094
2933
  stop(options = {}) {
@@ -3100,18 +2939,12 @@ export class Manager {
3100
2939
  }
3101
2940
  async stopOnce(withAgents) {
3102
2941
  this.leaseStopping = true;
2942
+ this.shutdownReadiness.abort();
3103
2943
  clearTimeout(this.credentialPushRetry);
3104
2944
  this.credentialPushRetry = undefined;
3105
2945
  this.transcripts?.stop();
3106
- this.staticReconcileStopping = true;
3107
- this.chatExpiry.stop();
2946
+ this.staticLifecycle.stop();
3108
2947
  const starting = this.startTask;
3109
- for (const item of this.staticReconcileItems.values()) {
3110
- if (item.timer)
3111
- clearTimeout(item.timer);
3112
- item.timer = undefined;
3113
- item.nextRetryAt = undefined;
3114
- }
3115
2948
  await this.awaitStaticReconcileDrain();
3116
2949
  await starting?.catch(() => { });
3117
2950
  if (this.leaseTimer)
@@ -3207,36 +3040,6 @@ export class Manager {
3207
3040
  if (failures.length)
3208
3041
  throw new Error(`manager shutdown incomplete: ${failures.join("; ")}`);
3209
3042
  }
3210
- /** Release this instance's liveness lease key on a clean stop, at the broker's own revision
3211
- * rather than a cached one that a renew still in flight moments ago may have already moved past.
3212
- * Re-reads the row and releases only what is PROVABLY this process's (absent, or another pid's,
3213
- * is left alone — the same test {@link reconcileLease} uses).
3214
- *
3215
- * A read or delete that gets no answer, as during a reconnect, is tried again until the delete is
3216
- * acknowledged or {@link LEASE_RELEASE_BUDGET_MS} has passed (#3916). Nothing here throws: a stop
3217
- * must complete either way, and a row that could not be released is left for the bucket TTL, with
3218
- * one line of warning so the cost (a same-root restart waiting out the TTL) is not silent. */
3219
- async releaseOwnManagerLease() {
3220
- const deadline = Date.now() + LEASE_RELEASE_BUDGET_MS;
3221
- for (;;) {
3222
- let why;
3223
- try {
3224
- const own = await this.ep.readOwnManagerLease(this.managerInstanceId);
3225
- if (own === undefined || own.info.pid !== process.pid)
3226
- return;
3227
- await this.ep.releaseManagerLease(this.managerInstanceId, own.revision);
3228
- return;
3229
- }
3230
- catch (e) {
3231
- why = rejectionText(e);
3232
- }
3233
- if (Date.now() >= deadline) {
3234
- console.error(`! manager instance ${this.managerInstanceId} could not release its liveness lease (space "${this.space}"): ${why}; a same-root restart inside the bucket TTL will be refused`);
3235
- return;
3236
- }
3237
- await new Promise((r) => setTimeout(r, LEASE_RELEASE_RETRY_MS));
3238
- }
3239
- }
3240
3043
  /**
3241
3044
  * REMOVE THIS INSTANCE'S SERVICE REGISTRATION on a clean stop (§13.5 deregistration).
3242
3045
  *
@@ -3336,128 +3139,6 @@ export class Manager {
3336
3139
  }
3337
3140
  })().catch(() => this.transportDown.add(nc));
3338
3141
  }
3339
- /** Keep this instance's liveness key fresh, and end the process only when another process holds it.
3340
- *
3341
- * A renew that throws is a question, not a verdict: the request may have timed out with the write
3342
- * landed and only its acknowledgement lost, the key may have expired during a stall, or a same-id
3343
- * process may hold it. The verdict comes from RE-READING the key ({@link reconcileLease}), and each
3344
- * answer has one response:
3345
- * - `held`: adopt the broker's revision and carry on.
3346
- * - `gone`: the key expired or was released while this process was still here, so put it back. The
3347
- * create is atomic, so a same-id process that got there first shows up as `taken` next tick.
3348
- * - `taken`: a different process holds this instance's key, so it took this instance over while
3349
- * this one stalled. This process is the superseded one and stops serving by exiting (SPEC 13.1).
3350
- * An open mesh has no barrier that would evict its serve connection, so nothing else stops it.
3351
- * - `unknown`: the broker could not be asked. Keep serving and ask again next tick, for as long as it
3352
- * takes. A manager that cannot reach its broker gains nothing by ending itself, and the seats it
3353
- * holds lose everything (a pty child dies with its parent).
3354
- *
3355
- * This replaces a fail-close that ended the process one tick past the lease TTL with no answer, which
3356
- * on a live mesh turned a ten-second broker or KV outage into a manager outage that lasted until an
3357
- * operator noticed. */
3358
- async renewLease() {
3359
- // A manager that is stopping never puts its own key back: a stop already fenced this loop, and
3360
- // any tick or explicit call landing after that must be a no-op, not a fresh acquire attempt.
3361
- if (this.leaseStopping)
3362
- return;
3363
- // A renew that runs long must not be overlapped by the next tick: both would CAS against the same
3364
- // cached revision, so whichever lands second is refused over a sequence the first legitimately
3365
- // moved, a conflict this instance manufactured itself.
3366
- if (this.leaseRenewInFlight)
3367
- return;
3368
- this.leaseRenewInFlight = true;
3369
- const task = this.renewLeaseAttempt();
3370
- this.leaseRenewTask = task;
3371
- return task;
3372
- }
3373
- /** The renew attempt itself, split out from {@link renewLease} only so `stop()` can hold the
3374
- * promise a renew already in flight is running ({@link leaseRenewTask}) and await it before
3375
- * releasing the key: releasing against a cached revision a live renew has since moved is a CAS
3376
- * the broker correctly refuses, silently, forever. */
3377
- async renewLeaseAttempt() {
3378
- try {
3379
- if (!this.leaseInfo || this.leaseRevision === undefined)
3380
- return;
3381
- try {
3382
- this.leaseRevision = await this.ep.renewManagerLease(this.leaseInfo, this.leaseRevision);
3383
- this.noteLease("held", `renews its liveness lease again (revision ${this.leaseRevision})`);
3384
- return;
3385
- }
3386
- catch (renewError) {
3387
- const why = rejectionText(renewError);
3388
- const verdict = await this.reconcileLease();
3389
- switch (verdict.kind) {
3390
- case "held":
3391
- // The re-read is the broker's truth about the revision: adopt it, whether our write landed
3392
- // with its acknowledgement lost (revision moved) or never landed (revision unchanged).
3393
- this.leaseRevision = verdict.revision;
3394
- this.noteLease("held-unrenewed", `could not renew its liveness lease (${why}) but the key is still its own at revision ${verdict.revision}; serving, retrying`);
3395
- return;
3396
- case "gone": {
3397
- // A stop that began while this renew was already in flight fences it here too: the
3398
- // await above can cross the point where `stop()` set the flag, and a re-acquire past
3399
- // that point would put a stopping process's key straight back.
3400
- if (this.leaseStopping)
3401
- return;
3402
- // The key being gone is a fact before the re-acquire is attempted, so a successful
3403
- // re-acquire is a change of state (gone to held) and prints, every time it happens.
3404
- const before = this.leaseState;
3405
- this.leaseState = "gone";
3406
- try {
3407
- this.leaseRevision = await this.ep.acquireManagerLease(this.leaseInfo);
3408
- this.noteLease("held", `found its liveness lease key gone (renew: ${why}) and re-acquired it at revision ${this.leaseRevision}`);
3409
- }
3410
- catch (e) {
3411
- this.leaseState = before;
3412
- this.noteLease("gone", `found its liveness lease key gone (renew: ${why}) and could not re-acquire it yet (${rejectionText(e)}); serving, retrying`);
3413
- }
3414
- return;
3415
- }
3416
- case "taken":
3417
- // No `stop()` on the way out: its deregistration deletes the instance's current
3418
- // registration, which is the other process's now. That process took over on the premise
3419
- // that this one was gone, so this exit leaves what a crash would, and seats a custodian or
3420
- // multiplexer owns outlive it the same way.
3421
- console.error(`! manager instance ${this.managerInstanceId} finds its liveness lease key held by ${verdict.by}, not by this process (renew: ${why}); that process serves this instance now, so this one stops serving and exits (space "${this.space}")`);
3422
- process.exit(1);
3423
- case "unknown":
3424
- this.noteLease("unknown", `could not renew its liveness lease (${why}) or re-read it (${verdict.why}); serving, retrying until the broker answers`);
3425
- return;
3426
- }
3427
- }
3428
- }
3429
- finally {
3430
- this.leaseRenewInFlight = false;
3431
- }
3432
- }
3433
- /** Print `what` only when the lease state CHANGES. The renew ticks every few seconds, so a long
3434
- * outage would otherwise print the same line thousands of times; an operator needs the line going
3435
- * in and the line coming out, with the instance and the space on both. */
3436
- noteLease(state, what) {
3437
- if (state === this.leaseState)
3438
- return;
3439
- this.leaseState = state;
3440
- console.error(`${state === "held" ? "✓" : "!"} manager instance ${this.managerInstanceId} ${what} (space "${this.space}")`);
3441
- }
3442
- /** What the broker actually says about THIS instance's lease key, right now. `unknown` is a first-class
3443
- * answer and never collapses into `gone`: not being able to look is not the same fact as looking and
3444
- * finding nothing. */
3445
- async reconcileLease() {
3446
- let current;
3447
- try {
3448
- current = await this.ep.readOwnManagerLease(this.managerInstanceId);
3449
- }
3450
- catch (e) {
3451
- return { kind: "unknown", why: rejectionText(e) };
3452
- }
3453
- if (current === undefined)
3454
- return { kind: "gone" };
3455
- // The pid is what distinguishes US from a same-id restart: the logical instance id and the serve
3456
- // identity both PERSIST across restart by design, so neither can tell the two processes apart.
3457
- if (current.info.pid !== process.pid)
3458
- return { kind: "taken", by: `pid ${current.info.pid} (${current.info.runtime}, root ${current.info.root})` };
3459
- return { kind: "held", revision: current.revision };
3460
- }
3461
3142
  async opFinalizeResume(rawArgs) {
3462
3143
  if (this.execution === "none")
3463
3144
  throw new EpEnvelopeError("unimplemented", this.executionRefusal());
@@ -3756,9 +3437,7 @@ export class Manager {
3756
3437
  const agent = [...this.agents.values()].find((a) => this.managedPrincipal(a) === caller && a.lifecycleUid === ctx.subject.caller.uid);
3757
3438
  if (agent === undefined || agent.launch.capabilities?.includes("run"))
3758
3439
  return;
3759
- const pending = [...this.pendingTurns.values()].find((p) => p.seat.owner === ctx.subject.caller.owner
3760
- && p.seat.actor === ctx.subject.caller.actor
3761
- && p.seat.uid === ctx.subject.caller.uid);
3440
+ const pending = this.turnRelay.pendingForSeat(ctx.subject.caller);
3762
3441
  if (pending === undefined)
3763
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}`);
3764
3443
  let payload;
@@ -3963,7 +3642,7 @@ export class Manager {
3963
3642
  if (observed !== undefined && observed.slotPhase !== "retired")
3964
3643
  throw new EpEnvelopeError("failed-precondition", `no live agent "${name}"; durable state contradicts absence ${renderStaticSlotObservation(observed)}`, [observed]);
3965
3644
  }
3966
- throw new EpEnvelopeError("not-found", `no agent "${name}"`);
3645
+ throw new EpEnvelopeError("not-found", `no agent "${name}"`, undefined, "not-executed");
3967
3646
  }
3968
3647
  return row;
3969
3648
  }),
@@ -4424,277 +4103,8 @@ export class Manager {
4424
4103
  })
4425
4104
  .finally(() => this.releaseLifecycle());
4426
4105
  }
4427
- /** The served spawn a hosted enrollment forwards. A run's spawn also names its run, so the host
4428
- * bounds the helper by what the run's starter held when the run was admitted (SPEC 14.8). */
4429
- servedSpawnRequest(served, caller) {
4430
- const run = caller !== undefined ? this.runHosting?.runAdmission(caller) : undefined;
4431
- return { served, ...(run !== undefined ? { runId: run.runId } : {}) };
4432
- }
4433
- /** USER-MODE spawn provisioning (the gate-1 counterpart to the static mint block): resolve the
4434
- * OWNER (ctl caller's principal, or the manifest's stamped owner — never a payload field),
4435
- * pre-create the principal-keyed durables + ACL row on the ephemeral provisioner, author the
4436
- * ledger grant (the upsert ROTATES the per-agent secret on every start — a non-running agent
4437
- * never holds a standing mint secret), materialize the 0600 secret/sentinel files, and
4438
- * PREFLIGHT the bearer chain once — the spawned agent must never be the first to discover a
4439
- * dead auth plane. Every failure is returned as the refusal sentence, with the grant + files
4440
- * rolled back. */
4441
- async provisionUserAgent(name, opts) {
4442
- if (opts.delegatedIntent) {
4443
- // startAgentActive refused a delegated launch on a manager without this callback.
4444
- const execute = this.remoteAuthority.executeDelegatedUserIntent;
4445
- const { intentId, owner } = opts.delegatedIntent;
4446
- // The hosted arm with the intent's execution in place of the holder's own enrollment: the
4447
- // spawning owner is the intent's, so its existing owner check refuses any other.
4448
- return this.enrollUserAgent(name, { ...opts, specOwner: owner }, async ({ target }) => {
4449
- const result = await execute({ intentId, operation: "launch", target: { actor: target.actor, tokenHash: target.tokenHash } });
4450
- if (result.operation !== "launch" || result.intentId !== intentId)
4451
- throw new Error(`the host answered delegated intent ${intentId} with another execution`);
4452
- return result.material;
4453
- });
4454
- }
4455
- if (this.remoteAuthority?.enrollManagedAgent)
4456
- return this.enrollUserAgent(name, opts, this.remoteAuthority.enrollManagedAgent);
4457
- const spawnerPr = opts.spawner ? parsePrincipalKey(opts.spawner) : null;
4458
- const owner = opts.specOwner ?? (spawnerPr && spawnerPr.owner.startsWith("u_") ? spawnerPr.owner : undefined);
4459
- if (!owner)
4460
- return {
4461
- 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`,
4462
- };
4463
- let provider;
4464
- try {
4465
- provider = resolveAuthProvider();
4466
- }
4467
- catch (e) {
4468
- return { error: rejectionText(e) };
4469
- }
4470
- const dir = userAuthStateDir(this.workspaceRoot, this.space);
4471
- // The agent's capability scope rides its ledger row (act.scope in every bearer) — same
4472
- // vocabulary as static capabilities; the broker maps them to the ctl tiers. `role:<r>` tokens
4473
- // pass through too (a persona may hold delegable roles) — the ledger's envelope walk still
4474
- // attenuates every one of these against the spawner chain.
4475
- const scope = (opts.capabilities ?? []).filter((c) => c === "spawn" || c === "run" || c === "admin" || /^role:[A-Za-z0-9_-]+$/.test(c));
4476
- // The manager's ONE store (injected for a hosted composition, workstation FS locally). A hosted
4477
- // user-mode spawn reads the callout material from it — the same store the auth-store kinds
4478
- // (callout/issuer/…) were migrated onto — so this is no longer a local-only path.
4479
- const secrets = this.secrets;
4480
- // LIFECYCLE-KEYED family (SPEC 13.1 name-disjointness on the FS): this incarnation's files
4481
- // embed its uid, so no teardown addressed to another incarnation can ever reach them.
4482
- const files = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, opts.lifecycleUid);
4483
- const { actorToken: tokenPath, sentinelCreds: sentinelPath, health: healthPath } = files;
4484
- try {
4485
- // The GRANT first — it is the envelope-rule enforcement point (a delegation must sit within
4486
- // the spawner's own grant), so a refused delegation exits here having touched nothing beyond
4487
- // the ledger: no durables, no broker footprint, nothing for a corrected respawn to race.
4488
- const grant = await provider.grantAgent({
4489
- store: secrets,
4490
- dir,
4491
- space: this.space,
4492
- owner,
4493
- actor: name,
4494
- scope,
4495
- allowSubscribe: opts.allowSubscribe,
4496
- allowPublish: opts.allowPublish ?? [],
4497
- ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
4498
- role: opts.role,
4499
- parent: spawnerPr ? opts.spawner : undefined,
4500
- label: opts.label,
4501
- lifecycleUid: opts.lifecycleUid,
4502
- // This manager attests its own persisted logical instance id: the same id a static slot
4503
- // records as its owner. Recovery binds a managed row to a manager only through this.
4504
- custody: { kind: "local-manager", instanceId: this.managerInstanceId },
4505
- });
4506
- // Durables + ACL row, LIFECYCLE-keyed (SPEC 13.1) — the same onboarding as static agents minus
4507
- // the mint (a user agent's credential is its bearer, minted by the callout per connect from the
4508
- // ledger row's recorded lifecycleUid — the same value provisioned here).
4509
- await this.withProvisioner((prov) => provisionAgentDurables(prov, { owner, actor: name, lifecycleUid: opts.lifecycleUid }, {
4510
- subscribe: opts.subscribe,
4511
- allowSubscribe: opts.allowSubscribe,
4512
- role: opts.role,
4513
- }));
4514
- // The store holds the source of truth; the bearer re-exec (`--token-file`) and the launch's
4515
- // sentinel handoff read FILES, so materialize both at the canonical paths (under the local
4516
- // FS composition, a byte-identical rewrite of the keys' own locations).
4517
- await secrets.put(agentSecretKeyForFile(tokenPath, this.space), grant.actorToken);
4518
- await secrets.put(agentSecretKeyForFile(sentinelPath, this.space), grant.sentinelCreds);
4519
- await materializeSecretToFile(secrets, agentSecretKeyForFile(tokenPath, this.space), tokenPath);
4520
- await materializeSecretToFile(secrets, agentSecretKeyForFile(sentinelPath, this.space), sentinelPath);
4521
- rmSync(healthPath, { force: true }); // a fresh start opens a fresh health window
4522
- const bearerCmd = [
4523
- // The manager's own invocation prefix (node + loader flags + the cotal entry) — the agent
4524
- // process execs this argv for every bearer, so it must resolve from ANY cwd. Correct
4525
- // whenever the manager runs under a real `cotal` entry (supervise/up); a test constructing
4526
- // Manager directly never reaches this branch (user meshes boot through the CLI).
4527
- ...bearerEntryArgv(),
4528
- provider.agentBearerCommand,
4529
- "--dir", dir,
4530
- "--space", this.space,
4531
- "--owner", owner,
4532
- "--actor", name,
4533
- "--token-file", tokenPath,
4534
- "--health-file", healthPath,
4535
- ];
4536
- // One bearer run before the launch is the end-to-end auth preflight (state dir, daemon, ledger
4537
- // row, secret); its failure sentence is the spawn refusal.
4538
- await runAgentBearer(bearerCmd);
4539
- return { owner, lifecycleUid: opts.lifecycleUid, files, launch: { owner, actor: name, sentinelCredsPath: sentinelPath, bearerCmd } };
4540
- }
4541
- catch (e) {
4542
- // Roll back everything this attempt materialized — a refused spawn must leave no standing
4543
- // secret, no ledger row, no durable footprint — and AWAIT the broker teardown: the caller
4544
- // may respawn the moment it reads the refusal, and a detached teardown would race (and
4545
- // delete) that fresh spawn's just-provisioned durables. deprovision shreds the secret family
4546
- // and revokes the grant, but only logs a failed revoke, so the revoke is attempted here first.
4547
- // Each failure joins the refusal, so the caller learns what this spawn left behind.
4548
- const failed = [];
4549
- await attemptCleanup(failed, "revoke agent grant", () => provider.revokeAgent({ dir, owner, actor: name }));
4550
- await attemptCleanup(failed, "deprovision", () => this.deprovision({ id: principalKey(owner, name).key, name, lifecycleUid: opts.lifecycleUid, userOwner: owner, secretPaths: files }));
4551
- const leftover = failed.length ? `; cleanup failed: ${describeCleanupFailures(failed)}` : "";
4552
- return { error: `agent auth preflight failed for "${name}": ${rejectionText(e)}${leftover}` };
4553
- }
4554
- }
4555
- /**
4556
- * HOSTED user-mode spawn provisioning (#1972): the participant arm of host-owned enrollment.
4557
- *
4558
- * A registered participant holds no ledger writer, no JetStream provisioner, and no signing seed,
4559
- * so every step the local arm above performs itself is the HOST's here. What stays local is the
4560
- * one thing that must: the standing `actorToken`. This method generates it, writes it at 0600
4561
- * BEFORE the request, and sends only its SHA-256 digest — so the plaintext never crosses the
4562
- * network and a host compromise cannot replay an agent's exchange secret.
4563
- *
4564
- * The HOST picks the lifecycle UID. It alone can see the retirement tombstones that make a UID
4565
- * permanently unusable (a retired uid is refused forever by the retirement frontier), so a
4566
- * participant-chosen uid could aim a fresh grant at a dead incarnation. The uid the host returns
4567
- * is the one the spawn records and the one the child's durables are keyed by.
4568
- *
4569
- * The bearer argv selects `--exchange-url`: the local `--dir` arm reads a state directory this
4570
- * machine does not have, and a signerless participant must never appear to hold one.
4571
- */
4572
- async enrollUserAgent(name, opts, enroll) {
4573
- let provider;
4574
- try {
4575
- provider = resolveAuthProvider();
4576
- }
4577
- catch (e) {
4578
- return { error: rejectionText(e) };
4579
- }
4580
- const secrets = this.secrets;
4581
- const input = {
4582
- target: {
4583
- actor: name,
4584
- ...(opts.role !== undefined ? { role: opts.role } : {}),
4585
- label: opts.label,
4586
- ...(opts.capabilities !== undefined ? { capabilities: opts.capabilities } : {}),
4587
- ...(opts.subscribe !== undefined ? { subscribe: opts.subscribe } : {}),
4588
- allowSubscribe: opts.allowSubscribe,
4589
- ...(opts.allowPublish !== undefined ? { allowPublish: opts.allowPublish } : {}),
4590
- ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
4591
- },
4592
- ...(opts.spawnRequest !== undefined ? { spawn: opts.spawnRequest } : {}),
4593
- };
4594
- // An unanswered enrollment may already hold the host's alias. Keep its request and standing
4595
- // token together until preflight succeeds, rather than minting a conflicting successor.
4596
- let pending;
4597
- if (!opts.delegatedIntent) {
4598
- try {
4599
- pending = await pendingEnrollment({ store: secrets, space: this.space,
4600
- instanceId: this.managerInstanceId, actor: name, input,
4601
- authority: { target: input.target, owner: this.remoteAuthority.owner,
4602
- managerLifecycleUid: this.remoteAuthority.lifecycleUid, specOwner: opts.specOwner, spawner: opts.spawner,
4603
- caller: opts.enrollmentCaller, runId: opts.spawnRequest?.runId } });
4604
- }
4605
- catch (e) {
4606
- return { error: `agent auth preflight failed for "${name}": ${rejectionText(e)}` };
4607
- }
4608
- }
4609
- const actorToken = pending?.record.actorToken ?? randomBytes(32).toString("base64url");
4610
- const tokenHash = createHash("sha256").update(actorToken, "utf8").digest("hex");
4611
- // Provisional paths under the participant's OWN uid: the token has to be on disk before the
4612
- // request (a host that granted against a digest whose plaintext was lost would leave an agent
4613
- // that can never exchange), and the host's uid is not known until the request answers. The
4614
- // family is re-keyed to the host's uid below.
4615
- const staged = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, pending?.record.lifecycleUid ?? opts.lifecycleUid);
4616
- let files = staged;
4617
- let material;
4618
- let sent = false;
4619
- try {
4620
- await secrets.put(agentSecretKeyForFile(staged.actorToken, this.space), actorToken);
4621
- await materializeSecretToFile(secrets, agentSecretKeyForFile(staged.actorToken, this.space), staged.actorToken);
4622
- const saved = pending?.record.input ?? input;
4623
- if (canonicalJson(saved.target) !== canonicalJson(input.target))
4624
- throw new Error(`pending enrollment for "${name}" names different target authority`);
4625
- sent = true;
4626
- // The original observation may have expired, or vanished on a host restart before commit.
4627
- // Same-authority retries keep the enrollment identity but carry this freshly served spawn.
4628
- material = await enroll({ ...input, target: { ...saved.target, tokenHash },
4629
- ...(pending ? { requestId: pending.record.requestId } : {}) });
4630
- if (material.actor !== name)
4631
- throw new Error(`the host enrolled actor "${material.actor}", not the requested "${name}"`);
4632
- const specOwner = opts.specOwner ?? (opts.spawner ? parsePrincipalKey(opts.spawner)?.owner : undefined);
4633
- if (specOwner !== undefined && specOwner.startsWith("u_") && material.owner !== specOwner)
4634
- throw new Error(`the host enrolled the agent under owner ${material.owner}, not the spawning owner ${specOwner}`);
4635
- assertLifecycleToken(material.lifecycleUid, "host-enrolled managed agent lifecycleUid");
4636
- // Re-key the family onto the HOST's uid (SPEC 13.1 name-disjointness on the FS): the child's
4637
- // credential paths must embed the uid its broker footprint carries, never the provisional one.
4638
- files = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, material.lifecycleUid);
4639
- // From here the host holds a grant at that uid.
4640
- opts.onEnrolled?.({ owner: material.owner, lifecycleUid: material.lifecycleUid, files });
4641
- if (files.actorToken !== staged.actorToken) {
4642
- await secrets.put(agentSecretKeyForFile(files.actorToken, this.space), actorToken);
4643
- await materializeSecretToFile(secrets, agentSecretKeyForFile(files.actorToken, this.space), files.actorToken);
4644
- await secrets.delete(agentSecretKeyForFile(staged.actorToken, this.space));
4645
- rmSync(staged.actorToken, { force: true });
4646
- }
4647
- await secrets.put(agentSecretKeyForFile(files.sentinelCreds, this.space), material.sentinelCreds);
4648
- await materializeSecretToFile(secrets, agentSecretKeyForFile(files.sentinelCreds, this.space), files.sentinelCreds);
4649
- rmSync(files.health, { force: true }); // a fresh start opens a fresh health window
4650
- const bearerCmd = [
4651
- ...bearerEntryArgv(),
4652
- provider.agentBearerCommand,
4653
- // The signerless arm: the pinned public exchange, never a local state dir.
4654
- "--exchange-url", material.agentBearerExchangeUrl,
4655
- "--space", this.space,
4656
- "--owner", material.owner,
4657
- "--actor", name,
4658
- "--token-file", files.actorToken,
4659
- "--health-file", files.health,
4660
- ];
4661
- await runAgentBearer(bearerCmd);
4662
- if (pending)
4663
- await secrets.delete(pending.key);
4664
- return {
4665
- owner: material.owner,
4666
- lifecycleUid: material.lifecycleUid,
4667
- files,
4668
- launch: { owner: material.owner, actor: name, sentinelCredsPath: files.sentinelCreds, bearerCmd },
4669
- enrolled: { material, actorToken },
4670
- };
4671
- }
4672
- catch (e) {
4673
- // Remove launch-file materializations, but retain the pending token and request when the
4674
- // host may have committed. The next same-authority spawn replays that enrollment.
4675
- // A failed removal joins the refusal instead of throwing, so every removal is attempted and
4676
- // the refusal still reaches the caller.
4677
- const unshredded = [];
4678
- for (const family of files.actorToken === staged.actorToken ? [staged] : [staged, files])
4679
- await this.shredUserSecrets(unshredded, family);
4680
- const rejected = material === undefined ? caughtEnvelope(e) : undefined;
4681
- // Only a first, definitively refused request proves there was no earlier commit. A refusal
4682
- // during replay cannot prove that an earlier unanswered attempt enrolled nothing.
4683
- const discard = pending?.created && (!sent || rejected?.outcome === "not-executed");
4684
- if (discard && pending) {
4685
- const key = pending.key;
4686
- await attemptCleanup(unshredded, "pending enrollment", () => secrets.delete(key));
4687
- }
4688
- const retained = pending && !discard;
4689
- const leftover = unshredded.length ? `; cleanup failed: ${describeCleanupFailures(unshredded)}` : "";
4690
- 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` : "";
4691
- const refusal = !retained && material === undefined && !unshredded.length ? rejected : undefined;
4692
- return {
4693
- error: `agent auth preflight failed for "${name}": ${rejectionText(e)}${leftover}${remedy}`,
4694
- ...(refusal?.outcome === "not-executed" ? { refused: refusal.code, ...(refusal.details ? { details: refusal.details } : {}) } : {}),
4695
- };
4696
- }
4697
- }
4106
+ servedSpawnRequest(served, caller) { return this.userProvision.servedSpawnRequest(served, caller); }
4107
+ provisionUserAgent(name, opts) { return this.userProvision.provisionUserAgent(name, opts); }
4698
4108
  /** Shred a user agent's secret family from the store and from disk. Every removal is attempted,
4699
4109
  * and each failure joins `unshredded`, so one fault cannot leave the rest of the family behind. */
4700
4110
  async shredUserSecrets(unshredded, family) {
@@ -4705,43 +4115,8 @@ export class Manager {
4705
4115
  if (path)
4706
4116
  await attemptCleanup(unshredded, `file ${path}`, () => rmSync(path, { force: true }));
4707
4117
  }
4708
- /** This manager's registry record for its space, which pins the broker and IdP a delegated seat's
4709
- * handoff carries. It must pin the exchange the host enrolls against, or the child would register
4710
- * a mesh whose bearers come from somewhere else. */
4711
- delegatedMeshRecord() {
4712
- const record = loadMeshes().find((m) => m.space === this.space);
4713
- if (!record?.userAuth)
4714
- throw new Error(`a delegated seat needs this manager's user-mode registry record for space "${this.space}", and there is none`);
4715
- if (record.userAuth.endpoints?.url !== this.remoteAuthority?.agentBearerExchangeUrl)
4716
- throw new Error(`the registry record for space "${this.space}" pins a different exchange than the host's agentBearerExchangeUrl`);
4717
- return record;
4718
- }
4719
- /** The one handoff a delegated seat receives, built from values this manager holds: the
4720
- * enrollment result, the token it generated, and its own registry record. No path crosses. */
4721
- composeManagedHandoff(enrolled, actorToken) {
4722
- const record = this.delegatedMeshRecord();
4723
- if (enrolled.agentBearerExchangeUrl !== record.userAuth.endpoints?.url)
4724
- throw new Error(`the host enrolled "${enrolled.actor}" against a different exchange than this manager's registry record pins`);
4725
- const { url, issuer, audience } = record.userAuth.idp;
4726
- return {
4727
- kind: MANAGED_HANDOFF_KIND,
4728
- space: this.space,
4729
- owner: enrolled.owner,
4730
- actor: enrolled.actor,
4731
- lifecycleUid: enrolled.lifecycleUid,
4732
- server: record.server,
4733
- tlsRequired: record.tlsRequired === true,
4734
- authProvider: record.userAuth.provider,
4735
- idp: { url, issuer, audience },
4736
- exchangeUrl: enrolled.agentBearerExchangeUrl,
4737
- sentinelCreds: enrolled.sentinelCreds,
4738
- actorToken,
4739
- subscribe: enrolled.subscribe,
4740
- allowSubscribe: enrolled.allowSubscribe,
4741
- allowPublish: enrolled.allowPublish,
4742
- ...(record.policy ? { policy: record.policy } : {}),
4743
- };
4744
- }
4118
+ delegatedMeshRecord() { return this.userProvision.delegatedMeshRecord(); }
4119
+ composeManagedHandoff(enrolled, actorToken) { return this.userProvision.composeManagedHandoff(enrolled, actorToken); }
4745
4120
  /**
4746
4121
  * WHY A SEAT LEFT — one line, at the one place every free path passes through.
4747
4122
  *
@@ -4813,76 +4188,7 @@ export class Manager {
4813
4188
  isOwnPresence(a, p) {
4814
4189
  return p !== undefined && p.card.id === this.managedPrincipal(a) && p.lifecycleUid === a.lifecycleUid;
4815
4190
  }
4816
- /** Drop a live agent's slot. When `floor` is set and the agent died young (lived less than
4817
- * MIN_LIFETIME), push a cooling stamp so the freed slot still counts toward the ceiling until it
4818
- * expires — flooring the RECYCLE, not the call, so both free paths (despawn + exit/reap) are
4819
- * covered (P4c). Floor self + own-child despawn and natural exit; NEVER admin despawn (operator
4820
- * emergency-kill stays unthrottled) and NEVER the reserved-rollback path (no cold-start paid). */
4821
- freeSlot(a, floor, cause, acceptedBeforeFence = false) {
4822
- if (this.agents.get(a.name) !== a)
4823
- return; // already freed (exit raced despawn, etc.)
4824
- // The terminalizing latch also covers exit/reap paths that never rode stopHandle.
4825
- this.logSeatReaped(a, cause);
4826
- a.terminalizing = true;
4827
- this.agents.delete(a.name);
4828
- this.recordContinuityAtStop(a, "stop");
4829
- if (a.restart?.sessionStatePath)
4830
- rmSync(a.restart.sessionStatePath, { force: true });
4831
- // A released seat's record is the next manager's only pointer to it. It stays until the
4832
- // retirement is confirmed. Dropping it here let a refused retirement leave the lifecycle active
4833
- // with nothing left for that manager to adopt.
4834
- if (!this.releasedSeatPending(a))
4835
- this.dropSeatRecord(a);
4836
- if (a.seatHome)
4837
- rmSync(a.seatHome, { recursive: true, force: true });
4838
- // End any live §13.6 attach session bound to THIS incarnation with the reason its cause names.
4839
- // Fires once per agent on every free path (despawn / self-stop / reap / exit) via the `agents`
4840
- // guard above; a no-op when no plane or no live session for the target.
4841
- this.sessionPlane?.endForTarget(a.name, a.lifecycleUid, typeof cause === "string" ? FREE_SLOT_ATTACH_END[cause] : "target-despawn");
4842
- // The turn relay's reap hook: every pending turn addressed to THIS incarnation is stamped
4843
- // with the death, and its deadline terminal carries it as `agentDownAt`. The addressee is gone
4844
- // and no successor may answer for it; the terminal is still the deadline's, not a new reason.
4845
- this.failSeatTurns(a.name, a.lifecycleUid);
4846
- if (floor && Date.now() - a.startedAt < MIN_LIFETIME)
4847
- this.cooling.push(a.startedAt + MIN_LIFETIME);
4848
- // The departed agent's own custody reference rides the teardown: the exit that freed this slot
4849
- // is usually the seat ending, but a stop that could not prove the process gone leaves one the
4850
- // terminal must still address before it frees the alias.
4851
- const target = this.teardownTarget(a);
4852
- // On a USER mesh the name is RESERVED PENDING RETIREMENT — despawn started this
4853
- // lifecycle's FULL teardown (footprint + standing-authority revoke + the auth-side retirement),
4854
- // and the alias frees only when all of it completes (not the retirement alone). The detached
4855
- // deprovision below drives it; a failed revoke or an unreachable rail keeps the name held,
4856
- // re-driven by a retry. Gate on userMode BY
4857
- // CONSTRUCTION (NEW-1): a static-auth mint has no user-mode lifecycle head to retire, so the
4858
- // reservation + rail request simply don't apply there (the incidental nkey-parse used to mask
4859
- // this, but the intent is "user mode only", not "any principal-shaped id").
4860
- if (this.userMode) {
4861
- const p = parsePrincipalKey(a.id);
4862
- if (p)
4863
- this.retirement.hold(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: p.owner, actor: p.actor, target, startedAt: Date.now() });
4864
- }
4865
- else if (this.auth) {
4866
- // A STATIC lifecycle now also holds its name pending its own terminal (the
4867
- // static retirement the detached deprovision below drives) — the alias frees only when the
4868
- // gate+head terminal completes, exactly the user-mode discipline. The wire principal is the
4869
- // incarnation-unique nkey; owner is the dev owner.
4870
- this.retirement.hold(a.name, { opId: managedRetirementOpId(a.lifecycleUid), owner: DEV_OWNER, actor: a.id, target, startedAt: Date.now() });
4871
- }
4872
- // Auth mode: tear down the departed agent's minted broker footprint + creds file (#159 B2). The
4873
- // process is already gone, so this must never block the slot free or throw into the caller — it runs
4874
- // detached, and a failure is logged loudly (never swallowed), not retried. The `agents` guard above
4875
- // makes this fire exactly once per agent across every free path (despawn / self-stop / reap / exit).
4876
- if (!a.suppressCleanup && (this.maintenanceState === "active" || acceptedBeforeFence)) {
4877
- // An inline seat's snapshot goes with the seat on every mesh. An open mesh runs no teardown
4878
- // below, and a preservation cut suppresses this, so a resumed seat still finds its snapshot.
4879
- // Settled means the file is gone or the seat never had one. A removal that failed is left to
4880
- // the teardown, which retries it and reports what it could not remove.
4881
- if (a.launch.source.kind !== "inline" || this.dropInlineSnapshot(a.name, a.lifecycleUid))
4882
- target.snapshotSettled = true;
4883
- this.trackDeprovision(target);
4884
- }
4885
- }
4191
+ freeSlot(a, floor, cause, acceptedBeforeFence = false) { this.namesCapacity.freeSlot(a, floor, cause, acceptedBeforeFence); }
4886
4192
  /** Remove one lifecycle's inline snapshot by the path its uid derives, never by a recorded one, so a
4887
4193
  * resume inventory cannot point the removal at another file. Returns whether the file is gone. A
4888
4194
  * failure is logged, never thrown, because the callers must still schedule the teardown. */
@@ -5058,58 +4364,9 @@ export class Manager {
5058
4364
  this.freeSlot(a, true, a.stopCause ?? "process-exit");
5059
4365
  this.reapChildrenOf(this.managedPrincipal(a));
5060
4366
  }
5061
- /** Agent names become `.cotal/agents/<name>.md` paths and mesh identities, so they must be bare
5062
- * tokens, never a path — blocks traversal / arbitrary writes from a model-supplied name. In user
5063
- * mode the name is ALSO the actor, which is a narrower alphabet still; {@link spawnNameError}
5064
- * holds both halves so this door and the auto-numbering that feeds it cannot disagree. */
5065
- nameError(name) {
5066
- return spawnNameError(name, { userMode: this.userMode });
5067
- }
5068
- /** The roster's LIVE occupant names (status !== offline) — occupants this manager may NOT manage
5069
- * (a foreground `cotal spawn`, a connector session, ANOTHER manager's agent). Allocating over any
5070
- * of them mints a sibling the broker/auth then refuses to admit, surfacing as the 30s launch-
5071
- * uncertain black hole. */
5072
- liveRosterNames() {
5073
- const live = new Set();
5074
- for (const p of this.ep.getRoster()) {
5075
- if (p.status === "offline")
5076
- continue;
5077
- const predecessor = this.retirement.predecessor(p.card.name);
5078
- if (predecessor !== undefined && predecessor.principal === p.card.id && predecessor.lifecycleUid === p.lifecycleUid)
5079
- continue;
5080
- live.add(p.card.name);
5081
- }
5082
- return live;
5083
- }
5084
- /** THE single name-liveness predicate both the hard-pinned collision refuse and
5085
- * uniqueName's numbering consult, so they can never drift: a name is taken if this manager
5086
- * reserves/manages/retires it OR a roster-live occupant already holds it. Pass a pre-built
5087
- * {@link liveRosterNames} set when checking many names in one allocation. */
5088
- nameInUse(name, live = this.liveRosterNames()) {
5089
- return this.agents.has(name) || this.reserved.has(name) || this.retirement.hasHold(name) || live.has(name);
5090
- }
5091
- /** First free name in the series `base`, `base_2`, `base_3`, … — checked against live slots,
5092
- * in-flight (reserved) slots, names held pending retirement, AND the live mesh roster. The
5093
- * roster check covers occupants this manager does not manage (a foreground `cotal spawn`, a
5094
- * connector session, another manager's agent): allocating their name would mint a sibling the
5095
- * broker/auth then refuses to admit, surfacing as a 30s launch-uncertain black hole instead of
5096
- * the auto-number the join path gives. Presence is ADVISORY (SPEC §6) — this is an availability
5097
- * choice at allocation, never an authority check (the broker still enforces): a stale
5098
- * still-live-looking row only costs a numbered suffix, and a missed freshly-joined occupant is
5099
- * still refused downstream exactly as before. Offline rows do NOT occupy — a properly retired
5100
- * name stays reusable. A row this manager itself confirmed retired (its alias, principal, and
5101
- * lifecycleUid all matching a {@link confirmedRetiredPredecessors} entry) does not occupy
5102
- * either, even while its advisory presence record ages out. A numbered name is never reissued
5103
- * ({@link issuedNumberedNames}), even after its holder retired. The requested base is exempt
5104
- * from that history: it is the persona's own name, which stays reusable even when it once came
5105
- * out of another persona's numbering. */
5106
- uniqueName(base, unavailable = new Set()) {
5107
- const live = this.liveRosterNames();
5108
- // The cap belongs to user mode alone: only there is the numbered name the actor. Static and open
5109
- // mode key the actor on the minted nkey, so a numbered name there has no length to fit.
5110
- const name = firstFreeName(base, (n) => unavailable.has(n) || this.nameInUse(n, live) || (n !== base && this.issuedNumberedNames.has(n)), this.userMode ? { actorBound: true } : undefined);
5111
- return name;
5112
- }
4367
+ nameError(name) { return this.namesCapacity.nameError(name); }
4368
+ nameInUse(name, live) { return this.namesCapacity.nameInUse(name, live); }
4369
+ uniqueName(base, unavailable = new Set()) { return this.namesCapacity.uniqueName(base, unavailable); }
5113
4370
  /** Spawn a teammate by persona ref (`name` loads `.cotal/agents/<name>.md`; the peer presents
5114
4371
  * under that file's own `name:`), as if a peer asked via the control plane. Used to pre-spawn the
5115
4372
  * demo's experts at startup so the manager owns them. */
@@ -5303,7 +4560,7 @@ export class Manager {
5303
4560
  let declared;
5304
4561
  if (this.installedExtensions) {
5305
4562
  try {
5306
- declared = loadExtensionsManifest().extensions.flatMap((ext) => extensionConnectors(ext));
4563
+ declared = loadExtensionsManifest().extensions.flatMap((ext) => extensionConnectors(ext).map((connector) => ({ ...connector, pkg: ext.pkg })));
5307
4564
  }
5308
4565
  catch (error) {
5309
4566
  const reason = rejectionText(error);
@@ -5320,8 +4577,27 @@ export class Manager {
5320
4577
  eventPlane: connector.eventChannel !== undefined,
5321
4578
  }));
5322
4579
  }
5323
- for (const { name, requires, eventPlane } of declared) {
5324
- 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
+ }
5325
4601
  if (reason) {
5326
4602
  rows.push({ agent: name, state: "unavailable", binaries, eventPlane, reason });
5327
4603
  this.bootNotes.push(`! manager boot: connector ${name} unavailable - ${reason}`);
@@ -5334,6 +4610,27 @@ export class Manager {
5334
4610
  if (!this.classSpawnEnabled())
5335
4611
  this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
5336
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
+ }
5337
4634
  /** True when at least one declared connector is available. Empty inventory (or a failed
5338
4635
  * inventory load) skips the class `one` subscribe for spawn/launch so this member cannot
5339
4636
  * consume an unpinned request a sibling could serve. */
@@ -5358,8 +4655,10 @@ export class Manager {
5358
4655
  /** The harness binaries a managed launch runs, as boot resolved them, or the refusal naming what is
5359
4656
  * missing. Spawn, resume and the model catalog all take it, so a seat launches from the same files
5360
4657
  * whichever path starts it and the catalog never disagrees with a launch about whether the harness
5361
- * 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. */
5362
4660
  launchHarness(connector) {
4661
+ this.refreshUnavailableConnectors(connector.name);
5363
4662
  const row = this.connectorStatuses.find((status) => status.agent === connector.name);
5364
4663
  if (row?.state === "unavailable")
5365
4664
  return { refusal: row.reason ?? `${connector.name} harness is unavailable` };
@@ -5448,14 +4747,14 @@ export class Manager {
5448
4747
  }
5449
4748
  /** The refusal for an event-plane choice the registration policy or the connector cannot meet.
5450
4749
  * Spawn and resume both ask before a seat's launch is built, so a seat retained without the
5451
- * 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. */
5452
4751
  eventsRefusal(connector, events) {
5453
4752
  if (this.eventsRequired && events === false)
5454
4753
  return `space "${this.space}" requires the event plane by registration policy; --no-events (events: false on the start op) is not allowed`;
5455
- if (events !== false && !connector.eventChannel)
4754
+ if ((this.eventsRequired || events === true) && !connector.eventChannel)
5456
4755
  return this.eventsRequired
5457
4756
  ? `space "${this.space}" requires the event plane by registration policy, but connector "${connector.name}" does not publish one`
5458
- : `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`;
5459
4758
  return undefined;
5460
4759
  }
5461
4760
  /** Return connector-provided model catalogs for selector UIs. Optional by connector: a host with no
@@ -5467,9 +4766,9 @@ export class Manager {
5467
4766
  const requested = String(args.agent ?? "").trim();
5468
4767
  const refresh = args.refresh === true;
5469
4768
  const one = async (connector) => {
4769
+ const harness = this.launchHarness(connector);
5470
4770
  if (!connector.listModels)
5471
4771
  return { agent: connector.name, supported: false, models: [] };
5472
- const harness = this.launchHarness(connector);
5473
4772
  if ("refusal" in harness)
5474
4773
  return { agent: connector.name, supported: true, models: [], error: harness.refusal };
5475
4774
  try {
@@ -6164,9 +5463,8 @@ export class Manager {
6164
5463
  catch (e) {
6165
5464
  return { ok: false, error: opts.resolved ? `launch agent: ${rejectionText(e)}` : `persona ${where}: ${rejectionText(e)}` };
6166
5465
  }
6167
- // The AG-UI event plane is on unless the launch explicitly opted out. A connector that cannot
6168
- // emit one is refused further down, before anything is minted.
6169
- 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);
6170
5468
  if (this.eventPayloadsWithheld && opts.eventPayloads === true)
6171
5469
  return { ok: false, error: "space policy withholds event payloads" };
6172
5470
  const eventPayloads = !this.eventPayloadsWithheld && (opts.eventPayloads ?? def?.eventPayloads) !== false;
@@ -6266,7 +5564,7 @@ export class Manager {
6266
5564
  // alone) so a retry re-drives the standing-authority revoke (INT-2) AND the broker cleanup before
6267
5565
  // any hold-clear (C): the alias must not free while the durable teardown or the revoke is still
6268
5566
  // outstanding. All the teardown ops are idempotent, and the rail request is single-flighted.
6269
- if (this.reconcilingAliases.has(identityName))
5567
+ if (this.staticLifecycle.isReconciling(identityName))
6270
5568
  return { ok: false, error: `the name "${identityName}" is still reconciling at manager startup; its prior lifecycle terminal owns this alias until it completes. Retry shortly.` };
6271
5569
  const held = this.retirement.held(identityName);
6272
5570
  if (held !== undefined) {
@@ -6374,7 +5672,7 @@ export class Manager {
6374
5672
  }
6375
5673
  // Another spawn may have reserved the candidate while the disk/broker proof awaited.
6376
5674
  // Recheck in the same synchronous window as the cap and reservation below.
6377
- if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.issuedNumberedNames.has(name))) {
5675
+ if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
6378
5676
  if (!hardPinned)
6379
5677
  continue;
6380
5678
  return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
@@ -6416,8 +5714,8 @@ export class Manager {
6416
5714
  // allocation, where there is no name to give back.
6417
5715
  hooks?.onEffect?.();
6418
5716
  if (!hardPinned && name !== identityName)
6419
- this.issuedNumberedNames.add(name);
6420
- this.reserved.set(name, owner);
5717
+ this.namesCapacity.rememberNumbered(name);
5718
+ this.namesCapacity.reserve(name, owner);
6421
5719
  try {
6422
5720
  // A stable nkey identity assigned at spawn: the public key is the agent's card.id (threaded via
6423
5721
  // COTAL_ID); the seed is retained to mint matching creds later.
@@ -6809,7 +6107,7 @@ export class Manager {
6809
6107
  });
6810
6108
  }
6811
6109
  this.agents.set(name, managed);
6812
- this.reservedLive.add(name);
6110
+ this.namesCapacity.placed(name);
6813
6111
  if (managed.once)
6814
6112
  this.watchOnceExit(managed);
6815
6113
  // The live slot now owns teardown — freeSlot deprovisions this identity on exit — so the
@@ -6863,7 +6161,7 @@ export class Manager {
6863
6161
  // task, never served, cancelled with the verdict.
6864
6162
  if (onceTask && connector.onceNeedsConfirmed !== undefined) {
6865
6163
  const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
6866
- if (managed.terminalizing) {
6164
+ if (managed.terminalizing || this.leaseStopping) {
6867
6165
  hooks?.onTerminalDeferred?.();
6868
6166
  return { ok: false, error: `${name} was stopped before its startup ended` };
6869
6167
  }
@@ -6883,7 +6181,7 @@ export class Manager {
6883
6181
  // starting it silently without push (#5737).
6884
6182
  if (!onceTask && connector.idleWakeNeedsConfirmed !== undefined && runtime.reportsStartupOutcome) {
6885
6183
  const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
6886
- if (managed.terminalizing) {
6184
+ if (managed.terminalizing || this.leaseStopping) {
6887
6185
  hooks?.onTerminalDeferred?.();
6888
6186
  return { ok: false, error: `${name} was stopped before its startup ended` };
6889
6187
  }
@@ -6992,8 +6290,7 @@ export class Manager {
6992
6290
  return { ok: false, error };
6993
6291
  }
6994
6292
  finally {
6995
- this.reserved.delete(name);
6996
- this.reservedLive.delete(name);
6293
+ this.namesCapacity.release(name);
6997
6294
  if (seatHome)
6998
6295
  rmSync(seatHome, { recursive: true, force: true });
6999
6296
  // A failed removal is logged, never thrown, so the grant's teardown below is still scheduled.
@@ -7087,11 +6384,11 @@ export class Manager {
7087
6384
  return { ok: false, agents: [], error: `retained principal "${principal}" is already live and this runtime cannot authoritatively adopt it` };
7088
6385
  orphans.push({ principal, reference: orphan });
7089
6386
  }
7090
- if (this.agents.has(entry.name) || this.reserved.has(entry.name))
6387
+ if (this.agents.has(entry.name) || this.namesCapacity.isReserved(entry.name))
7091
6388
  return { ok: false, agents: [], error: `retained agent "${entry.name}" is already managed or reserved` };
7092
6389
  }
7093
6390
  for (const entry of entries) {
7094
- this.reserved.set(entry.name, resumeOwner(entry));
6391
+ this.namesCapacity.reserve(entry.name, resumeOwner(entry));
7095
6392
  batchReservations.push(entry.name);
7096
6393
  }
7097
6394
  const preflight = [];
@@ -7130,8 +6427,7 @@ export class Manager {
7130
6427
  }
7131
6428
  finally {
7132
6429
  for (const name of batchReservations) {
7133
- this.reserved.delete(name);
7134
- this.reservedLive.delete(name);
6430
+ this.namesCapacity.release(name);
7135
6431
  }
7136
6432
  // Preflight builds every launch before any child starts, so a refused batch, a failed launch,
7137
6433
  // or the agents skipped after it leave built specs no runtime ever received.
@@ -7374,7 +6670,7 @@ export class Manager {
7374
6670
  const nameErr = this.nameError(entry.name);
7375
6671
  if (nameErr)
7376
6672
  return { ok: false, error: nameErr };
7377
- if (this.agents.has(entry.name) || (!batchReserved && this.reserved.has(entry.name)))
6673
+ if (this.agents.has(entry.name) || (!batchReserved && this.namesCapacity.isReserved(entry.name)))
7378
6674
  return { ok: false, error: `retained agent "${entry.name}" is already managed or reserved; same-principal resume never auto-numbers` };
7379
6675
  const occupancy = batchReserved ? undefined : this.occupancy();
7380
6676
  if (occupancy && occupancy.used >= MAX_AGENTS)
@@ -7520,7 +6816,7 @@ export class Manager {
7520
6816
  }
7521
6817
  async launchPreparedResume(entry, prepared, batchReserved, supervised) {
7522
6818
  if (!batchReserved)
7523
- this.reserved.set(entry.name, resumeOwner(entry));
6819
+ this.namesCapacity.reserve(entry.name, resumeOwner(entry));
7524
6820
  try {
7525
6821
  // Recover the STATIC identity's nkey seed from the adopted credential (the
7526
6822
  // creds file embeds it) so the manager stays this incarnation's RENEWAL OWNER across a
@@ -7600,7 +6896,7 @@ export class Manager {
7600
6896
  suppressCleanup: true,
7601
6897
  };
7602
6898
  this.agents.set(entry.name, managed);
7603
- this.reservedLive.add(entry.name);
6899
+ this.namesCapacity.placed(entry.name);
7604
6900
  if (this.resumeAttemptId)
7605
6901
  this.resumedAgentNames.add(entry.name);
7606
6902
  try {
@@ -7641,8 +6937,7 @@ export class Manager {
7641
6937
  }
7642
6938
  finally {
7643
6939
  if (!batchReserved) {
7644
- this.reserved.delete(entry.name);
7645
- this.reservedLive.delete(entry.name);
6940
+ this.namesCapacity.release(entry.name);
7646
6941
  }
7647
6942
  }
7648
6943
  }
@@ -7816,6 +7111,7 @@ export class Manager {
7816
7111
  if (joinedPoll !== undefined)
7817
7112
  clearInterval(joinedPoll);
7818
7113
  this.ep.off("presence", onPresence);
7114
+ this.shutdownReadiness.signal.removeEventListener("abort", onShutdown);
7819
7115
  unsubExit();
7820
7116
  resolve(r);
7821
7117
  };
@@ -7823,6 +7119,9 @@ export class Manager {
7823
7119
  if (joined())
7824
7120
  finish({ ok: true });
7825
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` });
7826
7125
  if (opts.joinedAfter !== undefined) {
7827
7126
  // Heartbeats bump roster.ts without emitting "presence" (same status/uid/activity).
7828
7127
  // A supervised restart needs that bump, so poll joined() rather than waiting on the event.
@@ -7911,8 +7210,11 @@ export class Manager {
7911
7210
  else
7912
7211
  pollProvedExit(a.handle, onExit, () => !done, READINESS_EXIT_POLL_MS);
7913
7212
  this.ep.on("presence", onPresence);
7213
+ this.shutdownReadiness.signal.addEventListener("abort", onShutdown, { once: true });
7914
7214
  // Subscribe-then-check (TOCTOU): a join or an exit that already landed before we subscribed.
7915
- if (s && a.handle.status() === "exited")
7215
+ if (this.shutdownReadiness.signal.aborted)
7216
+ onShutdown();
7217
+ else if (s && a.handle.status() === "exited")
7916
7218
  onExit();
7917
7219
  else
7918
7220
  onPresence();
@@ -7957,55 +7259,9 @@ export class Manager {
7957
7259
  if (!watched)
7958
7260
  console.error(`! ${a.name}: runtime "${handle.kind}" cannot prove a child exit (AgentHandle.waitForExit is not implemented) - it stays managed after it exits, until it is stopped`);
7959
7261
  }
7960
- /** Prune expired cooling stamps (drop those at/before now) and return the live count — the
7961
- * recycle floor's contribution to the ceiling (P4c). Lazy: pruned only when the gate consults it. */
7962
- coolingCount() {
7963
- const now = Date.now();
7964
- this.cooling = this.cooling.filter((stamp) => stamp > now);
7965
- return this.cooling.length;
7966
- }
7967
- /** What holds the ceiling's slots, one count per seat (#906). A launching seat sits in `reserved`
7968
- * from accept until its launch settles, in `agents` once its process exists, and in `cooling`
7969
- * if it then frees young, so a reservation stops counting once it reaches `agents`. `managed` is
7970
- * what this manager's `ps` lists, `reserved` is the accepted launches that have no process yet,
7971
- * and `launching` is every unsettled launch that still holds a slot through `reserved` or
7972
- * `agents`. A launch whose seat already freed holds no slot but its cooling stamp, so its
7973
- * failure can free nothing. */
7974
- occupancy() {
7975
- const cooling = this.coolingCount();
7976
- let reserved = 0;
7977
- let launching = 0;
7978
- for (const name of this.reserved.keys()) {
7979
- const placed = this.reservedLive.has(name);
7980
- if (!placed)
7981
- reserved++;
7982
- if (!placed || this.agents.has(name))
7983
- launching++;
7984
- }
7985
- const managed = this.agents.size;
7986
- return {
7987
- managed,
7988
- reserved,
7989
- cooling,
7990
- launching,
7991
- used: managed + reserved + cooling,
7992
- nextCoolingMs: cooling ? Math.min(...this.cooling) - Date.now() : undefined,
7993
- };
7994
- }
7995
- occupancyText(o) {
7996
- return `${o.used} of ${MAX_AGENTS} slots: ${o.managed} managed, ${o.reserved} reserved, ${o.cooling} cooling`;
7997
- }
7998
- /** The capacity refusal states the split it enforces and whether waiting can free a slot: a
7999
- * cooling slot frees at a known time, an unsettled launch frees one only if it fails, and a
8000
- * managed seat frees one only when it is stopped. */
8001
- capacityRefusal(o) {
8002
- const remedy = o.nextCoolingMs !== undefined
8003
- ? `waiting frees a cooling slot in ${Math.ceil(o.nextCoolingMs / 1000)}s, or despawn one`
8004
- : o.launching
8005
- ? `waiting frees a slot only if an unsettled launch fails (${o.launching} pending); otherwise despawn one`
8006
- : "waiting frees no slot; despawn one";
8007
- return `at capacity (${this.occupancyText(o)}); ${remedy}`;
8008
- }
7262
+ occupancy() { return this.namesCapacity.occupancy(); }
7263
+ occupancyText(o) { return this.namesCapacity.occupancyText(o); }
7264
+ capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
8009
7265
  /**
8010
7266
  * The owner a launch belongs to, read ONCE so the per-owner ceiling, the agent's addressing
8011
7267
  * triple and the user-mode provisioner cannot charge three different owners for one seat. A
@@ -8037,9 +7293,7 @@ export class Manager {
8037
7293
  for (const a of this.agents.values())
8038
7294
  if (this.seatOwner(a) === owner)
8039
7295
  seats++;
8040
- for (const [name, reservedFor] of this.reserved)
8041
- if (reservedFor === owner && !this.reservedLive.has(name))
8042
- seats++;
7296
+ seats += this.namesCapacity.ownerReservations(owner);
8043
7297
  return seats;
8044
7298
  }
8045
7299
  /**
@@ -8310,6 +7564,7 @@ export class Manager {
8310
7564
  * seats, as `ps` lists them ({@link psOwnerFilter}), so a person reading a shared Manager does not
8311
7565
  * learn how many seats other owners hold on it. */
8312
7566
  managerStatusData(ownerFilter) {
7567
+ this.refreshUnavailableConnectors();
8313
7568
  return {
8314
7569
  instanceId: this.managerInstanceId,
8315
7570
  lifecycleUid: this.managerLifecycleUid,
@@ -8332,10 +7587,10 @@ export class Manager {
8332
7587
  resumeRequired: this.resumeRequired,
8333
7588
  stopping: this.leaseStopping,
8334
7589
  lifecycleInFlight: this.lifecycleInFlight,
8335
- reservedLaunches: this.reserved.size,
7590
+ reservedLaunches: this.namesCapacity.reservedCount,
8336
7591
  retirementsPending: this.retirement.pendingCount,
8337
7592
  deprovisioningInFlight: this.retirement.inFlightCount,
8338
- staticReconciliationInFlight: this.staticReconcileSweepsInFlight,
7593
+ staticReconciliationInFlight: this.staticLifecycle.sweepsInFlight,
8339
7594
  agents: [...this.agents.values()]
8340
7595
  .filter((a) => ownerFilter === undefined || a.userOwner === ownerFilter)
8341
7596
  .map((a) => ({
@@ -8355,23 +7610,8 @@ export class Manager {
8355
7610
  },
8356
7611
  };
8357
7612
  }
8358
- /** Render the current operator snapshot. Recovered rows live until the next sweep starts, then
8359
- * clear, so recovery is visible without becoming stale process-lifetime history. */
8360
7613
  staticReconciliationStatus() {
8361
- const failures = [...this.staticReconcileItems.values()]
8362
- .map(({ owner: _owner, timer: _timer, flight: _flight, retryFlight: _retryFlight, ...item }) => ({ ...item }))
8363
- .sort((a, b) => a.alias.localeCompare(b.alias));
8364
- const state = this.staticReconcileLastSweep?.error !== undefined ? "failed" :
8365
- failures.some((item) => item.disposition === "retrying") ? "retrying" :
8366
- failures.some((item) => item.disposition === "retry-scheduled") ? "retry-wait" :
8367
- failures.some((item) => item.disposition === "refused" || item.disposition === "refused-foreign" || item.disposition === "retry-exhausted") ? "failed" :
8368
- this.staticReconcileSweepsInFlight > 0 ? "running" :
8369
- failures.some((item) => item.disposition === "recovered") ? "recovered" : "idle";
8370
- return {
8371
- state,
8372
- ...(this.staticReconcileLastSweep ? { lastSweep: { ...this.staticReconcileLastSweep } } : {}),
8373
- failures,
8374
- };
7614
+ return this.staticLifecycle.staticReconciliationStatus();
8375
7615
  }
8376
7616
  /** Complete a crashed predecessor's FROZEN registration gate before this incarnation starts a
8377
7617
  * new one (#783 item 3 / #871). The CLI `cotal reconcile-gate` already does this; a successor
@@ -8599,7 +7839,7 @@ export class Manager {
8599
7839
  // filters on (skip a goal whose accepting `iid` is a still-LIVE sibling — never settle its goal).
8600
7840
  for (const entry of entries) {
8601
7841
  const key = goalKey(entry.ref);
8602
- if (this.goalAcceptances.has(key) || this.turnAcceptances.has(key))
7842
+ if (this.goalAcceptances.has(key) || this.turnRelay.hasAcceptance(key))
8603
7843
  continue; // never settle a goal THIS incarnation drives
8604
7844
  try {
8605
7845
  // A note marks a TURN entry: its relay is rebuilt (the hold is its bounded ending), never
@@ -8621,11 +7861,11 @@ export class Manager {
8621
7861
  }
8622
7862
  finally {
8623
7863
  this.goalReconcileDone = true;
8624
- this.goalReconcileDoneAt = Date.now();
7864
+ this.turnRelay.markReconciled(Date.now());
8625
7865
  // A seat that pulled during the window was refused, and a predecessor may have died before
8626
7866
  // its notice went out, so every seat holding a rebuilt turn is told once.
8627
- const seats = new Map([...this.pendingTurns.values()].map((p) => [`${p.seat.owner}.${p.seat.actor}.${p.seat.uid}`, p.seat]));
8628
- for (const seat of seats.values())
7867
+ const seats = this.turnRelay.pendingSeats();
7868
+ for (const seat of seats)
8629
7869
  this.noticeSeatTurns(seat);
8630
7870
  }
8631
7871
  }
@@ -9050,178 +8290,10 @@ export class Manager {
9050
8290
  * path (idempotent retry map, index-CAS-before-bind, create-only bindGoal) but runs it INLINE:
9051
8291
  * there is no launch to hand off, so the accept either completes durably or unwinds its own
9052
8292
  * bound goal with a `failed` terminal before refusing. */
9053
- async serveTurnGoal(ctx, target) {
9054
- const gw = this.goalWriter;
9055
- if (!gw)
9056
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; turn-as-action cannot accept (SPEC 13.6)");
9057
- const serve = this.serviceServe;
9058
- if (!serve)
9059
- throw new EpEnvelopeError("unavailable", "the manager service endpoint is not serving; a turn's deadline hold is armed over its connection (SPEC 13.9)");
9060
- if (!this.goalReconcileDone)
9061
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; retry shortly (SPEC 13.6)");
9062
- const t = ctx.request.target; // targeted command: the serve boundary enforced presence + currency
9063
- const name = target.name;
9064
- const goalId = ctx.request.id;
9065
- const { fingerprint } = submissionFingerprint(ctx.request, ctx.subject);
9066
- const ref = goalRefOf(ctx.subject, goalId);
9067
- const key = goalKey(ref);
9068
- const executor = { lifecycleUid: this.managerInstanceId, epoch: this.serviceServe?.grant.epoch ?? 0 };
9069
- const acceptedAt = Date.now();
9070
- const prior = this.turnAcceptances.get(key)?.acceptance;
9071
- if (prior !== undefined) {
9072
- if (prior.fingerprint !== fingerprint)
9073
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted under a different submission; one goalId never carries two specs (SPEC 13.6)`);
9074
- return prior;
9075
- }
9076
- // Refused here, before anything durable, so the caller's goal id stays free for another seat.
9077
- this.assertSeatTurnFree(name, t, goalId);
9078
- if (target.kind === "managed" && target.agent.once)
9079
- throw new EpEnvelopeError("failed-precondition", `seat "${name}" is a once seat; it takes only the task it was spawned with`, undefined, "not-executed");
9080
- const raw = (ctx.request.args ?? {});
9081
- const payload = String(raw.payload);
9082
- const deadlineAt = raw.deadlineAt === undefined ? acceptedAt + Number(raw.deadlineMs) : Number(raw.deadlineAt);
9083
- if (deadlineAt <= acceptedAt)
9084
- 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)`);
9085
- const deadlineMs = deadlineAt - acceptedAt;
9086
- const handoffFrom = raw.handoffFrom === undefined ? undefined : String(raw.handoffFrom);
9087
- const holdToken = turnHoldToken(key);
9088
- const note = JSON.stringify({ payload, deadlineAt, holdEpoch: executor.epoch, holdToken, ...(handoffFrom !== undefined ? { handoffFrom } : {}) });
9089
- // A goal that already ENDED is never accepted again, whatever the retry carries: the bind is
9090
- // create-only and outlives an unwind (the failed terminal, the cleared index), so a retry of an
9091
- // unwound accept would otherwise re-record an index entry over a tombstone and, before that
9092
- // check existed, be served an acceptance rebuilt from it — a live deadline on a turn no seat
9093
- // would ever be shown. The terminal is the durable answer, and it is read before anything is
9094
- // written.
9095
- const ended = await readGoalResult(gw.ctx, ref);
9096
- if (ended !== undefined)
9097
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" already ended ${ended.state}; a bound goal is never accepted again (SPEC 13.6)`);
9098
- // Index-CAS-before-bind, exactly as spawn: the entry (floor + note) is the durable relay
9099
- // record a successor rebuilds from, so it must exist before the acceptance is servable.
9100
- const idx = await recordGoalIndex(gw.ctx, ref, executor.lifecycleUid, { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid, readinessDeadlineMs: deadlineMs }, note);
9101
- if (!idx.recorded && idx.existing.iid !== executor.lifecycleUid)
9102
- 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)`);
9103
- const b = await bindGoal(gw.ctx, ref, fingerprint);
9104
- if (!b.bound) {
9105
- if (b.existing.fingerprint !== fingerprint)
9106
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" is already bound to a different submission; one goalId never carries two specs (SPEC 13.6)`);
9107
- // Same submission, bound, not ended, and not in the acceptance map. Every relay this
9108
- // incarnation holds is in that map (the accept path and the boot sweep both write it), so
9109
- // this is a goal nobody is relaying: an earlier attempt bound it and could not finish its
9110
- // unwind, or a predecessor's relay was left unadopted. Nothing here can rebuild a relay a
9111
- // seat will be shown, so the caller is refused rather than served an acceptance no pending
9112
- // entry backs; the index entry this attempt recorded is withdrawn with it.
9113
- if (idx.recorded)
9114
- await clearGoalIndex(gw.ctx, ref);
9115
- throw new EpEnvelopeError("unavailable", `goal "${goalId}" is bound but no relay of it is pending on this instance; retry (SPEC 13.6)`);
9116
- }
9117
- try {
9118
- await createGoal(gw.ctx, ref, {
9119
- fingerprint,
9120
- command: ctx.subject.command,
9121
- caller: { id: `${ctx.subject.caller.owner}.${ctx.subject.caller.actor}`, lifecycleUid: ctx.subject.caller.uid },
9122
- acceptedEpoch: executor.epoch,
9123
- requestId: goalId,
9124
- sourceSeq: 0,
9125
- acceptedAt,
9126
- readinessDeadlineMs: deadlineMs,
9127
- // The §13.6 target pin: the seat INCARNATION this payload is addressed to. A successor
9128
- // under the same name is a different addressee; its uid differs and the pin holds that.
9129
- target: { owner: t.owner, actor: t.actor, lifecycleUid: t.lifecycleUid, mappingRevision: 0 },
9130
- });
9131
- // The deadline, as a goal-bound hold on the plane: its EXPIRED settle is the one predicate
9132
- // `commitGoalResult` accepts for the deny. The record rides the goal-writer's KV; the
9133
- // `.schedule` request rides the SERVE connection, because the timer row is the serving
9134
- // instance's own (`ept.<e>.<iid>.<epoch>.*.schedule`, SPEC 13.9) and the goal-writer holds
9135
- // none. Measured on an auth mesh: minted over the goal-writer, the schedule publish was
9136
- // broker-denied and every accept unwound.
9137
- await mintCheckpoint(gw.ctx.kv, jetstream(serve.nc), this.space, {
9138
- ref: { endpoint: ref.endpoint, token: holdToken },
9139
- instanceId: this.managerInstanceId,
9140
- epoch: executor.epoch,
9141
- goal: { caller: { owner: ctx.subject.caller.owner, actor: ctx.subject.caller.actor, uid: ctx.subject.caller.uid }, goalId },
9142
- holder: { id: MANAGER_ENDPOINT, lifecycleUid: this.managerInstanceId },
9143
- deadline: deadlineAt,
9144
- now: acceptedAt,
9145
- });
9146
- // Again after the awaits, with no await before the maps are written: another caller's
9147
- // accept of this id to this seat may have finished meanwhile, and this unwinds the loser.
9148
- this.assertSeatTurnFree(name, t, goalId);
9149
- }
9150
- catch (e) {
9151
- // The accept is inline (no launch closure to fail later), so a post-bind throw unwinds HERE:
9152
- // commit the failed terminal this attempt owns, clear the index, and refuse the accept — an
9153
- // accepted-but-unanswered goal must never be left for the boot sweep to find (H1's rule).
9154
- const msg = rejectionText(e);
9155
- try {
9156
- await this.assertGoalWriterEpochCurrent(executor.epoch);
9157
- // The goal is TARGET-PINNED, so its completion proves the seat's currency exactly as the
9158
- // yield's does (managed-seat epochs are 0 within an incarnation; the resolver answers from
9159
- // the live agents map). Committed without it, core refused the terminal and the unwind
9160
- // left a bound goal with no ending for every retry to find.
9161
- await commitGoalResult(gw.ctx, {
9162
- ref, now: Date.now(), cause: "complete", state: "failed", data: { error: msg },
9163
- committer: { instanceId: this.managerInstanceId, epoch: executor.epoch },
9164
- executor: { lifecycleUid: t.lifecycleUid, epoch: 0 },
9165
- resolveCurrentEpoch: (current) => this.turnExecutorEpoch(name, t.owner, t.actor, current.lifecycleUid),
9166
- });
9167
- await clearGoalIndex(gw.ctx, ref);
9168
- }
9169
- catch (e2) {
9170
- console.error(`! turn accept unwind for ${goalId}: ${rejectionText(e2)}`);
9171
- }
9172
- throw caughtEnvelope(e) ?? new EpEnvelopeError("internal", `turn accept for ${goalId} failed: ${msg}`);
9173
- }
9174
- const pending = {
9175
- ref, goalId,
9176
- seat: { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid },
9177
- payload, acceptedAt, deadlineAt,
9178
- holdToken, holdEpoch: executor.epoch,
9179
- ...(handoffFrom !== undefined ? { handoffFrom } : {}),
9180
- };
9181
- this.pendingTurns.set(key, pending);
9182
- this.ensureTurnSweep();
9183
- this.noticeSeatTurns(pending.seat);
9184
- const acceptance = { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid, goalId, fingerprint, deadlineAt, executor };
9185
- this.turnAcceptances.set(key, { acceptance, ref });
9186
- this.emitGoalProgress(ref, executor.epoch, { phase: "relayed" });
9187
- return acceptance;
9188
- }
8293
+ serveTurnGoal(ctx, target) { return this.turnRelay.serveTurnGoal(ctx, target); }
9189
8294
  /** The seat's pull: every pending turn addressed to the CALLER's incarnation, oldest first.
9190
8295
  * The uid is part of the address — a successor seat never receives a predecessor's turn. */
9191
- turnPendingFor(c) {
9192
- // AN EMPTY LIST IS AN ANSWER, so it must not be given before the index is rebuilt. Between
9193
- // registration and `reconcileGoalIndex`, `pendingTurns` holds nothing a predecessor accepted,
9194
- // and a seat that pulls in that window is told authoritatively that it has no turn. The seat
9195
- // treats a refusal as "keep what you hold" and an empty list as "you hold nothing", so the
9196
- // window has to refuse, the same way `serveTurnGoal` does.
9197
- if (!this.goalReconcileDone)
9198
- 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)");
9199
- // A once seat this manager does not hold, whose task has ended, is told to end itself. Nothing
9200
- // else rides that answer, and the settled task is never served again.
9201
- const stop = this.onceStops.get(c.uid);
9202
- if (stop !== undefined && stop.owner === c.owner && stop.actor === c.actor) {
9203
- stop.told = true;
9204
- return { turns: [], notices: true, stop: true };
9205
- }
9206
- // Two turns on one seat are serialized at the dispatch (cotal-lang 6.5): only the oldest
9207
- // unsettled one is served, and the next surfaces once it yields or its deadline denies, so a
9208
- // seat is never shown two turns at once.
9209
- // An ELAPSED turn is not servable: its hold is expirable and its run has already thrown from
9210
- // its own pause, so handing it to the seat buys work whose yield is refused. It also cannot be
9211
- // allowed to stay the head, or one expired turn dams every later turn for that seat. A once
9212
- // task is not served before its spawn's readiness verdict, and one with no deadline never
9213
- // elapses.
9214
- const now = Date.now();
9215
- const head = [...this.pendingTurns.values()]
9216
- .filter((p) => p.seat.owner === c.owner && p.seat.actor === c.actor && p.seat.uid === c.uid)
9217
- .filter((p) => (p.deadlineAt === undefined || now < p.deadlineAt) && p.once?.deliverable !== false)
9218
- .sort((x, y) => x.acceptedAt - y.acceptedAt)
9219
- .slice(0, 1);
9220
- for (const p of head)
9221
- p.pulledAt ??= now;
9222
- const turns = head.map((p) => ({ goalId: p.goalId, payload: p.payload, acceptedAt: p.acceptedAt, ...(p.deadlineAt !== undefined ? { deadlineAt: p.deadlineAt } : {}), ...(p.once ? { once: true } : {}) }));
9223
- return { turns, notices: true };
9224
- }
8296
+ turnPendingFor(c) { return this.turnRelay.turnPendingFor(c); }
9225
8297
  /** Tell a seat that its `turn-pending` answer changed (SPEC 14.3 turn notice), over the serve
9226
8298
  * connection that holds this instance's reply rows. The notice carries no turn and the seat
9227
8299
  * pulls on it, so a lost notice delays that seat until its next pull, and nothing else. */
@@ -9241,163 +8313,17 @@ export class Manager {
9241
8313
  console.error(`! turn notice for ${seat.actor} failed: ${rejectionText(e)}`);
9242
8314
  }
9243
8315
  }
9244
- /** A seat names a turn by goal id alone when it yields, so one incarnation holding two callers'
9245
- * turns under one id could not say which of the two it answered. */
9246
- assertSeatTurnFree(name, t, goalId) {
9247
- if (this.seatTurnKey({ owner: t.owner, actor: t.actor, uid: t.lifecycleUid }, goalId) !== undefined)
9248
- 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)`);
9249
- }
9250
- /** The relay key of the turn addressed to seat incarnation `c` under `goalId`, pending or kept
9251
- * for a retried yield. The accept path never hands one incarnation two turns under one goal
9252
- * id, so at most one matches. */
9253
- seatTurnKey(c, goalId) {
9254
- for (const [key, { acceptance: a }] of this.turnAcceptances)
9255
- if (a.goalId === goalId && a.owner === c.owner && a.actor === c.actor && a.uid === c.uid)
9256
- return key;
9257
- return undefined;
9258
- }
9259
8316
  /** The seat's yield: claim the hold (one-use; expiry fails closed), then commit the goal
9260
8317
  * `succeeded` carrying the TurnResult. A yield AFTER the deadline drives the deadline terminal
9261
8318
  * instead and refuses — the expiry outcome stands, never a late success over it. */
9262
- async serveTurnYield(c, raw) {
9263
- if (this.execution === "none")
9264
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
9265
- // Same boot window as the pull, and checked first because it is the earlier boot phase: before
9266
- // the index is rebuilt a predecessor's accepted turn is not in `pendingTurns`, and `not-found`
9267
- // would tell the seat to drop work it is holding.
9268
- if (!this.goalReconcileDone)
9269
- 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)");
9270
- const gw = this.goalWriter;
9271
- if (!gw)
9272
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
9273
- const goalId = String(raw.goalId);
9274
- const status = String(raw.status);
9275
- const to = raw.to === undefined ? undefined : String(raw.to);
9276
- const yieldNote = raw.note === undefined ? undefined : String(raw.note);
9277
- if (status === "handoff" && (to === undefined || to.length === 0))
9278
- throw new EpEnvelopeError("failed-precondition", `a handoff yield names its addressee ("to"); a handoff to nobody relays nothing`);
9279
- const key = this.seatTurnKey(c, goalId);
9280
- if (key === undefined)
9281
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
9282
- const p = this.pendingTurns.get(key);
9283
- if (!p)
9284
- return this.settledTurnAnswer(key, goalId);
9285
- await this.claimTurnHold(p);
9286
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9287
- await this.assertGoalWriterEpochCurrent(epoch);
9288
- const at = Date.now();
9289
- const data = { status, ...(to !== undefined ? { to } : {}), ...(yieldNote !== undefined ? { note: yieldNote } : {}), ...(p.handoffFrom !== undefined ? { handoffFrom: p.handoffFrom } : {}), at };
9290
- // The goal is TARGET-PINNED, so this completion proves the EXECUTOR's (the seat's) fresh
9291
- // currency, not the manager's: managed-seat epochs are 0 within an incarnation (the same
9292
- // convention resolveTarget serves), and the resolver answers from the live agents map — a
9293
- // seat that died between its yield call and this commit refuses `expired` here.
9294
- const { fact } = await commitGoalResult(gw.ctx, {
9295
- ref: p.ref, now: at, cause: "complete", state: "succeeded", data,
9296
- committer: { instanceId: this.managerInstanceId, epoch },
9297
- executor: { lifecycleUid: p.seat.uid, epoch: 0 },
9298
- resolveCurrentEpoch: (target) => this.turnExecutorEpoch(p.seat.name, p.seat.owner, p.seat.actor, target.lifecycleUid),
9299
- });
9300
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9301
- // A once task's index entry is its seat's debt, dropped at the seat's proved exit.
9302
- if (!p.once)
9303
- await clearGoalIndex(gw.ctx, p.ref);
9304
- this.pendingTurns.delete(key);
9305
- this.noticeSeatTurns(p.seat);
9306
- this.markTurnLatchDropped(key, at);
9307
- this.rememberSettledTurn(key, fact.state, at);
9308
- if (p.once)
9309
- this.endOnceSeat(p, `yielded ${status}`);
9310
- this.maybeStopTurnSweep();
9311
- return { goalId, state: fact.state };
9312
- }
9313
- /** A seat's answer for a turn no longer pending. A REPLY THAT WAS LOST IS NOT AN ANSWER THAT
9314
- * FAILED: the commit deleted the pending turn, so a retry found nothing and heard `not-found`,
9315
- * which a seat reads as "drop it", reporting failure for work the run already has. The answer
9316
- * the first reply carried is served again instead, to the addressee it was addressed to and
9317
- * nobody else. */
9318
- async settledTurnAnswer(key, goalId) {
9319
- const settled = this.turnAcceptances.get(key);
9320
- if (settled !== undefined) {
9321
- if (settled.settled !== undefined)
9322
- return { goalId, state: settled.settled.state };
9323
- // The in-memory answer is not yet remembered (pending deleted before the terminal CAS,
9324
- // or a concurrent sweep dropped `settled` while the commit was still in flight). The
9325
- // durable terminal is the one the run already has; name it, never `not-found`.
9326
- if (settled.ref !== undefined && this.goalWriter) {
9327
- const ended = await readGoalResult(this.goalWriter.ctx, settled.ref);
9328
- if (ended !== undefined) {
9329
- this.rememberSettledTurn(key, ended.state, ended.ts);
9330
- return { goalId, state: ended.state };
9331
- }
9332
- }
9333
- }
9334
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
9335
- }
9336
- /** Claim a pending turn's deadline hold before the seat's answer commits: one use, and a hold
9337
- * that already expired drives the deadline terminal instead and refuses the answer. A once task
9338
- * with no deadline has no hold. */
9339
- async claimTurnHold(p) {
9340
- if (p.holdToken === undefined)
9341
- return;
9342
- const gw = this.goalWriter;
9343
- const cpRef = { endpoint: p.ref.endpoint, token: p.holdToken };
9344
- try {
9345
- 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() });
9346
- }
9347
- catch (e) {
9348
- const settle = await readCheckpointSettle(gw.ctx.jsm, this.space, cpRef).catch(() => undefined);
9349
- if (settle?.settle === "expired") {
9350
- await this.commitTurnDeadline(p);
9351
- throw new EpEnvelopeError("failed-precondition", `turn "${p.goalId}" elapsed its deadline before the seat answered; the deadline terminal stands (SPEC 13.6)`);
9352
- }
9353
- // Already resumed BY THIS MANAGER (the hold is holder-bound): a prior attempt claimed it
9354
- // and then failed to commit. Fall through and commit; the claim is ours to finish.
9355
- if (settle?.settle !== "resumed")
9356
- throw e;
9357
- }
9358
- }
8319
+ serveTurnYield(c, raw) { return this.turnRelay.serveTurnYield(c, raw); }
9359
8320
  /** A once seat's report that its task's handoff to its harness was not confirmed. The seat sealed
9360
8321
  * the task before it reported, so nothing hands it over again; the task fails
9361
8322
  * `delivery-unconfirmed` and the seat is stopped. The commit proves the seat's live currency, as
9362
8323
  * a yield's does: a seat already gone commits nothing here, and its exit cancels the task. Only
9363
8324
  * the addressed seat may report, only for its once task; a repeat after the terminal is answered
9364
8325
  * with it. */
9365
- async serveTurnUnconfirmed(c, raw) {
9366
- if (this.execution === "none")
9367
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
9368
- if (!this.goalReconcileDone)
9369
- 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)");
9370
- const gw = this.goalWriter;
9371
- if (!gw)
9372
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
9373
- const goalId = String(raw.goalId);
9374
- const key = this.seatTurnKey(c, goalId);
9375
- if (key === undefined)
9376
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
9377
- const p = this.pendingTurns.get(key);
9378
- if (!p)
9379
- return this.settledTurnAnswer(key, goalId);
9380
- if (!p.once)
9381
- 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`);
9382
- await this.claimTurnHold(p);
9383
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9384
- await this.assertGoalWriterEpochCurrent(epoch);
9385
- const at = Date.now();
9386
- const { fact } = await commitGoalResult(gw.ctx, {
9387
- ref: p.ref, now: at, cause: "complete", state: "failed", data: { reason: "delivery-unconfirmed", at },
9388
- committer: { instanceId: this.managerInstanceId, epoch },
9389
- executor: { lifecycleUid: p.seat.uid, epoch: 0 },
9390
- resolveCurrentEpoch: (target) => this.turnExecutorEpoch(p.seat.name, p.seat.owner, p.seat.actor, target.lifecycleUid),
9391
- });
9392
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9393
- this.pendingTurns.delete(key);
9394
- this.noticeSeatTurns(p.seat);
9395
- this.markTurnLatchDropped(key, at);
9396
- this.rememberSettledTurn(key, fact.state, at);
9397
- this.endOnceSeat(p, "delivery-unconfirmed");
9398
- this.maybeStopTurnSweep();
9399
- return { goalId, state: fact.state };
9400
- }
8326
+ serveTurnUnconfirmed(c, raw) { return this.turnRelay.serveTurnUnconfirmed(c, raw); }
9401
8327
  /** The caller withdraws a turn it submitted (the reserved `cancel`, SPEC 13.6 item 4), so the
9402
8328
  * seat is not shown it again and a late yield is answered from the cancelled terminal. Only a
9403
8329
  * relay this incarnation holds is moved to `cancelling`, because only its holder can commit the
@@ -9408,317 +8334,20 @@ export class Manager {
9408
8334
  * held: a yield that read the entry first, or this commit with only its reply lost. An entry
9409
8335
  * whose outcome cannot be read back stays out and converges through the goal index at the
9410
8336
  * next boot, as a failed deadline commit does. */
9411
- async serveTurnCancel(ctx) {
9412
- if (this.execution === "none")
9413
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
9414
- if (!this.goalReconcileDone)
9415
- 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)");
9416
- const gw = this.goalWriter;
9417
- if (!gw)
9418
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
9419
- const raw = (ctx.request.args ?? {});
9420
- const goalId = String(raw.goalId);
9421
- const ref = goalRefOf(ctx.subject, goalId);
9422
- const key = goalKey(ref);
9423
- const p = this.pendingTurns.get(key);
9424
- if (p === undefined) {
9425
- const ended = await readGoalResult(gw.ctx, ref);
9426
- if (ended !== undefined)
9427
- throw goalAlreadyTerminal(goalId, ended);
9428
- throw new EpEnvelopeError("failed-precondition", `no turn "${goalId}" of this caller is pending on this manager; cancel withdraws a relayed turn (SPEC 13.6)`);
9429
- }
9430
- this.pendingTurns.delete(key);
9431
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9432
- let fact;
9433
- try {
9434
- await requestGoalCancel(gw.ctx, { request: ctx.subject, goalId, mode: (raw.mode ?? "graceful") });
9435
- await this.assertGoalWriterEpochCurrent(epoch);
9436
- ({ fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "caller" }, committer: { instanceId: this.managerInstanceId, epoch } }));
9437
- }
9438
- catch (e) {
9439
- // The remembered answer is read after the durable one, with no await before the put back:
9440
- // a yield that has dropped the entry remembered its answer, and one still committing drops
9441
- // the entry it finds. An ended relay is stamped so its acceptance still ages off.
9442
- if ((await readGoalResult(gw.ctx, ref)) !== undefined)
9443
- this.markTurnLatchDropped(key);
9444
- else if (this.turnAcceptances.get(key)?.settled === undefined)
9445
- this.pendingTurns.set(key, p);
9446
- throw e;
9447
- }
9448
- this.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9449
- this.noticeSeatTurns(p.seat);
9450
- this.markTurnLatchDropped(key);
9451
- this.rememberSettledTurn(key, fact.state, Date.now());
9452
- if (p.once)
9453
- this.endOnceSeat(p, "cancelled");
9454
- else
9455
- await clearGoalIndex(gw.ctx, ref);
9456
- this.maybeStopTurnSweep();
9457
- return { goalId, state: fact.state };
9458
- }
9459
- /** Commit the deadline terminal for one pending turn whose hold settled EXPIRED: the deny's
9460
- * predicate is that recorded settle, verified by core against the spec's goal binding. The map
9461
- * delete is the idempotency latch (yield-loss and sweep race here); a commit failure after it
9462
- * converges through the goal index at the next boot, the same narrow leg spawn leaves open. */
9463
- async commitTurnDeadline(p) {
9464
- const gw = this.goalWriter;
9465
- if (!gw)
9466
- return;
9467
- const key = goalKey(p.ref);
9468
- if (!this.pendingTurns.delete(key))
9469
- return;
9470
- this.noticeSeatTurns(p.seat);
9471
- this.markTurnLatchDropped(key);
9472
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9473
- try {
9474
- await this.assertGoalWriterEpochCurrent(epoch);
9475
- 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 } });
9476
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9477
- // Remember BEFORE the index clear: a late yield that arrives after the pending latch
9478
- // (the delete at the top of this function) and after this CAS has to name this terminal.
9479
- // Clearing first, then remembering, left a window where maybeStopTurnSweep saw no pending
9480
- // turn and no settled answer, wiped the acceptance, and rememberSettledTurn no-op'd.
9481
- this.rememberSettledTurn(key, fact.state, Date.now());
9482
- if (p.once)
9483
- this.endOnceSeat(p, "turn-deadline");
9484
- else
9485
- await clearGoalIndex(gw.ctx, p.ref);
9486
- }
9487
- catch (e) {
9488
- console.error(`! turn deadline terminal for ${p.goalId}: ${rejectionText(e)}`);
9489
- // A once seat stops at its deadline whether or not the terminal landed, and the task stays
9490
- // pending so the turn sweep writes the terminal again while this manager runs.
9491
- if (p.once) {
9492
- this.pendingTurns.set(key, p);
9493
- this.endOnceSeat(p, "turn-deadline");
9494
- this.ensureTurnSweep();
9495
- }
9496
- }
9497
- this.maybeStopTurnSweep();
9498
- }
8337
+ serveTurnCancel(ctx) { return this.turnRelay.serveTurnCancel(ctx); }
9499
8338
  /** The reap hook: a pending turn addressed to the reaped INCARNATION is MARKED dead, never
9500
8339
  * settled early — no honest terminal exists for it (a completion must prove the executor's
9501
8340
  * live currency, and the hold is only expirable once due), so the entry rides to its deadline
9502
8341
  * and the deny then records both facts. The addressee's own client observes the death from
9503
8342
  * presence long before that, which is the run's L4002. */
9504
- failSeatTurns(name, uid) {
9505
- for (const p of this.pendingTurns.values()) {
9506
- if (p.seat.name !== name || p.seat.uid !== uid || p.seatDiedAt !== undefined)
9507
- continue;
9508
- p.seatDiedAt = Date.now();
9509
- console.error(`turn ${p.goalId}: addressed seat ${name}/${uid} died before yielding; the deadline terminal will record it`);
9510
- }
9511
- }
9512
- /** Settle one DUE hold as its owner: the manager minted it, so once the deadline has passed it
9513
- * expires the pause itself ({@link expireCheckpoint}, the guard-hold precedent) rather than
9514
- * waiting on the broker's fire — which it holds no grant to read, and which a hold minted under
9515
- * a predecessor's epoch would carry on a subject this incarnation never subscribes. Idempotent
9516
- * by the plane: a yield that claimed the hold first is observed as `resumed` and left to its
9517
- * own commit, and an already-expired hold returns its recorded settle. */
9518
- async expireTurnHold(p) {
9519
- const gw = this.goalWriter;
9520
- if (!gw)
9521
- return undefined;
9522
- return expireCheckpoint(gw.ctx.kv, gw.ctx.js, gw.ctx.jsm, this.space, { ref: { endpoint: p.ref.endpoint, token: p.holdToken }, now: Date.now() });
9523
- }
9524
- ensureTurnSweep() {
9525
- if (this.turnSweepTimer !== undefined)
9526
- return;
9527
- const t = setInterval(() => { void this.sweepTurnDeadlines().catch((e) => console.error(`! turn deadline sweep: ${rejectionText(e)}`)); }, TURN_SWEEP_MS);
9528
- t.unref?.();
9529
- this.turnSweepTimer = t;
9530
- }
9531
- /** The answer a retried yield is served, held for {@link TURN_ANSWER_RETENTION_MS}. Only for a
9532
- * turn this incarnation accepted: an entry it has no acceptance for is one it cannot vouch for. */
9533
- rememberSettledTurn(key, state, at) {
9534
- const entry = this.turnAcceptances.get(key);
9535
- if (entry === undefined)
9536
- return;
9537
- entry.settled = { state, at };
9538
- }
9539
- /** Stamp when the pending latch dropped, so an unsettled leftover ages off that instant rather
9540
- * than the original deadline. Idempotent: the first drop is the one the retry window starts at. */
9541
- markTurnLatchDropped(key, at = Date.now()) {
9542
- const entry = this.turnAcceptances.get(key);
9543
- if (entry === undefined || entry.leftoverSince !== undefined)
9544
- return;
9545
- entry.leftoverSince = at;
9546
- }
9547
- /** Stop the sweep only when it has nothing left to do. It drives elapsed turns to their deadline
9548
- * terminals AND drops settled answers once their retry window has passed, so a stop while the
9549
- * second is still owed would leave one entry per turn for the process lifetime. */
9550
- maybeStopTurnSweep() {
9551
- if (this.pendingTurns.size > 0 || this.onceSettles.size > 0 || this.onceInherited.size > 0 || [...this.onceStops.values()].some((s) => !s.told))
9552
- return;
9553
- // An acceptance with no `settled` yet is the in-flight deadline commit: pending was the
9554
- // latch and is already gone, the terminal CAS has not returned, and a concurrent sweep
9555
- // tick used to clear the map here, so rememberSettledTurn no-op'd and a late yield heard
9556
- // `not-found` for a deny the run already has. Prune is the only deleter; stop only when
9557
- // it has left nothing.
9558
- if (this.turnAcceptances.size > 0)
9559
- return;
9560
- this.stopTurnSweep();
9561
- }
9562
- stopTurnSweep() {
9563
- if (this.turnSweepTimer === undefined)
9564
- return;
9565
- clearInterval(this.turnSweepTimer);
9566
- this.turnSweepTimer = undefined;
9567
- }
9568
- /** Drive every elapsed pending turn to its deadline terminal. Only entries at/past their own
9569
- * `deadlineAt` are read at all; a `resumed` settle is a yield mid-commit and is left alone. */
9570
- async sweepTurnDeadlines() {
9571
- const now = Date.now();
9572
- // A settled answer is kept only as long as a lost reply could still be retried under it.
9573
- // An UNSETTLED acceptance whose pending latch is already gone is the in-flight (or failed)
9574
- // deadline commit: keep it for the same window so a late yield can still read the durable
9575
- // terminal, then drop it so a commit that never remembered cannot pin the sweep forever.
9576
- for (const [key, e] of [...this.turnAcceptances.entries()]) {
9577
- if (this.pendingTurns.has(key))
9578
- continue;
9579
- // Unsettled leftovers age off the latch-drop stamp, never `deadlineAt`.
9580
- const at = e.settled?.at ?? e.leftoverSince;
9581
- if (at !== undefined && now - at >= TURN_ANSWER_RETENTION_MS)
9582
- this.turnAcceptances.delete(key);
9583
- }
9584
- // The prune above is the one event after which the sweep may have nothing left to do, and
9585
- // the settle-time callers cannot see it: they run when an answer has just been remembered.
9586
- this.maybeStopTurnSweep();
9587
- // A notice is at-most-once, so a seat offline when it went out has not pulled its head turn.
9588
- // Repeat the notice until it does; a seat that pulled is not told again for that turn.
9589
- const heads = new Map();
9590
- for (const p of this.pendingTurns.values()) {
9591
- if ((p.deadlineAt !== undefined && now >= p.deadlineAt) || p.once?.deliverable === false)
9592
- continue;
9593
- const k = `${p.seat.owner}.${p.seat.actor}.${p.seat.uid}`;
9594
- const h = heads.get(k);
9595
- if (h === undefined || p.acceptedAt < h.acceptedAt)
9596
- heads.set(k, p);
9597
- }
9598
- for (const p of heads.values())
9599
- if (p.pulledAt === undefined)
9600
- this.noticeSeatTurns(p.seat);
9601
- for (const stop of this.onceStops.values())
9602
- if (!stop.told)
9603
- this.noticeSeatTurns(stop);
9604
- for (const owed of [...this.onceSettles.values()])
9605
- if (!owed.flight)
9606
- void this.settleOnceTurn(owed.ref, owed.reason);
9607
- if (this.onceInherited.size > 0)
9608
- await this.settleInheritedOnce().catch((e) => console.error(`! inherited once tasks: ${rejectionText(e)}`));
9609
- for (const p of [...this.pendingTurns.values()]) {
9610
- if (p.deadlineAt === undefined || now < p.deadlineAt)
9611
- continue;
9612
- try {
9613
- const settle = await this.expireTurnHold(p);
9614
- if (settle?.settle === "expired")
9615
- await this.commitTurnDeadline(p);
9616
- }
9617
- catch (e) {
9618
- console.error(`! turn deadline sweep for ${p.goalId}: ${rejectionText(e)}`);
9619
- }
9620
- }
9621
- }
8343
+ failSeatTurns(name, uid) { return this.turnRelay.failSeatTurns(name, uid); }
9622
8344
  /** Adopt one inherited TURN goal at boot (the reconcile sweep's turn branch): a non-terminal
9623
8345
  * entry carrying a parseable note rebuilds its pending relay — never an `uncertain` settle,
9624
8346
  * because the deadline hold IS this goal's bounded ending and it survived the restart. No
9625
8347
  * liveness verdict is made here (the agents map is empty during reconcile, so absence means
9626
8348
  * "not yet re-registered", never "dead"); a garbled note or a floor that does not name the
9627
8349
  * seat's owner is logged and left, the dead-pointer honesty rule. */
9628
- async adoptTurnGoal(entry) {
9629
- const gw = this.goalWriter;
9630
- if (!gw)
9631
- return;
9632
- const status = await readGoalStatus(gw.ctx, entry.ref);
9633
- if (status === undefined)
9634
- return; // index points at no goal record: a dead pointer, left for honesty
9635
- const parsed = entry.note !== undefined ? parseTurnNote(entry.note) : undefined;
9636
- const ownOnce = parsed?.once === true && entry.iid === this.managerInstanceId && entry.allocated?.owner !== undefined;
9637
- if (GOAL_TERMINAL_STATES.includes(status.value.state)) {
9638
- // A once task's entry is its seat's debt until that seat's exit is proved, so it outlives
9639
- // the terminal: the stop the predecessor owed may never have landed.
9640
- if (ownOnce)
9641
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9642
- else
9643
- await clearGoalIndex(gw.ctx, entry.ref);
9644
- return;
9645
- }
9646
- if (entry.iid !== this.managerInstanceId) {
9647
- 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)`);
9648
- return;
9649
- }
9650
- if (entry.allocated?.owner === undefined || parsed === undefined) {
9651
- 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`);
9652
- return;
9653
- }
9654
- const spec = await readGoalSpec(gw.ctx, entry.ref);
9655
- if (spec === undefined) {
9656
- // NOW IS NOT WHEN THIS WAS ACCEPTED. `acceptedAt` is what orders a seat's queue, and a turn
9657
- // stamped with the boot instant sorts BEHIND every turn accepted since — a predecessor's
9658
- // oldest turn served last, which is the one thing the ordering exists to prevent. A goal
9659
- // with an index entry and no spec is a relay record that is not readable, and this is the
9660
- // same verdict the garbled-note branch above reaches: left unsettled, said out loud.
9661
- 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`);
9662
- return;
9663
- }
9664
- const p = {
9665
- ref: entry.ref, goalId: entry.ref.goalId,
9666
- seat: { name: entry.allocated.name, owner: entry.allocated.owner, actor: entry.allocated.actor, uid: entry.allocated.uid },
9667
- payload: parsed.payload,
9668
- acceptedAt: spec.value.acceptedAt,
9669
- holdEpoch: parsed.holdEpoch,
9670
- ...(parsed.deadlineAt !== undefined ? { deadlineAt: parsed.deadlineAt, holdToken: parsed.holdToken ?? turnHoldToken(entry.ref.goalId) } : {}),
9671
- ...(parsed.handoffFrom !== undefined ? { handoffFrom: parsed.handoffFrom } : {}),
9672
- // An inherited once task is served again only once its seat is bound to this incarnation.
9673
- ...(parsed.once ? { once: { deliverable: false } } : {}),
9674
- };
9675
- // The hold is the relay's bounded ending, minted AFTER the index entry and the goal record,
9676
- // so a crash between them leaves a goal with no hold: nothing could ever settle it, and the
9677
- // sweep would report the same missing pause every tick. Left unsettled, said once.
9678
- if (p.holdToken !== undefined && (await readCheckpointSpec(gw.ctx.kv, { endpoint: p.ref.endpoint, token: p.holdToken })) === undefined) {
9679
- // A once task's hold is minted before its seat launches, so without one no seat ever ran it:
9680
- // the task is cancelled and its entry dropped, with nothing launched to prove gone.
9681
- if (parsed.once) {
9682
- await this.settleOnceTurn(p.ref, "launch-failed");
9683
- return;
9684
- }
9685
- console.error(`turn reconcile ${p.goalId}: its deadline hold was never minted (the accept crashed before it); left unsettled`);
9686
- return;
9687
- }
9688
- // A once task whose spawn has no succeeded terminal was never served, whatever seat exists:
9689
- // it is cancelled, its row is not rebuilt so a later pull finds nothing, and its seat is
9690
- // settled as an inherited debt.
9691
- if (parsed.once && !(await this.onceServed(entry.ref, parsed))) {
9692
- await this.commitOnceCancel(entry.ref, NEVER_SERVED);
9693
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9694
- return;
9695
- }
9696
- const key = goalKey(p.ref);
9697
- this.pendingTurns.set(key, p);
9698
- // THE ACCEPTANCE TOO, or the adopted turn's answer is never remembered: `rememberSettledTurn`
9699
- // writes only against an acceptance this incarnation holds, and adoption rebuilt the pending
9700
- // relay without one, so a yield whose reply was lost after a restart still heard `not-found`
9701
- // on the very path adoption exists for. The acceptance is rebuilt from the same records the
9702
- // relay was: the spec holds the fingerprint, the index holds the seat, the note the deadline.
9703
- this.turnAcceptances.set(key, {
9704
- acceptance: {
9705
- name: p.seat.name, owner: p.seat.owner, actor: p.seat.actor, uid: p.seat.uid, goalId: p.goalId,
9706
- fingerprint: spec.value.fingerprint, deadlineAt: p.deadlineAt,
9707
- executor: { lifecycleUid: this.managerInstanceId, epoch: p.holdEpoch },
9708
- },
9709
- ref: p.ref,
9710
- });
9711
- // NO LIVENESS VERDICT AT BOOT. The agents map is empty here: seats are re-registered later,
9712
- // by the resume path, so `not in the map` at this moment means "not yet re-registered", never
9713
- // "dead". Stamping death from it marked EVERY adopted turn as a dead seat, and its deadline
9714
- // terminal then carried `agentDownAt`, so the run raised L4002 for a seat that was alive the
9715
- // whole time where the reference says L4003. The reap hook is the only honest writer of that
9716
- // fact: it fires when a managed seat actually dies.
9717
- console.error(`turn reconcile ${p.goalId}: pending relay to ${p.seat.name}/${p.seat.uid} adopted (deadline ${p.deadlineAt ?? "none"})`);
9718
- if (parsed.once)
9719
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9720
- this.ensureTurnSweep();
9721
- }
8350
+ adoptTurnGoal(entry) { return this.turnRelay.adoptTurnGoal(entry); }
9722
8351
  // ---- once (a spawn whose prompt is its one relayed task) ----------------------------------------
9723
8352
  //
9724
8353
  // A once spawn's prompt is not a kickoff: the manager accepts it as one turn addressed to the
@@ -9732,77 +8361,7 @@ export class Manager {
9732
8361
  * the goal ref and the seat given rather than read off a request. A task with no deadline mints
9733
8362
  * no hold; its goal still records the spawn's readiness budget, which a successor needs to settle
9734
8363
  * it. */
9735
- async acceptOnceTurn(o) {
9736
- const gw = this.goalWriter;
9737
- if (!gw)
9738
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; a once task cannot be accepted (SPEC 13.6)");
9739
- const serve = this.serviceServe;
9740
- if (o.deadlineMs !== undefined && !serve)
9741
- 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)");
9742
- const ref = { endpoint: o.spawnRef.endpoint, caller: { ...o.spawnRef.caller }, goalId: digestIdToken(`${o.spawnRef.goalId}:once`) };
9743
- const key = goalKey(ref);
9744
- const deadlineAt = o.deadlineMs === undefined ? undefined : o.acceptedAt + o.deadlineMs;
9745
- if (deadlineAt !== undefined && deadlineAt > MAX_SCHEDULE_MS)
9746
- throw new EpEnvelopeError("failed-precondition", `once: the deadline ends after the deadline scheduler's last instant (the end of year 9999)`);
9747
- const holdToken = deadlineAt === undefined ? undefined : turnHoldToken(key);
9748
- 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 });
9749
- const { seat } = o;
9750
- 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);
9751
- if (!idx.recorded)
9752
- throw new EpEnvelopeError("failed-precondition", `once: the task goal "${ref.goalId}" is already recorded; a spawn accepts its task once (SPEC 13.6)`);
9753
- const b = await bindGoal(gw.ctx, ref, o.fingerprint);
9754
- if (!b.bound) {
9755
- await clearGoalIndex(gw.ctx, ref);
9756
- throw new EpEnvelopeError("failed-precondition", `once: the task goal "${ref.goalId}" is already bound; a spawn accepts its task once (SPEC 13.6)`);
9757
- }
9758
- try {
9759
- await createGoal(gw.ctx, ref, {
9760
- fingerprint: o.fingerprint,
9761
- command: o.command,
9762
- caller: { id: `${ref.caller.owner}.${ref.caller.actor}`, lifecycleUid: ref.caller.uid },
9763
- acceptedEpoch: o.executor.epoch,
9764
- requestId: ref.goalId,
9765
- sourceSeq: 0,
9766
- acceptedAt: o.acceptedAt,
9767
- readinessDeadlineMs: o.readinessDeadlineMs,
9768
- target: { owner: seat.owner, actor: seat.actor, lifecycleUid: seat.uid, mappingRevision: 0 },
9769
- });
9770
- if (deadlineAt !== undefined)
9771
- await mintCheckpoint(gw.ctx.kv, jetstream(serve.nc), this.space, {
9772
- ref: { endpoint: ref.endpoint, token: holdToken },
9773
- instanceId: this.managerInstanceId,
9774
- epoch: o.executor.epoch,
9775
- goal: { caller: { ...ref.caller }, goalId: ref.goalId },
9776
- holder: { id: MANAGER_ENDPOINT, lifecycleUid: this.managerInstanceId },
9777
- deadline: deadlineAt,
9778
- now: o.acceptedAt,
9779
- });
9780
- }
9781
- catch (e) {
9782
- // Nothing launched and nothing was served, so the task is withdrawn with `cancel`.
9783
- try {
9784
- await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: "terminate" } });
9785
- await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "manager", reason: "accept-failed" }, committer: { instanceId: this.managerInstanceId, epoch: o.executor.epoch } });
9786
- await clearGoalIndex(gw.ctx, ref);
9787
- }
9788
- catch (e2) {
9789
- console.error(`! once task accept unwind for ${ref.goalId}: ${rejectionText(e2)}`);
9790
- }
9791
- throw e;
9792
- }
9793
- this.pendingTurns.set(key, {
9794
- ref, goalId: ref.goalId, seat: { ...seat }, payload, acceptedAt: o.acceptedAt, holdEpoch: o.executor.epoch,
9795
- ...(deadlineAt !== undefined ? { deadlineAt, holdToken } : {}),
9796
- once: { deliverable: false },
9797
- });
9798
- this.turnAcceptances.set(key, {
9799
- 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 },
9800
- ref,
9801
- });
9802
- this.ensureTurnSweep();
9803
- this.emitGoalProgress(ref, o.executor.epoch, { phase: "relayed" });
9804
- return { ref, ...(deadlineAt !== undefined ? { deadlineAt } : {}) };
9805
- }
8364
+ acceptOnceTurn(o) { return this.turnRelay.acceptOnceTurn(o); }
9806
8365
  /** How a once seat's startup watch ended, waited for until {@link STARTUP_OUTCOME_MS} after its
9807
8366
  * launch or the readiness window, whichever is longer. A watch that has not ended by then, or a
9808
8367
  * seat being stopped, answers what the handle reports at that moment. */
@@ -9810,19 +8369,13 @@ export class Manager {
9810
8369
  const until = launchedAt + Math.max(readinessTimeoutMs, STARTUP_OUTCOME_MS);
9811
8370
  for (;;) {
9812
8371
  const outcome = a.handle.startupOutcome?.() ?? "pending";
9813
- if (outcome !== "pending" || a.terminalizing || Date.now() >= until)
8372
+ if (outcome !== "pending" || a.terminalizing || this.leaseStopping || Date.now() >= until)
9814
8373
  return outcome;
9815
8374
  await new Promise((resolve) => setTimeout(resolve, 250));
9816
8375
  }
9817
8376
  }
9818
8377
  /** Serve a once task from now on: its spawn's succeeded terminal is written. */
9819
- openOnceDelivery(ref) {
9820
- const p = this.pendingTurns.get(goalKey(ref));
9821
- if (p?.once === undefined || p.once.deliverable)
9822
- return;
9823
- p.once.deliverable = true;
9824
- this.noticeSeatTurns(p.seat);
9825
- }
8378
+ openOnceDelivery(ref) { return this.turnRelay.openOnceDelivery(ref); }
9826
8379
  /** Stop the seat of a once task that just ended, found by its incarnation and never by its name.
9827
8380
  * After the readiness verdict the spawn goal's outcome belongs to that verdict, so the stop lets
9828
8381
  * go of the spawn goal first and never cancels it. Before the verdict it is a deliberate stop,
@@ -9858,62 +8411,9 @@ export class Manager {
9858
8411
  * the seat's launched processes gone, cancel the task with `reason` if it has no terminal yet,
9859
8412
  * then drop its index entry. One flight per task; a failure keeps it in {@link onceSettles} and
9860
8413
  * the turn sweep retries it. */
9861
- settleOnceTurn(ref, reason, retire) {
9862
- const key = goalKey(ref);
9863
- const owed = this.onceSettles.get(key) ?? { ref, reason, ...(retire !== undefined ? { retire } : {}) };
9864
- if (owed.flight)
9865
- return owed.flight;
9866
- this.onceSettles.set(key, owed);
9867
- const flight = this.runOnceSettle(key, owed).finally(() => { owed.flight = undefined; });
9868
- owed.flight = flight;
9869
- return flight;
9870
- }
9871
- async runOnceSettle(key, owed) {
9872
- const gw = this.goalWriter;
9873
- if (!gw)
9874
- return;
9875
- // The pending entry is the latch the yield and the deadline race on; a task settled here is
9876
- // served to no one again.
9877
- const p = this.pendingTurns.get(key);
9878
- // A task past its deadline owes the deadline terminal, which the turn sweep writes again until
9879
- // it lands; the settle waits for it rather than record a cancel in its place.
9880
- const denyOwed = p?.deadlineAt !== undefined && p.deadlineAt <= Date.now();
9881
- if (p && !denyOwed) {
9882
- this.pendingTurns.delete(key);
9883
- this.markTurnLatchDropped(key);
9884
- this.noticeSeatTurns(p.seat);
9885
- }
9886
- try {
9887
- if (denyOwed)
9888
- throw new Error("its deadline terminal is not written yet");
9889
- // A seat whose exit is proved may have left processes of its own running the task: the task
9890
- // is not recorded as ended, nor its debt cleared, before they are proved gone.
9891
- const retired = owed.retire === undefined ? undefined : await this.retireOnceSeat(owed.retire);
9892
- await this.commitOnceCancel(owed.ref, owed.reason);
9893
- await clearGoalIndex(gw.ctx, owed.ref);
9894
- this.onceSettles.delete(key);
9895
- this.onceWatched.delete(key);
9896
- await retired?.discard().catch((e) => console.error(`! once task ${owed.ref.goalId}: its retirement receipt was not discarded (${rejectionText(e)})`));
9897
- }
9898
- catch (e) {
9899
- console.error(`! once task ${owed.ref.goalId} (${owed.reason}): ${rejectionText(e)}; retried by the turn sweep`);
9900
- this.ensureTurnSweep();
9901
- }
9902
- this.maybeStopTurnSweep();
9903
- }
8414
+ settleOnceTurn(ref, reason, retire) { return this.turnRelay.settleOnceTurn(ref, reason, retire); }
9904
8415
  /** Cancel a once task with `reason` unless it already has a terminal. */
9905
- async commitOnceCancel(ref, reason) {
9906
- const gw = this.goalWriter;
9907
- if ((await readGoalResult(gw.ctx, ref)) !== undefined)
9908
- return;
9909
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9910
- await this.assertGoalWriterEpochCurrent(epoch);
9911
- if ((await readGoalStatus(gw.ctx, ref))?.value.state !== "cancelling")
9912
- await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: "terminate" } });
9913
- const { fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "manager", reason }, committer: { instanceId: this.managerInstanceId, epoch } });
9914
- this.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9915
- this.rememberSettledTurn(goalKey(ref), fact.state, Date.now());
9916
- }
8416
+ commitOnceCancel(ref, reason) { return this.turnRelay.commitOnceCancel(ref, reason); }
9917
8417
  /** Ask the seat's connector to prove its launched processes gone, within {@link ONCE_RETIRE_MS}.
9918
8418
  * Throws without that proof. */
9919
8419
  async retireOnceSeat(r) {
@@ -9922,107 +8422,9 @@ export class Manager {
9922
8422
  throw new Error(`the ${r.connector} connector cannot prove seat ${r.name}'s launched processes gone`);
9923
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`);
9924
8424
  }
9925
- /** Record a once task a predecessor accepted, and bind its seat if this incarnation already
9926
- * adopted it. The static adoption and the goal reconcile run in either order, so each side
9927
- * binds what the other has already found. */
9928
- async inheritOnce(ref, allocated, note) {
9929
- this.onceInherited.set(allocated.uid, {
9930
- ref, seat: { name: allocated.name, owner: allocated.owner, actor: allocated.actor, uid: allocated.uid },
9931
- ...(note.deadlineAt !== undefined ? { deadlineAt: note.deadlineAt } : {}),
9932
- readinessMs: allocated.readinessDeadlineMs ?? this.readinessTimeoutMs,
9933
- ...(note.retire !== undefined ? { retire: note.retire } : {}),
9934
- });
9935
- const a = this.findManagedByTarget({ owner: allocated.owner, actor: allocated.actor, lifecycleUid: allocated.uid });
9936
- if (a !== undefined)
9937
- await this.bindOnceSeat(a);
9938
- this.ensureTurnSweep();
9939
- }
9940
- /** An inherited once task whose seat this manager cannot hold: it adopts no seats (an open or
9941
- * user-mode mesh) and the seat is not bound here. */
9942
- onceSeatUnheld(p) {
9943
- return p.once !== undefined && this.onceInherited.has(p.seat.uid) && !(this.auth !== undefined && !this.userMode);
9944
- }
9945
- /** Whether a once task was served: its spawn's succeeded terminal is written. */
9946
- async onceServed(ref, note) {
9947
- if (note.spawn === undefined)
9948
- return false;
9949
- const spawn = await readGoalResult(this.goalWriter.ctx, { endpoint: ref.endpoint, caller: ref.caller, goalId: note.spawn });
9950
- return spawn?.state === "succeeded";
9951
- }
9952
8425
  /** Make an adopted seat a once seat again: its exit settles its task, and the task is served to
9953
8426
  * it. A task that ended before the restart owes the stop the predecessor may not have made. */
9954
- async bindOnceSeat(a) {
9955
- const inherited = this.onceInherited.get(a.lifecycleUid);
9956
- if (inherited === undefined || a.once !== undefined)
9957
- return;
9958
- this.onceInherited.delete(a.lifecycleUid);
9959
- a.once = { ref: inherited.ref, ...(inherited.retire !== undefined ? { retire: inherited.retire } : {}) };
9960
- this.watchOnceExit(a);
9961
- const p = this.pendingTurns.get(goalKey(inherited.ref));
9962
- if (p?.once) {
9963
- p.once.deliverable = true;
9964
- this.noticeSeatTurns(p.seat);
9965
- return;
9966
- }
9967
- const ended = this.goalWriter ? await readGoalResult(this.goalWriter.ctx, inherited.ref) : undefined;
9968
- if (ended !== undefined)
9969
- this.stopOnceSeat(a, "turn-ended");
9970
- }
9971
- /** Inherited once tasks whose seat is not bound here. On a static mesh the boot reconcile adopts
9972
- * every seat it can and reaps the rest by their custody reference, so once it has finished with
9973
- * a seat's slot, an unbound seat is proved gone. A manager that adopts no seats cannot reach the
9974
- * old seat or prove its exit: it does not serve the task to it, a task with a deadline ends at
9975
- * that deadline, and one without is settled `uncertain` after one readiness window. Its debt is
9976
- * never cleared here, since nothing proves that seat gone. */
9977
- async settleInheritedOnce() {
9978
- const gw = this.goalWriter;
9979
- if (!gw || !this.goalReconcileDone)
9980
- return;
9981
- const adopts = this.auth !== undefined && !this.userMode;
9982
- for (const [uid, d] of [...this.onceInherited]) {
9983
- const live = this.findManagedByTarget({ owner: d.seat.owner, actor: d.seat.actor, lifecycleUid: uid });
9984
- if (live !== undefined) {
9985
- await this.bindOnceSeat(live);
9986
- continue;
9987
- }
9988
- if (adopts) {
9989
- const reconciling = this.staticReconcileSweepsInFlight > 0
9990
- || [...this.staticReconcileItems.values()].some((i) => i.lifecycleUid === uid && i.disposition !== "recovered");
9991
- if (reconciling)
9992
- continue;
9993
- this.onceInherited.delete(uid);
9994
- void this.settleOnceTurn(d.ref, "seat-exited", retireOf(d));
9995
- continue;
9996
- }
9997
- if ((await readGoalResult(gw.ctx, d.ref)) !== undefined) {
9998
- this.onceInherited.delete(uid);
9999
- this.keepUnprovedOnceDebt(d);
10000
- continue;
10001
- }
10002
- if (d.deadlineAt !== undefined || Date.now() - this.goalReconcileDoneAt < d.readinessMs)
10003
- continue;
10004
- this.onceInherited.delete(uid);
10005
- const key = goalKey(d.ref);
10006
- this.pendingTurns.delete(key);
10007
- this.markTurnLatchDropped(key);
10008
- try {
10009
- 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` });
10010
- this.keepUnprovedOnceDebt(d);
10011
- }
10012
- catch (e) {
10013
- console.error(`! inherited once task ${d.ref.goalId}: ${rejectionText(e)}`);
10014
- }
10015
- }
10016
- }
10017
- /** An inherited task's seat this manager cannot reach: its terminal stands, and its index entry,
10018
- * the seat's debt, stays recorded, because nothing here can prove that seat gone. The seat is
10019
- * told to end itself on its next pull, and its notice repeats until a pull carries that. */
10020
- keepUnprovedOnceDebt(d) {
10021
- 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`);
10022
- this.onceStops.set(d.seat.uid, { ...d.seat });
10023
- this.noticeSeatTurns(d.seat);
10024
- this.ensureTurnSweep();
10025
- }
8427
+ bindOnceSeat(a) { return this.turnRelay.bindOnceSeat(a); }
10026
8428
  /** Settle race: a despawn MID-GOAL drives the goal's cancel terminal - transition to
10027
8429
  * `cancelling`, then commit the `cancel` cause on the goal-writer connection. First-terminal-fact
10028
8430
  * wins: if the readiness outcome already committed (succeeded/failed/uncertain) the transition or
@@ -10101,844 +8503,32 @@ export class Manager {
10101
8503
  reapOrphanSeat(a) {
10102
8504
  return this.seatCustody.reapOrphanSeat(a);
10103
8505
  }
10104
- /** The static terminal for one departed incarnation: delegates the gate/head CAS
10105
- * sequence to the shared core saga over the executor transport; the footprint teardown (creds
10106
- * file + broker durables/ACL) runs INSIDE the barrier as its cleanup step. On completion the
10107
- * wire principal joins {@link retiredPrincipals} (the retired-principal refusal index) and the name hold
10108
- * clears (ABA-guarded by uid). A lifecycle with no slot row (spawned before the
10109
- * durable registry existed) has nothing to terminalize: its footprint teardown runs directly
10110
- * and the hold clears, the honest upgrade path. `onDeprovision` receives the accounting of the
10111
- * broker teardown this call ran, on success or on a {@link DeprovisionError}. */
10112
- async driveStaticRetirement(a, surfaceFailure = false, onDeprovision) {
10113
- // A renewal that published its flight before the synchronous terminal latch is accepted work.
10114
- // Drain it before the durable terminal enumerates credential ids and before cleanup deletes its
10115
- // material; a failed renewal must not block retirement because it may still have staged an id.
10116
- const acceptedRenewal = a.staticCredentialRenewal;
10117
- if (acceptedRenewal)
10118
- await acceptedRenewal.catch(() => { });
10119
- const opId = managedRetirementOpId(a.lifecycleUid);
10120
- const evict = this.staticLifecycleEvict ?? makeManagerEndpointEvictionEvidence({
10121
- space: this.space,
10122
- servers: this.servers ?? DEFAULT_SERVER,
10123
- auth: this.auth,
10124
- log: (line) => console.error(`static retirement ${a.name}: ${line}`),
10125
- // A daemon credential reload briefly removes its responder while it reconnects.
10126
- unreachableWaitMs: DEPROVISION_TIMEOUT_MS,
10127
- });
10128
- const cleanup = async () => {
10129
- // SPEC 13.15: every issuance bound to this incarnation's ledger family is retired here,
10130
- // inside the barrier and after the ledger rows were revoked (the source is frozen first,
10131
- // then the index is walked). A retirement that lost is surfaced, never skipped: an active
10132
- // attempt row on a retired lifecycle would authorize a run the credential no longer can.
10133
- const retired = await this.withIssuer((i) => i.store.retireSource({ space: this.space, bucket: epAuthBucket(this.space), key: `cred.${a.lifecycleUid}` }));
10134
- if (retired > 0)
10135
- console.error(`static retirement ${a.name}: retired ${retired} issuance(s) bound to uid ${a.lifecycleUid}`);
10136
- const secrets = this.secrets;
10137
- const files = a.secretPaths ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, a.name, a.lifecycleUid);
10138
- // The broker teardown mints its own credential, so a creds file that cannot be removed must not
10139
- // skip it. The failures are thrown together, so the terminal still stops at an incomplete cleanup.
10140
- const failed = [];
10141
- if (files.creds) {
10142
- const creds = files.creds;
10143
- await attemptCleanup(failed, `secret ${creds}`, () => secrets.delete(agentSecretKeyForFile(creds, this.space)));
10144
- await attemptCleanup(failed, `file ${creds}`, () => rmSync(creds, { force: true }));
10145
- }
10146
- // The lifecycle's inline snapshot, when no earlier step settled it. Keyed by the uid, so a boot
10147
- // sweep or a reconcile that knows only the slot row removes it too.
10148
- if (!a.snapshotSettled) {
10149
- const snapshot = inlineSnapshotPath(this.workspaceRoot, a.lifecycleUid);
10150
- await attemptCleanup(failed, `file ${snapshot}`, () => removeInlineSnapshot(this.workspaceRoot, a.lifecycleUid));
10151
- }
10152
- await attemptCleanup(failed, "broker teardown", async () => {
10153
- try {
10154
- const accounting = await this.deprovisionBroker(a);
10155
- onDeprovision?.(accounting);
10156
- }
10157
- catch (e) {
10158
- if (e instanceof DeprovisionError)
10159
- onDeprovision?.(e.accounting);
10160
- throw e;
10161
- }
10162
- });
10163
- if (failed.length)
10164
- throw new Error(`cleanup failed: ${describeCleanupFailures(failed)}`);
10165
- };
10166
- // The process goes before its footprint: reap the orphan seat by reference, then tear down.
10167
- const reapThenCleanup = async () => {
10168
- await this.reapOrphanSeat(a);
10169
- await cleanup();
10170
- };
10171
- try {
10172
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: a.id, lifecycleUid: a.lifecycleUid, alias: a.name }, async (t) => {
10173
- const slot = await readStaticSlot(t, DEV_OWNER, a.name);
10174
- if (slot === undefined || slot.row.lifecycleUid !== a.lifecycleUid) {
10175
- // No durable registration for THIS incarnation: a spawn from before the registry (or a slot already
10176
- // replaced by a successor — then this stale teardown must not touch the registry at all).
10177
- await reapThenCleanup();
10178
- return;
10179
- }
10180
- await runStaticTerminal(t, {
10181
- owner: DEV_OWNER, alias: a.name, actor: a.id, lifecycleUid: a.lifecycleUid, opId,
10182
- managerInstance: this.managerInstanceId, managerProcessUid: this.managerLifecycleUid,
10183
- }, { cleanup: reapThenCleanup, evict, log: (line) => console.error(`static retirement ${a.name}: ${line}`) });
10184
- });
10185
- this.retirement.recordStaticRetirement(a);
10186
- }
10187
- catch (e) {
10188
- const h = this.retirement.held(a.name);
10189
- if (h && h.target.lifecycleUid === a.lifecycleUid)
10190
- h.lastError = `the static retirement did not complete (${rejectionText(e)}); the name stays held - a same-name spawn retries the same terminal (op ${opId})`;
10191
- console.error(`static retirement ${a.name} (${a.id}): ${rejectionText(e)}`);
10192
- if (surfaceFailure)
10193
- throw e;
10194
- }
8506
+ driveStaticRetirement(a, surfaceFailure = false, onDeprovision) {
8507
+ return this.staticLifecycle.driveStaticRetirement(a, surfaceFailure, onDeprovision);
10195
8508
  }
10196
- /** `chat-session-open`: admit one static chat session. The manager draws the `chat_` alias and a
10197
- * fresh nkey identity, then runs the same native steps a static spawn does: the slot intent and
10198
- * the shared activation saga, the provisioner's bind-only DM and DELIVER durables plus the ACL
10199
- * row, and the agent-profile mint. The leaf carries the spawn's three lists under the spawn's
10200
- * rules (`resolveReadAcl`, a default-deny post list, the foreign event-channel refusal) and
10201
- * nothing else: no role (so no TASK queue), no capabilities, no endpoint rows, no issuance. It
10202
- * expires at `ttl` with no renewal, because no managed row exists to renew it.
10203
- *
10204
- * The session is registered with the tracker before the first durable write and scheduled for
10205
- * its expiry before the reply is sent, or after a rollback that did not complete, so this
10206
- * process retires it at the expiry even when the reply is lost or the client never retires.
10207
- *
10208
- * The credential is ledgered before it leaves this process (slot credentialId, then the `cred.`
10209
- * row), so the static terminal marks the row revoked and verify-evicts the session's principal;
10210
- * the broker keeps accepting the leaf until its expiry. The direct ledger write is deliberate:
10211
- * the leaf is not an issuance, so the issuance seam, which writes the same row inside its
10212
- * finalization, never runs for it, and without the row the terminal's eviction set would be
10213
- * empty. The credential leaves only sealed to `sealTo`, bound to the space, this instance and
10214
- * the reply's fields, so a reply printed anywhere carries no usable credential. A failure at
10215
- * any step drives the terminal before the refusal is returned, and the refusal says whether it
10216
- * completed. */
10217
- async openStaticChatSession(raw) {
10218
- if (!this.auth || this.userMode)
10219
- throw new EpEnvelopeError("unimplemented", "chat-session-open admits static chat sessions only, and this manager is not a static-auth manager", undefined, "not-executed");
10220
- const input = readChatOpenInput(raw);
10221
- if ("error" in input)
10222
- throw new EpEnvelopeError("bad-request", input.error, undefined, "not-executed");
10223
- const lists = chatOpenLists(input);
10224
- if ("error" in lists)
10225
- throw new EpEnvelopeError("bad-request", lists.error, undefined, "not-executed");
10226
- const alias = drawChatAlias();
10227
- const identity = newIdentity();
10228
- // The spawn's rule, against the drawn actor: a concrete event channel of any other principal is
10229
- // refused, and a wildcard is an ordinary grant.
10230
- const foreign = foreignEventChannels([...lists.allowSubscribe, ...lists.allowPublish], DEV_OWNER, identity.id);
10231
- if (foreign.length)
10232
- throw new EpEnvelopeError("bad-request", `chat-session-open asks for another agent's event channel: ${foreign.join(", ")}. A session may be granted its OWN event plane and no other, because that plane carries the session's tool inputs and outputs. Grant a reader out of band rather than through a chat session: ${this.readerRemedy(DEV_OWNER, foreign[0])}`, undefined, "not-executed");
10233
- const lifecycleUid = mintLifecycleUid();
10234
- const exp = Math.floor(Date.now() / 1000) + input.ttl;
10235
- const pin = { owner: DEV_OWNER, actor: identity.id, lifecycleUid, alias };
10236
- const session = { alias, actor: identity.id, lifecycleUid, channels: lists.allowSubscribe, expiresAt: exp * 1000 };
10237
- // Registered before the first durable write, so the startup sweep never mistakes this opening's
10238
- // provisioning row for a crashed spawn, and the stop knows it.
10239
- try {
10240
- this.chatExpiry.register(session);
10241
- }
10242
- catch (e) {
10243
- throw new EpEnvelopeError("unavailable", rejectionText(e), undefined, "not-executed");
10244
- }
10245
- try {
10246
- await this.withLifecycleExecutor(pin, (t) => activateStaticLifecycle(t, { owner: DEV_OWNER, alias, actor: identity.id, lifecycleUid, managerInstance: this.managerLifecycleUid, ownerInstanceId: this.managerInstanceId }));
10247
- const creds = await this.withProvisioner((prov) => provisionAgent(prov, this.auth, identity, { subscribe: lists.subscribe, allowSubscribe: lists.allowSubscribe, allowPublish: lists.allowPublish, lifecycleUid, expiresAt: exp }));
10248
- // The same credential id the issuance path derives, so a re-sent identical credential maps to
10249
- // the same row.
10250
- const credentialId = credentialIdOf(creds);
10251
- await this.withLifecycleExecutor(pin, async (t) => {
10252
- await recordSlotCredential(t, DEV_OWNER, alias, lifecycleUid, credentialId);
10253
- await appendStaticCredentialRow(t, { lifecycleUid, credentialId, holderPrincipal: principalKey(DEV_OWNER, identity.id).key, exp });
10254
- const slot = await readStaticSlot(t, DEV_OWNER, alias);
10255
- if (slot === undefined || slot.row.lifecycleUid !== lifecycleUid || slot.row.phase !== "provisioning")
10256
- throw new Error(`the static slot for "${alias}" is ${slot === undefined ? "absent" : `${slot.row.phase} at uid ${slot.row.lifecycleUid}`}, not this opening's provisioning intent`);
10257
- await casStaticSlot(t, { ...slot.row, phase: "active" }, slot.revision);
10258
- });
10259
- const { sealer, sealed } = sealChatAdmission({
10260
- space: this.space, managerInstanceId: this.managerInstanceId, alias, actor: identity.id, lifecycleUid, expiresAt: exp * 1000, sealTo: input.sealTo, creds,
10261
- });
10262
- this.chatExpiry.arm(lifecycleUid);
10263
- console.error(`chat session ${alias} admitted as ${identity.id} (uid ${lifecycleUid}), expires ${new Date(exp * 1000).toISOString()}`);
10264
- return { alias, actor: identity.id, lifecycleUid, expiresAt: exp * 1000, sealer, sealed };
10265
- }
10266
- catch (e) {
10267
- // A confirmed rollback leaves a known state, a retired slot. An unconfirmed one does not, so
10268
- // the session stays registered and its expiry, or the stop, retries the same terminal.
10269
- let rollback;
10270
- try {
10271
- await this.chatTerminal(session);
10272
- }
10273
- catch (r) {
10274
- rollback = rejectionText(r);
10275
- try {
10276
- this.chatExpiry.arm(lifecycleUid);
10277
- }
10278
- catch (t) {
10279
- rollback += `; ${rejectionText(t)}`;
10280
- }
10281
- }
10282
- throw new EpEnvelopeError(e instanceof EpEnvelopeError ? e.code : "unavailable", `chat-session-open did not complete for ${alias}: ${rejectionText(e)}; ${rollback === undefined ? "its rollback retired the slot" : `its rollback was not confirmed (${rollback}), so the slot stays held until a retire, its expiry here, this manager's stop, or the next start of this manager instance`}`, undefined, rollback === undefined ? "executed" : "unknown");
10283
- }
10284
- }
10285
- /** `chat-session-retire`: end one static chat session through the native static terminal (ledger
10286
- * row marked revoked, verified eviction of its principal's live connections, footprint cleanup,
10287
- * gate and head retirement). It refuses before any effect unless {@link admitChatRetirement}
10288
- * admits the request. A terminal that cannot complete answers `failed` with the reason, never
10289
- * success; the slot stays held. The broker keeps accepting the leaf until its expiry either way. */
10290
- async retireStaticChatSession(raw) {
10291
- if (!this.auth || this.userMode)
10292
- throw new EpEnvelopeError("unimplemented", "chat-session-retire retires static chat sessions only, and this manager is not a static-auth manager", undefined, "not-executed");
10293
- const input = readChatRetireInput(raw);
10294
- if ("error" in input)
10295
- throw new EpEnvelopeError("bad-request", input.error, undefined, "not-executed");
10296
- if (await this.admitChatRetirement(input) === "alreadyRetired")
10297
- return { outcome: "alreadyRetired" };
10298
- try {
10299
- await this.chatTerminal({ ...input, channels: this.chatExpiry.channels(input.lifecycleUid) });
10300
- }
10301
- catch (e) {
10302
- return { outcome: "failed", reason: `retirement pending: ${rejectionText(e)}` };
10303
- }
10304
- return { outcome: "retired" };
8509
+ openStaticChatSession(raw) {
8510
+ return this.staticLifecycle.openStaticChatSession(raw);
10305
8511
  }
10306
- /** The expiry cleanup's retirement of one session this process admitted. It is lifecycle work, so
10307
- * it is admitted like a control call and a stop drains it. A throw is a failure the tracker
10308
- * retries; a slot that is no longer this instance's to retire ends the tracking instead. */
10309
- async expireStaticChatSession(session) {
10310
- const release = this.beginLifecycle();
10311
- if (!release)
10312
- throw new Error(this.maintenanceError());
10313
- try {
10314
- console.error(`chat session ${session.alias} (uid ${session.lifecycleUid}) reached its expiry; retiring it`);
10315
- let admitted;
10316
- try {
10317
- admitted = await this.admitChatRetirement(session);
10318
- }
10319
- catch (e) {
10320
- if (e instanceof EpEnvelopeError && (e.code === "not-found" || e.code === "failed-precondition")) {
10321
- console.error(`! chat session ${session.alias} expired, but its slot is not this instance's to retire (${e.message}); expiry tracking ends`);
10322
- return;
10323
- }
10324
- throw e;
10325
- }
10326
- if (admitted === "admitted")
10327
- await this.chatTerminal(session);
10328
- }
10329
- finally {
10330
- release();
10331
- }
8512
+ retireStaticChatSession(raw) {
8513
+ return this.staticLifecycle.retireStaticChatSession(raw);
10332
8514
  }
10333
- /** The ownership admission shared by `chat-session-retire`, the expiry and the stop. It throws a
10334
- * not-executed refusal unless the alias is a chat alias whose slot this logical instance owns
10335
- * at the requested UID and actor. An already retired slot ends its expiry tracking. */
10336
- async admitChatRetirement(s) {
10337
- if (!isChatAlias(s.alias))
10338
- throw new EpEnvelopeError("permission-denied", `"${s.alias}" is not a chat session alias`, undefined, "not-executed");
10339
- if (this.reconcilingAliases.has(s.alias))
10340
- throw new EpEnvelopeError("unavailable", `the chat session "${s.alias}" is still reconciling at manager startup; that terminal owns it`, undefined, "not-executed");
10341
- const recordsKv = this.goalWriter?.ctx.kv;
10342
- if (!recordsKv)
10343
- throw new EpEnvelopeError("unavailable", `the durable static slot store is not ready while retiring "${s.alias}"`, undefined, "not-executed");
10344
- let slot;
10345
- try {
10346
- slot = await readStaticSlot(staticLifecycleTransport(recordsKv, recordsKv), DEV_OWNER, s.alias);
10347
- }
10348
- catch (e) {
10349
- throw new EpEnvelopeError("unavailable", `the durable slot for "${s.alias}" could not be read: ${rejectionText(e)}`, undefined, "not-executed");
10350
- }
10351
- const refused = chatRetireRefusal(slot?.row, s, this.managerInstanceId);
10352
- if (refused)
10353
- throw new EpEnvelopeError(refused.code, refused.message, undefined, "not-executed");
10354
- if (slot.row.phase !== "retired")
10355
- return "admitted";
10356
- this.chatExpiry.forget(s.lifecycleUid);
10357
- return "alreadyRetired";
10358
- }
10359
- /** One static terminal per chat session UID, however many callers ask: the explicit retire, the
10360
- * expiry cleanup and the open's rollback join it instead of racing its CAS sequence. A completed
10361
- * terminal ends the expiry tracking. `channels` names the membership rows to delete by name;
10362
- * without it the delivery inventory alone finds them. */
10363
- chatTerminal(s) {
10364
- let flight = this.chatRetirements.get(s.lifecycleUid);
10365
- if (!flight) {
10366
- flight = this.withRetirementSlot(() => this.driveStaticRetirement({ id: s.actor, name: s.alias, lifecycleUid: s.lifecycleUid, secretPaths: {}, ...(s.channels ? { launch: { allowSubscribe: s.channels } } : {}) }, true))
10367
- .then(() => this.chatExpiry.forget(s.lifecycleUid))
10368
- .finally(() => this.chatRetirements.delete(s.lifecycleUid));
10369
- this.chatRetirements.set(s.lifecycleUid, flight);
10370
- }
10371
- return flight;
10372
- }
10373
- /** Whether `row` is a chat slot this process registered, at its exact alias, actor and UID,
10374
- * under this logical instance and this process's incarnation. */
10375
- holdsLiveChatSlot(row) {
10376
- return row.ownerInstanceId === this.managerInstanceId && row.managerInstance === this.managerLifecycleUid && this.chatExpiry.holdsExact(row);
10377
- }
10378
- /** The stop's retirement of every chat session this process still tracks, through the same
10379
- * ownership admission and terminal as `chat-session-retire`, at most
10380
- * {@link CHAT_EXPIRY_CONCURRENCY} at a time. It runs after the lifecycle fence closed and every
10381
- * admitted operation drained, as the seat teardown does, and mints nothing the terminal does not
10382
- * already mint. Every outcome is logged. It throws, naming each one, when any session was not
10383
- * retired; that session stays held until the next start of this manager instance. */
10384
- async retireChatSessionsOnStop() {
10385
- const queue = this.chatExpiry.remaining();
10386
- const failed = [];
10387
- const retireOne = async (session) => {
10388
- const at = `chat session ${session.alias} (uid ${session.lifecycleUid})`;
10389
- try {
10390
- if (await this.admitChatRetirement(session) === "alreadyRetired") {
10391
- console.error(`${at} was already retired at stop`);
10392
- return;
10393
- }
10394
- await this.chatTerminal(session);
10395
- console.error(`${at} retired at stop`);
10396
- }
10397
- catch (e) {
10398
- if (e instanceof EpEnvelopeError && (e.code === "not-found" || e.code === "failed-precondition")) {
10399
- this.chatExpiry.forget(session.lifecycleUid);
10400
- console.error(`! ${at} was not retired at stop: its slot is not this instance's to retire (${e.message})`);
10401
- return;
10402
- }
10403
- failed.push(`${session.alias} (uid ${session.lifecycleUid}): ${rejectionText(e)}`);
10404
- console.error(`! ${at} was not retired at stop (${rejectionText(e)}); it stays held until the next start of this manager instance`);
10405
- }
10406
- };
10407
- await Promise.all(Array.from({ length: Math.min(CHAT_EXPIRY_CONCURRENCY, queue.length) }, async () => {
10408
- for (let next = queue.shift(); next !== undefined; next = queue.shift())
10409
- await retireOne(next);
10410
- }));
10411
- if (failed.length)
10412
- throw new Error(`${failed.length} chat session(s) were not retired and stay held until the next start of this manager instance: ${failed.join("; ")}`);
8515
+ retireChatSessionsOnStop() {
8516
+ return this.staticLifecycle.retireChatSessionsOnStop();
10413
8517
  }
10414
- /** Name, at a stop that does not retire them, each chat session this process still tracks. */
10415
8518
  reportChatSessionsLeftAtStop(why) {
10416
- for (const session of this.chatExpiry.remaining())
10417
- console.error(`! chat session ${session.alias} (uid ${session.lifecycleUid}) was not retired because ${why}; the next start of this manager instance retires it`);
10418
- }
10419
- /** Push renewal of ONE live managed-static credential: re-mint the SAME nkey
10420
- * identity with the SAME scope (recorded on the managed row at spawn) and a fresh bounded
10421
- * exp, ledger the new credentialId (slot record first, then the row, then the file — a
10422
- * credential is never materialized before its ledger row exists), and re-sign the SAME
10423
- * lifecycle-keyed file the agent endpoint's source seam re-reads. Never advances the epoch;
10424
- * renewal remains the THIRD transition. */
10425
- async renewManagedStaticCred(a) {
10426
- if (!this.auth || !a.seed || !a.secretPaths?.creds)
10427
- throw new Error("renewManagedStaticCred: not a renewable managed-static agent");
10428
- // Admission is synchronous. An accepted renewal publishes its flight before its first caller can
10429
- // terminalize the agent; terminalization rejects later callers and drains this flight before the
10430
- // durable terminal starts, giving renewal-before-terminal and terminal-before-renewal one order.
10431
- if (a.terminalizing)
10432
- throw new Error("renewManagedStaticCred: the lifecycle is terminalizing; no credential is minted after the terminal begins");
10433
- if (a.staticCredentialRenewal)
10434
- return a.staticCredentialRenewal;
10435
- const renewal = this.driveManagedStaticCredRenewal(a).finally(() => {
10436
- if (a.staticCredentialRenewal === renewal)
10437
- a.staticCredentialRenewal = undefined;
10438
- });
10439
- a.staticCredentialRenewal = renewal;
10440
- return renewal;
10441
- }
10442
- async driveManagedStaticCredRenewal(a) {
10443
- // The SAME permission scope the spawn minted (recorded on the managed row): allowSubscribe/
10444
- // allowPublish/role/capabilities are the JWT-shaping inputs; `subscribe` (the active read
10445
- // set) shapes durable membership only and is not a mint input.
10446
- if (!a.issued)
10447
- throw new Error(`renewManagedStaticCred: ${a.name} carries no issuance; a static credential minted before SPEC 13.15 is not renewed under an unbound generation - respawn the agent`);
10448
- // A renewal never outlives the generation's horizon, and none is minted at or past it: the
10449
- // generation then authorizes nothing and its rows are being removed (SPEC 13.15).
10450
- const now = Math.floor(Date.now() / 1000);
10451
- const horizon = issuedHorizon(a.issued.generation);
10452
- if (now >= horizon)
10453
- throw new Error(`renewManagedStaticCred: ${a.name}'s issued generation reached its horizon ${new Date(horizon * 1000).toISOString()} (${STATIC_GENERATION_HORIZON_SEC / 86_400} days after its spawn) and is not renewed - respawn the agent (rotation instead of this cap: Cotal-AI/Cotal#4942)`);
10454
- const exp = Math.min(now + MANAGED_STATIC_TTL_SEC, horizon);
10455
- // A RENEWAL keeps the generation (SPEC 13.15): the same JWT-shaping inputs produce the same
10456
- // ceiling, which `confirm` verifies against the recorded evidence before the ledger append. A
10457
- // changed ceiling is refused there: that is a fresh issuance on a new connection, never a renewal.
10458
- const issued = a.issued;
10459
- const endpoints = lowerPersonaEndpoints(a.launch.endpoints);
10460
- const reads = this.managedStaticInstanceReads(a.launch.capabilities);
10461
- if (reads.length) {
10462
- // Resolve this incarnation's original issuance, not its current spawner or a reconstructed
10463
- // run admission. Old seats and run helpers keep the exact ceiling they were minted with.
10464
- const caller = { owner: DEV_OWNER, actor: a.id, uid: a.lifecycleUid, generation: issued.generation };
10465
- const { evidence } = await withIssuerSession({ servers: this.servers ?? DEFAULT_SERVER, space: this.space, auth: this.auth, tls: false }, (s) => s.store.resolve({ space: this.space, ...caller }, s.sourceIsLive));
10466
- if (!grantOverreach(this.space, caller, evidence.permissions, { endpoints: reads }).length)
10467
- endpoints.push(...reads);
10468
- }
10469
- const creds = await this.withIssuer((i) => mintCreds(this.auth, { id: a.id, seed: a.seed }, "agent", {
10470
- eventPayloads: this.eventPayloadsWithheld ? false : a.launch.eventPayloads,
10471
- allowSubscribe: a.launch.allowSubscribe,
10472
- allowPublish: a.launch.allowPublish,
10473
- role: a.role,
10474
- capabilities: a.launch.capabilities,
10475
- ...(endpoints.length ? { endpointCapabilities: endpoints } : {}),
10476
- lifecycleUid: a.lifecycleUid,
10477
- expiresAt: exp,
10478
- issued,
10479
- issuance: this.issuanceSeam(i, "renew", a, exp),
10480
- }));
10481
- const secrets = this.secrets;
10482
- const credsPath = a.secretPaths.creds;
10483
- await secrets.put(agentSecretKeyForFile(credsPath, this.space), creds);
10484
- await materializeSecretToFile(secrets, agentSecretKeyForFile(credsPath, this.space), credsPath);
10485
- // The record pins the credential's digest, so it follows the re-signed file.
10486
- this.refreshSeatRecord(a);
10487
- console.error(`managed cred renewal ${a.name}: re-signed for the same identity (exp +${exp - now}s); the agent endpoint's source re-read adopts it`);
10488
- }
10489
- /** The static-slot reconciliation ("no active orphan"): ensure the authority stores, then sweep
10490
- * every durable slot row and act by the TOTAL resume table — `provisioning`/`terminalizing`
10491
- * re-drive the exact-op terminal; an `active` row survives ONLY when a LIVE managed agent this
10492
- * manager process owns backs it at the same uid (`adopted`), else no managed owner claimed it and
10493
- * its broker authority is contained and terminalized; `retired` rows seed the retired-principal refusal index. Two call sites: the BOOT sweep
10494
- * (`postAdoption=false`, under the lease before control serving) DEFERS active-non-adopted
10495
- * slots while a resume is still pending (adoption runs after it); the POST-ADOPTION sweep
10496
- * (`postAdoption=true`, inside finalizeResume while `resumeRequired` still fences ordinary
10497
- * spawns) terminalizes any active slot the resume did not claim. */
10498
- staticReconcileKey(row) {
10499
- return JSON.stringify([row.owner, row.alias, row.lifecycleUid]);
10500
- }
10501
- /** Read one retry coordinate from the durable slot store. The status snapshot never authorizes a
10502
- * re-drive: every timer comes through this fresh read before the planner and exact terminal. */
10503
- async readStaticReconcileSlot(alias) {
10504
- if (!this.auth)
10505
- return undefined;
10506
- const identity = newIdentity();
10507
- const creds = await mintCreds(this.auth, identity, "provisioner");
10508
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
10509
- try {
10510
- const recordsKv = await new Kvm(nc).open(recordsBucket(this.space));
10511
- return (await readStaticSlot(staticLifecycleTransport(recordsKv, recordsKv), DEV_OWNER, alias))?.row;
10512
- }
10513
- finally {
10514
- await drainAndClose(nc);
10515
- }
8519
+ return this.staticLifecycle.reportChatSessionsLeftAtStop(why);
10516
8520
  }
10517
- scheduleStaticReconcileRetry(key, item) {
10518
- if (this.staticReconcileStopping || item.timer || item.attempts >= item.maxAttempts)
10519
- return;
10520
- const delay = this.staticReconcileRetryDelaysMs[item.attempts - 1];
10521
- if (delay === undefined)
10522
- return;
10523
- const nextRetryAtMs = Date.now() + delay;
10524
- item.disposition = "retry-scheduled";
10525
- item.nextRetryAt = new Date(nextRetryAtMs).toISOString();
10526
- item.timer = setTimeout(() => {
10527
- item.timer = undefined;
10528
- item.nextRetryAt = undefined;
10529
- const run = async () => {
10530
- // The timer may fire while the failed attempt is still unwinding, especially in compressed
10531
- // smoke schedules. Join that flight before consuming another budget entry; never overlap it.
10532
- if (item.flight)
10533
- await item.flight;
10534
- await this.retryStaticReconcile(key);
10535
- };
10536
- void run().catch((error) => {
10537
- item.lastError = `retry driver failed before the exact terminal: ${rejectionText(error)}`;
10538
- item.disposition = "retry-exhausted";
10539
- item.remedy = "restart this manager for a fresh per-process retry budget";
10540
- console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
10541
- });
10542
- }, delay);
10543
- item.timer.unref?.();
10544
- console.error(`! static reconcile retry-scheduled alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid} attempt=${item.attempts + 1}/${item.maxAttempts} nextRetryAt=${item.nextRetryAt}`);
10545
- }
10546
- retryStaticReconcile(key) {
10547
- const item = this.staticReconcileItems.get(key);
10548
- if (!item || this.staticReconcileStopping || item.disposition === "recovered")
10549
- return Promise.resolve();
10550
- if (item.retryFlight)
10551
- return item.retryFlight;
10552
- const flight = this.driveStaticReconcileRetry(key, item);
10553
- let wrapped;
10554
- wrapped = flight.finally(() => {
10555
- if (item.retryFlight === wrapped)
10556
- item.retryFlight = undefined;
10557
- });
10558
- item.retryFlight = wrapped;
10559
- return wrapped;
8521
+ renewManagedStaticCred(a) {
8522
+ return this.staticLifecycle.renewManagedStaticCred(a);
10560
8523
  }
10561
- async driveStaticReconcileRetry(key, item) {
10562
- if (item.flight)
10563
- await item.flight;
10564
- if (this.staticReconcileStopping || item.disposition === "recovered")
10565
- return;
10566
- // A retry trigger consumes one finite budget entry even if the authoritative re-read itself
10567
- // fails. Otherwise a broker outage before the planner could reschedule forever without ever
10568
- // incrementing `attempts`, violating the bounded-retry guarantee.
10569
- item.attempts++;
10570
- item.disposition = "retrying";
10571
- item.remedy = undefined;
10572
- console.error(`static reconcile retrying alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid} attempt=${item.attempts}/${item.maxAttempts}`);
10573
- let row;
10574
- try {
10575
- row = await this.readStaticReconcileSlot(item.alias);
10576
- }
10577
- catch (error) {
10578
- item.lastError = `durable slot re-read failed: ${rejectionText(error)}`;
10579
- if (item.attempts >= item.maxAttempts) {
10580
- item.disposition = "retry-exhausted";
10581
- item.remedy = "restart this manager for a fresh per-process retry budget";
10582
- console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
10583
- }
10584
- else {
10585
- this.scheduleStaticReconcileRetry(key, item);
10586
- }
10587
- return;
10588
- }
10589
- if (row === undefined || row.owner !== item.owner || row.actor !== item.actor || row.lifecycleUid !== item.lifecycleUid) {
10590
- item.disposition = "refused";
10591
- item.remedy = "inspect the durable slot; reconciliation will not cross incarnations";
10592
- item.lastError = row === undefined
10593
- ? "the durable slot vanished; reconciliation never acts from the in-memory snapshot"
10594
- : `the durable slot moved to actor ${row.actor} uid ${row.lifecycleUid}; reconciliation never crosses incarnations`;
10595
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
10596
- return;
10597
- }
10598
- item.phase = row.phase;
10599
- if (row.phase === "retired") {
10600
- item.disposition = "recovered";
10601
- item.recoveredAt = new Date().toISOString();
10602
- item.lastError = undefined;
10603
- console.error(`✓ static reconcile recovered alias=${item.alias} phase=retired uid=${item.lifecycleUid} attempts=${item.attempts}/${item.maxAttempts}`);
10604
- return;
10605
- }
10606
- if (ownedBySibling(row, this.managerInstanceId)) {
10607
- item.disposition = "refused";
10608
- item.remedy = "the owning manager must reconcile or an operator must perform an explicit CAS takeover";
10609
- item.lastError = `the durable slot belongs to manager instance ${row.ownerInstanceId}, not ${this.managerInstanceId}`;
10610
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
10611
- return;
10612
- }
10613
- const live = this.agents.get(row.alias);
10614
- const adopted = live !== undefined && live.lifecycleUid === row.lifecycleUid;
10615
- if (planStaticSlotResume(row, adopted) !== "drive-terminal") {
10616
- item.disposition = "refused";
10617
- item.remedy = adopted ? "leave the adopted live lifecycle running" : "inspect the fresh durable slot state";
10618
- item.lastError = adopted
10619
- ? "the durable lifecycle is now backed by an adopted live managed agent"
10620
- : `the fresh durable phase ${row.phase} is not terminal-plannable`;
10621
- console.error(`! static reconcile refused alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
10622
- return;
10623
- }
10624
- await this.attemptStaticReconcile(key, item, row, false);
10625
- }
10626
- /** Enter one exact terminal at most once per coordinate. Sweep and timer triggers join the same
10627
- * promise. A settled failed item keeps its original per-process budget; a restart builds a fresh
10628
- * map from the still-authoritative durable row. */
10629
- attemptStaticReconcile(key, item, row, countAttempt = true) {
10630
- if (item.flight)
10631
- return item.flight;
10632
- if (item.timer)
10633
- return Promise.resolve({ succeeded: false });
10634
- // A timer/retry driver increments before its mandatory durable re-read, then calls with
10635
- // countAttempt=false. Let that already-consumed budget entry enter the terminal. Only a fresh
10636
- // sweep entry (countAttempt=true) is refused once the per-process budget is exhausted.
10637
- if (countAttempt && item.attempts >= item.maxAttempts)
10638
- return Promise.resolve({ succeeded: false });
10639
- const flight = (async () => {
10640
- if (countAttempt)
10641
- item.attempts++;
10642
- item.phase = row.phase;
10643
- item.disposition = "retrying";
10644
- item.nextRetryAt = undefined;
10645
- this.reconcilingAliases.add(row.alias);
10646
- console.error(`static reconcile terminal alias=${row.alias} phase=${row.phase} uid=${row.lifecycleUid} attempt=${item.attempts}/${item.maxAttempts}`);
10647
- let deprovision;
10648
- try {
10649
- await this.withRetirementSlot(() => this.driveStaticRetirement({ id: row.actor, name: row.alias, lifecycleUid: row.lifecycleUid, runtime: row.runtime }, true, (accounting) => { deprovision = accounting; }));
10650
- if (item.attempts === 1) {
10651
- this.staticReconcileItems.delete(key);
10652
- }
10653
- else {
10654
- item.phase = "retired";
10655
- item.disposition = "recovered";
10656
- item.recoveredAt = new Date().toISOString();
10657
- item.lastError = undefined;
10658
- console.error(`✓ static reconcile recovered alias=${item.alias} phase=retired uid=${item.lifecycleUid} attempts=${item.attempts}/${item.maxAttempts}`);
10659
- }
10660
- return { succeeded: true, deprovision };
10661
- }
10662
- catch (error) {
10663
- item.lastError = rejectionText(error);
10664
- try {
10665
- const fresh = await this.readStaticReconcileSlot(item.alias);
10666
- if (fresh?.lifecycleUid === item.lifecycleUid && fresh.actor === item.actor)
10667
- item.phase = fresh.phase;
10668
- }
10669
- catch { /* the terminal error remains primary; the next retry re-reads authoritatively */ }
10670
- const blocked = lifecycleBlockedFrom(error);
10671
- const ownOp = managedRetirementOpId(item.lifecycleUid);
10672
- const foreign = blocked !== undefined && (blocked.blockedOp !== "retirement" || blocked.opId !== ownOp);
10673
- if (foreign) {
10674
- item.disposition = "refused-foreign";
10675
- item.remedy = blocked?.remedy ?? "resolve the foreign durable operation; it is never force-cleared";
10676
- console.error(`! static reconcile refused-foreign alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}`);
10677
- }
10678
- else if (item.attempts >= item.maxAttempts) {
10679
- item.disposition = "retry-exhausted";
10680
- item.remedy = "restart this manager for a fresh per-process retry budget";
10681
- console.error(`! static reconcile retry-exhausted alias=${item.alias} phase=${item.phase} uid=${item.lifecycleUid}: ${item.lastError}; NEXT: restart this manager for a fresh per-process retry budget`);
10682
- }
10683
- else {
10684
- // The initial serial sweep must publish its complete failed aggregate before any timer can
10685
- // re-enter a middle row. Mark it now; the sweep arms the timer after its last planned row.
10686
- if (this.staticReconcileSweepsInFlight > 0)
10687
- item.disposition = "retry-scheduled";
10688
- else
10689
- this.scheduleStaticReconcileRetry(key, item);
10690
- }
10691
- return { succeeded: false, deprovision };
10692
- }
10693
- finally {
10694
- this.reconcilingAliases.delete(row.alias);
10695
- }
10696
- })();
10697
- item.flight = flight.finally(() => {
10698
- if (item.flight === wrapped)
10699
- item.flight = undefined;
10700
- });
10701
- const wrapped = item.flight;
10702
- return wrapped;
10703
- }
10704
- releaseStaticReconcileSweep() {
10705
- this.staticReconcileSweepsInFlight--;
10706
- if (this.staticReconcileSweepsInFlight !== 0)
10707
- return;
10708
- const waiters = this.staticReconcileDrainWaiters;
10709
- this.staticReconcileDrainWaiters = [];
10710
- for (const wake of waiters)
10711
- wake();
8524
+ readStaticReconcileSlot(alias) {
8525
+ return this.staticLifecycle.readStaticReconcileSlot(alias);
10712
8526
  }
10713
- /** Shutdown accepts no new static reconciliation work, then drains every sweep and exact-terminal
10714
- * flight that crossed the fence before stop(). A sweep can discover several rows before its first
10715
- * await, so the serial loop also consults the fence and never starts a later row after shutdown. */
10716
- async awaitStaticReconcileDrain() {
10717
- while (true) {
10718
- if (this.staticReconcileSweepsInFlight > 0)
10719
- await new Promise((resolve) => this.staticReconcileDrainWaiters.push(resolve));
10720
- const flights = [];
10721
- for (const item of this.staticReconcileItems.values()) {
10722
- if (item.flight)
10723
- flights.push(item.flight);
10724
- if (item.retryFlight)
10725
- flights.push(item.retryFlight);
10726
- }
10727
- if (flights.length === 0 && this.staticReconcileSweepsInFlight === 0)
10728
- return;
10729
- await Promise.allSettled(flights);
10730
- }
8527
+ awaitStaticReconcileDrain() {
8528
+ return this.staticLifecycle.awaitStaticReconcileDrain();
10731
8529
  }
10732
- async reconcileStaticLifecycles(postAdoption = false) {
10733
- if (!this.auth || this.staticReconcileStopping)
10734
- return;
10735
- // Admission is synchronous with the shutdown fence. Once this increments, stop() must drain the
10736
- // whole accepted sweep even if it is still minting its short-lived provisioner credential.
10737
- this.staticReconcileSweepsInFlight++;
10738
- try {
10739
- // Recovered is a transition report, not permanent history. The next sweep clears it before
10740
- // deriving a fresh plan; failed coordinates keep their per-process budget and are joined.
10741
- for (const [key, item] of this.staticReconcileItems) {
10742
- if (item.disposition === "recovered")
10743
- this.staticReconcileItems.delete(key);
10744
- }
10745
- const sweep = {
10746
- kind: postAdoption ? "post-adoption" : "startup",
10747
- startedAt: new Date().toISOString(),
10748
- attempted: 0,
10749
- succeeded: 0,
10750
- failed: 0,
10751
- };
10752
- this.staticReconcileLastSweep = sweep;
10753
- const slotRows = [];
10754
- // A sweep that stops before it plans any alias records why on the sweep itself: otherwise
10755
- // `status` cannot tell it from a sweep that collected and found nothing.
10756
- try {
10757
- const identity = newIdentity();
10758
- const creds = await mintCreds(this.auth, identity, "provisioner");
10759
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
10760
- try {
10761
- const jsm = await jetstreamManager(nc);
10762
- const kvm = new Kvm(nc);
10763
- await ensureAuthorityStores(jsm, kvm, this.space);
10764
- const recordsKv = await kvm.open(recordsBucket(this.space));
10765
- for (const slot of await walkStaticSlots(recordsKv, DEV_OWNER))
10766
- slotRows.push(slot.row);
10767
- }
10768
- finally {
10769
- await drainAndClose(nc);
10770
- }
10771
- }
10772
- catch (error) {
10773
- sweep.completedAt = new Date().toISOString();
10774
- sweep.error = rejectionText(error);
10775
- throw error;
10776
- }
10777
- let retiredSlots = 0;
10778
- let preservedForeign = 0;
10779
- let preservedAdopted = 0;
10780
- let deferredSlots = 0;
10781
- const terminalRows = [];
10782
- const restartRows = [];
10783
- for (const row of slotRows) {
10784
- if (row.phase === "retired") {
10785
- // A retirement is a GLOBAL refusal fact — seed the retired-principal index for EVERY retired incarnation
10786
- // regardless of which instance owned it, so a sibling-retired incarnation's copied credential
10787
- // is refused at this control surface too. Ownership gates only the DESTRUCTIVE sweep below.
10788
- this.retirement.rememberRetired(principalKey(row.owner, row.actor).key);
10789
- retiredSlots++;
10790
- continue;
10791
- }
10792
- // RECONCILE OWNERSHIP (multi-manager-per-space): a manager adjudicates ONLY the non-retired
10793
- // rows THIS logical instance owns. A SIBLING manager's active/provisioning row is LEFT UNTOUCHED —
10794
- // sweep-terminalizing it would destroy the sibling's live agent (the historical all-agents-kill
10795
- // hazard, now cross-instance). A legacy row (no owner recorded) predates multi-manager,
10796
- // so this manager is its legitimate single-manager-past successor and reconciles it. An orphaned
10797
- // sibling row is reclaimed only by an explicit operator CAS takeover, never here.
10798
- if (ownedBySibling(row, this.managerInstanceId)) {
10799
- preservedForeign++;
10800
- continue;
10801
- }
10802
- // A chat session this process is opening or holds is live membership, as an adopted seat
10803
- // is: its own open, expiry or stop runs its terminal, which this sweep must not race. The
10804
- // match is the exact registered alias, actor and UID under this logical instance and this
10805
- // process's incarnation, so a foreign, legacy or unrecorded row, or any UID this process
10806
- // did not register, falls through to the ordinary plan below.
10807
- if (this.holdsLiveChatSlot(row)) {
10808
- preservedAdopted++;
10809
- continue;
10810
- }
10811
- // ADOPTION is genuine membership: a slot backed by a live managed agent THIS process owns
10812
- // at the SAME uid is never an orphan (empty at boot; exactly the adopted set at the
10813
- // post-adoption sweep — the fix for the resume hole).
10814
- const live = this.agents.get(row.alias);
10815
- const adopted = live !== undefined && live.lifecycleUid === row.lifecycleUid;
10816
- if (adopted) {
10817
- preservedAdopted++;
10818
- }
10819
- // Boot sweep with a resume PENDING: an active slot may yet be adopted (the resume path runs
10820
- // AFTER this boot sweep), so DEFER it — the post-adoption sweep terminalizes any the resume
10821
- // did not claim. provisioning/terminalizing NEVER defer (they are crashed operations, never
10822
- // an agent to adopt). At `postAdoption` (or a non-resume boot) nothing defers.
10823
- if (!postAdoption && row.phase === "active" && !adopted && this.resumeRequired) {
10824
- deferredSlots++;
10825
- continue;
10826
- }
10827
- // A boot after this instance's manager ended without stopping its seats: a seat with a record
10828
- // is taken back instead of retired, restarted under its policy when supervised (#4094) and
10829
- // adopted while it still runs otherwise (#4095).
10830
- if (!postAdoption && row.phase === "active" && !adopted) {
10831
- const record = this.seatRecordFor(row);
10832
- if (record) {
10833
- restartRows.push({ row, record });
10834
- continue;
10835
- }
10836
- }
10837
- if (planStaticSlotResume(row, adopted) !== "none")
10838
- terminalRows.push(row);
10839
- }
10840
- try {
10841
- // Mark the complete planned set before the first terminal awaits. A timer owns only its own
10842
- // alias, but the initial serial sweep must close every discovery-to-await gap up front.
10843
- for (const row of terminalRows)
10844
- this.reconcilingAliases.add(row.alias);
10845
- for (const { row } of restartRows)
10846
- this.reconcilingAliases.add(row.alias);
10847
- // Restarts run first; one that cannot restart joins the terminals below.
10848
- for (const { row, record } of restartRows) {
10849
- if (this.staticReconcileStopping)
10850
- break;
10851
- // A supervised seat is restarted; any other seat is adopted while it still runs.
10852
- const refusal = record.supervise ? await this.restartSupervisedSeat(row, record) : await this.adoptSeat(row, record);
10853
- if (refusal === undefined) {
10854
- this.reconcilingAliases.delete(row.alias);
10855
- continue;
10856
- }
10857
- console.error(record.supervise
10858
- ? `! ${row.alias}: the supervised seat its previous manager left was not restarted (${refusal}); retiring the lifecycle`
10859
- : `! ${row.alias}: the seat its previous manager left was not adopted (${refusal}); retiring the lifecycle`);
10860
- this.dropSeatRecord({ name: row.alias, lifecycleUid: row.lifecycleUid });
10861
- terminalRows.push(row);
10862
- }
10863
- const sweepDeprovision = {
10864
- examined: 0,
10865
- deleted: 0,
10866
- absent: 0,
10867
- refused: 0,
10868
- acknowledged: 0,
10869
- disappeared: 0,
10870
- consumers: { examined: 0, deleted: 0, absent: 0, refused: 0, acknowledged: 0, disappeared: 0 },
10871
- acls: { examined: 0, deleted: 0, absent: 0, refused: 0, disappeared: 0 },
10872
- members: { examined: 0, deleted: 0, absent: 0, refused: 0, disappeared: 0 },
10873
- };
10874
- for (const row of terminalRows) {
10875
- if (this.staticReconcileStopping)
10876
- break;
10877
- sweep.attempted++;
10878
- const key = this.staticReconcileKey(row);
10879
- let item = this.staticReconcileItems.get(key);
10880
- if (!item) {
10881
- item = {
10882
- owner: row.owner,
10883
- alias: row.alias,
10884
- actor: row.actor,
10885
- lifecycleUid: row.lifecycleUid,
10886
- phase: row.phase,
10887
- attempts: 0,
10888
- maxAttempts: STATIC_RECONCILE_MAX_ATTEMPTS,
10889
- disposition: "retrying",
10890
- };
10891
- this.staticReconcileItems.set(key, item);
10892
- }
10893
- const attempt = await this.attemptStaticReconcile(key, item, row);
10894
- if (attempt.deprovision)
10895
- addDeprovisionAccounting(sweepDeprovision, attempt.deprovision);
10896
- if (attempt.succeeded)
10897
- sweep.succeeded++;
10898
- else
10899
- sweep.failed++;
10900
- this.reconcilingAliases.delete(row.alias);
10901
- }
10902
- sweep.completedAt = new Date().toISOString();
10903
- this.staticReconcileLastSweepResources = {
10904
- slots: {
10905
- examined: slotRows.length,
10906
- retired: retiredSlots,
10907
- preservedForeign,
10908
- preservedAdopted,
10909
- deferred: deferredSlots,
10910
- terminalized: sweep.succeeded,
10911
- failed: sweep.failed,
10912
- },
10913
- deprovision: sweepDeprovision,
10914
- };
10915
- for (const row of terminalRows) {
10916
- const key = this.staticReconcileKey(row);
10917
- const item = this.staticReconcileItems.get(key);
10918
- if (item?.disposition === "retry-scheduled" && !item.timer)
10919
- this.scheduleStaticReconcileRetry(key, item);
10920
- }
10921
- const failed = terminalRows.flatMap((row) => {
10922
- const item = this.staticReconcileItems.get(this.staticReconcileKey(row));
10923
- return item && item.disposition !== "recovered" ? [`${item.alias}:${item.phase}:${item.disposition}`] : [];
10924
- });
10925
- if (sweep.failed === 0) {
10926
- console.error(`✓ static reconcile completed: ${sweep.attempted} attempted, ${sweep.succeeded} succeeded, 0 failed`);
10927
- }
10928
- else {
10929
- console.error(`! static reconcile completed: ${sweep.attempted} attempted, ${sweep.succeeded} succeeded, ${sweep.failed} failed; failed=${failed.join(",")}`);
10930
- }
10931
- }
10932
- finally {
10933
- for (const row of terminalRows)
10934
- this.reconcilingAliases.delete(row.alias);
10935
- for (const { row } of restartRows)
10936
- this.reconcilingAliases.delete(row.alias);
10937
- }
10938
- }
10939
- finally {
10940
- this.releaseStaticReconcileSweep();
10941
- }
8530
+ reconcileStaticLifecycles(postAdoption = false) {
8531
+ return this.staticLifecycle.reconcileStaticLifecycles(postAdoption);
10942
8532
  }
10943
8533
  /** The membership gate: decide a control caller by its
10944
8534
  * AUTHENTICATED wire principal. A LIVE managed slot passes (unless terminalizing); a RETIRING