@cotal-ai/manager 0.171.4 → 0.172.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 (111) hide show
  1. package/dist/boot.d.ts +162 -0
  2. package/dist/boot.d.ts.map +1 -0
  3. package/dist/boot.js +627 -0
  4. package/dist/boot.js.map +1 -0
  5. package/dist/broker-transport.d.ts +6 -0
  6. package/dist/broker-transport.d.ts.map +1 -1
  7. package/dist/broker-transport.js +25 -6
  8. package/dist/broker-transport.js.map +1 -1
  9. package/dist/command-dispatch.d.ts +3 -0
  10. package/dist/command-dispatch.d.ts.map +1 -1
  11. package/dist/command-dispatch.js +67 -0
  12. package/dist/command-dispatch.js.map +1 -1
  13. package/dist/connector-inventory.d.ts +8 -0
  14. package/dist/connector-inventory.d.ts.map +1 -1
  15. package/dist/connector-inventory.js +28 -4
  16. package/dist/connector-inventory.js.map +1 -1
  17. package/dist/credential-renewal.d.ts +5 -1
  18. package/dist/credential-renewal.d.ts.map +1 -1
  19. package/dist/credential-renewal.js +65 -3
  20. package/dist/credential-renewal.js.map +1 -1
  21. package/dist/goal-writer.d.ts +3 -0
  22. package/dist/goal-writer.d.ts.map +1 -1
  23. package/dist/goal-writer.js +30 -0
  24. package/dist/goal-writer.js.map +1 -1
  25. package/dist/harness-resolution.d.ts +3 -0
  26. package/dist/harness-resolution.d.ts.map +1 -1
  27. package/dist/harness-resolution.js +14 -0
  28. package/dist/harness-resolution.js.map +1 -1
  29. package/dist/lease-keeper.d.ts +4 -0
  30. package/dist/lease-keeper.d.ts.map +1 -1
  31. package/dist/lease-keeper.js +10 -0
  32. package/dist/lease-keeper.js.map +1 -1
  33. package/dist/managed-static-lifecycle.d.ts +3 -0
  34. package/dist/managed-static-lifecycle.d.ts.map +1 -1
  35. package/dist/managed-static-lifecycle.js +42 -0
  36. package/dist/managed-static-lifecycle.js.map +1 -1
  37. package/dist/manager-service-contract.d.ts +6 -1
  38. package/dist/manager-service-contract.d.ts.map +1 -1
  39. package/dist/manager-service-contract.js +11 -3
  40. package/dist/manager-service-contract.js.map +1 -1
  41. package/dist/manager.d.ts +549 -354
  42. package/dist/manager.d.ts.map +1 -1
  43. package/dist/manager.js +86 -2222
  44. package/dist/manager.js.map +1 -1
  45. package/dist/names-capacity.d.ts +4 -0
  46. package/dist/names-capacity.d.ts.map +1 -1
  47. package/dist/names-capacity.js +29 -0
  48. package/dist/names-capacity.js.map +1 -1
  49. package/dist/persona-catalog.d.ts +3 -0
  50. package/dist/persona-catalog.d.ts.map +1 -1
  51. package/dist/persona-catalog.js +19 -0
  52. package/dist/persona-catalog.js.map +1 -1
  53. package/dist/preservation.d.ts +3 -0
  54. package/dist/preservation.d.ts.map +1 -1
  55. package/dist/preservation.js +48 -0
  56. package/dist/preservation.js.map +1 -1
  57. package/dist/preserved-resume.d.ts +220 -0
  58. package/dist/preserved-resume.d.ts.map +1 -0
  59. package/dist/preserved-resume.js +1222 -0
  60. package/dist/preserved-resume.js.map +1 -0
  61. package/dist/readiness-wait.d.ts +3 -0
  62. package/dist/readiness-wait.d.ts.map +1 -1
  63. package/dist/readiness-wait.js +11 -0
  64. package/dist/readiness-wait.js.map +1 -1
  65. package/dist/retirement.d.ts +4 -0
  66. package/dist/retirement.d.ts.map +1 -1
  67. package/dist/retirement.js +29 -0
  68. package/dist/retirement.js.map +1 -1
  69. package/dist/seat-custody.d.ts +4 -0
  70. package/dist/seat-custody.d.ts.map +1 -1
  71. package/dist/seat-custody.js +25 -0
  72. package/dist/seat-custody.js.map +1 -1
  73. package/dist/seat-launch.d.ts +3 -0
  74. package/dist/seat-launch.d.ts.map +1 -1
  75. package/dist/seat-launch.js +69 -0
  76. package/dist/seat-launch.js.map +1 -1
  77. package/dist/seat-stop.d.ts +3 -0
  78. package/dist/seat-stop.d.ts.map +1 -1
  79. package/dist/seat-stop.js +40 -0
  80. package/dist/seat-stop.js.map +1 -1
  81. package/dist/seat-types.d.ts +6 -6
  82. package/dist/seat-types.d.ts.map +1 -1
  83. package/dist/serve-plane.d.ts +5 -0
  84. package/dist/serve-plane.d.ts.map +1 -1
  85. package/dist/serve-plane.js +78 -1
  86. package/dist/serve-plane.js.map +1 -1
  87. package/dist/session-recovery.d.ts +4 -0
  88. package/dist/session-recovery.d.ts.map +1 -1
  89. package/dist/session-recovery.js +31 -0
  90. package/dist/session-recovery.js.map +1 -1
  91. package/dist/spawn-goal.d.ts +3 -0
  92. package/dist/spawn-goal.d.ts.map +1 -1
  93. package/dist/spawn-goal.js +23 -0
  94. package/dist/spawn-goal.js.map +1 -1
  95. package/dist/start-doors.d.ts +3 -0
  96. package/dist/start-doors.d.ts.map +1 -1
  97. package/dist/start-doors.js +14 -0
  98. package/dist/start-doors.js.map +1 -1
  99. package/dist/status-and-models.d.ts +3 -0
  100. package/dist/status-and-models.d.ts.map +1 -1
  101. package/dist/status-and-models.js +42 -1
  102. package/dist/status-and-models.js.map +1 -1
  103. package/dist/terminal-input.d.ts +3 -0
  104. package/dist/terminal-input.d.ts.map +1 -1
  105. package/dist/terminal-input.js +12 -0
  106. package/dist/terminal-input.js.map +1 -1
  107. package/dist/user-provision.d.ts +4 -0
  108. package/dist/user-provision.d.ts.map +1 -1
  109. package/dist/user-provision.js +17 -0
  110. package/dist/user-provision.js.map +1 -1
  111. package/package.json +12 -12
package/dist/manager.js CHANGED
@@ -1,57 +1,52 @@
1
- import { UserProvision } from "./user-provision.js";
2
- import { TurnRelay, goalKey, caughtEnvelope, TURN_ANSWER_RETENTION_MS } from "./turn-relay.js";
3
- import { createHash, randomBytes } from "node:crypto";
4
- import { drainAndClose } from "@cotal-ai/core";
5
- import { hostname } from "node:os";
6
- import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
1
+ import { UserProvision, userProvisionDeps } from "./user-provision.js";
2
+ import { TurnRelay, goalKey, TURN_ANSWER_RETENTION_MS } from "./turn-relay.js";
3
+ import { createHash } from "node:crypto";
4
+ import { existsSync, lstatSync, readFileSync, readdirSync, rmSync } from "node:fs";
7
5
  import { join, resolve } from "node:path";
8
- import { CotalEndpoint, copyPersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, injectedSecretStoreIdentity, idFromCreds, identityFromCreds, loadAgentFile, loadCotalConfig, mintCreds, mintLifecycleUid, newIdentity, oneLine, parsePrincipalKey, principalKey, probeConnect, resolveAuthProvider, } from "@cotal-ai/core";
6
+ import { CotalEndpoint, accountFromCreds, DEFAULT_SERVER, DEV_OWNER, injectedSecretStoreIdentity, mintLifecycleUid, oneLine, parsePrincipalKey, principalKey, probeConnect, resolveAuthProvider } from "@cotal-ai/core";
9
7
  import { retainConnectorSeat } from "@cotal-ai/workspace";
10
8
  import { logicalExecutionEntry } from "@cotal-ai/workspace";
11
- import { agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, DEFAULT_SEAT_CAP, findCotalRoot, getSpaceAuth, hasUserAuthState, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
12
- import { createRuntime, isCustodialRuntime, requireRuntimeAdopt, requireRuntimeReap, } from "./runtime/index.js";
13
- import { Retirement } from "./retirement.js";
14
- import { ServePlane } from "./serve-plane.js";
15
- import { NamesCapacity } from "./names-capacity.js";
9
+ import { agentSecretKeyForFile, DEFAULT_SEAT_CAP, findCotalRoot, loadManagerInstanceIdentity, manifestExtensionNames, materializeFromManifest, runtimeInstallHint, spaceKey, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
10
+ import { createRuntime, isCustodialRuntime, requireRuntimeAdopt, } from "./runtime/index.js";
11
+ import { Retirement, retirementDeps } from "./retirement.js";
12
+ import { ServePlane, servePlaneDeps } from "./serve-plane.js";
13
+ import { NamesCapacity, namesCapacityDeps } from "./names-capacity.js";
16
14
  import { AttachEndpoint } from "./attach-endpoint.js";
17
- import { DELIVERY_ADMIN_BOOT_WAIT_MS, makeManagerEndpointHolderEvictor } from "./endpoint-evict.js";
18
- import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
19
- import { ManagedStaticLifecycle, STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
15
+ import { ManagedStaticLifecycle, managedStaticLifecycleDeps, STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
20
16
  export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
21
17
  export { credRenewIntervalMs } from "./credential-renewal.js";
22
- import { LeaseKeeper } from "./lease-keeper.js";
18
+ import { LeaseKeeper, leaseKeeperDeps } from "./lease-keeper.js";
23
19
  export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
24
- import { SessionRecovery } from "./session-recovery.js";
25
- import { SeatCustody, watchConnectorHolder } from "./seat-custody.js";
26
- import { GoalWriter } from "./goal-writer.js";
27
- import { DEPROVISION_TIMEOUT_MS, SeatStop } from "./seat-stop.js";
28
- import { CommandDispatch, participantKey } from "./command-dispatch.js";
29
- import { SpawnGoal } from "./spawn-goal.js";
30
- import { PersonaCatalog } from "./persona-catalog.js";
31
- import { TerminalInput } from "./terminal-input.js";
32
- import { StatusAndModels, MANAGER_VERSION } from "./status-and-models.js";
33
- import { ReadinessWait } from "./readiness-wait.js";
34
- import { BrokerTransport } from "./broker-transport.js";
35
- import { StartDoors } from "./start-doors.js";
36
- import { HarnessResolution, resolveHarness } from "./harness-resolution.js";
37
- import { ConnectorInventory } from "./connector-inventory.js";
38
- import { Preservation } from "./preservation.js";
20
+ import { SessionRecovery, sessionRecoveryDeps } from "./session-recovery.js";
21
+ import { SeatCustody, seatCustodyDeps, watchConnectorHolder } from "./seat-custody.js";
22
+ import { GoalWriter, goalWriterDeps } from "./goal-writer.js";
23
+ import { SeatStop, seatStopDeps } from "./seat-stop.js";
24
+ import { CommandDispatch, commandDispatchDeps, participantKey } from "./command-dispatch.js";
25
+ import { SpawnGoal, spawnGoalDeps } from "./spawn-goal.js";
26
+ import { PersonaCatalog, personaCatalogDeps } from "./persona-catalog.js";
27
+ import { TerminalInput, terminalInputDeps } from "./terminal-input.js";
28
+ import { StatusAndModels, statusAndModelsDeps, MANAGER_VERSION } from "./status-and-models.js";
29
+ import { ReadinessWait, readinessWaitDeps } from "./readiness-wait.js";
30
+ import { BrokerTransport, brokerTransportDeps } from "./broker-transport.js";
31
+ import { StartDoors, startDoorsDeps } from "./start-doors.js";
32
+ import { HarnessResolution, harnessResolutionDeps, resolveHarness } from "./harness-resolution.js";
33
+ import { ConnectorInventory, connectorInventoryDeps } from "./connector-inventory.js";
34
+ import { Preservation, preservationDeps } from "./preservation.js";
35
+ import { PreservedResume, preservedResumeDeps, bearerEntryArgv } from "./preserved-resume.js";
39
36
  export { PASTE_END, PASTE_START, RUNTIME_NO_TERMINAL_DETAIL } from "./terminal-input.js";
40
- import { CredentialRenewal, credRenewIntervalMs, REMOTE_STANDING_BUDGET_MS, remoteStandingTimeLeft, sameStrings } from "./credential-renewal.js";
41
- import { SeatLaunch, foreignEventChannels } from "./seat-launch.js";
37
+ import { CredentialRenewal, credentialRenewalDeps } from "./credential-renewal.js";
38
+ import { SeatLaunch, seatLaunchDeps } from "./seat-launch.js";
39
+ import { ManagerBoot, bootDeps } from "./boot.js";
42
40
  import { withTimeout } from "./manager-timeout.js";
43
- import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
44
- import { inlineSnapshotPath, launchSpecForRun } from "./launch.js";
41
+ import { inlineSnapshotPath } from "./launch.js";
45
42
  import { authorizeNamedControl } from "./authorize.js";
46
43
  import { RunHosting } from "./run-hosting.js";
47
44
  import { rejectionText, attemptCleanup } from "@cotal-ai/core";
48
- import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference } from "./resume.js";
45
+ import { readReleasedSeatReference } from "./resume.js";
49
46
  import { TranscriptReceiver } from "./transcript-receive.js";
50
47
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
51
48
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
52
- import { jetstreamManager } from "@nats-io/jetstream";
53
- import { Kvm } from "@nats-io/kv";
54
- import { recordsBucket, ensureAuthorityStores, standaloneConnectOpts } from "@cotal-ai/core";
49
+ import {} from "@cotal-ai/core";
55
50
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
56
51
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
57
52
  // per-session credentials on their own short-lived connections).
@@ -59,9 +54,8 @@ import { ManagerSessionPlane } from "./session/index.js";
59
54
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
60
55
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
61
56
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
62
- import { epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, listGoalIndex, turnNoticeSubject, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom } from "@cotal-ai/core";
57
+ import { readEndpointGateGeneration, deregisterServiceInstance, turnNoticeSubject, EpEnvelopeError } from "@cotal-ai/core";
63
58
  import { MANAGER_ENDPOINT } from "./manager-service-contract.js";
64
- import { ownedBySibling, } from "./static-lifecycle.js";
65
59
  /** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
66
60
  * stays and the turn sweep asks again. */
67
61
  const ONCE_RETIRE_MS = 60_000;
@@ -78,10 +72,6 @@ export const READINESS_TIMEOUT_MS = 30_000;
78
72
  * from its launch: the watch's 15s for the confirm prompt and 15s for its notice, plus 5s for the
79
73
  * last read. The readiness window applies when it is longer. */
80
74
  const STARTUP_OUTCOME_MS = 35_000;
81
- /** How often a resumed seat whose readiness was uncertain is checked for a join its predecessor's
82
- * presence row hides (see {@link Manager.watchResumeAdoption}). The wait has no end of its own, so
83
- * it asks less often than the readiness fence's 50 ms poll. */
84
- const LATE_JOIN_POLL_MS = 1_000;
85
75
  /** At most this many retirements run at once (#4965). A retirement dials up to four fresh broker
86
76
  * connections in turn and queues an eviction and an inventory on the delivery daemon's admin rail,
87
77
  * each against a fixed deadline. A stop that started all 50 seats' retirements together lost most of
@@ -94,46 +84,6 @@ const RETIREMENT_CONCURRENCY = 8;
94
84
  /** A hard preservation stop should settle quickly. The manager still waits and reports a partial
95
85
  * cut rather than pretending a child is gone. Held in ManagerOptions so fake runtimes can shorten it. */
96
86
  const PRESERVE_STOP_TIMEOUT_MS = 10_000;
97
- /** How long a resume waits for a reaped orphan's principal to leave presence. Presence rows age
98
- * out after their 6s TTL, so three TTLs covers a killed seat that never published its leave. */
99
- const ORPHAN_PRESENCE_CLEAR_MS = 20_000;
100
- /** Startup reconciliation overlaps control-service registration. A spawn or attach for one of
101
- * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
102
- * a reuse. */
103
- const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
104
- /** The owner a retained seat resumes under: its inventory identity's, which is the same value the
105
- * adopted seat records as `userOwner`, so a resumed seat is counted against the owner that held
106
- * it before the restart ({@link Manager.ownerSeats}) and not against the mesh's default one. */
107
- function resumeOwner(entry) {
108
- return entry.identity.mode === "user" ? entry.identity.owner : DEV_OWNER;
109
- }
110
- /** Why a frozen manager gate stays frozen on an open mesh. Reconciliation must prove the holder
111
- * gone, and an open mesh runs no delivery daemon to prove it, so neither boot self-heal nor
112
- * `cotal manager reconcile` can reopen the gate there. */
113
- const OPEN_MESH_GATE_LIMIT = "reconciliation needs liveness evidence an open mesh cannot currently provide, so `cotal manager reconcile` refuses this gate. Keep this store intact; upgrading alone does not recover it";
114
- /** The open mesh's registration evictor. An open mesh has no eviction oracle, so the superseded
115
- * family's holders stay unverified as they do with no evictor, and the barrier keeps the gate
116
- * frozen. Throwing instead of answering `false` only puts the reason in the refusal. */
117
- function openMeshUnverifiedEviction(holders) {
118
- throw new Error(`principal(s) ${holders.map((h) => `"${h}"`).join(", ")} not verified evicted: ${OPEN_MESH_GATE_LIMIT}`);
119
- }
120
- /** An open-mesh registration refused by a gate another registration froze, restated without the
121
- * `cotal reconcile-gate` remedy that cannot run there. Code, gate state, blocked op and op id are
122
- * kept. Any other failure is returned as it is. */
123
- function openMeshFrozenGateRefusal(e, instanceId) {
124
- const envelope = caughtEnvelope(e);
125
- const blocked = lifecycleBlockedFrom(envelope);
126
- if (envelope === undefined || blocked?.gateState !== "frozen" || blocked.blockedOp !== "registration")
127
- return e;
128
- return lifecycleBlocked(envelope.code, `the issuance gate for "${instanceId}" is frozen under another registration, and this manager cannot register while it is; ${OPEN_MESH_GATE_LIMIT} (SPEC 13.8)`, { blockedOp: blocked.blockedOp, gateState: blocked.gateState, ...(blocked.opId !== undefined ? { opId: blocked.opId } : {}) }, envelope.outcome);
129
- }
130
- /** The start of every agent's bearer command: node, its loader flags and this manager's entry,
131
- * resolved through every symlink. The agent runs that command for each renewal for as long as it
132
- * lives, and an install can replace the bin link meanwhile: get.cotal.ai writes a shell launcher
133
- * over `~/.local/bin/cotal`, which `npm i -g` had made a link to `dist/cotal.js`. */
134
- function bearerEntryArgv() {
135
- return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
136
- }
137
87
  const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
138
88
  /** The refusal a control instance with `execution: none` gives every launch, hosting, model and write door. */
139
89
  const EXECUTION_NONE_REFUSAL = "execution: none forbids seat launch, workflow hosting, model inspection and caller-driven writes on this control instance; select the participant Manager with an instance-pinned manager-caller view";
@@ -356,79 +306,8 @@ export class Manager {
356
306
  /** True on a USER-AUTH space (the on-disk marker; cross-checked against the registry at start).
357
307
  * Gates the whole spawn path: user mode grants ledger actors + bearer plumbing, never static mints. */
358
308
  userMode = false;
359
- namesCapacity = new NamesCapacity({
360
- userMode: () => this.userMode,
361
- seatCap: () => this.seatCap,
362
- managerInstanceId: () => this.managerInstanceId,
363
- agents: () => this.agents.values(),
364
- authEnabled: () => this.auth !== undefined,
365
- maintenanceActive: () => this.maintenanceState === "active",
366
- roster: () => this.ep.getRoster(),
367
- agentFor: (name) => this.agents.get(name),
368
- hasAgent: (name) => this.agents.has(name),
369
- removeAgent: (name) => { this.agents.delete(name); },
370
- managedCount: () => this.agents.size,
371
- predecessor: (name) => this.retirement.predecessor(name),
372
- hasRetirementHold: (name) => this.retirement.hasHold(name),
373
- holdRetirement: (name, hold) => this.retirement.hold(name, hold),
374
- endSessionsForTarget: (...args) => { this.sessionPlane?.endForTarget(...args); },
375
- logSeatReaped: (...args) => this.logSeatReaped(...args),
376
- recordContinuityAtStop: (...args) => this.recordContinuityAtStop(...args),
377
- releasedSeatPending: (...args) => this.releasedSeatPending(...args),
378
- dropSeatRecord: (...args) => this.dropSeatRecord(...args),
379
- failSeatTurns: (...args) => this.failSeatTurns(...args),
380
- teardownTarget: (...args) => this.teardownTarget(...args),
381
- dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
382
- trackDeprovision: (...args) => this.trackDeprovision(...args),
383
- });
384
- servePlane = new ServePlane({
385
- auth: () => this.auth,
386
- remoteAuthority: () => this.remoteAuthority,
387
- space: () => this.space,
388
- servers: () => this.servers,
389
- workspaceRoot: () => this.workspaceRoot,
390
- managerInstanceId: () => this.managerInstanceId,
391
- managerServeIdentity: () => this.managerServeIdentity,
392
- leaseStopping: () => this.leaseStopping,
393
- remoteBundleRenewal: () => this.remoteBundleRenewal,
394
- maxSessions: () => this.maxSessions,
395
- serviceServe: () => this.serviceServe,
396
- setServiceServe: (value) => { this.serviceServe = value; },
397
- sessionLedgerIdentity: () => this.sessionLedgerIdentity,
398
- setSessionLedgerIdentity: (value) => { this.sessionLedgerIdentity = value; },
399
- sessionLedgerCreds: () => this.sessionLedgerCreds,
400
- setSessionLedgerCreds: (value) => { this.sessionLedgerCreds = value; },
401
- sessionLedgerConn: () => this.sessionLedgerConn,
402
- setSessionLedgerConn: (value) => { this.sessionLedgerConn = value; },
403
- sessionPlane: () => this.sessionPlane,
404
- setSessionPlane: (value) => { this.sessionPlane = value; },
405
- sessionKeyRenewTimer: () => this.sessionKeyRenewTimer,
406
- setSessionKeyRenewTimer: (value) => { this.sessionKeyRenewTimer = value; },
407
- connectorStatuses: () => { this.refreshUnavailableConnectors(); return this.connectorStatuses; },
408
- setGoalWriterIdentity: (value) => { this.goalWriterIdentity = value; },
409
- setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
410
- remoteStandingBudgetMs: REMOTE_STANDING_BUDGET_MS,
411
- dial: (...args) => this.dial(...args),
412
- dialRemoteStanding: (...args) => this.dialRemoteStanding(...args),
413
- trackTransport: (...args) => this.trackTransport(...args),
414
- discardServeCandidate: (...args) => this.discardServeCandidate(...args),
415
- managerServiceDefs: (...args) => this.managerServiceDefs(...args),
416
- omitClassCommands: (...args) => this.omitClassCommands(...args),
417
- resolveTarget: (target) => this.resolveServeTarget(target),
418
- withEndpointServeExecutor: (...args) => this.withEndpointServeExecutor(...args),
419
- withOpenServeConnection: (...args) => this.withOpenServeConnection(...args),
420
- boundedReconnect: (...args) => this.boundedReconnect(...args),
421
- renewRemoteBeforeRedial: (...args) => this.renewRemoteBeforeRedial(...args),
422
- scheduleServeRenewal: (...args) => this.scheduleServeRenewal(...args),
423
- stop: (...args) => this.stop(...args),
424
- healFrozenRegistrationGate: (...args) => this.healFrozenRegistrationGate(...args),
425
- mintAndStageGoalWriter: (...args) => this.mintAndStageGoalWriter(...args),
426
- retireConnection: (...args) => this.retireConnection(...args),
427
- withTimeout,
428
- remoteStandingTimeLeft,
429
- openMeshUnverifiedEviction,
430
- openMeshFrozenGateRefusal,
431
- });
309
+ namesCapacity = new NamesCapacity(namesCapacityDeps(this));
310
+ servePlane = new ServePlane(servePlaneDeps(this));
432
311
  resolveServeTarget(t) {
433
312
  if (this.remoteAuthority) {
434
313
  const key = principalKey(t.owner, t.actor).key;
@@ -450,35 +329,8 @@ export class Manager {
450
329
  return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
451
330
  return undefined;
452
331
  }
453
- retirement = new Retirement({
454
- auth: () => this.auth,
455
- remoteAuthority: () => this.remoteAuthority,
456
- userMode: () => this.userMode,
457
- workspaceRoot: () => this.workspaceRoot,
458
- space: () => this.space,
459
- servers: () => this.servers,
460
- secrets: () => this.secrets,
461
- serveIdentity: () => this.managerServeIdentity,
462
- lifecycleUid: () => this.managerLifecycleUid,
463
- instanceId: () => this.managerInstanceId,
464
- serveEpoch: () => this.serviceServe?.grant.epoch,
465
- dial: (opts) => this.dial(opts),
466
- withRetirementSlot: (run) => this.withRetirementSlot(run),
467
- driveStaticRetirement: (a) => this.driveStaticRetirement(a),
468
- awaitHandleExit: (handle) => this.awaitHandleExit(handle),
469
- shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
470
- dropSeatRecord: (a) => this.dropSeatRecord(a),
471
- fenceRetiringAcl: (a) => this.fenceRetiringAcl(a),
472
- lifecycleMembershipInventory: (a) => this.lifecycleMembershipInventory(a),
473
- brokerTeardown: (task, message) => withTimeout(task, DEPROVISION_TIMEOUT_MS, message),
474
- trackLifecycle: () => { this.lifecycleInFlight++; return () => this.releaseLifecycle(); },
475
- });
476
- lease = new LeaseKeeper({
477
- endpoint: () => this.ep,
478
- instanceId: () => this.managerInstanceId,
479
- space: () => this.space,
480
- stopping: () => this.leaseStopping,
481
- });
332
+ retirement = new Retirement(retirementDeps(this));
333
+ lease = new LeaseKeeper(leaseKeeperDeps(this));
482
334
  get leaseInfo() { return this.lease.leaseInfo; }
483
335
  set leaseInfo(info) { this.lease.leaseInfo = info; }
484
336
  get leaseRevision() { return this.lease.leaseRevision; }
@@ -519,17 +371,8 @@ export class Manager {
519
371
  unverifiedStops = [];
520
372
  preservationInventory;
521
373
  resumeAttemptId;
522
- resumeInventoryDigest;
523
- resumeInventory;
524
- resumeTask;
525
- resumeResult;
526
374
  resumeRequired = false;
527
- resumeAwaitingCommit = false;
528
- resumeCommitted = false;
529
- resumeCommitTask;
530
- resumeFinalized = false;
531
375
  resumeDurableCommitToken;
532
- resumedAgentNames = new Set();
533
376
  remoteAuthority;
534
377
  remoteExecutorCreds;
535
378
  remoteSupervisorCreds;
@@ -543,545 +386,47 @@ export class Manager {
543
386
  dial(...args) { return this.brokerTransportComponent.dial(...args); }
544
387
  /** {@link BrokerTransport.dialRemoteStanding}. */
545
388
  dialRemoteStanding(...args) { return this.brokerTransportComponent.dialRemoteStanding(...args); }
546
- seatCustody = new SeatCustody({
547
- staticAuth: () => !!this.auth && !this.userMode,
548
- workspaceRoot: () => this.workspaceRoot,
549
- space: () => this.space,
550
- instanceId: () => this.managerInstanceId,
551
- endpoint: () => this.ep,
552
- secrets: () => this.secrets,
553
- eventPayloadsWithheld: () => this.eventPayloadsWithheld,
554
- runtimeFor: (kind) => this.runtimeFor(kind),
555
- requiredRuntime: () => this.requiredRuntime,
556
- withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
557
- watchConnectorHolder: (handle, holder) => this.watchConnectorHolder(handle, holder),
558
- resumeEntryOf: (agent) => this.resumeEntryOf(agent),
559
- inventoryReferenceError: (entry) => this.inventoryReferenceError(entry),
560
- registerAgent: (name, agent) => { this.agents.set(name, agent); },
561
- agentFor: (name) => this.agents.get(name),
562
- watchExit: (agent) => this.watchExit(agent),
563
- bindOnceSeat: (agent) => this.bindOnceSeat(agent),
564
- renewManagedStaticCred: (agent) => this.renewManagedStaticCred(agent),
565
- resumeSupervisedAgent: (entry, supervised) => this.resumePreservedAgent(entry, false, false, undefined, supervised),
566
- });
567
- sessionRecovery = new SessionRecovery({
568
- workspaceRoot: () => this.workspaceRoot,
569
- execution: () => this.execution,
570
- executionRefusal: () => this.executionRefusal(),
571
- instanceId: () => this.managerInstanceId,
572
- endpoint: () => this.ep,
573
- beginLifecycle: () => this.beginLifecycle(),
574
- freeSlot: (agent, floor, cause) => this.freeSlot(agent, floor, cause),
575
- reapChildrenOf: (principal) => this.reapChildrenOf(principal),
576
- managedPrincipal: (agent) => this.managedPrincipal(agent),
577
- inlineSnapshotChange: (agent) => this.inlineSnapshotChange(agent),
578
- agentFor: (name) => this.agents.get(name),
579
- maintenanceState: () => this.maintenanceState,
580
- resolveConnector: (name) => this.resolveConnector(name),
581
- runtimeFor: (kind) => this.runtimeFor(kind),
582
- reserveCustody: (runtime) => this.reserveCustody(runtime),
583
- recordSlotCustody: (agent, reference) => this.recordSlotCustody(agent, reference),
584
- spawnCustodied: (runtime, name, spec, cwd, reserved) => this.spawnCustodied(runtime, name, spec, cwd, reserved),
585
- awaitReadiness: (agent, timeoutMs, opts) => this.awaitReadiness(agent, timeoutMs, opts),
586
- readinessTimeoutMs: () => this.readinessTimeoutMs,
587
- recordSlotRuntime: (agent) => this.recordSlotRuntime(agent),
588
- refreshSeatRecord: (agent) => this.refreshSeatRecord(agent),
589
- watchExit: (agent) => this.watchExit(agent),
590
- tail: (session) => this.tail(session),
591
- stopHandle: (agent, graceful, cause) => this.stopHandle(agent, graceful, cause),
592
- trackStoppedHandle: (agent, floor, cause) => this.trackStoppedHandle(agent, floor, cause),
593
- });
389
+ seatCustody = new SeatCustody(seatCustodyDeps(this));
390
+ sessionRecovery = new SessionRecovery(sessionRecoveryDeps(this));
594
391
  get staticReconcileLastSweepResources() { return this.staticLifecycle.resources(); }
595
392
  set staticReconcileLastSweepResources(value) { this.staticLifecycle.setResources(value); }
596
- staticLifecycle = new ManagedStaticLifecycle({
597
- space: () => this.space,
598
- servers: () => this.servers,
599
- auth: () => this.auth,
600
- secrets: () => this.secrets,
601
- workspaceRoot: () => this.workspaceRoot,
602
- instanceId: () => this.managerInstanceId,
603
- processUid: () => this.managerLifecycleUid,
604
- userMode: () => this.userMode,
605
- eventPayloadsWithheld: () => this.eventPayloadsWithheld,
606
- evictor: () => this.staticLifecycleEvict,
607
- retryDelays: () => this.staticReconcileRetryDelaysMs,
608
- resumeRequired: () => this.resumeRequired,
609
- records: () => this.goalWriter?.ctx.kv,
610
- agentFor: (name) => this.agents.get(name),
611
- retirementFor: (name) => this.retirement.held(name),
612
- recordStaticRetirement: (a) => this.retirement.recordStaticRetirement(a),
613
- noteRetiredPrincipal: (principal) => { this.retirement.rememberRetired(principal); },
614
- foreignEventChannels: (channels, owner, actor) => foreignEventChannels(channels, owner, actor),
615
- withIssuer: (fn) => this.withIssuer(fn),
616
- deprovisionBroker: (a) => this.deprovisionBroker(a),
617
- reapOrphanSeat: (a) => this.reapOrphanSeat(a),
618
- withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
619
- readerRemedy: (owner, channel) => this.readerRemedy(owner, channel),
620
- withProvisioner: (fn) => this.withProvisioner(fn),
621
- beginLifecycle: (resumeOperation) => this.beginLifecycle(resumeOperation),
622
- maintenanceError: () => this.maintenanceError(),
623
- withRetirementSlot: (run) => this.withRetirementSlot(run),
624
- managedStaticInstanceReads: (capabilities) => this.managedStaticInstanceReads(capabilities),
625
- issuanceSeam: (i, mode, a, exp) => this.issuanceSeam(i, mode, a, exp),
626
- refreshSeatRecord: (a) => this.refreshSeatRecord(a),
627
- dial: (opts) => this.dial(opts),
628
- seatRecordFor: (row) => this.seatRecordFor(row),
629
- restartSupervisedSeat: (row, record) => this.restartSupervisedSeat(row, record),
630
- adoptSeat: (row, record) => this.adoptSeat(row, record),
631
- dropSeatRecord: (a) => this.dropSeatRecord(a),
632
- });
393
+ staticLifecycle = new ManagedStaticLifecycle(managedStaticLifecycleDeps(this));
633
394
  /** User-mode provisioning owns no manager state: each dependency reads through at its use. */
634
- userProvision = new UserProvision({
635
- space: () => this.space,
636
- workspaceRoot: () => this.workspaceRoot,
637
- secrets: () => this.secrets,
638
- managerInstanceId: () => this.managerInstanceId,
639
- runHosting: () => this.runHosting,
640
- remoteAuthority: () => this.remoteAuthority,
641
- deprovision: (target) => this.deprovision(target),
642
- withProvisioner: (fn) => this.withProvisioner(fn),
643
- shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
644
- bearerEntryArgv,
645
- });
395
+ userProvision = new UserProvision(userProvisionDeps(this));
646
396
  /** Seat stop, exit, recursive reap and named despawn. Every dependency reads through at its use. */
647
- seatStopComponent = new SeatStop({
648
- agentGoals: () => this.agentGoals,
649
- agents: () => this.agents,
650
- auth: () => this.auth,
651
- ep: () => this.ep,
652
- execution: () => this.execution,
653
- goalWriter: () => this.goalWriter,
654
- lifecycleInFlight: () => this.lifecycleInFlight,
655
- setLifecycleInFlight: (value) => { this.lifecycleInFlight = value; },
656
- maintenanceState: () => this.maintenanceState,
657
- managerInstanceId: () => this.managerInstanceId,
658
- remoteAuthority: () => this.remoteAuthority,
659
- retirement: () => this.retirement,
660
- servers: () => this.servers,
661
- serviceServe: () => this.serviceServe,
662
- space: () => this.space,
663
- unverifiedStops: () => this.unverifiedStops,
664
- setUnverifiedStops: (value) => { this.unverifiedStops = value; },
665
- workspaceRoot: () => this.workspaceRoot,
666
- assertGoalWriterEpochCurrent: (...args) => this.assertGoalWriterEpochCurrent(...args),
667
- authorizeNamed: (...args) => this.authorizeNamed(...args),
668
- awaitHandleExit: (...args) => this.awaitHandleExit(...args),
669
- beginLifecycle: (...args) => this.beginLifecycle(...args),
670
- confirmRetirement: (...args) => this.confirmRetirement(...args),
671
- emitGoalProgress: (...args) => this.emitGoalProgress(...args),
672
- executionRefusal: (...args) => this.executionRefusal(...args),
673
- expireGoalAcceptance: (...args) => this.expireGoalAcceptance(...args),
674
- freeSlot: (...args) => this.freeSlot(...args),
675
- maintenanceError: (...args) => this.maintenanceError(...args),
676
- managedPrincipal: (...args) => this.managedPrincipal(...args),
677
- readManagedSessionState: (...args) => this.readManagedSessionState(...args),
678
- recoverManagedSession: (...args) => this.recoverManagedSession(...args),
679
- releaseLifecycle: (...args) => this.releaseLifecycle(...args),
680
- shredUserSecrets: (...args) => this.shredUserSecrets(...args),
681
- trackDeprovision: (...args) => this.trackDeprovision(...args),
682
- });
397
+ seatStopComponent = new SeatStop(seatStopDeps(this));
683
398
  /** The typed command table and its admission. Every dependency reads through at its use. */
684
- commandDispatch = new CommandDispatch({
685
- agents: () => this.agents,
686
- auth: () => this.auth,
687
- execution: () => this.execution,
688
- goalWriter: () => this.goalWriter,
689
- managerInstanceId: () => this.managerInstanceId,
690
- participants: () => this.participants,
691
- remoteAuthority: () => this.remoteAuthority,
692
- resumeRequired: () => this.resumeRequired,
693
- runHosting: () => this.runHosting,
694
- space: () => this.space,
695
- transcripts: () => this.transcripts,
696
- userMode: () => this.userMode,
697
- workspaceRoot: () => this.workspaceRoot,
698
- attachAuthorized: (...args) => this.attachAuthorized(...args),
699
- authorizeNamed: (...args) => this.authorizeNamed(...args),
700
- authorizeRunAmend: (...args) => this.authorizeRunAmend(...args),
701
- authorizeRunAnswer: (...args) => this.authorizeRunAnswer(...args),
702
- beginLifecycle: (...args) => this.beginLifecycle(...args),
703
- despawnAuthorized: (...args) => this.despawnAuthorized(...args),
704
- executionRefusal: (...args) => this.executionRefusal(...args),
705
- findManagedByTarget: (...args) => this.findManagedByTarget(...args),
706
- inputAuthorized: (...args) => this.inputAuthorized(...args),
707
- lifecycleMembershipRefusal: (...args) => this.lifecycleMembershipRefusal(...args),
708
- list: (...args) => this.list(...args),
709
- listSpawnDirectory: (...args) => this.listSpawnDirectory(...args),
710
- loggedSpawnRefusal: (ctx, fn) => this.loggedSpawnRefusal(ctx, fn),
711
- maintenanceError: (...args) => this.maintenanceError(...args),
712
- managedPrincipal: (...args) => this.managedPrincipal(...args),
713
- managerStatusData: (...args) => this.managerStatusData(...args),
714
- opCommitResume: (...args) => this.opCommitResume(...args),
715
- opDefinePersona: (...args) => this.opDefinePersona(...args),
716
- opFinalizeResume: (...args) => this.opFinalizeResume(...args),
717
- opLaunch: (...args) => this.opLaunch(...args),
718
- opListPersonas: (...args) => this.opListPersonas(...args),
719
- opModels: (...args) => this.opModels(...args),
720
- opPreservationCtl: (...args) => this.opPreservationCtl(...args),
721
- opPurge: (...args) => this.opPurge(...args),
722
- opRemovePersona: (...args) => this.opRemovePersona(...args),
723
- opResumePreserved: (...args) => this.opResumePreserved(...args),
724
- opShowPersona: (...args) => this.opShowPersona(...args),
725
- opStart: (...args) => this.opStart(...args),
726
- openStaticChatSession: (...args) => this.openStaticChatSession(...args),
727
- psOwnerFilter: (...args) => this.psOwnerFilter(...args),
728
- resolveSpawnCwd: (...args) => this.resolveSpawnCwd(...args),
729
- retireStaticChatSession: (...args) => this.retireStaticChatSession(...args),
730
- runAnswerer: (...args) => this.runAnswerer(...args),
731
- runHost: (...args) => this.runHost(...args),
732
- serveGated: (ctx, fn) => this.serveGated(ctx, fn),
733
- serveObservation: (ctx, fn) => this.serveObservation(ctx, fn),
734
- serveSpawnGoal: (...args) => this.serveSpawnGoal(...args),
735
- serveTurnCancel: (...args) => this.serveTurnCancel(...args),
736
- serveTurnGoal: (...args) => this.serveTurnGoal(...args),
737
- serveTurnParticipation: (...args) => this.serveTurnParticipation(...args),
738
- serveTurnUnconfirmed: (...args) => this.serveTurnUnconfirmed(...args),
739
- serveTurnYield: (...args) => this.serveTurnYield(...args),
740
- spawnPersona: (...args) => this.spawnPersona(...args),
741
- stopHandle: (...args) => this.stopHandle(...args),
742
- stopWindowsSeat: (...args) => this.stopWindowsSeat(...args),
743
- trackStoppedHandle: (...args) => this.trackStoppedHandle(...args),
744
- turnPendingFor: (...args) => this.turnPendingFor(...args),
745
- turnTarget: (...args) => this.turnTarget(...args),
746
- });
399
+ commandDispatch = new CommandDispatch(commandDispatchDeps(this));
747
400
  /** The spawn and launch goal path. Every dependency reads through at its use. */
748
- spawnGoalComponent = new SpawnGoal({
749
- agentGoals: () => this.agentGoals,
750
- execution: () => this.execution,
751
- goalAcceptanceRetentionMs: () => this.goalAcceptanceRetentionMs,
752
- goalAcceptances: () => this.goalAcceptances,
753
- goalReconcileDone: () => this.goalReconcileDone,
754
- goalWriter: () => this.goalWriter,
755
- managerInstanceId: () => this.managerInstanceId,
756
- onceWatched: () => this.onceWatched,
757
- readinessTimeoutMs: () => this.readinessTimeoutMs,
758
- serviceServe: () => this.serviceServe,
759
- userMode: () => this.userMode,
760
- acceptOnceTurn: (...args) => this.acceptOnceTurn(...args),
761
- assertGoalWriterEpochCurrent: (...args) => this.assertGoalWriterEpochCurrent(...args),
762
- commitOnceCancel: (...args) => this.commitOnceCancel(...args),
763
- emitGoalProgress: (...args) => this.emitGoalProgress(...args),
764
- executionRefusal: (...args) => this.executionRefusal(...args),
765
- settleOnceTurn: (...args) => this.settleOnceTurn(...args),
766
- });
401
+ spawnGoalComponent = new SpawnGoal(spawnGoalDeps(this));
767
402
  /** The persona catalog doors. Every dependency reads through at its use. */
768
- personaCatalogComponent = new PersonaCatalog({
769
- agents: () => this.agents,
770
- execution: () => this.execution,
771
- meshMode: () => this.meshMode,
772
- remoteAuthority: () => this.remoteAuthority,
773
- space: () => this.space,
774
- userMode: () => this.userMode,
775
- workspaceRoot: () => this.workspaceRoot,
776
- executionRefusal: (...args) => this.executionRefusal(...args),
777
- managedPrincipal: (...args) => this.managedPrincipal(...args),
778
- nameError: (...args) => this.nameError(...args),
779
- spawnBoundRefusal: (...args) => this.spawnBoundRefusal(...args),
780
- spawnRun: (...args) => this.spawnRun(...args),
781
- staticSpawnBound: (...args) => this.staticSpawnBound(...args),
782
- });
403
+ personaCatalogComponent = new PersonaCatalog(personaCatalogDeps(this));
783
404
  /** Seat terminal input and attach sessions. Every dependency reads through at its use. */
784
- terminalInputComponent = new TerminalInput({
785
- agents: () => this.agents,
786
- auth: () => this.auth,
787
- managerLifecycleUid: () => this.managerLifecycleUid,
788
- sessionPlane: () => this.sessionPlane,
789
- wsPort: () => this.wsPort,
790
- runtimeFor: (...args) => this.runtimeFor(...args),
791
- });
405
+ terminalInputComponent = new TerminalInput(terminalInputDeps(this));
792
406
  /** Status, seat list and model catalog reads. Every dependency reads through at its use. */
793
- statusAndModelsComponent = new StatusAndModels({
794
- agents: () => this.agents,
795
- auth: () => this.auth,
796
- connectorStatuses: () => this.connectorStatuses,
797
- ep: () => this.ep,
798
- execution: () => this.execution,
799
- leaseStopping: () => this.leaseStopping,
800
- lifecycleInFlight: () => this.lifecycleInFlight,
801
- maintenanceState: () => this.maintenanceState,
802
- managerInstanceId: () => this.managerInstanceId,
803
- managerLifecycleUid: () => this.managerLifecycleUid,
804
- namesCapacity: () => this.namesCapacity,
805
- preservationAttemptId: () => this.preservationAttemptId,
806
- preservationInventory: () => this.preservationInventory,
807
- remoteAuthority: () => this.remoteAuthority,
808
- requiredRuntime: () => this.requiredRuntime,
809
- resumeRequired: () => this.resumeRequired,
810
- retirement: () => this.retirement,
811
- runtimeKind: () => this.runtimeKind,
812
- space: () => this.space,
813
- startedAtMs: () => this.startedAtMs,
814
- staticLifecycle: () => this.staticLifecycle,
815
- userMode: () => this.userMode,
816
- workspaceRoot: () => this.workspaceRoot,
817
- classSpawnEnabled: (...args) => this.classSpawnEnabled(...args),
818
- connectorNames: (...args) => this.connectorNames(...args),
819
- epAdminReach: (...args) => this.epAdminReach(...args),
820
- executionRefusal: (...args) => this.executionRefusal(...args),
821
- forkProvenance: (...args) => this.forkProvenance(...args),
822
- isOwnPresence: (a, p) => this.isOwnPresence(a, p),
823
- isProcessBoundSeat: (...args) => this.isProcessBoundSeat(...args),
824
- launchHarness: (...args) => this.launchHarness(...args),
825
- refreshUnavailableConnectors: (...args) => this.refreshUnavailableConnectors(...args),
826
- resolveConnector: (...args) => this.resolveConnector(...args),
827
- staticReconciliationStatus: (...args) => this.staticReconciliationStatus(...args),
828
- });
407
+ statusAndModelsComponent = new StatusAndModels(statusAndModelsDeps(this));
829
408
  /** The launch readiness race and exit watch. Every dependency reads through at its use. */
830
- readinessWaitComponent = new ReadinessWait({
831
- agents: () => this.agents,
832
- ep: () => this.ep,
833
- shutdownReadiness: () => this.shutdownReadiness,
834
- managedPrincipal: (...args) => this.managedPrincipal(...args),
835
- onAgentExit: (...args) => this.onAgentExit(...args),
836
- });
409
+ readinessWaitComponent = new ReadinessWait(readinessWaitDeps(this));
837
410
  /** Broker dials and scoped executor connections. Every dependency reads through at its use. */
838
- brokerTransportComponent = new BrokerTransport({
839
- auth: () => this.auth,
840
- endpointServeExecutorExpiresInSeconds: () => this.endpointServeExecutorExpiresInSeconds,
841
- leaseStopping: () => this.leaseStopping,
842
- managerInstanceId: () => this.managerInstanceId,
843
- remoteAuthority: () => this.remoteAuthority,
844
- remoteBundleAdoption: () => this.remoteBundleAdoption,
845
- remoteExecutorCreds: () => this.remoteExecutorCreds,
846
- servers: () => this.servers,
847
- space: () => this.space,
848
- transportDown: () => this.transportDown,
849
- renewRemoteExecutor: (...args) => this.renewRemoteExecutor(...args),
850
- renewRemoteStandingBundle: (...args) => this.renewRemoteStandingBundle(...args),
851
- });
411
+ brokerTransportComponent = new BrokerTransport(brokerTransportDeps(this));
852
412
  /** The start and launch control doors. Every dependency reads through at its use. */
853
- startDoorsComponent = new StartDoors({
854
- eventsRequired: () => this.eventsRequired,
855
- execution: () => this.execution,
856
- remoteAuthority: () => this.remoteAuthority,
857
- space: () => this.space,
858
- userMode: () => this.userMode,
859
- workspaceRoot: () => this.workspaceRoot,
860
- executionRefusal: (...args) => this.executionRefusal(...args),
861
- startAgent: (...args) => this.startAgent(...args),
862
- });
413
+ startDoorsComponent = new StartDoors(startDoorsDeps(this));
863
414
  /** Connector and harness resolution for a launch. Every dependency reads through at its use. */
864
- harnessResolutionComponent = new HarnessResolution({
865
- connectorStatuses: () => this.connectorStatuses,
866
- eventPayloadsWithheld: () => this.eventPayloadsWithheld,
867
- eventsRequired: () => this.eventsRequired,
868
- expectedConnectorGeneration: () => this.expectedConnectorGeneration,
869
- installedExtensions: () => this.installedExtensions,
870
- servers: () => this.servers,
871
- space: () => this.space,
872
- workspaceRoot: () => this.workspaceRoot,
873
- });
415
+ harnessResolutionComponent = new HarnessResolution(harnessResolutionDeps(this));
874
416
  /** The boot connector inventory. Every dependency reads through at its use. */
875
- connectorInventoryComponent = new ConnectorInventory({
876
- bootNotes: () => this.bootNotes,
877
- setBootNotes: (value) => { this.bootNotes = value; },
878
- connectorRequirements: () => this.connectorRequirements,
879
- setConnectorRequirements: (value) => { this.connectorRequirements = value; },
880
- connectorStatuses: () => this.connectorStatuses,
881
- setConnectorStatuses: (value) => { this.connectorStatuses = value; },
882
- execution: () => this.execution,
883
- installedExtensions: () => this.installedExtensions,
884
- machineSetupCommand: () => this.machineSetupCommand,
885
- classSpawnEnabled: (...args) => this.classSpawnEnabled(...args),
886
- prepareClaudeWake: (...args) => this.prepareClaudeWake(...args),
887
- });
417
+ connectorInventoryComponent = new ConnectorInventory(connectorInventoryDeps(this));
888
418
  /** Manager preservation and released-seat adoption. Every dependency reads through at its use. */
889
- preservationComponent = new Preservation({
890
- agents: () => this.agents,
891
- auth: () => this.auth,
892
- credRenewTimer: () => this.credRenewTimer,
893
- setCredRenewTimer: (value) => { this.credRenewTimer = value; },
894
- ep: () => this.ep,
895
- execution: () => this.execution,
896
- lifecycleInFlight: () => this.lifecycleInFlight,
897
- maintenanceState: () => this.maintenanceState,
898
- setMaintenanceState: (value) => { this.maintenanceState = value; },
899
- managerInstanceId: () => this.managerInstanceId,
900
- meshMode: () => this.meshMode,
901
- preservationAttemptId: () => this.preservationAttemptId,
902
- setPreservationAttemptId: (value) => { this.preservationAttemptId = value; },
903
- preservationGeneration: () => this.preservationGeneration,
904
- setPreservationGeneration: (value) => { this.preservationGeneration = value; },
905
- preservationInventory: () => this.preservationInventory,
906
- setPreservationInventory: (value) => { this.preservationInventory = value; },
907
- preserveStopTimeoutMs: () => this.preserveStopTimeoutMs,
908
- resumeCredRenewal: () => this.resumeCredRenewal,
909
- space: () => this.space,
910
- unverifiedStops: () => this.unverifiedStops,
911
- setUnverifiedStops: (value) => { this.unverifiedStops = value; },
912
- userMode: () => this.userMode,
913
- workspaceRoot: () => this.workspaceRoot,
914
- awaitLifecycleDrain: (...args) => this.awaitLifecycleDrain(...args),
915
- deprovision: (...args) => this.deprovision(...args),
916
- dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
917
- dropSeatRecord: (...args) => this.dropSeatRecord(...args),
918
- executionRefusal: (...args) => this.executionRefusal(...args),
919
- fileDigest: (...args) => this.fileDigest(...args),
920
- logSeatReaped: (...args) => this.logSeatReaped(...args),
921
- onAgentExit: (...args) => this.onAgentExit(...args),
922
- recordContinuityAtStop: (...args) => this.recordContinuityAtStop(...args),
923
- renewDaemonCreds: (...args) => this.renewDaemonCreds(...args),
924
- resumeEntry: (...args) => this.resumeEntry(...args),
925
- resumeEntryOf: (...args) => this.resumeEntryOf(...args),
926
- runtimeFor: (...args) => this.runtimeFor(...args),
927
- stopHandle: (...args) => this.stopHandle(...args),
928
- teardownTarget: (...args) => this.teardownTarget(...args),
929
- validateRetainedAuthority: (...args) => this.validateRetainedAuthority(...args),
930
- watchExit: (...args) => this.watchExit(...args),
931
- withProvisioner: (fn) => this.withProvisioner(fn),
932
- });
419
+ preservationComponent = new Preservation(preservationDeps(this));
420
+ /** Preserved-manager resume and its control doors. Every dependency reads through at its use. */
421
+ preservedResumeComponent = new PreservedResume(preservedResumeDeps(this));
933
422
  /** The goal-writer connection and the goal index it reconciles. Every dependency reads through at its use. */
934
- goalWriterComponent = new GoalWriter({
935
- auth: () => this.auth,
936
- goalAcceptances: () => this.goalAcceptances,
937
- goalWriter: () => this.goalWriter,
938
- setGoalWriter: (value) => { this.goalWriter = value; },
939
- goalWriterCreds: () => this.goalWriterCreds,
940
- setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
941
- goalWriterIdentity: () => this.goalWriterIdentity,
942
- leaseStopping: () => this.leaseStopping,
943
- managerInstanceId: () => this.managerInstanceId,
944
- readinessTimeoutMs: () => this.readinessTimeoutMs,
945
- remoteAuthority: () => this.remoteAuthority,
946
- serviceServe: () => this.serviceServe,
947
- space: () => this.space,
948
- turnRelay: () => this.turnRelay,
949
- goalReconcileDone: () => this.goalReconcileDone,
950
- setGoalReconcileDone: (value) => { this.goalReconcileDone = value; },
951
- adoptTurnGoal: (...args) => this.adoptTurnGoal(...args),
952
- boundedReconnect: (...args) => this.boundedReconnect(...args),
953
- dial: (...args) => this.dial(...args),
954
- noticeSeatTurns: (...args) => this.noticeSeatTurns(...args),
955
- renewRemoteBeforeRedial: (...args) => this.renewRemoteBeforeRedial(...args),
956
- retireConnection: (...args) => this.retireConnection(...args),
957
- trackTransport: (...args) => this.trackTransport(...args),
958
- withEndpointServeExecutor: (fn) => this.withEndpointServeExecutor(fn),
959
- });
423
+ goalWriterComponent = new GoalWriter(goalWriterDeps(this));
960
424
  /** Renewal of the manager's standing credentials. Every dependency reads through at its use. */
961
- credentialRenewal = new CredentialRenewal({
962
- agents: () => this.agents,
963
- auth: () => this.auth,
964
- credentialPushRetry: () => this.credentialPushRetry,
965
- setCredentialPushRetry: (value) => { this.credentialPushRetry = value; },
966
- credentialPushes: () => this.credentialPushes,
967
- daemonRenewalEligible: () => this.daemonRenewalEligible,
968
- setDaemonRenewalEligible: (value) => { this.daemonRenewalEligible = value; },
969
- daemonRenewalOwner: () => this.daemonRenewalOwner,
970
- setDaemonRenewalOwner: (value) => { this.daemonRenewalOwner = value; },
971
- endpointServeRenewalTimer: () => this.endpointServeRenewalTimer,
972
- setEndpointServeRenewalTimer: (value) => { this.endpointServeRenewalTimer = value; },
973
- ep: () => this.ep,
974
- finishRemoteBundleAdoption: () => this.finishRemoteBundleAdoption,
975
- setFinishRemoteBundleAdoption: (value) => { this.finishRemoteBundleAdoption = value; },
976
- goalWriter: () => this.goalWriter,
977
- goalWriterCreds: () => this.goalWriterCreds,
978
- setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
979
- leaseStopping: () => this.leaseStopping,
980
- managerInstanceId: () => this.managerInstanceId,
981
- pendingCredentialPushes: () => this.pendingCredentialPushes,
982
- remoteAuthority: () => this.remoteAuthority,
983
- remoteBundleAdoption: () => this.remoteBundleAdoption,
984
- setRemoteBundleAdoption: (value) => { this.remoteBundleAdoption = value; },
985
- remoteBundleRenewal: () => this.remoteBundleRenewal,
986
- setRemoteBundleRenewal: (value) => { this.remoteBundleRenewal = value; },
987
- remoteExecutorCreds: () => this.remoteExecutorCreds,
988
- setRemoteExecutorCreds: (value) => { this.remoteExecutorCreds = value; },
989
- remoteRenewalDebt: () => this.remoteRenewalDebt,
990
- setRemoteRenewalDebt: (value) => { this.remoteRenewalDebt = value; },
991
- remoteSupervisorCreds: () => this.remoteSupervisorCreds,
992
- setRemoteSupervisorCreds: (value) => { this.remoteSupervisorCreds = value; },
993
- runHosting: () => this.runHosting,
994
- secretStoreIdentity: () => this.secretStoreIdentity,
995
- setSecretStoreIdentity: (value) => { this.secretStoreIdentity = value; },
996
- secrets: () => this.secrets,
997
- serviceServe: () => this.serviceServe,
998
- sessionLedgerConn: () => this.sessionLedgerConn,
999
- sessionLedgerCreds: () => this.sessionLedgerCreds,
1000
- setSessionLedgerCreds: (value) => { this.sessionLedgerCreds = value; },
1001
- space: () => this.space,
1002
- supervisorCredentialPush: () => this.supervisorCredentialPush,
1003
- setSupervisorCredentialPush: (value) => { this.supervisorCredentialPush = value; },
1004
- supervisorCredentialPushPending: () => this.supervisorCredentialPushPending,
1005
- setSupervisorCredentialPushPending: (value) => { this.supervisorCredentialPushPending = value; },
1006
- userMode: () => this.userMode,
1007
- workspaceRoot: () => this.workspaceRoot,
1008
- beginLifecycle: (...args) => this.beginLifecycle(...args),
1009
- dialRemoteStanding: (...args) => this.dialRemoteStanding(...args),
1010
- dialServeConnection: (...args) => this.dialServeConnection(...args),
1011
- discardServeCandidate: (...args) => this.discardServeCandidate(...args),
1012
- mintAndStageGoalWriter: (...args) => this.mintAndStageGoalWriter(...args),
1013
- mintAndStageSessionLedger: (...args) => this.mintAndStageSessionLedger(...args),
1014
- probeStaticCredential: (...args) => this.probeStaticCredential(...args),
1015
- renewManagedStaticCred: (...args) => this.renewManagedStaticCred(...args),
1016
- withEndpointServeExecutor: (fn) => this.withEndpointServeExecutor(fn),
1017
- renewRemoteStandingBundle: (...args) => this.renewRemoteStandingBundle(...args),
1018
- });
425
+ credentialRenewal = new CredentialRenewal(credentialRenewalDeps(this));
1019
426
  /** The launch pipeline's leaf steps. Every dependency reads through at its use. */
1020
- seatLaunch = new SeatLaunch({
1021
- space: () => this.space,
1022
- servers: () => this.servers,
1023
- workspaceRoot: () => this.workspaceRoot,
1024
- installedExtensions: () => this.installedExtensions,
1025
- ep: () => this.ep,
1026
- auth: () => this.auth,
1027
- userMode: () => this.userMode,
1028
- managerInstanceId: () => this.managerInstanceId,
1029
- serviceServe: () => this.serviceServe,
1030
- runHosting: () => this.runHosting,
1031
- connectorStatuses: () => this.connectorStatuses,
1032
- execution: () => this.execution,
1033
- requiredRuntime: () => this.requiredRuntime,
1034
- meshMode: () => this.meshMode,
1035
- executionRefusal: () => this.executionRefusal(),
1036
- nameError: (name) => this.nameError(name),
1037
- canReadPersona: (owner, caller, admin) => this.canReadPersona(owner, caller, admin),
1038
- epAdminReach: (caller) => this.epAdminReach(caller),
1039
- startAgent: (opts) => this.startAgent(opts),
1040
- awaitReadiness: (...args) => this.awaitReadiness(...args),
1041
- awaitStartupOutcome: (...args) => this.awaitStartupOutcome(...args),
1042
- capabilityRefusal: (...args) => this.capabilityRefusal(...args),
1043
- delegatedLaunched: () => this.delegatedLaunched,
1044
- dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
1045
- endOnceBeforeServe: (...args) => this.endOnceBeforeServe(...args),
1046
- eventPayloadsWithheld: () => this.eventPayloadsWithheld,
1047
- eventsRefusal: (...args) => this.eventsRefusal(...args),
1048
- eventsRequired: () => this.eventsRequired,
1049
- fileDigest: (...args) => this.fileDigest(...args),
1050
- hostLaunchFields: (...args) => this.hostLaunchFields(...args),
1051
- issuanceSeam: (...args) => this.issuanceSeam(...args),
1052
- launchHarness: (...args) => this.launchHarness(...args),
1053
- launchOwner: (...args) => this.launchOwner(...args),
1054
- leaseStopping: () => this.leaseStopping,
1055
- loadSeatRuntime: (...args) => this.loadSeatRuntime(...args),
1056
- managerLifecycleUid: () => this.managerLifecycleUid,
1057
- namesCapacity: () => this.namesCapacity,
1058
- openOnceDelivery: (...args) => this.openOnceDelivery(...args),
1059
- personaOwner: (...args) => this.personaOwner(...args),
1060
- place: (...args) => this.place(...args),
1061
- provisionUserAgent: (...args) => this.provisionUserAgent(...args),
1062
- readerRemedy: (...args) => this.readerRemedy(...args),
1063
- readinessTimeoutMs: () => this.readinessTimeoutMs,
1064
- refreshUnavailableConnectors: (...args) => this.refreshUnavailableConnectors(...args),
1065
- remoteAuthority: () => this.remoteAuthority,
1066
- resolveConnector: (...args) => this.resolveConnector(...args),
1067
- retirement: () => this.retirement,
1068
- runtimeFor: (...args) => this.runtimeFor(...args),
1069
- seatCapRefusal: (...args) => this.seatCapRefusal(...args),
1070
- seatCustody: () => this.seatCustody,
1071
- secrets: () => this.secrets,
1072
- sessionRecovery: () => this.sessionRecovery,
1073
- shredUserSecrets: (...args) => this.shredUserSecrets(...args),
1074
- staticLifecycle: () => this.staticLifecycle,
1075
- stopAndTrack: (...args) => this.stopAndTrack(...args),
1076
- trackDeprovision: (...args) => this.trackDeprovision(...args),
1077
- transcripts: () => this.transcripts,
1078
- userProvision: () => this.userProvision,
1079
- watchExit: (...args) => this.watchExit(...args),
1080
- watchOnceExit: (...args) => this.watchOnceExit(...args),
1081
- withIssuer: (fn) => this.withIssuer(fn),
1082
- withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
1083
- withProvisioner: (fn) => this.withProvisioner(fn),
1084
- });
427
+ seatLaunch = new SeatLaunch(seatLaunchDeps(this));
428
+ /** Manager boot: execution admission, connect, registration and lease. Every dependency reads through at its use. */
429
+ bootComponent = new ManagerBoot(bootDeps(this));
1085
430
  constructor(opts) {
1086
431
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
1087
432
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -1357,422 +702,10 @@ export class Manager {
1357
702
  executionRecordPath(instanceId) {
1358
703
  return join(this.workspaceRoot, ".cotal", `manager-execution.${spaceKey(this.space)}.${instanceId}.json`);
1359
704
  }
1360
- claimExecutionRecord(instanceId) {
1361
- const record = claimIdentityRecord(this.executionRecordPath(instanceId), "manager execution capability", (raw) => {
1362
- if (!raw || typeof raw !== "object" || Array.isArray(raw))
1363
- return undefined;
1364
- const r = raw;
1365
- return Object.keys(r).sort().join(",") === "execution,instanceId,space,v" && r.v === 1 && r.space === this.space &&
1366
- r.instanceId === instanceId && (r.execution === "none" || r.execution === "runtime") ? r : undefined;
1367
- }, () => ({ v: 1, space: this.space, instanceId, execution: this.execution }));
1368
- if (record.execution !== this.execution)
1369
- throw new Error("manager execution capability differs from its retained instance record; execution cannot change across restart");
1370
- }
1371
- async admitExecutionState() {
1372
- if (!this.remoteAuthority) {
1373
- let local = this.admittedLocalIdentity;
1374
- this.admittedLocalIdentity = undefined;
1375
- if (this.execution === "none") {
1376
- const recorded = loadMeshes().find((m) => m.space === this.space);
1377
- const auth = hasUserAuthState(this.workspaceRoot, this.space) && recorded?.mode === "user"
1378
- ? await getSpaceAuth(this.secrets, this.space) : undefined;
1379
- if (!auth)
1380
- throw new Error("execution: none requires a genuine hosting user-auth root and its user-mode mesh record");
1381
- if (!local)
1382
- local = loadManagerInstanceIdentity(this.workspaceRoot, this.space);
1383
- if (local && !existsSync(this.executionRecordPath(local.instanceId)))
1384
- throw new Error("execution: none refuses an existing unclassified manager instance; keep its runtime and retained state, or register a fresh control instance");
1385
- if (!local) {
1386
- const proposed = { instanceId: mintLifecycleUid(), serveIdentity: newIdentity() };
1387
- local = createManagerInstanceIdentity(this.workspaceRoot, this.space, () => proposed);
1388
- if (local.instanceId !== proposed.instanceId)
1389
- throw new Error("execution: none refuses a concurrently claimed unclassified manager identity");
1390
- }
1391
- const localInstanceId = local.instanceId;
1392
- this.claimExecutionRecord(localInstanceId);
1393
- const nc = await this.dial({ ...standaloneConnectOpts({ creds: await mintCreds(auth, newIdentity(), "provisioner"), tls: false }), maxReconnectAttempts: 0 });
1394
- try {
1395
- const kvm = new Kvm(nc);
1396
- await ensureAuthorityStores(await jetstreamManager(nc), kvm, this.space);
1397
- const entries = await listGoalIndex(await kvm.open(recordsBucket(this.space)), MANAGER_ENDPOINT);
1398
- if (entries.some((entry) => entry.iid === localInstanceId && (entry.allocated !== undefined || entry.note !== undefined)))
1399
- throw new Error("execution: none refuses retained seat or turn inventory before recovery; keep the execution-owning Manager");
1400
- }
1401
- finally {
1402
- await drainAndClose(nc);
1403
- }
1404
- this.admittedLocalIdentity = local;
1405
- }
1406
- else {
1407
- local ??= createManagerInstanceIdentity(this.workspaceRoot, this.space, () => ({ instanceId: mintLifecycleUid(), serveIdentity: newIdentity() }));
1408
- this.claimExecutionRecord(local.instanceId);
1409
- this.admittedLocalIdentity = local;
1410
- }
1411
- return;
1412
- }
1413
- if (this.remoteAuthority) {
1414
- if (this.execution === "none" && (await localTrustOfSpace(this.secrets, this.space)).present)
1415
- throw new Error("remote manager-service authority cannot be combined with local space signing trust - choose one authority path, never a fallback");
1416
- // Execution is fixed for a registered instance. An older instance with no capability
1417
- // record might own retained seats/runs, so it cannot be converted to none by omission.
1418
- const remote = this.remoteAuthority;
1419
- const path = this.executionRecordPath(remote.instanceId);
1420
- if (this.execution === "none" && !existsSync(path) && remote.serveGrant.epoch !== 0)
1421
- throw new Error("execution: none refuses an existing unclassified manager instance; keep its runtime and retained state, or register a fresh control instance");
1422
- if (this.execution === "none") {
1423
- const entries = await remote.scanGoalIndex();
1424
- if (entries.some((entry) => entry.iid === remote.instanceId && (entry.allocated !== undefined || entry.note !== undefined)))
1425
- throw new Error("execution: none refuses retained seat or turn inventory before recovery; keep the execution-owning Manager");
1426
- }
1427
- if (this.execution === "none" || existsSync(path))
1428
- this.claimExecutionRecord(remote.instanceId);
1429
- }
1430
- }
1431
- async runStart() {
1432
- await this.admitExecutionState();
1433
- this.staticLifecycle.start();
1434
- await this.inspectConnectorsAtBoot();
1435
- await this.attach.start();
1436
- // In auth mode the manager is just another user in the space's account — it mints
1437
- // itself creds from the same signing key it uses for the agents it spawns. The signer comes
1438
- // through the SecretStore seam (`this.secrets` — the injected `ManagerOptions.secretStore`, or
1439
- // the local `.cotal/auth/auth.json` FS default), so a HOSTED composition mints from its KMS/Vault
1440
- // and no signing seed is ever read from the hosted disk. `this.space` cross-checks the bundle.
1441
- //
1442
- // REMOTE AUTHORITY (#1944): a manager holding host-issued remote authority mints nothing from a
1443
- // local signer, so it never composes or validates local trust. It asks ONE question of the
1444
- // store — does THIS space's own local signing trust exist (`localTrustOfSpace`) — because that
1445
- // alone is the conflict of authorities a supervisor refuses. The stock behaviour this replaces
1446
- // read the whole root's trust chain (`getSpaceAuth`): with no records for this space it fell
1447
- // back to the legacy monolith of an UNRELATED static tenant and reported that bundle as
1448
- // "corrupt or mislabeled". Other tenants' records — split (their account + the shared
1449
- // per-root broker record) or monolith — are not this space's trust and never refuse; an
1450
- // unreadable record on a key that is read refuses loud with the store's own parse message.
1451
- //
1452
- // An OPEN mesh mints nothing, also in a root that still holds a static stack's accounts. A
1453
- // credential minted there joins this instance's family in the open account, and the next open
1454
- // boot could re-register only by verify-evicting it through a delivery daemon that an open mesh
1455
- // does not run.
1456
- const recorded = loadMeshes().find((m) => m.space === this.space);
1457
- if (this.remoteAuthority) {
1458
- if ((await localTrustOfSpace(this.secrets, this.space)).present)
1459
- throw new Error("remote manager-service authority cannot be combined with local space signing trust - choose one authority path, never a fallback");
1460
- this.auth = undefined;
1461
- }
1462
- else {
1463
- this.auth = recorded?.mode === "open" ? undefined : await getSpaceAuth(this.secrets, this.space);
1464
- }
1465
- // USER-MODE detection is FAIL-CLOSED on the on-disk marker (the space-scoped state dir), never
1466
- // on the mutable mesh registry alone — registry drift/tamper must not let a user-auth space
1467
- // take the static self-mint branch. A marker/registry disagreement is a refused start with the
1468
- // repair, not a guess.
1469
- this.userMode = this.remoteAuthority !== undefined || hasUserAuthState(this.workspaceRoot, this.space);
1470
- if (!this.remoteAuthority && recorded && (recorded.mode === "user") !== this.userMode)
1471
- throw new Error(`mesh registry says space "${this.space}" is ${recorded.mode}-mode but the on-disk user-auth marker ${this.userMode ? "exists" : "is missing"} (${userAuthStateDir(this.workspaceRoot, this.space)}) - \`cotal down\` and re-\`cotal up\` this space to reconcile before running a manager`);
1472
- if (!this.remoteAuthority && this.userMode && !recorded)
1473
- throw new Error(`space "${this.space}" has user-auth state on disk but no mesh registry entry - a user-mode manager needs the authoritative record (\`cotal up\` writes it before the control plane); \`cotal up --user-auth\` this space, or remove the stale ${userAuthStateDir(this.workspaceRoot, this.space)}`);
1474
- if (!this.remoteAuthority && this.userMode && !this.auth)
1475
- throw new Error(`space "${this.space}" has user-auth state but no auth.json under ${authDir(this.workspaceRoot)} - the pre-flip manager still needs the space trust bundle; re-run \`cotal up --user-auth\` here`);
1476
- // SPEC 13.6 item 7: the LOGICAL instance id + serve identity PERSIST across restart
1477
- // (a space-scoped manager identity file under .cotal). A restart re-registers the SAME id with an
1478
- // ADVANCED epoch (the successor fences the predecessor); a fresh mint over a malformed file is
1479
- // refused loud (no-fallbacks - a restart never silently becomes a fresh instance). A second
1480
- // manager in a DIFFERENT workspace root is a DIFFERENT logical id by construction (its own state
1481
- // dir) - two managers in ONE space are two workspace roots.
1482
- //
1483
- // First mint on a fresh root is exclusive create (#1263). Two processes that both observe no
1484
- // file must not keep different in-memory ids: of N concurrent starts exactly one publishes the
1485
- // file by hard link and the others adopt that identity before taking a lease, or refuse with
1486
- // identity-record-create-lost. A filesystem without hard links refuses the first start with
1487
- // atomic-publish-unsupported. Atomic rename is not enough, because the loser
1488
- // of a replace would still serve under the id it minted.
1489
- {
1490
- if (this.remoteAuthority) {
1491
- this.managerInstanceId = this.remoteAuthority.instanceId;
1492
- this.managerServeIdentity = this.remoteAuthority.identities.serve;
1493
- }
1494
- else {
1495
- // Admission already resolved this identity, including the first mint. A second claim here
1496
- // would stat the same record again.
1497
- const claimed = this.admittedLocalIdentity;
1498
- if (!claimed)
1499
- throw new Error("manager start has no admitted local identity");
1500
- this.admittedLocalIdentity = undefined;
1501
- this.managerInstanceId = claimed.instanceId;
1502
- this.managerServeIdentity = claimed.serveIdentity;
1503
- }
1504
- }
1505
- await this.onServiceIdentity?.(this.serviceIdentityObservation());
1506
- let creds;
1507
- let id;
1508
- if (this.remoteAuthority) {
1509
- const remote = this.remoteAuthority;
1510
- id = remote.identities.supervisor.id;
1511
- creds = async () => this.remoteSupervisorCreds;
1512
- }
1513
- else if (this.auth) {
1514
- const identity = newIdentity();
1515
- const auth = this.auth;
1516
- id = identity.id;
1517
- // The long-lived SUPERVISOR cred (closure (ii), residual 2): serve the three control tiers, hold the
1518
- // singleton lease (open-only), publish + watch presence — and nothing else. Provisioning runs on an
1519
- // EPHEMERAL provisioner connection per spawn (withProvisioner); destructive purge mints a PURGER per
1520
- // call. So the always-on daemon holds no DM/DLV read, no consumer-create, no stream-admin tamper.
1521
- //
1522
- // STANDING RENEWAL (class 1): the manager holds the DATA signing seed, so it is its
1523
- // own renewal owner — the cred rides the endpoint's SOURCE seam and self-remints (same identity,
1524
- // pinned by the endpoint) ahead of each bounded supervisor JWT's expiry. A copied supervisor
1525
- // cred is broker-dead within the matrix TTL.
1526
- creds = () => mintCreds(auth, identity, "supervisor");
1527
- }
1528
- this.ep = new CotalEndpoint({
1529
- space: this.space,
1530
- servers: this.servers,
1531
- channels: [],
1532
- creds,
1533
- // The supervisor registers on the roster, and an authed presence-registering endpoint is
1534
- // lifecycle-keyed (SPEC 13.1, fail-before-presence). The manager process is the top of its
1535
- // own launch chain (the operator command IS its launcher): its incarnation uid is the
1536
- // per-process `managerLifecycleUid` field (also the `managerInstance` audit coordinate on
1537
- // every static activation).
1538
- lifecycleUid: this.remoteAuthority?.lifecycleUid ?? this.managerLifecycleUid,
1539
- // The supervisor serves control + watches presence; it never consumes chat/dm/task
1540
- // (no message handler). consume:false avoids binding consumers it doesn't use — and
1541
- // under auth avoids trying to bind its own DM/task durables that nothing pre-created.
1542
- // It still pre-creates OTHERS' durables via provisionDmInbox/provisionTaskQueue (lazy jsm).
1543
- consume: false,
1544
- // It also never reads the channel registry (it provisions + serves control, no channel
1545
- // pull/display), so skip the channel-registry watch — the supervisor cred (residual 2) then
1546
- // holds no channel-KV read grant. Presence (the roster) is still watched.
1547
- watchChannels: false,
1548
- // `host` says which machine runs this manager, as an agent's card does: an owner with several
1549
- // managers tells them apart by it. Advisory display metadata, never a routing input.
1550
- card: { id, ...(this.remoteAuthority ? { owner: this.remoteAuthority.owner, actor: this.remoteAuthority.actors.supervisor } : {}), name: this.name, role: "manager", kind: "endpoint", meta: { host: hostname(), terminal: this.streamsTerminal ? "stream" : "none" } },
1551
- });
1552
- // Raw failures ride error; conditions the endpoint is already surviving ride warning. Both
1553
- // matter to a supervisor operator, especially a failed standing-credential renewal.
1554
- const reportEndpoint = (e) => console.error(`! manager endpoint: ${e.message}`);
1555
- this.ep.on("error", reportEndpoint);
1556
- this.ep.on("warning", reportEndpoint);
1557
- // Every roster change and every view transition, so a seat that is offline in a fresh snapshot
1558
- // (recorded with no presence event) is logged the moment the view can support the verdict.
1559
- this.ep.on("roster", () => this.logSeatMeshTransitions());
1560
- this.ep.on("presence-view", () => this.logSeatMeshTransitions());
1561
- console.error("manager startup: connecting the supervisor endpoint");
1562
- await this.ep.start();
1563
- await this.ep.setActivity(`supervisor (${this.runtimeKind})`);
1564
- // Per-instance liveness lease (the old per-space singleton is DEMOTED). Acquire
1565
- // THIS logical instance's own key (atomic CAS create). A DIFFERENT instance (a second manager in a
1566
- // second workspace root) has a distinct id ⇒ a distinct key ⇒ it coexists; the create THROWS only
1567
- // when the SAME instance id is already live (a same-root double-start, or a restart racing the
1568
- // crashed predecessor's not-yet-expired key). A double-start REFUSES loud; a restart whose
1569
- // predecessor is provably dead on this host waits for that key's bucket TTL to remove it (#4092,
1570
- // {@link acquireInstanceLease}). Losing the key LATER ends this process only when another process holds it; otherwise
1571
- // the renew loop puts it back or keeps retrying ({@link renewLease}).
1572
- this.leaseInfo = { holder: this.ep.ref().id, instanceId: this.managerInstanceId, runtime: this.runtimeKind, root: resolve(this.workspaceRoot), pid: process.pid };
1573
- try {
1574
- console.error("manager startup: acquiring the instance liveness lease");
1575
- this.leaseRevision = await this.acquireInstanceLease(this.leaseInfo);
1576
- }
1577
- catch (e) {
1578
- await this.ep.stop();
1579
- await this.attach.stop();
1580
- throw e;
1581
- }
1582
- this.leaseTimer = setInterval(() => { void this.renewLease(); }, MANAGER_LEASE_RENEW_MS);
1583
- this.leaseTimer.unref?.();
1584
- // THE PEER-READABLE LIVENESS RESPONDER for the manager plane (#1577). Bound HERE — after the
1585
- // lease, before registration — precisely so it is up during the window in which the manager is
1586
- // NOT yet serving. A responder that only appeared once everything worked could never report the
1587
- // broken state it exists to report, which is the reported defect in a new place.
1588
- //
1589
- // WHAT IT GRADES is `serviceServe`, the v0.4 service endpoint's serve handle, which is assigned
1590
- // only after `serveEndpoint` has bound this instance's rails, AND that handle's connection. A
1591
- // closed serve connection holds no subscriptions, while `onServeConnectionClosed` keeps the
1592
- // handle through its re-dial waits, so the handle alone would answer `bound` with every rail
1593
- // gone. The re-dial swaps in the fresh connection and handle together, so `bound` returns only
1594
- // once the rails are served again. A DISCONNECTED serve connection is the same fault without the
1595
- // close: it reconnects without limit, so it stays open while the broker holds none of its rails,
1596
- // and this probe arrives on the separate supervisor connection that is still up. So the grade
1597
- // also requires the serve transport to be connected. That is a RESPONDER fact. It is
1598
- // deliberately NOT "this process is alive": this process is trivially alive whenever it answers
1599
- // at all, so grading on that would make the surface a `pgrep` that also lies in both directions
1600
- // — the exact instrument the reporter's evidence table indicts. Between lease acquisition and a
1601
- // successful registration the honest answer is `unbound`, and that is what a peer is told.
1602
- //
1603
- // The lease row is never consulted and never sent: presence is the whole ask, and the row
1604
- // carries the operator's workspace root and pid.
1605
- this.ep.serveLiveness("manager", () => {
1606
- const s = this.serviceServe;
1607
- return s?.handle && !s.nc.isClosed() && !this.transportDown.has(s.nc) ? "bound" : "unbound";
1608
- });
1609
- // Static §13.1: after this instance holds its lease, collect the durable static rows
1610
- // now, but do not let their exact-op terminals make the whole space unreachable. The service
1611
- // comes up below, then the sweep overlaps the remaining registration work. Two-window
1612
- // heal-then-register is slower than one executor, but the overlap is still the no-outage
1613
- // property: `reconcilingAliases` refuses spawn or attach of THAT alias until its terminal
1614
- // attempt returns.
1615
- const startupReconcile = this.auth && !this.userMode ? this.reconcileStaticLifecycles() : undefined;
1616
- if (startupReconcile)
1617
- void startupReconcile.catch((e) => console.error(`! ${STARTUP_RECONCILING}: ${rejectionText(e)} - no per-alias retry could be planned; a later manager start re-reads unfinished durable terminals`));
1618
- // A default stop records a user-mode seat it released while the seat was still running. This
1619
- // start adopts that seat, or retires it when the runtime proves it gone. Static seats stay on
1620
- // the sweep above.
1621
- if (this.userMode)
1622
- void this.adoptReleasedSeats().catch((e) => console.error(`! a released seat was not adopted: ${rejectionText(e)}`));
1623
- // The manager serves NO ctl tiers - its whole control surface is the v0.4
1624
- // service endpoint registered below. The old three-tier rail (self/manager/admin) is deleted;
1625
- // `ctl.delivery`/`ctl.delivery-admin` (the delivery daemon) and `ctl.auth-admin` (the auth
1626
- // plane) are separate services and keep their rails.
1627
- // Class 2: the manager is the CLASS-2 RENEWAL OWNER — the one control-plane process
1628
- // that is resident in EVERY mesh mode (foreground `up`, `up --detach`, same-root refresh) and
1629
- // holds the signer. Ordered initial pass NOW (ensureControlPlane starts delivery BEFORE the
1630
- // manager, so the daemon's launch-time creds write always precedes this — no write race), then
1631
- // every half-TTL: re-sign the daemon creds files for their EXISTING nkeys, request the explicit
1632
- // `reloadCreds` adoption on the delivery-admin rail, and persist the audit record doctor renders.
1633
- if (this.auth) {
1634
- // #1634: a space may be served by several managers, so ownership of the daemon's credential
1635
- // renewal is decided here rather than by being the only manager able to start. #871: a daemon
1636
- // that is still binding or re-acquiring its lease leaves this challenge unanswered for a few
1637
- // seconds, so boot waits that out instead of exiting over a daemon about to answer.
1638
- await this.claimDaemonRenewalOwnership(DELIVERY_ADMIN_BOOT_WAIT_MS);
1639
- // ARMED BEFORE the first remint, not after. That first `renewDaemonCreds()` re-signs through
1640
- // the SecretStore, and a slow or contended store makes the one pass outlast the lease's
1641
- // MANAGER_LEASE_TTL_MS. Arming afterwards leaves the whole first remint unprotected: the lease
1642
- // expires mid-pass, a second manager's CAS create succeeds, and both remint into one store.
1643
- this.daemonRenewalLeaseTimer = setInterval(() => { void this.keepDaemonRenewalLease(); }, MANAGER_LEASE_RENEW_MS);
1644
- this.daemonRenewalLeaseTimer.unref?.();
1645
- await this.renewDaemonCreds();
1646
- this.credRenewTimer = setInterval(() => { void this.renewDaemonCreds(); }, credRenewIntervalMs(STANDING_RENEWABLE_TTL_SEC));
1647
- this.credRenewTimer.unref?.();
1648
- }
1649
- else if (this.remoteAuthority) {
1650
- if (this.remoteAuthority.renewStandingBundle)
1651
- await this.renewRemoteStandingBundle();
1652
- else
1653
- await this.renewRemoteExecutor();
1654
- let standingTtl = STANDING_RENEWABLE_TTL_SEC;
1655
- if (this.remoteSupervisorCreds) {
1656
- try {
1657
- const claims = credsClaims(this.remoteSupervisorCreds);
1658
- if (typeof claims.exp === "number" && typeof claims.iat === "number" && claims.exp > claims.iat) {
1659
- standingTtl = claims.exp - claims.iat;
1660
- }
1661
- }
1662
- catch { }
1663
- }
1664
- // A refused family needs another pass inside the final quarter of its lifetime.
1665
- const intervalMs = Math.min(credRenewIntervalMs(5 * 60), Math.max(1, Math.floor(standingTtl * 1000 / 8)));
1666
- this.resumeCredRenewal = () => {
1667
- if (this.credRenewTimer || this.leaseStopping)
1668
- return;
1669
- this.credRenewTimer = setInterval(async () => {
1670
- try {
1671
- if (this.remoteAuthority?.renewStandingBundle)
1672
- await this.renewRemoteStandingBundle();
1673
- else
1674
- await this.renewRemoteExecutor();
1675
- }
1676
- catch (e) {
1677
- console.error(`! remote manager renewal pass failed: ${rejectionText(e)}`);
1678
- }
1679
- try {
1680
- await this.runHosting?.renew();
1681
- }
1682
- catch (e) {
1683
- console.error(`! remote run-hosting renewal pass failed: ${rejectionText(e)}`);
1684
- }
1685
- }, intervalMs);
1686
- this.credRenewTimer.unref?.();
1687
- };
1688
- this.resumeCredRenewal();
1689
- }
1690
- // stop() fences before it waits for an accepted startup reconciliation terminal. Once that
1691
- // terminal drains, start() and stop() resume from the same await boundary; start must observe
1692
- // the fence before it can publish a fresh service registration after shutdown.
1693
- if (this.staticLifecycle.stopping)
1694
- return;
1695
- // Register the manager as an ordinary v0.4 `service` endpoint (SPEC §13.7/§13.9)
1696
- // and serve its typed command surface on the ep rails - the ONLY control door, in
1697
- // EVERY mesh mode. Static + user meshes mint the scoped executor + endpoint-serve credential;
1698
- // an open mesh runs the same gate/registration ceremony over bare connections and never mints
1699
- // (there is no credential system - the broker enforces nothing, matching the old open-mesh ctl
1700
- // trust). Fail-loud: a manager that cannot register does not start half-registered.
1701
- console.error("manager startup: binding the service endpoint");
1702
- await this.registerManagerService();
1703
- if (this.staticLifecycle.stopping)
1704
- return;
1705
- // Stand up the standing goal-writer connection for spawn-as-action — AFTER
1706
- // registration (it writes this endpoint's goal facts/records), disjoint from the serve cred.
1707
- await this.startGoalWriter();
1708
- // Stand up the ONE §13.6 session plane for `attach` — AFTER registration too (it
1709
- // rides the serve grant's epoch + the family-staged session-ledger cred), on its own standing
1710
- // connection disjoint from both the serve and goal-writer creds.
1711
- await this.startSessionPlane();
1712
- // Reconcile any accepted-but-unterminal goals inherited from a predecessor
1713
- // BEFORE spawn-as-action begins accepting (the goalReconcileDone gate) — a fresh incarnation
1714
- // never drops a goal a dead predecessor accepted. Never fatal; the gate opens either way.
1715
- console.error("manager startup: reconciling predecessor goals");
1716
- await this.reconcileGoalIndex();
1717
- // SPEC 14.3: the manager hosts workflow runs. Stood up AFTER registration (it names this
1718
- // instance's coordinates) and reconciled AFTER the goal index, for the same reason: a fresh
1719
- // incarnation takes back every run a dead predecessor was driving before it accepts new ones.
1720
- // The serve surface is already live by here, so the family itself holds the gate: `runHost()`
1721
- // refuses `run-start`/`run-resume` as `unavailable` until the host exists and `RunHosting`
1722
- // refuses them until its reconcile has returned. A remote user-auth manager uses its four
1723
- // registered issuer callbacks instead of holding a signer; a local user mesh stands none up.
1724
- const remoteRuns = this.remoteAuthority?.runHosting;
1725
- if (this.execution !== "none" && this.remoteAuthority && remoteRuns) {
1726
- this.runHosting = new RunHosting({
1727
- space: this.space,
1728
- servers: this.servers,
1729
- endpoint: MANAGER_ENDPOINT,
1730
- instanceId: this.managerInstanceId,
1731
- holder: { id: this.remoteAuthority.identities.supervisor.id, lifecycleUid: this.managerLifecycleUid },
1732
- auth: undefined,
1733
- log: (line) => console.error(line),
1734
- admitRun: remoteRuns.admitRun,
1735
- submitRun: remoteRuns.submitRun,
1736
- revokeRun: remoteRuns.revokeRun,
1737
- cancelRun: remoteRuns.cancelRun,
1738
- issueAttempt: remoteRuns.issueAttempt,
1739
- issueOperator: remoteRuns.issueOperator,
1740
- renewRun: remoteRuns.renewRun,
1741
- });
1742
- await this.runHosting.reconcile();
1743
- }
1744
- else if (!this.remoteAuthority && !this.userMode) {
1745
- this.runHosting = new RunHosting({
1746
- space: this.space,
1747
- servers: this.servers,
1748
- endpoint: MANAGER_ENDPOINT,
1749
- instanceId: this.managerInstanceId,
1750
- holder: { id: this.ep.ref().id, lifecycleUid: this.managerLifecycleUid },
1751
- auth: this.auth,
1752
- log: (line) => console.error(line),
1753
- });
1754
- await this.runHosting.reconcile();
1755
- }
1756
- // A carried resume (#1499) needs this instance's transfer reader: minted from the space's signing
1757
- // seed, issued by the host to a remote manager, or none on an open mesh.
1758
- if (this.execution !== "none" && (!this.remoteAuthority || this.remoteAuthority.mintTransferReader)) {
1759
- this.transcripts = new TranscriptReceiver({
1760
- space: this.space,
1761
- instanceId: this.managerInstanceId,
1762
- workspaceRoot: this.workspaceRoot,
1763
- withReader: (fn) => this.withTransferReader(fn),
1764
- log: (line) => console.error(line),
1765
- });
1766
- await this.transcripts.start();
1767
- }
1768
- for (const note of this.bootNotes.splice(0))
1769
- console.error(note);
1770
- // Plane-3 (durable backstop) is NOT the manager's job — the manager only manages agent lifecycle.
1771
- // The server-side delivery daemon hosts the fan-out writer + trusted reader, owns the durable
1772
- // membership registry, and serves the runtime durable join/leave/list ops (on `ctl.delivery`). The
1773
- // manager records each agent's read ACL at spawn (`commitAcl`, in provisionAgent) so the daemon can
1774
- // re-authorize it; that is the only Plane-3 state the manager touches, and it rides minting.
1775
- }
705
+ /** {@link ManagerBoot.claimExecutionRecord}. */
706
+ claimExecutionRecord(...args) { return this.bootComponent.claimExecutionRecord(...args); }
707
+ /** {@link ManagerBoot.runStart}. */
708
+ runStart(...args) { return this.bootComponent.runStart(...args); }
1776
709
  /** The delivery shard whose lease names the process that reloads the standing credentials.
1777
710
  * Delivery is single-shard today and the endpoint's own responder reads row 0; naming it here
1778
711
  * keeps the manager's binding check and that reply arguing about the same row. */
@@ -1853,84 +786,10 @@ export class Manager {
1853
786
  fileDigest(path) { return fileDigest(path); }
1854
787
  /** {@link Preservation.fileDigestOrEmpty}. */
1855
788
  fileDigestOrEmpty(...args) { return this.preservationComponent.fileDigestOrEmpty(...args); }
1856
- resumeEntry(a, backfillFloor) {
1857
- // A preservation cut is a stop boundary too, so a manifest launch after it reopens what a resume would.
1858
- this.recordContinuityAtStop(a, "preservation");
1859
- return this.resumeEntryOf(a, backfillFloor);
1860
- }
1861
- /** The resume entry of one live seat, with no side effect: a preservation cut and a supervised
1862
- * seat's record both build it. The entry is its own copy, so a caller's write to the plan it was
1863
- * handed cannot change the launch the manager keeps supervising (#3241). */
1864
- resumeEntryOf(a, backfillFloor) {
1865
- const principal = a.userOwner
1866
- ? parsePrincipalKey(a.id)
1867
- : { owner: DEV_OWNER, actor: a.id };
1868
- if (!principal)
1869
- throw new Error(`managed agent ${a.name} has an invalid principal ${a.id}`);
1870
- // The RECORDED secret-family paths (set at spawn or adoption) — never a re-derivation by name:
1871
- // under mixed generations (a name-keyed pre-split incarnation adopted by this manager) the
1872
- // recorded path is the only truth, and re-deriving would preserve a family that isn't there.
1873
- const files = a.secretPaths;
1874
- const identity = a.userOwner
1875
- ? (() => {
1876
- if (!files?.actorToken || !files.sentinelCreds || !files.health)
1877
- throw new Error(`managed agent ${a.name} is user-mode but its secret-family paths were not recorded`);
1878
- return {
1879
- mode: "user",
1880
- owner: principal.owner,
1881
- actor: principal.actor,
1882
- lifecycleUid: a.lifecycleUid,
1883
- actorToken: { kind: "file", path: files.actorToken, sha256: this.fileDigestOrEmpty(files.actorToken) },
1884
- sentinelCredential: { kind: "file", path: files.sentinelCreds, sha256: this.fileDigestOrEmpty(files.sentinelCreds) },
1885
- health: { kind: "file", path: files.health },
1886
- };
1887
- })()
1888
- : this.auth
1889
- ? (() => {
1890
- if (!files?.creds)
1891
- throw new Error(`managed agent ${a.name} is static-auth but its credential path was not recorded`);
1892
- return { mode: "static", id: principal.actor, lifecycleUid: a.lifecycleUid, credential: { kind: "file", path: files.creds, sha256: this.fileDigestOrEmpty(files.creds) }, ...(a.issued ? { issued: a.issued } : {}) };
1893
- })()
1894
- : { mode: "open", id: principal.actor, lifecycleUid: a.lifecycleUid };
1895
- const dependencies = [a.launch.source.configPath];
1896
- if (a.launch.source.kind === "manifest" && a.launch.source.runId)
1897
- dependencies.unshift(join(this.workspaceRoot, ".cotal", "run", `${a.launch.source.runId}.json`));
1898
- return structuredClone({
1899
- space: this.space,
1900
- name: a.name,
1901
- role: a.role,
1902
- identity,
1903
- launch: {
1904
- connector: a.agent,
1905
- runtime: a.handle.kind,
1906
- cwd: a.launch.cwd,
1907
- source: a.launch.source,
1908
- model: a.launch.model,
1909
- variant: a.launch.variant,
1910
- subscribe: a.launch.subscribe,
1911
- allowSubscribe: a.launch.allowSubscribe,
1912
- allowPublish: a.launch.allowPublish,
1913
- capabilities: a.launch.capabilities,
1914
- ...(a.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(a.launch.endpoints) } : {}),
1915
- events: a.launch.events,
1916
- eventPayloads: a.launch.eventPayloads,
1917
- shareTools: a.launch.shareTools,
1918
- forkSource: a.launch.forkSource,
1919
- ...(this.forkProvenance(a) ? { resumed: this.forkProvenance(a) } : {}),
1920
- // A supervised seat whose connector keeps no session state is armed with no state file to read.
1921
- sessionId: a.restart?.armed && a.restart.sessionStatePath ? this.readManagedSession(a) : a.launch.sessionId,
1922
- // Additive and only when the connector supplied one. A seat with no pointer records no
1923
- // field, which is what keeps an older inventory and a fresh one the same document shape.
1924
- ...(a.restart?.sessionStatePath ? { sessionStatePath: a.restart.sessionStatePath } : {}),
1925
- unresolvedLaunchOptionKeys: a.launch.unresolvedLaunchOptionKeys,
1926
- },
1927
- dependencies,
1928
- spawner: a.spawner,
1929
- authorityParent: a.authorityParent,
1930
- startedAt: new Date(a.startedAt).toISOString(),
1931
- ...(backfillFloor !== undefined ? { backfillFloor } : {}),
1932
- });
1933
- }
789
+ /** {@link PreservedResume.resumeEntry}. */
790
+ resumeEntry(...args) { return this.preservedResumeComponent.resumeEntry(...args); }
791
+ /** {@link PreservedResume.resumeEntryOf}. */
792
+ resumeEntryOf(...args) { return this.preservedResumeComponent.resumeEntryOf(...args); }
1934
793
  /** {@link Preservation.teardownManagedAgents}. */
1935
794
  teardownManagedAgents(...args) { return this.preservationComponent.teardownManagedAgents(...args); }
1936
795
  /** {@link Preservation.isProcessBoundSeat}. */
@@ -2144,158 +1003,14 @@ export class Manager {
2144
1003
  discardServeCandidate(...args) { return this.brokerTransportComponent.discardServeCandidate(...args); }
2145
1004
  /** {@link BrokerTransport.trackTransport}. */
2146
1005
  trackTransport(...args) { return this.brokerTransportComponent.trackTransport(...args); }
2147
- async opFinalizeResume(rawArgs) {
2148
- if (this.execution === "none")
2149
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2150
- {
2151
- let args;
2152
- try {
2153
- args = parseResumeFinalizeArgs(rawArgs);
2154
- }
2155
- catch (e) {
2156
- return { ok: false, error: rejectionText(e) };
2157
- }
2158
- if (!this.resumeAttemptId || this.resumeAttemptId !== args.attemptId)
2159
- return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId ?? "<none>"}, not ${args.attemptId}` };
2160
- if (!this.resumeCommitted || !this.resumeDurableCommitToken)
2161
- return { ok: false, error: `resume attempt ${args.attemptId} has no successful commit to finalize` };
2162
- if (this.resumeDurableCommitToken !== args.durableCommitToken)
2163
- return { ok: false, error: `resume attempt ${args.attemptId} durable commit token does not match` };
2164
- if (this.resumeFinalized)
2165
- return { ok: true, data: { attemptId: args.attemptId, state: "active" } };
2166
- const inventory = this.resumeInventory;
2167
- if (!inventory)
2168
- return { ok: false, error: `resume attempt ${args.attemptId} has no bound inventory` };
2169
- let inactive;
2170
- try {
2171
- inactive = this.resumeLivenessErrors(inventory, this.ep.getRoster());
2172
- }
2173
- catch (e) {
2174
- return { ok: false, error: `resume attempt ${args.attemptId} cannot verify live principals at finalize: ${rejectionText(e)}` };
2175
- }
2176
- if (inactive.length)
2177
- return { ok: false, error: `resume attempt ${args.attemptId} is not live at finalize: ${inactive.join("; ")}` };
2178
- for (const entry of this.resumeInventory?.agents ?? []) {
2179
- const managed = this.agents.get(entry.name);
2180
- if (managed)
2181
- managed.suppressCleanup = false;
2182
- }
2183
- // distsys/security CONDITIONAL @ 9e13648: the boot sweep DEFERRED every active
2184
- // slot while a resume was pending (it could not know which would be adopted). Now adoption
2185
- // is complete and `this.agents` is EXACTLY the adopted set, so re-sweep to terminalize any
2186
- // active slot the resume did NOT claim — a durable ACTIVE ORPHAN (crashed after slot->active
2187
- // before agents.set, then not in the resumed inventory). This runs while `resumeRequired` is
2188
- // still true, so no ordinary spawn can race it (beginLifecycle refuses non-resume ops), and
2189
- // it closes both the alias wedge AND the membership-gate gap (the orphan's principal enters
2190
- // retiredPrincipals, so a copied JWT is refused). Best-effort + loud: a sweep failure must
2191
- // not fail the finalize (the next non-resume boot re-drives it), but it is never swallowed.
2192
- if (this.auth && !this.userMode)
2193
- await this.reconcileStaticLifecycles(true).catch((e) => console.error(`! post-resume static reconcile: ${rejectionText(e)} - no per-alias retry could be planned; a later manager start re-reads unfinished durable terminals`));
2194
- this.resumeFinalized = true;
2195
- this.resumeRequired = false;
2196
- return { ok: true, data: { attemptId: args.attemptId, state: "active" } };
2197
- }
2198
- }
2199
- async opCommitResume(rawArgs) {
2200
- if (this.execution === "none")
2201
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2202
- {
2203
- let attemptId;
2204
- try {
2205
- attemptId = parseResumeCommitArgs(rawArgs).attemptId;
2206
- }
2207
- catch (e) {
2208
- return { ok: false, error: rejectionText(e) };
2209
- }
2210
- if (!this.resumeAttemptId || this.resumeAttemptId !== attemptId)
2211
- return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId ?? "<none>"}, not ${attemptId}` };
2212
- if (this.resumeCommitted)
2213
- return {
2214
- ok: true,
2215
- data: {
2216
- attemptId,
2217
- state: this.resumeFinalized ? "active" : "awaitingFinalize",
2218
- durableCommitToken: this.resumeDurableCommitToken,
2219
- },
2220
- };
2221
- if (this.resumeCommitTask)
2222
- return this.resumeCommitTask;
2223
- const task = this.commitResumeActivation(attemptId);
2224
- this.resumeCommitTask = task;
2225
- try {
2226
- return await task;
2227
- }
2228
- finally {
2229
- if (this.resumeCommitTask === task)
2230
- this.resumeCommitTask = undefined;
2231
- }
2232
- }
2233
- }
2234
- async opResumePreserved(rawArgs) {
2235
- if (this.execution === "none")
2236
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2237
- {
2238
- try {
2239
- const args = parseResumeControlArgs(rawArgs);
2240
- const inventoryDigest = createHash("sha256").update(JSON.stringify(args.inventory)).digest("hex");
2241
- if (!this.resumeAttemptId)
2242
- return { ok: false, error: "resumePreserved requires a manager started with --resume-attempt" };
2243
- if (this.resumeAttemptId !== args.attemptId)
2244
- return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId}, not ${args.attemptId}` };
2245
- if (this.resumeInventoryDigest && this.resumeInventoryDigest !== inventoryDigest)
2246
- return { ok: false, error: `resume attempt ${args.attemptId} is already bound to a different inventory` };
2247
- if (!this.resumeInventoryDigest) {
2248
- this.resumeInventoryDigest = inventoryDigest;
2249
- this.resumeInventory = args.inventory;
2250
- }
2251
- if (!this.resumeTask && !this.resumeResult) {
2252
- this.resumeTask = this.resumePreserved(args.inventory).then((result) => {
2253
- if (result.ok || this.resumedAgentNames.size > 0)
2254
- this.resumeResult = result;
2255
- return result;
2256
- }).finally(() => {
2257
- this.resumeTask = undefined;
2258
- });
2259
- }
2260
- const result = this.resumeResult ?? await this.resumeTask;
2261
- const data = { attemptId: args.attemptId, state: result.ok ? "awaitingCommit" : "degraded", ...result };
2262
- return result.ok
2263
- ? { ok: true, data }
2264
- : { ok: false, data, error: result.error ?? "retained-agent resume failed" };
2265
- }
2266
- catch (e) {
2267
- return { ok: false, error: rejectionText(e) };
2268
- }
2269
- }
2270
- }
2271
- async opPreservationCtl(op, rawArgs) {
2272
- if (this.execution === "none")
2273
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2274
- if (this.resumeRequired)
2275
- return { ok: false, error: this.maintenanceError() };
2276
- const attemptId = String(rawArgs?.attemptId ?? "").trim();
2277
- if (!attemptId)
2278
- return { ok: false, error: `${op} requires attemptId` };
2279
- try {
2280
- if (op === "abortPreservation") {
2281
- this.abortPreservation(attemptId);
2282
- return { ok: true, data: { attemptId, state: "active" } };
2283
- }
2284
- const result = op === "preparePreservation"
2285
- ? await this.preparePreservation(attemptId)
2286
- : await this.commitPreservation(attemptId);
2287
- return result.ok
2288
- ? { ok: true, data: result }
2289
- : {
2290
- ok: false,
2291
- data: result,
2292
- error: `preservation incomplete: ${result.failures.map((f) => `${f.name}: ${f.error}`).join("; ")}`,
2293
- };
2294
- }
2295
- catch (e) {
2296
- return { ok: false, error: rejectionText(e) };
2297
- }
2298
- }
1006
+ /** {@link PreservedResume.opFinalizeResume}. */
1007
+ opFinalizeResume(...args) { return this.preservedResumeComponent.opFinalizeResume(...args); }
1008
+ /** {@link PreservedResume.opCommitResume}. */
1009
+ opCommitResume(...args) { return this.preservedResumeComponent.opCommitResume(...args); }
1010
+ /** {@link PreservedResume.opResumePreserved}. */
1011
+ opResumePreserved(...args) { return this.preservedResumeComponent.opResumePreserved(...args); }
1012
+ /** {@link PreservedResume.opPreservationCtl}. */
1013
+ opPreservationCtl(...args) { return this.preservedResumeComponent.opPreservationCtl(...args); }
2299
1014
  /** {@link CommandDispatch.admitControl}. */
2300
1015
  admitControl(...args) { return this.commandDispatch.admitControl(...args); }
2301
1016
  /** Run one v0.4 service-command handler through the SHARED admission chokepoint
@@ -2486,41 +1201,6 @@ export class Manager {
2486
1201
  }
2487
1202
  /** {@link CommandDispatch.managerServiceDefs}. */
2488
1203
  managerServiceDefs(...args) { return this.commandDispatch.managerServiceDefs(...args); }
2489
- async commitResumeActivation(attemptId) {
2490
- if (!this.resumeAwaitingCommit || !this.resumeResult?.ok)
2491
- return { ok: false, error: `resume attempt ${attemptId} has no successful activation to commit` };
2492
- const inventory = this.resumeInventory;
2493
- if (!inventory)
2494
- return { ok: false, error: `resume attempt ${attemptId} has no bound inventory` };
2495
- const authority = await Promise.all(inventory.agents.map(async (entry) => {
2496
- try {
2497
- await this.validateRetainedAuthority(entry);
2498
- return undefined;
2499
- }
2500
- catch (e) {
2501
- return `${entry.name}: ${rejectionText(e)}`;
2502
- }
2503
- }));
2504
- const drift = authority.filter((error) => error !== undefined);
2505
- if (drift.length)
2506
- return { ok: false, error: `resume attempt ${attemptId} retained authority changed before commit: ${drift.join("; ")}` };
2507
- let inactive;
2508
- try {
2509
- inactive = this.resumeLivenessErrors(inventory, this.ep.getRoster());
2510
- }
2511
- catch (e) {
2512
- return { ok: false, error: `resume attempt ${attemptId} cannot verify live principals: ${rejectionText(e)}` };
2513
- }
2514
- if (inactive.length)
2515
- return { ok: false, error: `resume attempt ${attemptId} is not live at commit: ${inactive.join("; ")}` };
2516
- this.resumeAwaitingCommit = false;
2517
- this.resumeCommitted = true;
2518
- this.resumeDurableCommitToken ??= randomBytes(32).toString("hex");
2519
- return {
2520
- ok: true,
2521
- data: { attemptId, state: "awaitingFinalize", durableCommitToken: this.resumeDurableCommitToken },
2522
- };
2523
- }
2524
1204
  /** Collapsed despawn/attach authorization (P4b). The caller already reached the command's ep
2525
1205
  * row (cred-gated: owner-mode rows via the spawn capability, any-mode rows only in admin
2526
1206
  * instruments). With admin=true (any-mode) any named target is allowed (operator). Otherwise
@@ -2557,55 +1237,6 @@ export class Manager {
2557
1237
  }
2558
1238
  /** The wire principal of a managed agent: {@link managedPrincipal}. */
2559
1239
  managedPrincipal(a) { return managedPrincipal(a); }
2560
- resumeLivenessErrors(inventory, roster) {
2561
- const inactive = [];
2562
- const expectedNames = new Set(inventory.agents.map((entry) => entry.name));
2563
- for (const name of this.resumedAgentNames)
2564
- if (!expectedNames.has(name))
2565
- inactive.push(`${name} is not part of the bound inventory`);
2566
- for (const entry of inventory.agents) {
2567
- const managed = this.agents.get(entry.name);
2568
- if (!managed) {
2569
- inactive.push(`${entry.name} is no longer managed`);
2570
- continue;
2571
- }
2572
- const expectedId = entry.identity.mode === "user"
2573
- ? principalKey(entry.identity.owner, entry.identity.actor).key
2574
- : entry.identity.id;
2575
- const expectedPrincipal = entry.identity.mode === "user"
2576
- ? expectedId
2577
- : principalKey(DEV_OWNER, entry.identity.id).key;
2578
- if (managed.id !== expectedId || this.managedPrincipal(managed) !== expectedPrincipal) {
2579
- inactive.push(`${entry.name} no longer holds retained principal ${expectedPrincipal}`);
2580
- continue;
2581
- }
2582
- // The late paths (commit/finalize) must prove the SAME incarnation the incarnation-exact
2583
- // readiness fence proved (§13.1): a principal-only match lets a wrong/absent-uid presence under
2584
- // the reused alias satisfy commit/finalize after a readiness timeout, undoing the fence.
2585
- if (managed.lifecycleUid !== entry.identity.lifecycleUid) {
2586
- inactive.push(`${entry.name} manager metadata incarnation ${managed.lifecycleUid} drifted from the inventory's ${entry.identity.lifecycleUid}`);
2587
- continue;
2588
- }
2589
- if (managed.handle.name !== entry.name || managed.handle.kind !== entry.launch.runtime) {
2590
- inactive.push(`${entry.name} is not attached to its exact retained ${entry.launch.runtime} handle`);
2591
- continue;
2592
- }
2593
- try {
2594
- if (managed.handle.status() !== "running") {
2595
- inactive.push(`${entry.name} runtime is not running`);
2596
- continue;
2597
- }
2598
- }
2599
- catch (e) {
2600
- inactive.push(`${entry.name} runtime status failed: ${rejectionText(e)}`);
2601
- continue;
2602
- }
2603
- if (!roster.some((presence) => presence.card.id === expectedPrincipal && presence.card.name === entry.name && presence.status !== "offline" &&
2604
- presence.lifecycleUid === entry.identity.lifecycleUid))
2605
- inactive.push(`${entry.name} incarnation ${entry.identity.lifecycleUid} (principal ${expectedPrincipal}) is not exactly present`);
2606
- }
2607
- return inactive;
2608
- }
2609
1240
  /** {@link CommandDispatch.opStopSelf}. */
2610
1241
  opStopSelf(...args) { return this.commandDispatch.opStopSelf(...args); }
2611
1242
  // Plane-3 durable join/leave/list ops moved OFF the manager onto the server-side delivery daemon's
@@ -2862,738 +1493,15 @@ export class Manager {
2862
1493
  spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") { return this.seatLaunch.spawnBoundRefusal(bound, grant, armsEvents, door); }
2863
1494
  /** {@link SeatLaunch.managedStaticInstanceReads}. */
2864
1495
  managedStaticInstanceReads(capabilities) { return this.seatLaunch.managedStaticInstanceReads(capabilities); }
2865
- /** Preflight the whole inventory before launching its first process, then adopt each exact retained
2866
- * principal without provisioning. A later runtime launch failure is reported per-agent, but malformed
2867
- * or missing inventory material can never produce a partially resumed set. */
2868
- async resumePreserved(inventory) {
2869
- if (this.execution === "none")
2870
- return { ok: false, agents: [], error: this.executionRefusal() };
2871
- const release = this.beginLifecycle(true);
2872
- if (!release)
2873
- return { ok: false, agents: [], error: this.maintenanceError() };
2874
- const batchReservations = [];
2875
- const prepared = new Map();
2876
- try {
2877
- if (inventory.version !== "cotal-manager-resume/v2")
2878
- return { ok: false, agents: [], error: `unsupported manager resume inventory version ${String(inventory.version)}` };
2879
- if (inventory.space !== this.space)
2880
- return { ok: false, agents: [], error: `resume inventory belongs to space "${inventory.space}", not "${this.space}"` };
2881
- // The caller keeps its inventory, so it is copied before the first await: a later write to it
2882
- // cannot change what a resumed seat launches with or what the next preservation retains.
2883
- const entries = structuredClone(inventory.agents);
2884
- const seen = new Set();
2885
- const principals = new Set();
2886
- const orphans = [];
2887
- await this.ep.waitForPresenceSnapshot();
2888
- const liveRoster = this.ep.getRoster().filter((presence) => presence.status !== "offline");
2889
- const occupancy = this.occupancy();
2890
- if (occupancy.used + entries.length > MAX_AGENTS)
2891
- return { ok: false, agents: [], error: `resume inventory of ${entries.length} would exceed manager capacity (${this.occupancyText(occupancy)})` };
2892
- for (const entry of entries) {
2893
- if (seen.has(entry.name))
2894
- return { ok: false, agents: [], error: `resume inventory contains duplicate agent name "${entry.name}"` };
2895
- seen.add(entry.name);
2896
- // A manager-local retirement hold is stronger and more precise than presence. The stopped
2897
- // predecessor can remain roster-live until its TTL/offline update lands, but that stale row
2898
- // must not hide the durable teardown state the manager already owns. Refuse and re-drive the
2899
- // exact held lifecycle before consulting generic principal liveness. A confirmed terminal has
2900
- // already removed the hold, so fresh-lifecycle resume still reaches the fail-closed roster gate.
2901
- const held = this.retirement.held(entry.name);
2902
- if (held) {
2903
- void this.deprovision(held.target).catch(() => { });
2904
- return {
2905
- ok: false,
2906
- agents: [],
2907
- error: `retained agent "${entry.name}" is reserved pending retirement: its previous lifecycle ${held.target.lifecycleUid} still owns the alias${held.lastError ? ` (last attempt: ${held.lastError})` : ""}; retrying re-drives that exact teardown`,
2908
- };
2909
- }
2910
- let principal;
2911
- try {
2912
- principal = entry.identity.mode === "user"
2913
- ? principalKey(entry.identity.owner, entry.identity.actor).key
2914
- : principalKey(DEV_OWNER, entry.identity.id).key;
2915
- }
2916
- catch (e) {
2917
- return { ok: false, agents: [], error: `invalid retained principal for ${entry.name}: ${rejectionText(e)}` };
2918
- }
2919
- if (principals.has(principal))
2920
- return { ok: false, agents: [], error: `resume inventory contains duplicate principal "${principal}"` };
2921
- principals.add(principal);
2922
- const confirmedPredecessor = this.retirement.predecessor(entry.name);
2923
- const principalIsLive = liveRoster.some((presence) => {
2924
- if (presence.card.id !== principal)
2925
- return false;
2926
- return confirmedPredecessor === undefined ||
2927
- confirmedPredecessor.principal !== principal ||
2928
- confirmedPredecessor.lifecycleUid !== presence.lifecycleUid ||
2929
- presence.card.name !== entry.name ||
2930
- entry.identity.lifecycleUid === confirmedPredecessor.lifecycleUid;
2931
- });
2932
- if (principalIsLive) {
2933
- const orphan = await this.orphanedResumeSeat(entry, principal, liveRoster);
2934
- if (!orphan)
2935
- return { ok: false, agents: [], error: `retained principal "${principal}" is already live and this runtime cannot authoritatively adopt it` };
2936
- orphans.push({ principal, reference: orphan });
2937
- }
2938
- if (this.agents.has(entry.name) || this.namesCapacity.isReserved(entry.name))
2939
- return { ok: false, agents: [], error: `retained agent "${entry.name}" is already managed or reserved` };
2940
- }
2941
- for (const entry of entries) {
2942
- this.namesCapacity.reserve(entry.name, resumeOwner(entry));
2943
- batchReservations.push(entry.name);
2944
- }
2945
- const preflight = [];
2946
- for (const entry of entries) {
2947
- const reply = await this.resumePreservedAgent(entry, true, true, prepared);
2948
- preflight.push({ name: entry.name, reply });
2949
- }
2950
- const preflightFailures = preflight.filter(({ reply }) => !reply.ok);
2951
- if (preflightFailures.length)
2952
- return {
2953
- ok: false,
2954
- agents: preflight,
2955
- error: `${preflightFailures.length} retained agent${preflightFailures.length === 1 ? "" : "s"} failed preflight`,
2956
- };
2957
- // Only now, with the whole inventory through preflight, is an orphan reaped: a refused batch
2958
- // leaves every seat as it found it.
2959
- for (const { principal, reference } of orphans) {
2960
- const refusal = await this.reapOrphanedResumeSeat(principal, reference);
2961
- if (refusal)
2962
- return { ok: false, agents: [], error: refusal };
2963
- }
2964
- const agents = [];
2965
- for (let i = 0; i < entries.length; i++) {
2966
- const entry = entries[i];
2967
- const reply = await this.resumePreservedAgent(entry, false, true, prepared);
2968
- agents.push({ name: entry.name, reply });
2969
- if (!reply.ok) {
2970
- for (const skipped of entries.slice(i + 1))
2971
- agents.push({ name: skipped.name, reply: { ok: false, error: `not launched because ${entry.name} failed` } });
2972
- return { ok: false, agents, error: reply.error };
2973
- }
2974
- }
2975
- if (this.resumeAttemptId)
2976
- this.resumeAwaitingCommit = true;
2977
- return { ok: true, agents };
2978
- }
2979
- finally {
2980
- for (const name of batchReservations) {
2981
- this.namesCapacity.release(name);
2982
- }
2983
- // Preflight builds every launch before any child starts, so a refused batch, a failed launch,
2984
- // or the agents skipped after it leave built specs no runtime ever received.
2985
- for (const { spec, spawned } of prepared.values()) {
2986
- if (spawned)
2987
- continue;
2988
- try {
2989
- discardLaunchArtifacts(spec.artifacts);
2990
- }
2991
- catch (e) {
2992
- console.error(`! resume: ${rejectionText(e)}`);
2993
- }
2994
- }
2995
- release();
2996
- }
2997
- }
2998
- /** Re-read every retained identity input and its current authority without provisioning. This runs
2999
- * during whole-inventory preflight, immediately before each individual spawn, and at commit. */
3000
- async validateRetainedAuthority(entry) {
3001
- const referenceError = this.inventoryReferenceError(entry);
3002
- if (referenceError)
3003
- throw new Error(`retained agent ${entry.name}: ${referenceError}`);
3004
- // THE OWN-CHANNEL RULE, ON THE RESUME DOOR, and it belongs here rather than beside the launch
3005
- // because BOTH resume paths funnel through this function and neither may skip it.
3006
- //
3007
- // A resume document is admin-supplied JSON. It carries the ACLs the managed row is re-armed
3008
- // from, and `renewManagedStaticCred` re-mints the credential out of that row at half TTL, so a
3009
- // foreign event channel written into an inventory becomes a minted read on another agent's tool
3010
- // inputs and outputs one renewal later. In static mode nothing else stops it: the checks below
3011
- // pin the credential's PATH, its IDENTITY and the broker's acceptance of it, and say nothing at
3012
- // all about its ACL. User mode compares the adopted authority's ACL against the inventory's, so
3013
- // it refuses a divergence on both fields already, but it refuses it as DRIFT rather than as this
3014
- // rule, and an inventory whose record and credential agree with each other and disagree with
3015
- // this rule is exactly the document an operator would not notice.
3016
- //
3017
- // Refuses rather than strips. Silently narrowing an admin document would leave the operator
3018
- // holding a record that says one thing and a mesh that does another, and the whole reason this
3019
- // is reachable is that nobody reads the record.
3020
- {
3021
- const owner = entry.identity.mode === "user" ? entry.identity.owner : DEV_OWNER;
3022
- // The ACTOR HALF IS THE PRINCIPAL, never the display name. In user mode the row this
3023
- // document re-arms is keyed by `identity.actor` (it is what the provider adopts below and
3024
- // what every liveness check reads), and an inventory supplies `name` and `identity.actor`
3025
- // independently, so judging the channel against `name` would judge it against the half that
3026
- // does not own the plane.
3027
- const actor = entry.identity.mode === "user" ? entry.identity.actor : entry.identity.id;
3028
- const foreign = foreignEventChannels([...(entry.launch.allowSubscribe ?? []), ...(entry.launch.allowPublish ?? [])], owner, actor);
3029
- if (foreign.length)
3030
- throw new Error(`retained agent ${entry.name}: its record claims another agent's event channel ` +
3031
- `(${foreign.join(", ")}). An agent may hold its OWN event plane and no other, because that ` +
3032
- `plane carries the session's tool inputs and outputs. Remove it from the inventory and ` +
3033
- `grant the reader out of band instead: ` +
3034
- `${this.readerRemedy(owner, foreign[0])}`);
3035
- }
3036
- if (entry.identity.mode === "open") {
3037
- if (this.auth || this.userMode)
3038
- throw new Error(`retained agent ${entry.name} is open-mode but the current manager is authenticated`);
3039
- return { id: entry.identity.id };
3040
- }
3041
- if (entry.identity.mode === "static") {
3042
- if (!this.auth || this.userMode)
3043
- throw new Error(`retained agent ${entry.name} is static-auth but the current manager is not`);
3044
- // CLOSED candidate set, not an open path: the lifecycle-keyed derivation (this generation's
3045
- // layout) or the name-keyed one (a pre-split inventory being carried across the upgrade).
3046
- // Anything else is a foreign path and refused exactly as before.
3047
- const candidates = [
3048
- resolve(agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, entry.name, entry.identity.lifecycleUid).creds),
3049
- resolve(agentSecretFilePaths(this.workspaceRoot, this.space, entry.name).creds),
3050
- ];
3051
- const expected = resolve(entry.identity.credential.path);
3052
- if (!candidates.includes(expected))
3053
- throw new Error(`retained credential reference for ${entry.name} is not a manager-owned path (expected ${candidates.join(" or ")})`);
3054
- let credentialText;
3055
- try {
3056
- // The lstat guards the FS MATERIALIZATION the child will read at launch; the identity check
3057
- // runs on the store's value — the source of truth (byte-identical here, the local FS
3058
- // composition resolves the key to this same path).
3059
- const st = lstatSync(expected);
3060
- if (!st.isFile() || st.isSymbolicLink())
3061
- throw new Error("not a regular non-symlink file");
3062
- const stored = await this.secrets.get(agentSecretKeyForFile(expected, this.space));
3063
- if (stored === undefined)
3064
- throw new Error("the credential is not in the secret store");
3065
- credentialText = stored;
3066
- const actual = idFromCreds(credentialText);
3067
- if (actual !== entry.identity.id)
3068
- throw new Error(`retained credential identity ${actual} does not match inventory principal ${entry.identity.id}`);
3069
- }
3070
- catch (e) {
3071
- throw new Error(`retained credential for ${entry.name} is unusable: ${rejectionText(e)}`);
3072
- }
3073
- const accepted = await this.probeStaticCredential(credentialText);
3074
- if (!accepted.ok)
3075
- throw new Error(`retained credential for ${entry.name} is not accepted by the current broker (${accepted.reason})`);
3076
- return { id: entry.identity.id, creds: expected };
3077
- }
3078
- if (!this.userMode)
3079
- throw new Error(`retained agent ${entry.name} is user-auth but the current manager is not`);
3080
- try {
3081
- const provider = resolveAuthProvider();
3082
- // Mirror the static branch's expected-path discipline, but pin the WHOLE secret FAMILY as ONE
3083
- // unit: all three of {actorToken, sentinelCreds, health} must equal the lifecycle-keyed triple
3084
- // (this generation) OR the name-keyed triple (a pre-split inventory carried across the upgrade).
3085
- // A per-file OR-pin let a corrupt inventory MIX families (lifecycle token + legacy sentinel)
3086
- // and, worse, left `health` UNPINNED entirely — an arbitrary recorded health path flowed into
3087
- // the bearer argv and was `rmSync`'d at terminal teardown (inventory-as-delete-gadget). Pinning
3088
- // the atomic family closes both: `health` is pinned by PATH EQUALITY (never by file existence,
3089
- // so a transiently-absent health file still validates), and the store reads below key off the
3090
- // RECORDED path, so a foreign path can neither pass the pin nor address a different row.
3091
- // Both triples are derived under THIS manager's space, and the key builder is given
3092
- // `this.space` rather than reading the segment out of the recorded path: an inventory row is
3093
- // caller data, and a recorded path may not choose which tenant's material is addressed.
3094
- const lifecycleFiles = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, entry.name, entry.identity.lifecycleUid);
3095
- const legacyFiles = agentSecretFilePaths(this.workspaceRoot, this.space, entry.name);
3096
- const recordedToken = resolve(entry.identity.actorToken.path);
3097
- const recordedSentinel = resolve(entry.identity.sentinelCredential.path);
3098
- const recordedHealth = resolve(entry.identity.health.path);
3099
- const matchesFamily = (f) => recordedToken === resolve(f.actorToken) && recordedSentinel === resolve(f.sentinelCreds) && recordedHealth === resolve(f.health);
3100
- if (!matchesFamily(lifecycleFiles) && !matchesFamily(legacyFiles))
3101
- throw new Error(`retained identity references for ${entry.name} are not one manager-owned secret family: all of actor-token, sentinel, and health must be the lifecycle-<uid> triple or the legacy name-keyed triple under ${agentCredsDir(this.workspaceRoot, this.space)} (no mixed families, no foreign health path)`);
3102
- const secrets = this.secrets;
3103
- const actorToken = await secrets.get(agentSecretKeyForFile(recordedToken, this.space));
3104
- const sentinelCreds = await secrets.get(agentSecretKeyForFile(recordedSentinel, this.space));
3105
- if (actorToken === undefined || sentinelCreds === undefined)
3106
- throw new Error("the retained actor token / sentinel credential is not in the secret store");
3107
- const adopted = this.remoteAuthority
3108
- ? await this.remoteAuthority.validateRetainedAgent({
3109
- owner: entry.identity.owner,
3110
- actor: entry.identity.actor,
3111
- lifecycleUid: entry.identity.lifecycleUid,
3112
- actorToken,
3113
- sentinelCreds,
3114
- })
3115
- : await provider.validateRetainedAgent({
3116
- store: secrets,
3117
- dir: userAuthStateDir(this.workspaceRoot, this.space),
3118
- space: this.space,
3119
- owner: entry.identity.owner,
3120
- actor: entry.identity.actor,
3121
- actorToken,
3122
- sentinelCreds,
3123
- });
3124
- if (adopted.owner !== entry.identity.owner || adopted.actor !== entry.identity.actor)
3125
- throw new Error(`auth provider returned a replacement principal; expected ${entry.identity.owner}.${entry.identity.actor}`);
3126
- // Bind the inventory's uid to the CURRENT authority row BEFORE any spawn: a corrupt or
3127
- // admin-supplied inventory naming a different incarnation is refused at pre-effect validation,
3128
- // never left to broker-fail after the child is already running (SPEC §13.1).
3129
- if (adopted.lifecycleUid !== entry.identity.lifecycleUid)
3130
- throw new Error(`retained user authority for ${entry.identity.owner}.${entry.identity.actor} is incarnation ${adopted.lifecycleUid}, not the inventory's ${entry.identity.lifecycleUid}; a resume binds the exact recovered uid before any spawn (SPEC 13.1)`);
3131
- if (!sameStrings(adopted.allowSubscribe, entry.launch.allowSubscribe) ||
3132
- !sameStrings(adopted.allowPublish, entry.launch.allowPublish) ||
3133
- !sameStrings(adopted.scope, entry.launch.capabilities) ||
3134
- adopted.role !== entry.role || adopted.parent !== entry.authorityParent)
3135
- throw new Error(`retained user authority for ${entry.identity.owner}.${entry.identity.actor} no longer matches the inventory`);
3136
- return {
3137
- userAuth: {
3138
- owner: entry.identity.owner,
3139
- actor: entry.identity.actor,
3140
- sentinelCredsPath: entry.identity.sentinelCredential.path,
3141
- bearerCmd: [
3142
- ...bearerEntryArgv(),
3143
- provider.agentBearerCommand,
3144
- ...(this.remoteAuthority
3145
- ? ["--exchange-url", this.remoteAuthority.agentBearerExchangeUrl]
3146
- : ["--dir", userAuthStateDir(this.workspaceRoot, this.space)]),
3147
- "--space", this.space,
3148
- "--owner", entry.identity.owner,
3149
- "--actor", entry.identity.actor,
3150
- "--token-file", entry.identity.actorToken.path,
3151
- "--health-file", entry.identity.health.path,
3152
- ],
3153
- },
3154
- };
3155
- }
3156
- catch (e) {
3157
- throw new Error(`retained user principal ${entry.identity.owner}.${entry.identity.actor} could not be reused: ${rejectionText(e)}`);
3158
- }
3159
- }
3160
- /** The seat reference behind a live retained principal, when that seat is provably one a lost
3161
- * manager of this logical instance launched for this exact incarnation. The resume binds the
3162
- * launched handle's reference to the incarnation's active slot before it waits for readiness, and
3163
- * the coordinator journals `resume-active` only after that wait, so a coordinator crash between the
3164
- * two leaves `resume-intent` behind a live seat. Undefined for everything else, which stays refused:
3165
- * another incarnation's presence, a slot another instance owns, a runtime that cannot reap the
3166
- * reference, and user or open meshes, which keep no slot. */
3167
- async orphanedResumeSeat(entry, principal, liveRoster) {
3168
- if (!this.auth || this.userMode || entry.identity.mode !== "static")
3169
- return undefined;
3170
- const runtime = this.runtimeFor(entry.launch.runtime);
3171
- if (typeof runtime.reap !== "function")
3172
- return undefined;
3173
- if (liveRoster.some((p) => p.card.id === principal && p.lifecycleUid !== entry.identity.lifecycleUid))
3174
- return undefined;
3175
- const slot = await this.readStaticReconcileSlot(entry.name);
3176
- if (slot?.phase !== "active" || slot.actor !== entry.identity.id || slot.lifecycleUid !== entry.identity.lifecycleUid)
3177
- return undefined;
3178
- if (ownedBySibling(slot, this.managerInstanceId))
3179
- return undefined;
3180
- return slot.runtime?.kind === runtime.kind ? slot.runtime : undefined;
3181
- }
3182
- /** Reap a seat {@link orphanedResumeSeat} found, then wait for its principal to leave presence so
3183
- * the relaunch's readiness cannot match the dead seat's row. Returns the refusal when the reap
3184
- * proves nothing or the principal stays live, which means another process holds it. */
3185
- async reapOrphanedResumeSeat(principal, reference) {
3186
- try {
3187
- const evidence = await requireRuntimeReap(this.runtimeFor(reference.kind), reference);
3188
- console.error(`resume: reaped orphaned seat ${reference.kind}:${reference.id} of retained principal "${principal}" (${evidence.detail})`);
3189
- }
3190
- catch (e) {
3191
- return `retained principal "${principal}" is already live and its recorded seat ${reference.kind}:${reference.id} could not be reaped: ${rejectionText(e)}`;
3192
- }
3193
- const deadline = Date.now() + ORPHAN_PRESENCE_CLEAR_MS;
3194
- while (this.ep.getRoster().some((p) => p.card.id === principal && p.status !== "offline")) {
3195
- if (Date.now() >= deadline)
3196
- return `retained principal "${principal}" is still live after its recorded seat ${reference.kind}:${reference.id} was reaped, so another process holds it and this runtime cannot authoritatively adopt it`;
3197
- await new Promise((resolveWait) => setTimeout(resolveWait, 250));
3198
- }
3199
- return undefined;
3200
- }
3201
- /** Validate/relaunch one retained inventory entry. Called through resumePreserved so all records
3202
- * pass the same preflight before the first child is exposed, and through restartSupervisedSeat
3203
- * with the one record a crashed manager left (`supervised`). */
3204
- async resumePreservedAgent(entry, preflightOnly = false, batchReserved = false, prepared, supervised) {
3205
- if (this.execution === "none")
3206
- return { ok: false, error: this.executionRefusal() };
3207
- const release = this.beginLifecycle(batchReserved);
3208
- if (!release)
3209
- return { ok: false, error: this.maintenanceError() };
3210
- try {
3211
- if (entry.space !== this.space)
3212
- return { ok: false, error: `retained agent ${entry.name} belongs to space "${entry.space}", not "${this.space}"` };
3213
- try {
3214
- await this.loadSeatRuntime(entry.launch.runtime);
3215
- }
3216
- catch (e) {
3217
- return { ok: false, error: `retained agent ${entry.name} requires runtime "${entry.launch.runtime}", which this manager cannot resolve: ${rejectionText(e)}` };
3218
- }
3219
- if (entry.launch.runtime !== this.runtimeFor(entry.launch.runtime).kind)
3220
- return { ok: false, error: `retained agent ${entry.name} requires runtime "${entry.launch.runtime}", which this manager cannot resolve` };
3221
- const nameErr = this.nameError(entry.name);
3222
- if (nameErr)
3223
- return { ok: false, error: nameErr };
3224
- if (this.agents.has(entry.name) || (!batchReserved && this.namesCapacity.isReserved(entry.name)))
3225
- return { ok: false, error: `retained agent "${entry.name}" is already managed or reserved; same-principal resume never auto-numbers` };
3226
- const occupancy = batchReserved ? undefined : this.occupancy();
3227
- if (occupancy && occupancy.used >= MAX_AGENTS)
3228
- return { ok: false, error: `${this.capacityRefusal(occupancy)}; same-principal resume refused` };
3229
- const cached = prepared?.get(entry.name);
3230
- if (!preflightOnly && cached) {
3231
- try {
3232
- // Do not trust the earlier batch preflight across another agent's sequential readiness wait.
3233
- await this.validateRetainedAuthority(entry);
3234
- }
3235
- catch (e) {
3236
- return { ok: false, error: rejectionText(e) };
3237
- }
3238
- return this.launchPreparedResume(entry, cached, batchReserved, supervised);
3239
- }
3240
- try {
3241
- const cwd = lstatSync(entry.launch.cwd);
3242
- if (!cwd.isDirectory() || cwd.isSymbolicLink())
3243
- return { ok: false, error: `retained cwd is not a real directory: ${entry.launch.cwd}` };
3244
- }
3245
- catch (e) {
3246
- return { ok: false, error: `retained cwd unavailable: ${entry.launch.cwd} (${rejectionText(e)})` };
3247
- }
3248
- let connector;
3249
- try {
3250
- // The SAME resolver the spawn path uses. A bare `registry.resolve` here made preserve→resume
3251
- // fail for EVERY retained agent on the published binary: the resuming manager is a fresh
3252
- // process whose registry is empty (its supervise child runs with the connector seed
3253
- // skipped), so nothing is registered until something materializes it from the ext manifest.
3254
- // That is precisely what `resolveConnector` does and what every spawn path already calls.
3255
- // Resolving bare meant a preserved mesh could never come back — first-party connectors
3256
- // included, since the asymmetry is about materialization, not about which connector it is.
3257
- connector = await this.resolveConnector(entry.launch.connector);
3258
- }
3259
- catch (e) {
3260
- return { ok: false, error: rejectionText(e) };
3261
- }
3262
- await this.refreshUnavailableConnectors(connector.name, true);
3263
- const harness = this.launchHarness(connector);
3264
- if ("refusal" in harness)
3265
- return { ok: false, error: harness.refusal };
3266
- let retainedSession;
3267
- try {
3268
- retainedSession = this.retainedSessionId(entry, connector);
3269
- }
3270
- catch (error) {
3271
- return { ok: false, error: rejectionText(error) };
3272
- }
3273
- if (entry.launch.forkSource && !retainedSession && !connector.supportsResume)
3274
- return { ok: false, error: `${connector.name} connector does not support session fork (resume)` };
3275
- if (retainedSession && !connector.supportsSessionContinuation)
3276
- return { ok: false, error: `${connector.name} connector does not support exact-session continuation` };
3277
- let launchOptions;
3278
- let exact = false;
3279
- if (entry.launch.source.kind === "manifest") {
3280
- const launchSource = entry.launch.source;
3281
- if (!launchSource.runId)
3282
- return { ok: false, error: `retained manifest launch for ${entry.name} has no runId; refusing to guess a .cotal/run source` };
3283
- let spec;
3284
- try {
3285
- const source = launchSpecForRun(this.workspaceRoot, launchSource.runId);
3286
- if (source.space !== this.space)
3287
- return { ok: false, error: `retained launch spec space "${source.space}" does not match manager space "${this.space}"` };
3288
- spec = source.agents.find((a) => a.name === launchSource.requested);
3289
- }
3290
- catch (e) {
3291
- return { ok: false, error: rejectionText(e) };
3292
- }
3293
- if (!spec || spec.hash !== launchSource.hash)
3294
- return { ok: false, error: `retained manifest agent ${launchSource.requested} is missing or its hash changed; refusing same-principal resume` };
3295
- launchOptions = spec.launchOptions;
3296
- exact = spec.continuity === "exact";
3297
- }
3298
- else {
3299
- try {
3300
- launchOptions = loadAgentFile(entry.launch.source.configPath).launchOptions;
3301
- }
3302
- catch (e) {
3303
- return { ok: false, error: rejectionText(e) };
3304
- }
3305
- }
3306
- // Asked once `exact` is known: an exact seat reopens its retained session or fails, like its
3307
- // manifest launch, so the connector must honor reopenSession before the batch starts any child.
3308
- const unsupported = this.capabilityRefusal(connector, { variant: entry.launch.variant, prompt: entry.launch.prompt, exact });
3309
- if (unsupported)
3310
- return { ok: false, error: unsupported };
3311
- const eventsRefused = this.eventsRefusal(connector, entry.launch.events);
3312
- if (eventsRefused)
3313
- return { ok: false, error: eventsRefused };
3314
- let authority;
3315
- try {
3316
- authority = await this.validateRetainedAuthority(entry);
3317
- }
3318
- catch (e) {
3319
- return { ok: false, error: rejectionText(e) };
3320
- }
3321
- try {
3322
- const launchOpts = {
3323
- ...this.hostLaunchFields(loadCotalConfig(this.workspaceRoot), entry.launch.connector, entry.launch.shareTools, harness),
3324
- name: entry.name,
3325
- role: entry.role,
3326
- id: authority.id,
3327
- creds: authority.creds,
3328
- userAuth: authority.userAuth,
3329
- // Recover the ORIGINAL incarnation uid (never a fresh mint on resume): the child endpoint
3330
- // binds its lifecycle-keyed dm/dlv/chathist durables by this exact value, and its creds pin
3331
- // the same names. Omitting it here (as the pre-fix resume path did) leaves the resumed child
3332
- // with no COTAL_LIFECYCLE_UID: static/user fail the connector auth gate and open self-mints a
3333
- // fresh uid that orphans the preserved durables and never matches the readiness fence.
3334
- lifecycleUid: entry.identity.lifecycleUid,
3335
- backfillFloor: entry.backfillFloor,
3336
- acceptedToken: entry.identity.mode === "static" ? entry.identity.issued?.acceptedToken : undefined,
3337
- configPath: entry.launch.source.configPath,
3338
- model: entry.launch.model,
3339
- variant: entry.launch.variant,
3340
- launchOptions,
3341
- resume: retainedSession ? undefined : entry.launch.forkSource,
3342
- continueSession: exact ? undefined : retainedSession,
3343
- reopenSession: exact ? retainedSession : undefined,
3344
- subscribe: entry.launch.subscribe,
3345
- allowSubscribe: entry.launch.allowSubscribe,
3346
- allowPublish: entry.launch.allowPublish,
3347
- capabilities: entry.launch.capabilities,
3348
- endpoints: copyPersonaEndpoints(entry.launch.endpoints) ?? [],
3349
- events: entry.launch.events,
3350
- eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
3351
- cwd: entry.launch.cwd,
3352
- };
3353
- const spec = connector.buildLaunch(launchOpts);
3354
- spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
3355
- const value = { spec, launchOpts, ...authority, exact };
3356
- prepared?.set(entry.name, value);
3357
- if (preflightOnly)
3358
- return { ok: true, data: { name: entry.name, preflight: true } };
3359
- return this.launchPreparedResume(entry, value, batchReserved, supervised);
3360
- }
3361
- catch (e) {
3362
- return { ok: false, error: rejectionText(e) };
3363
- }
3364
- }
3365
- finally {
3366
- release();
3367
- }
3368
- }
3369
- async launchPreparedResume(entry, prepared, batchReserved, supervised) {
3370
- if (!batchReserved)
3371
- this.namesCapacity.reserve(entry.name, resumeOwner(entry));
3372
- try {
3373
- // Recover the STATIC identity's nkey seed from the adopted credential (the
3374
- // creds file embeds it) so the manager stays this incarnation's RENEWAL OWNER across a
3375
- // preserve/resume — without it the adopted cred would die loud at its TTL with no remint.
3376
- let adoptedSeed;
3377
- if (entry.identity.mode === "static") {
3378
- const stored = await this.secrets.get(agentSecretKeyForFile(resolve(entry.identity.credential.path), this.space));
3379
- // The core parser, which reads the creds format's six-dash END marker. A local pattern that
3380
- // expected five matched no real file, so every resumed seat lost its renewal.
3381
- try {
3382
- adoptedSeed = stored === undefined ? undefined : identityFromCreds(stored).seed;
3383
- }
3384
- catch {
3385
- adoptedSeed = undefined;
3386
- }
3387
- if (adoptedSeed === undefined)
3388
- console.error(`! resume ${entry.name}: the adopted credential carries no readable nkey seed - the manager cannot renew it (it dies loud at its exp)`);
3389
- }
3390
- const connector = await this.resolveConnector(entry.launch.connector);
3391
- const readinessTimeoutMs = connector.readinessTimeoutMs ?? this.readinessTimeoutMs;
3392
- if (!Number.isSafeInteger(readinessTimeoutMs) || readinessTimeoutMs <= 0)
3393
- return { ok: false, error: `connector ${connector.name} declares invalid readinessTimeoutMs ${JSON.stringify(connector.readinessTimeoutMs)}; expected a positive safe integer` };
3394
- const resumeId = entry.identity.mode === "user" ? principalKey(entry.identity.owner, entry.identity.actor).key : entry.identity.id;
3395
- const runtime = this.runtimeFor(entry.launch.runtime);
3396
- const custody = this.reserveCustody(runtime);
3397
- if (custody)
3398
- await this.recordSlotCustody({ name: entry.name, id: resumeId, lifecycleUid: entry.identity.lifecycleUid }, custody);
3399
- prepared.spawned = true;
3400
- const handle = await this.spawnCustodied(runtime, entry.name, prepared.spec, entry.launch.cwd, custody);
3401
- const managed = {
3402
- name: entry.name,
3403
- role: entry.role,
3404
- agent: entry.launch.connector,
3405
- id: resumeId,
3406
- seed: adoptedSeed,
3407
- ...(entry.identity.mode === "static" && entry.identity.issued ? { issued: entry.identity.issued } : {}),
3408
- // Recover the ORIGINAL incarnation uid the durables are keyed by (never a fresh mint on resume).
3409
- lifecycleUid: entry.identity.lifecycleUid,
3410
- // Adopt the INVENTORY's recorded family (possibly a pre-split name-keyed layout) — the
3411
- // validated paths above, so this incarnation's later teardown addresses exactly what its
3412
- // spawn materialized, never a re-derivation.
3413
- secretPaths: entry.identity.mode === "user"
3414
- ? { actorToken: entry.identity.actorToken.path, sentinelCreds: entry.identity.sentinelCredential.path, health: entry.identity.health.path }
3415
- : entry.identity.mode === "static"
3416
- ? { creds: entry.identity.credential.path }
3417
- : undefined,
3418
- userOwner: entry.identity.mode === "user" ? entry.identity.owner : undefined,
3419
- spawner: entry.spawner,
3420
- authorityParent: entry.authorityParent,
3421
- startedAt: Date.now(),
3422
- handle,
3423
- control: prepared.spec.control,
3424
- launch: {
3425
- runtime: entry.launch.runtime,
3426
- source: entry.launch.source,
3427
- cwd: entry.launch.cwd,
3428
- model: entry.launch.model,
3429
- variant: entry.launch.variant,
3430
- subscribe: entry.launch.subscribe,
3431
- allowSubscribe: entry.launch.allowSubscribe,
3432
- allowPublish: entry.launch.allowPublish,
3433
- capabilities: entry.launch.capabilities,
3434
- ...(entry.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(entry.launch.endpoints) } : {}),
3435
- events: entry.launch.events,
3436
- eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
3437
- shareTools: entry.launch.shareTools,
3438
- forkSource: entry.launch.forkSource,
3439
- ...(entry.launch.resumed ? { resumed: entry.launch.resumed } : {}),
3440
- ...(prepared.launchOpts.resume !== undefined && prepared.spec.resumeRecordPath ? { resumeRecordPath: prepared.spec.resumeRecordPath } : {}),
3441
- sessionId: entry.launch.sessionId,
3442
- },
3443
- ...(supervised
3444
- ? { restart: { opts: prepared.launchOpts, sessionStatePath: prepared.spec.sessionStatePath, crashes: supervised.crashes, recovering: false, armed: false, policy: supervised.policy } }
3445
- : prepared.spec.sessionStatePath
3446
- ? { restart: { opts: prepared.launchOpts, sessionStatePath: prepared.spec.sessionStatePath, crashes: [], recovering: false, armed: false } }
3447
- : {}),
3448
- suppressCleanup: true,
3449
- };
3450
- this.agents.set(entry.name, managed);
3451
- this.namesCapacity.placed(entry.name);
3452
- if (this.resumeAttemptId)
3453
- this.resumedAgentNames.add(entry.name);
3454
- try {
3455
- await this.recordSlotRuntime(managed);
3456
- }
3457
- catch (error) {
3458
- return await this.stopFailedResume(managed, "resume-custody-unrecorded", `${managed.name} resumed, but ${rejectionText(error)}`);
3459
- }
3460
- const readiness = await this.awaitReadiness(managed, readinessTimeoutMs, supervised ? { joinedAfter: supervised.joinedAfter } : {});
3461
- if (!readiness.ok && !readiness.uncertain)
3462
- return { ok: false, error: readiness.detail };
3463
- if (!readiness.ok) {
3464
- this.watchExit(managed);
3465
- // The restart was counted when it launched, so the record carries that crash whether or not
3466
- // the seat ever joins: a successor reads the record to decide whether another fits the budget.
3467
- if (supervised)
3468
- this.refreshSeatRecord(managed);
3469
- this.watchResumeAdoption(managed, supervised?.joinedAfter, () => this.armLateResume(managed, connector, prepared, supervised));
3470
- return { ok: false, error: readiness.detail };
3471
- }
3472
- const unbound = await this.armResumedSeat(managed, connector, prepared, supervised);
3473
- if (unbound !== undefined)
3474
- return await this.stopFailedResume(managed, "resume-session-rebind-failed", unbound);
3475
- if (!this.resumeAttemptId)
3476
- managed.suppressCleanup = false;
3477
- if (supervised)
3478
- this.refreshSeatRecord(managed);
3479
- this.watchExit(managed);
3480
- if (this.agents.get(managed.name) !== managed)
3481
- return { ok: false, error: `${managed.name} exited immediately after same-principal readiness` };
3482
- return {
3483
- ok: true,
3484
- data: { name: managed.name, role: managed.role, agent: managed.agent, id: managed.id, mode: handle.kind, resumed: true },
3485
- };
3486
- }
3487
- catch (e) {
3488
- return { ok: false, error: rejectionText(e) };
3489
- }
3490
- finally {
3491
- if (!batchReserved) {
3492
- this.namesCapacity.release(entry.name);
3493
- }
3494
- }
3495
- }
3496
- /** Arm a resumed seat's restart once it is ready, whether it joined inside the readiness window or
3497
- * after it (#4144). A supervised restart arms the way its spawn did: a connector with no session
3498
- * continuation is armed at readiness, one with it once its session is proved. Returns why the
3499
- * session could not be rebound, and the caller stops the seat. */
3500
- async armResumedSeat(managed, connector, prepared, supervised) {
3501
- if (supervised && managed.restart && !connector.supportsSessionContinuation && !prepared.exact) {
3502
- managed.restart.armed = true;
3503
- return undefined;
3504
- }
3505
- if (!managed.restart && !prepared.exact)
3506
- return undefined;
3507
- try {
3508
- await this.armSessionRecovery(managed);
3509
- // As on a manifest launch, an exact seat is recorded only at the session it asked for,
3510
- // proved over the connector's authenticated control endpoint.
3511
- if (prepared.exact && !managed.restart?.armed)
3512
- throw new Error("continuity: exact needs the connector to prove its session over an authenticated control endpoint, and it supplied none");
3513
- managed.launch.sessionId = this.readManagedSession(managed);
3514
- const asked = prepared.launchOpts.reopenSession;
3515
- if (asked !== undefined && managed.launch.sessionId !== asked)
3516
- throw new Error(`continuity: exact asked for session ${asked}, the connector bound ${managed.launch.sessionId}`);
3517
- if (prepared.exact) {
3518
- managed.continuity = { space: this.space, name: managed.name, connector: managed.agent, cwd: managed.launch.cwd };
3519
- this.recordContinuity(managed, managed.launch.sessionId);
3520
- }
3521
- return undefined;
3522
- }
3523
- catch (error) {
3524
- return `${managed.name} resumed, but its exact host session could not be rebound: ${rejectionText(error)}`;
3525
- }
3526
- }
3527
- /** A resumed seat whose readiness was uncertain gets what a ready one gets once it joins: its
3528
- * restart is armed and its record rewritten. Without this, a supervised seat restarted after a
3529
- * manager crash that joined late was retired on its next exit instead of restarted. */
3530
- async armLateResume(managed, connector, prepared, supervised) {
3531
- const current = () => this.agents.get(managed.name) === managed && !managed.terminalizing;
3532
- if (!current())
3533
- return;
3534
- const unbound = await this.armResumedSeat(managed, connector, prepared, supervised);
3535
- if (!current())
3536
- return;
3537
- if (unbound !== undefined) {
3538
- const stopped = await this.stopFailedResume(managed, "resume-session-rebind-failed", unbound);
3539
- if (!stopped.ok)
3540
- console.error(`! ${stopped.error}`);
3541
- return;
3542
- }
3543
- if (supervised)
3544
- this.refreshSeatRecord(managed);
3545
- }
3546
- /** A resumed seat keeps its retained credentials, so freeing it runs no deprovision and nothing
3547
- * would reap it: it is freed only once its exit is proved, and otherwise stays managed until it
3548
- * exits or the manager stops it. */
3549
- async stopFailedResume(managed, cause, detail) {
3550
- const refused = this.stopHandle(managed, false, cause);
3551
- const unproven = refused === undefined
3552
- ? await this.awaitHandleExit(managed.handle).then(() => undefined, rejectionText)
3553
- : `stop failed: ${refused}`;
3554
- if (unproven !== undefined) {
3555
- this.watchExit(managed);
3556
- return { ok: false, error: `${detail}; it stays managed because its stop is unproven: ${unproven}` };
3557
- }
3558
- this.freeSlot(managed, true, cause, true);
3559
- return { ok: false, error: detail };
3560
- }
1496
+ /** {@link PreservedResume.resumePreserved}. */
1497
+ resumePreserved(...args) { return this.preservedResumeComponent.resumePreserved(...args); }
1498
+ /** {@link PreservedResume.validateRetainedAuthority}. */
1499
+ validateRetainedAuthority(...args) { return this.preservedResumeComponent.validateRetainedAuthority(...args); }
1500
+ /** {@link PreservedResume.resumePreservedAgent}. */
1501
+ resumePreservedAgent(...args) { return this.preservedResumeComponent.resumePreservedAgent(...args); }
3561
1502
  probeStaticCredential(creds) {
3562
1503
  return probeConnect(this.servers ?? DEFAULT_SERVER, { creds, timeoutMs: 5_000 });
3563
1504
  }
3564
- /** An uncertain resume remains non-destructive until exact-principal AND exact-incarnation presence
3565
- * arrives later, and then `adopted` runs. Same predicate as the readiness fence: a principal-only
3566
- * match would let a wrong/absent-uid presence under the reused alias clear cleanup suppression on
3567
- * another incarnation. A supervised restart keeps its principal and uid, so it also carries the
3568
- * fence's `joinedAfter` bound: the row the dead seat left must not stand in for the new process.
3569
- * A heartbeat on that row moves only its time and emits no presence event, so the bound is polled. */
3570
- watchResumeAdoption(a, joinedAfter, adopted) {
3571
- const wanted = this.managedPrincipal(a);
3572
- let poll;
3573
- const done = () => {
3574
- this.ep.off("presence", onPresence);
3575
- if (poll !== undefined)
3576
- clearInterval(poll);
3577
- };
3578
- const onPresence = () => {
3579
- if (this.agents.get(a.name) !== a) {
3580
- done();
3581
- return;
3582
- }
3583
- if (!this.ep.getRoster().some((p) => p.card.id === wanted && p.status !== "offline" && p.lifecycleUid === a.lifecycleUid && (joinedAfter === undefined || p.ts >= joinedAfter)))
3584
- return;
3585
- if (!this.resumeRequired)
3586
- a.suppressCleanup = false;
3587
- done();
3588
- adopted().catch((error) => console.error(`! ${a.name}: joined after its readiness window, but ${rejectionText(error)}`));
3589
- };
3590
- this.ep.on("presence", onPresence);
3591
- if (joinedAfter !== undefined) {
3592
- poll = setInterval(onPresence, LATE_JOIN_POLL_MS);
3593
- poll.unref?.();
3594
- }
3595
- onPresence();
3596
- }
3597
1505
  /** {@link ReadinessWait.awaitReadiness}. */
3598
1506
  awaitReadiness(...args) { return this.readinessWaitComponent.awaitReadiness(...args); }
3599
1507
  /** {@link ReadinessWait.tail}. */
@@ -3638,52 +1546,8 @@ export class Manager {
3638
1546
  staticReconciliationStatus() {
3639
1547
  return this.staticLifecycle.staticReconciliationStatus();
3640
1548
  }
3641
- /** Complete a crashed predecessor's FROZEN registration gate before this incarnation starts a
3642
- * new one (#783 item 3 / #871). The CLI `cotal reconcile-gate` already does this; a successor
3643
- * that cannot register is exactly the state that command exists to repair, so boot must run
3644
- * the SAME composition rather than waiting for an operator.
3645
- *
3646
- * Admit only `gone` AND `sweepComplete=true` (the probe mapping already folds an incomplete
3647
- * `gone` into `unestablishable`). Live / unknown / unestablishable / wrong-op-kind stay loud
3648
- * refusals. No TTL: request-ingress has no process-epoch fence, so a clock would either let a
3649
- * superseded serve credential keep consuming ingress or just rename the freeze. An open gate
3650
- * is a no-op (the successor's own freeze comes next). A committed spec under that freeze is
3651
- * finished at the committed registrationRevision; only a definite no-commit abort-reopens. */
3652
- async healFrozenRegistrationGate(authKv, instanceId, auth, recordsKv) {
3653
- const key = epgateKey(MANAGER_ENDPOINT, instanceId);
3654
- const entry = await authKv.get(key);
3655
- if (!entry || entry.operation !== "PUT")
3656
- return;
3657
- const row = parseEndpointGate(entry.value, key);
3658
- if (row.state !== "frozen")
3659
- return;
3660
- const servers = this.servers ?? DEFAULT_SERVER;
3661
- const log = (line) => console.error(` ${line}`);
3662
- let report;
3663
- try {
3664
- report = await reconcileEndpointGate({
3665
- kv: authKv, space: this.space, endpoint: MANAGER_ENDPOINT, instanceId,
3666
- probeHolder: makeManagerHolderLivenessProbe({ space: this.space, servers, auth, log, unreachableWaitMs: DELIVERY_ADMIN_BOOT_WAIT_MS }),
3667
- evictHolders: makeManagerEndpointHolderEvictor({ space: this.space, servers, auth, log }),
3668
- log,
3669
- recordsKv,
3670
- });
3671
- }
3672
- catch (e) {
3673
- // We observed frozen, then a concurrent reconciler finished first. If the gate is now open,
3674
- // this incarnation continues the takeover. Every other refusal — including raced-but-still-
3675
- // frozen — stays loud.
3676
- if (e instanceof GateReconcileRefused && (e.condition === "not-frozen" || e.condition === "raced")) {
3677
- const latest = await authKv.get(key);
3678
- if (latest && latest.operation === "PUT" && parseEndpointGate(latest.value, key).state === "open") {
3679
- console.error(`boot self-heal: ${MANAGER_ENDPOINT}/${instanceId} is open after ${e.condition}; continuing the normal takeover`);
3680
- return;
3681
- }
3682
- }
3683
- throw e;
3684
- }
3685
- console.error(`✓ boot self-heal: ${MANAGER_ENDPOINT}/${instanceId} registration gate reopened at generation ${report.reopenedAtGeneration} (processEpoch ${report.after.processEpoch}, registrationRevision ${report.after.registrationRevision}; freeze-holder gone, sweepComplete=true). Continuing the normal takeover.`);
3686
- }
1549
+ /** {@link ManagerBoot.healFrozenRegistrationGate}. */
1550
+ healFrozenRegistrationGate(...args) { return this.bootComponent.healFrozenRegistrationGate(...args); }
3687
1551
  dialServeConnection(state, readCreds = () => state.creds, deadline) { return this.servePlane.dialServeConnection(state, readCreds, deadline); }
3688
1552
  registerManagerService() { return this.servePlane.registerManagerService(); }
3689
1553
  /** {@link GoalWriter.mintAndStageGoalWriter}. */