@cotal-ai/manager 0.171.3 → 0.171.5

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 (107) 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 +132 -0
  6. package/dist/broker-transport.d.ts.map +1 -0
  7. package/dist/broker-transport.js +282 -0
  8. package/dist/broker-transport.js.map +1 -0
  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 +40 -0
  14. package/dist/connector-inventory.d.ts.map +1 -0
  15. package/dist/connector-inventory.js +90 -0
  16. package/dist/connector-inventory.js.map +1 -0
  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 +74 -0
  26. package/dist/harness-resolution.d.ts.map +1 -0
  27. package/dist/harness-resolution.js +125 -0
  28. package/dist/harness-resolution.js.map +1 -0
  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.d.ts +613 -553
  38. package/dist/manager.d.ts.map +1 -1
  39. package/dist/manager.js +192 -3621
  40. package/dist/manager.js.map +1 -1
  41. package/dist/names-capacity.d.ts +4 -0
  42. package/dist/names-capacity.d.ts.map +1 -1
  43. package/dist/names-capacity.js +29 -0
  44. package/dist/names-capacity.js.map +1 -1
  45. package/dist/persona-catalog.d.ts +3 -0
  46. package/dist/persona-catalog.d.ts.map +1 -1
  47. package/dist/persona-catalog.js +19 -0
  48. package/dist/persona-catalog.js.map +1 -1
  49. package/dist/preservation.d.ts +160 -0
  50. package/dist/preservation.d.ts.map +1 -0
  51. package/dist/preservation.js +631 -0
  52. package/dist/preservation.js.map +1 -0
  53. package/dist/preserved-resume.d.ts +220 -0
  54. package/dist/preserved-resume.d.ts.map +1 -0
  55. package/dist/preserved-resume.js +1222 -0
  56. package/dist/preserved-resume.js.map +1 -0
  57. package/dist/readiness-wait.d.ts +67 -0
  58. package/dist/readiness-wait.d.ts.map +1 -0
  59. package/dist/readiness-wait.js +255 -0
  60. package/dist/readiness-wait.js.map +1 -0
  61. package/dist/retirement.d.ts +4 -0
  62. package/dist/retirement.d.ts.map +1 -1
  63. package/dist/retirement.js +29 -0
  64. package/dist/retirement.js.map +1 -1
  65. package/dist/seat-custody.d.ts +4 -0
  66. package/dist/seat-custody.d.ts.map +1 -1
  67. package/dist/seat-custody.js +25 -0
  68. package/dist/seat-custody.js.map +1 -1
  69. package/dist/seat-launch.d.ts +3 -0
  70. package/dist/seat-launch.d.ts.map +1 -1
  71. package/dist/seat-launch.js +69 -0
  72. package/dist/seat-launch.js.map +1 -1
  73. package/dist/seat-stop.d.ts +3 -0
  74. package/dist/seat-stop.d.ts.map +1 -1
  75. package/dist/seat-stop.js +40 -0
  76. package/dist/seat-stop.js.map +1 -1
  77. package/dist/seat-types.d.ts +6 -6
  78. package/dist/seat-types.d.ts.map +1 -1
  79. package/dist/serve-plane.d.ts +4 -0
  80. package/dist/serve-plane.d.ts.map +1 -1
  81. package/dist/serve-plane.js +76 -0
  82. package/dist/serve-plane.js.map +1 -1
  83. package/dist/session-recovery.d.ts +4 -0
  84. package/dist/session-recovery.d.ts.map +1 -1
  85. package/dist/session-recovery.js +31 -0
  86. package/dist/session-recovery.js.map +1 -1
  87. package/dist/spawn-goal.d.ts +3 -0
  88. package/dist/spawn-goal.d.ts.map +1 -1
  89. package/dist/spawn-goal.js +23 -0
  90. package/dist/spawn-goal.js.map +1 -1
  91. package/dist/start-doors.d.ts +54 -0
  92. package/dist/start-doors.d.ts.map +1 -0
  93. package/dist/start-doors.js +201 -0
  94. package/dist/start-doors.js.map +1 -0
  95. package/dist/status-and-models.d.ts +158 -0
  96. package/dist/status-and-models.d.ts.map +1 -0
  97. package/dist/status-and-models.js +330 -0
  98. package/dist/status-and-models.js.map +1 -0
  99. package/dist/terminal-input.d.ts +3 -0
  100. package/dist/terminal-input.d.ts.map +1 -1
  101. package/dist/terminal-input.js +12 -0
  102. package/dist/terminal-input.js.map +1 -1
  103. package/dist/user-provision.d.ts +4 -0
  104. package/dist/user-provision.d.ts.map +1 -1
  105. package/dist/user-provision.js +17 -0
  106. package/dist/user-provision.js.map +1 -1
  107. package/package.json +12 -12
package/dist/manager.js CHANGED
@@ -1,51 +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 Headless from "@xterm/headless";
9
- import { CotalEndpoint, copyPersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, injectedSecretStoreIdentity, dialerFor, connectorServers, spawnEnvAllow, idFromCreds, identityFromCreds, inspectCredHealth, loadAgentFile, loadCotalConfig, mintCreds, bindIssuedStores, mintLifecycleUid, newIdentity, oneLine, parsePrincipalKey, principalKey, probeConnect, registry, resolveAuthProvider, } from "@cotal-ai/core";
6
+ import { CotalEndpoint, accountFromCreds, DEFAULT_SERVER, DEV_OWNER, injectedSecretStoreIdentity, mintLifecycleUid, oneLine, parsePrincipalKey, principalKey, probeConnect, resolveAuthProvider } from "@cotal-ai/core";
10
7
  import { retainConnectorSeat } from "@cotal-ai/workspace";
11
- import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
12
- import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
13
- import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
14
- import { Retirement } from "./retirement.js";
15
- import { ServePlane } from "./serve-plane.js";
16
- import { NamesCapacity } from "./names-capacity.js";
8
+ import { logicalExecutionEntry } from "@cotal-ai/workspace";
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";
17
14
  import { AttachEndpoint } from "./attach-endpoint.js";
18
- import { DELIVERY_ADMIN_BOOT_WAIT_MS, makeManagerEndpointHolderEvictor, withScopedEndpoint } from "./endpoint-evict.js";
19
- import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
20
- 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";
21
16
  export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
22
17
  export { credRenewIntervalMs } from "./credential-renewal.js";
23
- import { LeaseKeeper } from "./lease-keeper.js";
18
+ import { LeaseKeeper, leaseKeeperDeps } from "./lease-keeper.js";
24
19
  export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
25
- import { SessionRecovery } from "./session-recovery.js";
26
- import { SeatCustody, watchConnectorHolder } from "./seat-custody.js";
27
- import { GoalWriter } from "./goal-writer.js";
28
- import { DEPROVISION_TIMEOUT_MS, SeatStop } from "./seat-stop.js";
29
- import { CommandDispatch, participantKey } from "./command-dispatch.js";
30
- import { SpawnGoal } from "./spawn-goal.js";
31
- import { PersonaCatalog } from "./persona-catalog.js";
32
- import { TerminalInput } from "./terminal-input.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";
33
36
  export { PASTE_END, PASTE_START, RUNTIME_NO_TERMINAL_DETAIL } from "./terminal-input.js";
34
- import { CredentialRenewal, credRenewIntervalMs, REMOTE_STANDING_BUDGET_MS, remoteStandingTimeLeft, sameStrings } from "./credential-renewal.js";
35
- 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";
36
40
  import { withTimeout } from "./manager-timeout.js";
37
- import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
38
- import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, parseLaunchSpec, persistLaunchSpec } from "./launch.js";
39
- import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
41
+ import { inlineSnapshotPath } from "./launch.js";
42
+ import { authorizeNamedControl } from "./authorize.js";
40
43
  import { RunHosting } from "./run-hosting.js";
41
44
  import { rejectionText, attemptCleanup } from "@cotal-ai/core";
42
- import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
45
+ import { readReleasedSeatReference } from "./resume.js";
43
46
  import { TranscriptReceiver } from "./transcript-receive.js";
44
47
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
45
48
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
46
- import { jetstreamManager } from "@nats-io/jetstream";
47
- import { Kvm } from "@nats-io/kv";
48
- import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts } from "@cotal-ai/core";
49
+ import {} from "@cotal-ai/core";
49
50
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
50
51
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
51
52
  // per-session credentials on their own short-lived connections).
@@ -53,13 +54,8 @@ import { ManagerSessionPlane } from "./session/index.js";
53
54
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
54
55
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
55
56
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
56
- import { epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, listGoalIndex, MAX_SCHEDULE_MS, turnNoticeSubject, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom } from "@cotal-ai/core";
57
+ import { readEndpointGateGeneration, deregisterServiceInstance, turnNoticeSubject, EpEnvelopeError } from "@cotal-ai/core";
57
58
  import { MANAGER_ENDPOINT } from "./manager-service-contract.js";
58
- import { staticLifecycleTransport, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, } from "./static-lifecycle.js";
59
- // Capture the loaded package version before an installation can replace its files.
60
- const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
61
- /** A `once` spawn's task deadline when the caller names none: one hour from the spawn's accept. */
62
- const ONCE_DEFAULT_DEADLINE_MS = 60 * 60_000;
63
59
  /** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
64
60
  * stays and the turn sweep asks again. */
65
61
  const ONCE_RETIRE_MS = 60_000;
@@ -76,18 +72,6 @@ export const READINESS_TIMEOUT_MS = 30_000;
76
72
  * from its launch: the watch's 15s for the confirm prompt and 15s for its notice, plus 5s for the
77
73
  * last read. The readiness window applies when it is longer. */
78
74
  const STARTUP_OUTCOME_MS = 35_000;
79
- /** How often the readiness race asks a runtime that streams no exit whether its child has exited, and
80
- * how long it waits past the window for the proof of its last read. An operator waits on this reply,
81
- * so it asks more often than the exit watch that outlives readiness. */
82
- const READINESS_EXIT_POLL_MS = 1_000;
83
- /** How often a resumed seat whose readiness was uncertain is checked for a join its predecessor's
84
- * presence row hides (see {@link Manager.watchResumeAdoption}). The wait has no end of its own, so
85
- * it asks less often than the readiness fence's 50 ms poll. */
86
- const LATE_JOIN_POLL_MS = 1_000;
87
- /** How long the process of a launch that waits for the operator ({@link Connector.waitsForOperator})
88
- * must run without exiting before it is ready: long enough that a harness refusing its arguments
89
- * exits first and is reported as failed. */
90
- const OPERATOR_READINESS_MS = 3_000;
91
75
  /** At most this many retirements run at once (#4965). A retirement dials up to four fresh broker
92
76
  * connections in turn and queues an eviction and an inventory on the delivery daemon's admin rail,
93
77
  * each against a fixed deadline. A stop that started all 50 seats' retirements together lost most of
@@ -100,65 +84,7 @@ const RETIREMENT_CONCURRENCY = 8;
100
84
  /** A hard preservation stop should settle quickly. The manager still waits and reports a partial
101
85
  * cut rather than pretending a child is gone. Held in ManagerOptions so fake runtimes can shorten it. */
102
86
  const PRESERVE_STOP_TIMEOUT_MS = 10_000;
103
- /** How long a resume waits for a reaped orphan's principal to leave presence. Presence rows age
104
- * out after their 6s TTL, so three TTLs covers a killed seat that never published its leave. */
105
- const ORPHAN_PRESENCE_CLEAR_MS = 20_000;
106
- /** Startup reconciliation overlaps control-service registration. A spawn or attach for one of
107
- * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
108
- * a reuse. */
109
- const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
110
- /** The owner a retained seat resumes under: its inventory identity's, which is the same value the
111
- * adopted seat records as `userOwner`, so a resumed seat is counted against the owner that held
112
- * it before the restart ({@link Manager.ownerSeats}) and not against the mesh's default one. */
113
- function resumeOwner(entry) {
114
- return entry.identity.mode === "user" ? entry.identity.owner : DEV_OWNER;
115
- }
116
- /** Sentinel owner-filter value that matches NO agent's `userOwner` (owner tokens never contain a
117
- * dash) — what {@link Manager.psOwnerFilter} returns for an unparseable caller so a malformed
118
- * principal fail-closes to an empty `ps` instead of an unbounded one. */
119
- const NO_OWNER_MATCHES = "-no-owner-";
120
- /** Why a frozen manager gate stays frozen on an open mesh. Reconciliation must prove the holder
121
- * gone, and an open mesh runs no delivery daemon to prove it, so neither boot self-heal nor
122
- * `cotal manager reconcile` can reopen the gate there. */
123
- 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";
124
- /** The open mesh's registration evictor. An open mesh has no eviction oracle, so the superseded
125
- * family's holders stay unverified as they do with no evictor, and the barrier keeps the gate
126
- * frozen. Throwing instead of answering `false` only puts the reason in the refusal. */
127
- function openMeshUnverifiedEviction(holders) {
128
- throw new Error(`principal(s) ${holders.map((h) => `"${h}"`).join(", ")} not verified evicted: ${OPEN_MESH_GATE_LIMIT}`);
129
- }
130
- /** An open-mesh registration refused by a gate another registration froze, restated without the
131
- * `cotal reconcile-gate` remedy that cannot run there. Code, gate state, blocked op and op id are
132
- * kept. Any other failure is returned as it is. */
133
- function openMeshFrozenGateRefusal(e, instanceId) {
134
- const envelope = caughtEnvelope(e);
135
- const blocked = lifecycleBlockedFrom(envelope);
136
- if (envelope === undefined || blocked?.gateState !== "frozen" || blocked.blockedOp !== "registration")
137
- return e;
138
- 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);
139
- }
140
- /** The start of every agent's bearer command: node, its loader flags and this manager's entry,
141
- * resolved through every symlink. The agent runs that command for each renewal for as long as it
142
- * lives, and an install can replace the bin link meanwhile: get.cotal.ai writes a shell launcher
143
- * over `~/.local/bin/cotal`, which `npm i -g` had made a link to `dist/cotal.js`. */
144
- function bearerEntryArgv() {
145
- return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
146
- }
147
87
  const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
148
- /** One connector's declared harness binaries resolved on PATH now. The refusal sentence is built only
149
- * here, so the boot row and the check for a connector registered after boot can never word it apart. */
150
- function resolveHarness(name, requires) {
151
- const binaries = {};
152
- const missing = [];
153
- for (const bin of requires) {
154
- const path = resolveOnPath(bin);
155
- if (path)
156
- binaries[bin] = path;
157
- else
158
- missing.push(bin);
159
- }
160
- return missing.length ? { binaries, reason: `${name} harness needs ${missing.join(", ")} on PATH - not found` } : { binaries };
161
- }
162
88
  /** The refusal a control instance with `execution: none` gives every launch, hosting, model and write door. */
163
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";
164
90
  /** The sha256 hex digest of a file's bytes. */
@@ -380,79 +306,8 @@ export class Manager {
380
306
  /** True on a USER-AUTH space (the on-disk marker; cross-checked against the registry at start).
381
307
  * Gates the whole spawn path: user mode grants ledger actors + bearer plumbing, never static mints. */
382
308
  userMode = false;
383
- namesCapacity = new NamesCapacity({
384
- userMode: () => this.userMode,
385
- seatCap: () => this.seatCap,
386
- managerInstanceId: () => this.managerInstanceId,
387
- agents: () => this.agents.values(),
388
- authEnabled: () => this.auth !== undefined,
389
- maintenanceActive: () => this.maintenanceState === "active",
390
- roster: () => this.ep.getRoster(),
391
- agentFor: (name) => this.agents.get(name),
392
- hasAgent: (name) => this.agents.has(name),
393
- removeAgent: (name) => { this.agents.delete(name); },
394
- managedCount: () => this.agents.size,
395
- predecessor: (name) => this.retirement.predecessor(name),
396
- hasRetirementHold: (name) => this.retirement.hasHold(name),
397
- holdRetirement: (name, hold) => this.retirement.hold(name, hold),
398
- endSessionsForTarget: (...args) => { this.sessionPlane?.endForTarget(...args); },
399
- logSeatReaped: (...args) => this.logSeatReaped(...args),
400
- recordContinuityAtStop: (...args) => this.recordContinuityAtStop(...args),
401
- releasedSeatPending: (...args) => this.releasedSeatPending(...args),
402
- dropSeatRecord: (...args) => this.dropSeatRecord(...args),
403
- failSeatTurns: (...args) => this.failSeatTurns(...args),
404
- teardownTarget: (...args) => this.teardownTarget(...args),
405
- dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
406
- trackDeprovision: (...args) => this.trackDeprovision(...args),
407
- });
408
- servePlane = new ServePlane({
409
- auth: () => this.auth,
410
- remoteAuthority: () => this.remoteAuthority,
411
- space: () => this.space,
412
- servers: () => this.servers,
413
- workspaceRoot: () => this.workspaceRoot,
414
- managerInstanceId: () => this.managerInstanceId,
415
- managerServeIdentity: () => this.managerServeIdentity,
416
- leaseStopping: () => this.leaseStopping,
417
- remoteBundleRenewal: () => this.remoteBundleRenewal,
418
- maxSessions: () => this.maxSessions,
419
- serviceServe: () => this.serviceServe,
420
- setServiceServe: (value) => { this.serviceServe = value; },
421
- sessionLedgerIdentity: () => this.sessionLedgerIdentity,
422
- setSessionLedgerIdentity: (value) => { this.sessionLedgerIdentity = value; },
423
- sessionLedgerCreds: () => this.sessionLedgerCreds,
424
- setSessionLedgerCreds: (value) => { this.sessionLedgerCreds = value; },
425
- sessionLedgerConn: () => this.sessionLedgerConn,
426
- setSessionLedgerConn: (value) => { this.sessionLedgerConn = value; },
427
- sessionPlane: () => this.sessionPlane,
428
- setSessionPlane: (value) => { this.sessionPlane = value; },
429
- sessionKeyRenewTimer: () => this.sessionKeyRenewTimer,
430
- setSessionKeyRenewTimer: (value) => { this.sessionKeyRenewTimer = value; },
431
- connectorStatuses: () => { this.refreshUnavailableConnectors(); return this.connectorStatuses; },
432
- setGoalWriterIdentity: (value) => { this.goalWriterIdentity = value; },
433
- setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
434
- remoteStandingBudgetMs: REMOTE_STANDING_BUDGET_MS,
435
- dial: (...args) => this.dial(...args),
436
- dialRemoteStanding: (...args) => this.dialRemoteStanding(...args),
437
- trackTransport: (...args) => this.trackTransport(...args),
438
- discardServeCandidate: (...args) => this.discardServeCandidate(...args),
439
- managerServiceDefs: (...args) => this.managerServiceDefs(...args),
440
- omitClassCommands: (...args) => this.omitClassCommands(...args),
441
- resolveTarget: (target) => this.resolveServeTarget(target),
442
- withEndpointServeExecutor: (...args) => this.withEndpointServeExecutor(...args),
443
- withOpenServeConnection: (...args) => this.withOpenServeConnection(...args),
444
- boundedReconnect: (...args) => this.boundedReconnect(...args),
445
- renewRemoteBeforeRedial: (...args) => this.renewRemoteBeforeRedial(...args),
446
- scheduleServeRenewal: (...args) => this.scheduleServeRenewal(...args),
447
- stop: (...args) => this.stop(...args),
448
- healFrozenRegistrationGate: (...args) => this.healFrozenRegistrationGate(...args),
449
- mintAndStageGoalWriter: (...args) => this.mintAndStageGoalWriter(...args),
450
- retireConnection: (...args) => this.retireConnection(...args),
451
- withTimeout,
452
- remoteStandingTimeLeft,
453
- openMeshUnverifiedEviction,
454
- openMeshFrozenGateRefusal,
455
- });
309
+ namesCapacity = new NamesCapacity(namesCapacityDeps(this));
310
+ servePlane = new ServePlane(servePlaneDeps(this));
456
311
  resolveServeTarget(t) {
457
312
  if (this.remoteAuthority) {
458
313
  const key = principalKey(t.owner, t.actor).key;
@@ -474,35 +329,8 @@ export class Manager {
474
329
  return { lifecycleUid: a.lifecycleUid, mappingRevision: 0 };
475
330
  return undefined;
476
331
  }
477
- retirement = new Retirement({
478
- auth: () => this.auth,
479
- remoteAuthority: () => this.remoteAuthority,
480
- userMode: () => this.userMode,
481
- workspaceRoot: () => this.workspaceRoot,
482
- space: () => this.space,
483
- servers: () => this.servers,
484
- secrets: () => this.secrets,
485
- serveIdentity: () => this.managerServeIdentity,
486
- lifecycleUid: () => this.managerLifecycleUid,
487
- instanceId: () => this.managerInstanceId,
488
- serveEpoch: () => this.serviceServe?.grant.epoch,
489
- dial: (opts) => this.dial(opts),
490
- withRetirementSlot: (run) => this.withRetirementSlot(run),
491
- driveStaticRetirement: (a) => this.driveStaticRetirement(a),
492
- awaitHandleExit: (handle) => this.awaitHandleExit(handle),
493
- shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
494
- dropSeatRecord: (a) => this.dropSeatRecord(a),
495
- fenceRetiringAcl: (a) => this.fenceRetiringAcl(a),
496
- lifecycleMembershipInventory: (a) => this.lifecycleMembershipInventory(a),
497
- brokerTeardown: (task, message) => withTimeout(task, DEPROVISION_TIMEOUT_MS, message),
498
- trackLifecycle: () => { this.lifecycleInFlight++; return () => this.releaseLifecycle(); },
499
- });
500
- lease = new LeaseKeeper({
501
- endpoint: () => this.ep,
502
- instanceId: () => this.managerInstanceId,
503
- space: () => this.space,
504
- stopping: () => this.leaseStopping,
505
- });
332
+ retirement = new Retirement(retirementDeps(this));
333
+ lease = new LeaseKeeper(leaseKeeperDeps(this));
506
334
  get leaseInfo() { return this.lease.leaseInfo; }
507
335
  set leaseInfo(info) { this.lease.leaseInfo = info; }
508
336
  get leaseRevision() { return this.lease.leaseRevision; }
@@ -538,26 +366,13 @@ export class Manager {
538
366
  maintenanceState = "active";
539
367
  lifecycleInFlight = 0;
540
368
  lifecycleDrainWaiters = [];
541
- preservationTask;
542
- preparationTask;
543
369
  preservationGeneration = 0;
544
370
  preservationAttemptId;
545
- preservationStarted = false;
546
- preservationFailures = [];
547
371
  unverifiedStops = [];
548
372
  preservationInventory;
549
373
  resumeAttemptId;
550
- resumeInventoryDigest;
551
- resumeInventory;
552
- resumeTask;
553
- resumeResult;
554
374
  resumeRequired = false;
555
- resumeAwaitingCommit = false;
556
- resumeCommitted = false;
557
- resumeCommitTask;
558
- resumeFinalized = false;
559
375
  resumeDurableCommitToken;
560
- resumedAgentNames = new Set();
561
376
  remoteAuthority;
562
377
  remoteExecutorCreds;
563
378
  remoteSupervisorCreds;
@@ -567,434 +382,51 @@ export class Manager {
567
382
  /** A refused or failed standing candidate is cleanup debt, never a silent loss: the last-good
568
383
  * family stays live and this records what the host may have signed but the manager never adopted. */
569
384
  remoteRenewalDebt;
570
- /** Every broker dial this manager makes, through ONE transport decision.
571
- *
572
- * `this.servers` is whatever the mesh record held (`cotal supervise` reads it from there), so it
573
- * can be a `ws://`/`wss://` broker published through an HTTPS edge. The raw node transport
574
- * refuses such a URL instead of dialing it, so the scheme picks the dialer here rather than at
575
- * thirteen call sites. `dialerFor` also owns the websocket transport's options, which is why
576
- * callers below still pass their own auth options unchanged. */
577
- dial(opts) {
578
- const servers = this.servers ?? DEFAULT_SERVER;
579
- return dialerFor(servers)({ ...opts, servers });
580
- }
581
- /** Initial NATS timeout is per dial, not per server list. Keep the aggregate deadline too, and
582
- * close a late result rather than letting an abandoned preflight or recovery install a transport. */
583
- async dialRemoteStanding(opts, deadline) {
584
- const ms = remoteStandingTimeLeft(deadline);
585
- const pending = this.dial({ ...opts, timeout: ms });
586
- try {
587
- const nc = await withTimeout(pending, ms, "remote manager standing dial exceeded its 10000ms aggregate budget");
588
- remoteStandingTimeLeft(deadline);
589
- if (this.leaseStopping)
590
- throw new Error("manager stopped while a remote standing dial was in flight");
591
- return nc;
592
- }
593
- catch (e) {
594
- // Timing out our wait does not cancel connect(). It still owns its socket until it rejects
595
- // or returns a connection, which must close without serving or changing a current holder.
596
- void pending.then((nc) => nc.close(), () => { }).catch((error) => console.error(`! remote manager abandoned standing dial cleanup: ${rejectionText(error)}`));
597
- throw e;
598
- }
599
- }
600
- seatCustody = new SeatCustody({
601
- staticAuth: () => !!this.auth && !this.userMode,
602
- workspaceRoot: () => this.workspaceRoot,
603
- space: () => this.space,
604
- instanceId: () => this.managerInstanceId,
605
- endpoint: () => this.ep,
606
- secrets: () => this.secrets,
607
- eventPayloadsWithheld: () => this.eventPayloadsWithheld,
608
- runtimeFor: (kind) => this.runtimeFor(kind),
609
- requiredRuntime: () => this.requiredRuntime,
610
- withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
611
- watchConnectorHolder: (handle, holder) => this.watchConnectorHolder(handle, holder),
612
- resumeEntryOf: (agent) => this.resumeEntryOf(agent),
613
- inventoryReferenceError: (entry) => this.inventoryReferenceError(entry),
614
- registerAgent: (name, agent) => { this.agents.set(name, agent); },
615
- agentFor: (name) => this.agents.get(name),
616
- watchExit: (agent) => this.watchExit(agent),
617
- bindOnceSeat: (agent) => this.bindOnceSeat(agent),
618
- renewManagedStaticCred: (agent) => this.renewManagedStaticCred(agent),
619
- resumeSupervisedAgent: (entry, supervised) => this.resumePreservedAgent(entry, false, false, undefined, supervised),
620
- });
621
- sessionRecovery = new SessionRecovery({
622
- workspaceRoot: () => this.workspaceRoot,
623
- execution: () => this.execution,
624
- executionRefusal: () => this.executionRefusal(),
625
- instanceId: () => this.managerInstanceId,
626
- endpoint: () => this.ep,
627
- beginLifecycle: () => this.beginLifecycle(),
628
- freeSlot: (agent, floor, cause) => this.freeSlot(agent, floor, cause),
629
- reapChildrenOf: (principal) => this.reapChildrenOf(principal),
630
- managedPrincipal: (agent) => this.managedPrincipal(agent),
631
- inlineSnapshotChange: (agent) => this.inlineSnapshotChange(agent),
632
- agentFor: (name) => this.agents.get(name),
633
- maintenanceState: () => this.maintenanceState,
634
- resolveConnector: (name) => this.resolveConnector(name),
635
- runtimeFor: (kind) => this.runtimeFor(kind),
636
- reserveCustody: (runtime) => this.reserveCustody(runtime),
637
- recordSlotCustody: (agent, reference) => this.recordSlotCustody(agent, reference),
638
- spawnCustodied: (runtime, name, spec, cwd, reserved) => this.spawnCustodied(runtime, name, spec, cwd, reserved),
639
- awaitReadiness: (agent, timeoutMs, opts) => this.awaitReadiness(agent, timeoutMs, opts),
640
- readinessTimeoutMs: () => this.readinessTimeoutMs,
641
- recordSlotRuntime: (agent) => this.recordSlotRuntime(agent),
642
- refreshSeatRecord: (agent) => this.refreshSeatRecord(agent),
643
- watchExit: (agent) => this.watchExit(agent),
644
- tail: (session) => this.tail(session),
645
- stopHandle: (agent, graceful, cause) => this.stopHandle(agent, graceful, cause),
646
- trackStoppedHandle: (agent, floor, cause) => this.trackStoppedHandle(agent, floor, cause),
647
- });
385
+ /** {@link BrokerTransport.dial}. */
386
+ dial(...args) { return this.brokerTransportComponent.dial(...args); }
387
+ /** {@link BrokerTransport.dialRemoteStanding}. */
388
+ dialRemoteStanding(...args) { return this.brokerTransportComponent.dialRemoteStanding(...args); }
389
+ seatCustody = new SeatCustody(seatCustodyDeps(this));
390
+ sessionRecovery = new SessionRecovery(sessionRecoveryDeps(this));
648
391
  get staticReconcileLastSweepResources() { return this.staticLifecycle.resources(); }
649
392
  set staticReconcileLastSweepResources(value) { this.staticLifecycle.setResources(value); }
650
- staticLifecycle = new ManagedStaticLifecycle({
651
- space: () => this.space,
652
- servers: () => this.servers,
653
- auth: () => this.auth,
654
- secrets: () => this.secrets,
655
- workspaceRoot: () => this.workspaceRoot,
656
- instanceId: () => this.managerInstanceId,
657
- processUid: () => this.managerLifecycleUid,
658
- userMode: () => this.userMode,
659
- eventPayloadsWithheld: () => this.eventPayloadsWithheld,
660
- evictor: () => this.staticLifecycleEvict,
661
- retryDelays: () => this.staticReconcileRetryDelaysMs,
662
- resumeRequired: () => this.resumeRequired,
663
- records: () => this.goalWriter?.ctx.kv,
664
- agentFor: (name) => this.agents.get(name),
665
- retirementFor: (name) => this.retirement.held(name),
666
- recordStaticRetirement: (a) => this.retirement.recordStaticRetirement(a),
667
- noteRetiredPrincipal: (principal) => { this.retirement.rememberRetired(principal); },
668
- foreignEventChannels: (channels, owner, actor) => foreignEventChannels(channels, owner, actor),
669
- withIssuer: (fn) => this.withIssuer(fn),
670
- deprovisionBroker: (a) => this.deprovisionBroker(a),
671
- reapOrphanSeat: (a) => this.reapOrphanSeat(a),
672
- withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
673
- readerRemedy: (owner, channel) => this.readerRemedy(owner, channel),
674
- withProvisioner: (fn) => this.withProvisioner(fn),
675
- beginLifecycle: (resumeOperation) => this.beginLifecycle(resumeOperation),
676
- maintenanceError: () => this.maintenanceError(),
677
- withRetirementSlot: (run) => this.withRetirementSlot(run),
678
- managedStaticInstanceReads: (capabilities) => this.managedStaticInstanceReads(capabilities),
679
- issuanceSeam: (i, mode, a, exp) => this.issuanceSeam(i, mode, a, exp),
680
- refreshSeatRecord: (a) => this.refreshSeatRecord(a),
681
- dial: (opts) => this.dial(opts),
682
- seatRecordFor: (row) => this.seatRecordFor(row),
683
- restartSupervisedSeat: (row, record) => this.restartSupervisedSeat(row, record),
684
- adoptSeat: (row, record) => this.adoptSeat(row, record),
685
- dropSeatRecord: (a) => this.dropSeatRecord(a),
686
- });
393
+ staticLifecycle = new ManagedStaticLifecycle(managedStaticLifecycleDeps(this));
687
394
  /** User-mode provisioning owns no manager state: each dependency reads through at its use. */
688
- userProvision = new UserProvision({
689
- space: () => this.space,
690
- workspaceRoot: () => this.workspaceRoot,
691
- secrets: () => this.secrets,
692
- managerInstanceId: () => this.managerInstanceId,
693
- runHosting: () => this.runHosting,
694
- remoteAuthority: () => this.remoteAuthority,
695
- deprovision: (target) => this.deprovision(target),
696
- withProvisioner: (fn) => this.withProvisioner(fn),
697
- shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
698
- bearerEntryArgv,
699
- });
395
+ userProvision = new UserProvision(userProvisionDeps(this));
700
396
  /** Seat stop, exit, recursive reap and named despawn. Every dependency reads through at its use. */
701
- seatStopComponent = new SeatStop({
702
- agentGoals: () => this.agentGoals,
703
- agents: () => this.agents,
704
- auth: () => this.auth,
705
- ep: () => this.ep,
706
- execution: () => this.execution,
707
- goalWriter: () => this.goalWriter,
708
- lifecycleInFlight: () => this.lifecycleInFlight,
709
- setLifecycleInFlight: (value) => { this.lifecycleInFlight = value; },
710
- maintenanceState: () => this.maintenanceState,
711
- managerInstanceId: () => this.managerInstanceId,
712
- remoteAuthority: () => this.remoteAuthority,
713
- retirement: () => this.retirement,
714
- servers: () => this.servers,
715
- serviceServe: () => this.serviceServe,
716
- space: () => this.space,
717
- unverifiedStops: () => this.unverifiedStops,
718
- setUnverifiedStops: (value) => { this.unverifiedStops = value; },
719
- workspaceRoot: () => this.workspaceRoot,
720
- assertGoalWriterEpochCurrent: (...args) => this.assertGoalWriterEpochCurrent(...args),
721
- authorizeNamed: (...args) => this.authorizeNamed(...args),
722
- awaitHandleExit: (...args) => this.awaitHandleExit(...args),
723
- beginLifecycle: (...args) => this.beginLifecycle(...args),
724
- confirmRetirement: (...args) => this.confirmRetirement(...args),
725
- emitGoalProgress: (...args) => this.emitGoalProgress(...args),
726
- executionRefusal: (...args) => this.executionRefusal(...args),
727
- expireGoalAcceptance: (...args) => this.expireGoalAcceptance(...args),
728
- freeSlot: (...args) => this.freeSlot(...args),
729
- maintenanceError: (...args) => this.maintenanceError(...args),
730
- managedPrincipal: (...args) => this.managedPrincipal(...args),
731
- readManagedSessionState: (...args) => this.readManagedSessionState(...args),
732
- recoverManagedSession: (...args) => this.recoverManagedSession(...args),
733
- releaseLifecycle: (...args) => this.releaseLifecycle(...args),
734
- shredUserSecrets: (...args) => this.shredUserSecrets(...args),
735
- trackDeprovision: (...args) => this.trackDeprovision(...args),
736
- });
397
+ seatStopComponent = new SeatStop(seatStopDeps(this));
737
398
  /** The typed command table and its admission. Every dependency reads through at its use. */
738
- commandDispatch = new CommandDispatch({
739
- agents: () => this.agents,
740
- auth: () => this.auth,
741
- execution: () => this.execution,
742
- goalWriter: () => this.goalWriter,
743
- managerInstanceId: () => this.managerInstanceId,
744
- participants: () => this.participants,
745
- remoteAuthority: () => this.remoteAuthority,
746
- resumeRequired: () => this.resumeRequired,
747
- runHosting: () => this.runHosting,
748
- space: () => this.space,
749
- transcripts: () => this.transcripts,
750
- userMode: () => this.userMode,
751
- workspaceRoot: () => this.workspaceRoot,
752
- attachAuthorized: (...args) => this.attachAuthorized(...args),
753
- authorizeNamed: (...args) => this.authorizeNamed(...args),
754
- authorizeRunAmend: (...args) => this.authorizeRunAmend(...args),
755
- authorizeRunAnswer: (...args) => this.authorizeRunAnswer(...args),
756
- beginLifecycle: (...args) => this.beginLifecycle(...args),
757
- despawnAuthorized: (...args) => this.despawnAuthorized(...args),
758
- executionRefusal: (...args) => this.executionRefusal(...args),
759
- findManagedByTarget: (...args) => this.findManagedByTarget(...args),
760
- inputAuthorized: (...args) => this.inputAuthorized(...args),
761
- lifecycleMembershipRefusal: (...args) => this.lifecycleMembershipRefusal(...args),
762
- list: (...args) => this.list(...args),
763
- listSpawnDirectory: (...args) => this.listSpawnDirectory(...args),
764
- loggedSpawnRefusal: (ctx, fn) => this.loggedSpawnRefusal(ctx, fn),
765
- maintenanceError: (...args) => this.maintenanceError(...args),
766
- managedPrincipal: (...args) => this.managedPrincipal(...args),
767
- managerStatusData: (...args) => this.managerStatusData(...args),
768
- opCommitResume: (...args) => this.opCommitResume(...args),
769
- opDefinePersona: (...args) => this.opDefinePersona(...args),
770
- opFinalizeResume: (...args) => this.opFinalizeResume(...args),
771
- opLaunch: (...args) => this.opLaunch(...args),
772
- opListPersonas: (...args) => this.opListPersonas(...args),
773
- opModels: (...args) => this.opModels(...args),
774
- opPreservationCtl: (...args) => this.opPreservationCtl(...args),
775
- opPurge: (...args) => this.opPurge(...args),
776
- opRemovePersona: (...args) => this.opRemovePersona(...args),
777
- opResumePreserved: (...args) => this.opResumePreserved(...args),
778
- opShowPersona: (...args) => this.opShowPersona(...args),
779
- opStart: (...args) => this.opStart(...args),
780
- openStaticChatSession: (...args) => this.openStaticChatSession(...args),
781
- psOwnerFilter: (...args) => this.psOwnerFilter(...args),
782
- resolveSpawnCwd: (...args) => this.resolveSpawnCwd(...args),
783
- retireStaticChatSession: (...args) => this.retireStaticChatSession(...args),
784
- runAnswerer: (...args) => this.runAnswerer(...args),
785
- runHost: (...args) => this.runHost(...args),
786
- serveGated: (ctx, fn) => this.serveGated(ctx, fn),
787
- serveObservation: (ctx, fn) => this.serveObservation(ctx, fn),
788
- serveSpawnGoal: (...args) => this.serveSpawnGoal(...args),
789
- serveTurnCancel: (...args) => this.serveTurnCancel(...args),
790
- serveTurnGoal: (...args) => this.serveTurnGoal(...args),
791
- serveTurnParticipation: (...args) => this.serveTurnParticipation(...args),
792
- serveTurnUnconfirmed: (...args) => this.serveTurnUnconfirmed(...args),
793
- serveTurnYield: (...args) => this.serveTurnYield(...args),
794
- spawnPersona: (...args) => this.spawnPersona(...args),
795
- stopHandle: (...args) => this.stopHandle(...args),
796
- stopWindowsSeat: (...args) => this.stopWindowsSeat(...args),
797
- trackStoppedHandle: (...args) => this.trackStoppedHandle(...args),
798
- turnPendingFor: (...args) => this.turnPendingFor(...args),
799
- turnTarget: (...args) => this.turnTarget(...args),
800
- });
399
+ commandDispatch = new CommandDispatch(commandDispatchDeps(this));
801
400
  /** The spawn and launch goal path. Every dependency reads through at its use. */
802
- spawnGoalComponent = new SpawnGoal({
803
- agentGoals: () => this.agentGoals,
804
- execution: () => this.execution,
805
- goalAcceptanceRetentionMs: () => this.goalAcceptanceRetentionMs,
806
- goalAcceptances: () => this.goalAcceptances,
807
- goalReconcileDone: () => this.goalReconcileDone,
808
- goalWriter: () => this.goalWriter,
809
- managerInstanceId: () => this.managerInstanceId,
810
- onceWatched: () => this.onceWatched,
811
- readinessTimeoutMs: () => this.readinessTimeoutMs,
812
- serviceServe: () => this.serviceServe,
813
- userMode: () => this.userMode,
814
- acceptOnceTurn: (...args) => this.acceptOnceTurn(...args),
815
- assertGoalWriterEpochCurrent: (...args) => this.assertGoalWriterEpochCurrent(...args),
816
- commitOnceCancel: (...args) => this.commitOnceCancel(...args),
817
- emitGoalProgress: (...args) => this.emitGoalProgress(...args),
818
- executionRefusal: (...args) => this.executionRefusal(...args),
819
- settleOnceTurn: (...args) => this.settleOnceTurn(...args),
820
- });
401
+ spawnGoalComponent = new SpawnGoal(spawnGoalDeps(this));
821
402
  /** The persona catalog doors. Every dependency reads through at its use. */
822
- personaCatalogComponent = new PersonaCatalog({
823
- agents: () => this.agents,
824
- execution: () => this.execution,
825
- meshMode: () => this.meshMode,
826
- remoteAuthority: () => this.remoteAuthority,
827
- space: () => this.space,
828
- userMode: () => this.userMode,
829
- workspaceRoot: () => this.workspaceRoot,
830
- executionRefusal: (...args) => this.executionRefusal(...args),
831
- managedPrincipal: (...args) => this.managedPrincipal(...args),
832
- nameError: (...args) => this.nameError(...args),
833
- spawnBoundRefusal: (...args) => this.spawnBoundRefusal(...args),
834
- spawnRun: (...args) => this.spawnRun(...args),
835
- staticSpawnBound: (...args) => this.staticSpawnBound(...args),
836
- });
403
+ personaCatalogComponent = new PersonaCatalog(personaCatalogDeps(this));
837
404
  /** Seat terminal input and attach sessions. Every dependency reads through at its use. */
838
- terminalInputComponent = new TerminalInput({
839
- agents: () => this.agents,
840
- auth: () => this.auth,
841
- managerLifecycleUid: () => this.managerLifecycleUid,
842
- sessionPlane: () => this.sessionPlane,
843
- wsPort: () => this.wsPort,
844
- runtimeFor: (...args) => this.runtimeFor(...args),
845
- });
405
+ terminalInputComponent = new TerminalInput(terminalInputDeps(this));
406
+ /** Status, seat list and model catalog reads. Every dependency reads through at its use. */
407
+ statusAndModelsComponent = new StatusAndModels(statusAndModelsDeps(this));
408
+ /** The launch readiness race and exit watch. Every dependency reads through at its use. */
409
+ readinessWaitComponent = new ReadinessWait(readinessWaitDeps(this));
410
+ /** Broker dials and scoped executor connections. Every dependency reads through at its use. */
411
+ brokerTransportComponent = new BrokerTransport(brokerTransportDeps(this));
412
+ /** The start and launch control doors. Every dependency reads through at its use. */
413
+ startDoorsComponent = new StartDoors(startDoorsDeps(this));
414
+ /** Connector and harness resolution for a launch. Every dependency reads through at its use. */
415
+ harnessResolutionComponent = new HarnessResolution(harnessResolutionDeps(this));
416
+ /** The boot connector inventory. Every dependency reads through at its use. */
417
+ connectorInventoryComponent = new ConnectorInventory(connectorInventoryDeps(this));
418
+ /** Manager preservation and released-seat adoption. Every dependency reads through at its use. */
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));
846
422
  /** The goal-writer connection and the goal index it reconciles. Every dependency reads through at its use. */
847
- goalWriterComponent = new GoalWriter({
848
- auth: () => this.auth,
849
- goalAcceptances: () => this.goalAcceptances,
850
- goalWriter: () => this.goalWriter,
851
- setGoalWriter: (value) => { this.goalWriter = value; },
852
- goalWriterCreds: () => this.goalWriterCreds,
853
- setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
854
- goalWriterIdentity: () => this.goalWriterIdentity,
855
- leaseStopping: () => this.leaseStopping,
856
- managerInstanceId: () => this.managerInstanceId,
857
- readinessTimeoutMs: () => this.readinessTimeoutMs,
858
- remoteAuthority: () => this.remoteAuthority,
859
- serviceServe: () => this.serviceServe,
860
- space: () => this.space,
861
- turnRelay: () => this.turnRelay,
862
- goalReconcileDone: () => this.goalReconcileDone,
863
- setGoalReconcileDone: (value) => { this.goalReconcileDone = value; },
864
- adoptTurnGoal: (...args) => this.adoptTurnGoal(...args),
865
- boundedReconnect: (...args) => this.boundedReconnect(...args),
866
- dial: (...args) => this.dial(...args),
867
- noticeSeatTurns: (...args) => this.noticeSeatTurns(...args),
868
- renewRemoteBeforeRedial: (...args) => this.renewRemoteBeforeRedial(...args),
869
- retireConnection: (...args) => this.retireConnection(...args),
870
- trackTransport: (...args) => this.trackTransport(...args),
871
- withEndpointServeExecutor: (fn) => this.withEndpointServeExecutor(fn),
872
- });
423
+ goalWriterComponent = new GoalWriter(goalWriterDeps(this));
873
424
  /** Renewal of the manager's standing credentials. Every dependency reads through at its use. */
874
- credentialRenewal = new CredentialRenewal({
875
- agents: () => this.agents,
876
- auth: () => this.auth,
877
- credentialPushRetry: () => this.credentialPushRetry,
878
- setCredentialPushRetry: (value) => { this.credentialPushRetry = value; },
879
- credentialPushes: () => this.credentialPushes,
880
- daemonRenewalEligible: () => this.daemonRenewalEligible,
881
- setDaemonRenewalEligible: (value) => { this.daemonRenewalEligible = value; },
882
- daemonRenewalOwner: () => this.daemonRenewalOwner,
883
- setDaemonRenewalOwner: (value) => { this.daemonRenewalOwner = value; },
884
- endpointServeRenewalTimer: () => this.endpointServeRenewalTimer,
885
- setEndpointServeRenewalTimer: (value) => { this.endpointServeRenewalTimer = value; },
886
- ep: () => this.ep,
887
- finishRemoteBundleAdoption: () => this.finishRemoteBundleAdoption,
888
- setFinishRemoteBundleAdoption: (value) => { this.finishRemoteBundleAdoption = value; },
889
- goalWriter: () => this.goalWriter,
890
- goalWriterCreds: () => this.goalWriterCreds,
891
- setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
892
- leaseStopping: () => this.leaseStopping,
893
- managerInstanceId: () => this.managerInstanceId,
894
- pendingCredentialPushes: () => this.pendingCredentialPushes,
895
- remoteAuthority: () => this.remoteAuthority,
896
- remoteBundleAdoption: () => this.remoteBundleAdoption,
897
- setRemoteBundleAdoption: (value) => { this.remoteBundleAdoption = value; },
898
- remoteBundleRenewal: () => this.remoteBundleRenewal,
899
- setRemoteBundleRenewal: (value) => { this.remoteBundleRenewal = value; },
900
- remoteExecutorCreds: () => this.remoteExecutorCreds,
901
- setRemoteExecutorCreds: (value) => { this.remoteExecutorCreds = value; },
902
- remoteRenewalDebt: () => this.remoteRenewalDebt,
903
- setRemoteRenewalDebt: (value) => { this.remoteRenewalDebt = value; },
904
- remoteSupervisorCreds: () => this.remoteSupervisorCreds,
905
- setRemoteSupervisorCreds: (value) => { this.remoteSupervisorCreds = value; },
906
- runHosting: () => this.runHosting,
907
- secretStoreIdentity: () => this.secretStoreIdentity,
908
- setSecretStoreIdentity: (value) => { this.secretStoreIdentity = value; },
909
- secrets: () => this.secrets,
910
- serviceServe: () => this.serviceServe,
911
- sessionLedgerConn: () => this.sessionLedgerConn,
912
- sessionLedgerCreds: () => this.sessionLedgerCreds,
913
- setSessionLedgerCreds: (value) => { this.sessionLedgerCreds = value; },
914
- space: () => this.space,
915
- supervisorCredentialPush: () => this.supervisorCredentialPush,
916
- setSupervisorCredentialPush: (value) => { this.supervisorCredentialPush = value; },
917
- supervisorCredentialPushPending: () => this.supervisorCredentialPushPending,
918
- setSupervisorCredentialPushPending: (value) => { this.supervisorCredentialPushPending = value; },
919
- userMode: () => this.userMode,
920
- workspaceRoot: () => this.workspaceRoot,
921
- beginLifecycle: (...args) => this.beginLifecycle(...args),
922
- dialRemoteStanding: (...args) => this.dialRemoteStanding(...args),
923
- dialServeConnection: (...args) => this.dialServeConnection(...args),
924
- discardServeCandidate: (...args) => this.discardServeCandidate(...args),
925
- mintAndStageGoalWriter: (...args) => this.mintAndStageGoalWriter(...args),
926
- mintAndStageSessionLedger: (...args) => this.mintAndStageSessionLedger(...args),
927
- probeStaticCredential: (...args) => this.probeStaticCredential(...args),
928
- renewManagedStaticCred: (...args) => this.renewManagedStaticCred(...args),
929
- withEndpointServeExecutor: (fn) => this.withEndpointServeExecutor(fn),
930
- renewRemoteStandingBundle: (...args) => this.renewRemoteStandingBundle(...args),
931
- });
425
+ credentialRenewal = new CredentialRenewal(credentialRenewalDeps(this));
932
426
  /** The launch pipeline's leaf steps. Every dependency reads through at its use. */
933
- seatLaunch = new SeatLaunch({
934
- space: () => this.space,
935
- servers: () => this.servers,
936
- workspaceRoot: () => this.workspaceRoot,
937
- installedExtensions: () => this.installedExtensions,
938
- ep: () => this.ep,
939
- auth: () => this.auth,
940
- userMode: () => this.userMode,
941
- managerInstanceId: () => this.managerInstanceId,
942
- serviceServe: () => this.serviceServe,
943
- runHosting: () => this.runHosting,
944
- connectorStatuses: () => this.connectorStatuses,
945
- execution: () => this.execution,
946
- requiredRuntime: () => this.requiredRuntime,
947
- meshMode: () => this.meshMode,
948
- executionRefusal: () => this.executionRefusal(),
949
- nameError: (name) => this.nameError(name),
950
- canReadPersona: (owner, caller, admin) => this.canReadPersona(owner, caller, admin),
951
- epAdminReach: (caller) => this.epAdminReach(caller),
952
- startAgent: (opts) => this.startAgent(opts),
953
- awaitReadiness: (...args) => this.awaitReadiness(...args),
954
- awaitStartupOutcome: (...args) => this.awaitStartupOutcome(...args),
955
- capabilityRefusal: (...args) => this.capabilityRefusal(...args),
956
- delegatedLaunched: () => this.delegatedLaunched,
957
- dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
958
- endOnceBeforeServe: (...args) => this.endOnceBeforeServe(...args),
959
- eventPayloadsWithheld: () => this.eventPayloadsWithheld,
960
- eventsRefusal: (...args) => this.eventsRefusal(...args),
961
- eventsRequired: () => this.eventsRequired,
962
- fileDigest: (...args) => this.fileDigest(...args),
963
- hostLaunchFields: (...args) => this.hostLaunchFields(...args),
964
- issuanceSeam: (...args) => this.issuanceSeam(...args),
965
- launchHarness: (...args) => this.launchHarness(...args),
966
- launchOwner: (...args) => this.launchOwner(...args),
967
- leaseStopping: () => this.leaseStopping,
968
- loadSeatRuntime: (...args) => this.loadSeatRuntime(...args),
969
- managerLifecycleUid: () => this.managerLifecycleUid,
970
- namesCapacity: () => this.namesCapacity,
971
- openOnceDelivery: (...args) => this.openOnceDelivery(...args),
972
- personaOwner: (...args) => this.personaOwner(...args),
973
- place: (...args) => this.place(...args),
974
- provisionUserAgent: (...args) => this.provisionUserAgent(...args),
975
- readerRemedy: (...args) => this.readerRemedy(...args),
976
- readinessTimeoutMs: () => this.readinessTimeoutMs,
977
- refreshUnavailableConnectors: (...args) => this.refreshUnavailableConnectors(...args),
978
- remoteAuthority: () => this.remoteAuthority,
979
- resolveConnector: (...args) => this.resolveConnector(...args),
980
- retirement: () => this.retirement,
981
- runtimeFor: (...args) => this.runtimeFor(...args),
982
- seatCapRefusal: (...args) => this.seatCapRefusal(...args),
983
- seatCustody: () => this.seatCustody,
984
- secrets: () => this.secrets,
985
- sessionRecovery: () => this.sessionRecovery,
986
- shredUserSecrets: (...args) => this.shredUserSecrets(...args),
987
- staticLifecycle: () => this.staticLifecycle,
988
- stopAndTrack: (...args) => this.stopAndTrack(...args),
989
- trackDeprovision: (...args) => this.trackDeprovision(...args),
990
- transcripts: () => this.transcripts,
991
- userProvision: () => this.userProvision,
992
- watchExit: (...args) => this.watchExit(...args),
993
- watchOnceExit: (...args) => this.watchOnceExit(...args),
994
- withIssuer: (fn) => this.withIssuer(fn),
995
- withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
996
- withProvisioner: (fn) => this.withProvisioner(fn),
997
- });
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));
998
430
  constructor(opts) {
999
431
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
1000
432
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -1235,28 +667,6 @@ export class Manager {
1235
667
  return "static";
1236
668
  return "open";
1237
669
  }
1238
- /** The CHAT stream frontier at a preservation cut (issue #545), read through whichever local
1239
- * authority this mesh mode holds: open mode's own endpoint already has `$JS.API.STREAM.INFO`
1240
- * on the CHAT stream. Local and remote supervisor credentials also hold this metadata grant
1241
- * for transcript startup checks, but this preservation path retains its existing local-authority
1242
- * boundary. Static/user modes borrow the ephemeral `provisioner` profile the manager already
1243
- * mints per spawn. A remote-authority manager (`this.auth`
1244
- * undefined in static/user mode) has no local space authority to mint that provisioner with, so
1245
- * it prints one line and returns no floor — the inventory then carries none and resumed seats
1246
- * behave exactly as before this fix, not a silent partial degrade. */
1247
- async chatFrontierForPreservation() {
1248
- switch (this.meshMode) {
1249
- case "open":
1250
- return this.ep.chatFrontier();
1251
- case "static":
1252
- case "user":
1253
- if (!this.auth) {
1254
- console.error("! preservation: this manager holds no local space authority to read the chat frontier; retained seats replay their channel windows on resume");
1255
- return undefined;
1256
- }
1257
- return this.withProvisioner((prov) => prov.chatFrontier());
1258
- }
1259
- }
1260
670
  readerRemedy(owner, channel) {
1261
671
  switch (this.meshMode) {
1262
672
  case "user":
@@ -1292,422 +702,10 @@ export class Manager {
1292
702
  executionRecordPath(instanceId) {
1293
703
  return join(this.workspaceRoot, ".cotal", `manager-execution.${spaceKey(this.space)}.${instanceId}.json`);
1294
704
  }
1295
- claimExecutionRecord(instanceId) {
1296
- const record = claimIdentityRecord(this.executionRecordPath(instanceId), "manager execution capability", (raw) => {
1297
- if (!raw || typeof raw !== "object" || Array.isArray(raw))
1298
- return undefined;
1299
- const r = raw;
1300
- return Object.keys(r).sort().join(",") === "execution,instanceId,space,v" && r.v === 1 && r.space === this.space &&
1301
- r.instanceId === instanceId && (r.execution === "none" || r.execution === "runtime") ? r : undefined;
1302
- }, () => ({ v: 1, space: this.space, instanceId, execution: this.execution }));
1303
- if (record.execution !== this.execution)
1304
- throw new Error("manager execution capability differs from its retained instance record; execution cannot change across restart");
1305
- }
1306
- async admitExecutionState() {
1307
- if (!this.remoteAuthority) {
1308
- let local = this.admittedLocalIdentity;
1309
- this.admittedLocalIdentity = undefined;
1310
- if (this.execution === "none") {
1311
- const recorded = loadMeshes().find((m) => m.space === this.space);
1312
- const auth = hasUserAuthState(this.workspaceRoot, this.space) && recorded?.mode === "user"
1313
- ? await getSpaceAuth(this.secrets, this.space) : undefined;
1314
- if (!auth)
1315
- throw new Error("execution: none requires a genuine hosting user-auth root and its user-mode mesh record");
1316
- if (!local)
1317
- local = loadManagerInstanceIdentity(this.workspaceRoot, this.space);
1318
- if (local && !existsSync(this.executionRecordPath(local.instanceId)))
1319
- throw new Error("execution: none refuses an existing unclassified manager instance; keep its runtime and retained state, or register a fresh control instance");
1320
- if (!local) {
1321
- const proposed = { instanceId: mintLifecycleUid(), serveIdentity: newIdentity() };
1322
- local = createManagerInstanceIdentity(this.workspaceRoot, this.space, () => proposed);
1323
- if (local.instanceId !== proposed.instanceId)
1324
- throw new Error("execution: none refuses a concurrently claimed unclassified manager identity");
1325
- }
1326
- const localInstanceId = local.instanceId;
1327
- this.claimExecutionRecord(localInstanceId);
1328
- const nc = await this.dial({ ...standaloneConnectOpts({ creds: await mintCreds(auth, newIdentity(), "provisioner"), tls: false }), maxReconnectAttempts: 0 });
1329
- try {
1330
- const kvm = new Kvm(nc);
1331
- await ensureAuthorityStores(await jetstreamManager(nc), kvm, this.space);
1332
- const entries = await listGoalIndex(await kvm.open(recordsBucket(this.space)), MANAGER_ENDPOINT);
1333
- if (entries.some((entry) => entry.iid === localInstanceId && (entry.allocated !== undefined || entry.note !== undefined)))
1334
- throw new Error("execution: none refuses retained seat or turn inventory before recovery; keep the execution-owning Manager");
1335
- }
1336
- finally {
1337
- await drainAndClose(nc);
1338
- }
1339
- this.admittedLocalIdentity = local;
1340
- }
1341
- else {
1342
- local ??= createManagerInstanceIdentity(this.workspaceRoot, this.space, () => ({ instanceId: mintLifecycleUid(), serveIdentity: newIdentity() }));
1343
- this.claimExecutionRecord(local.instanceId);
1344
- this.admittedLocalIdentity = local;
1345
- }
1346
- return;
1347
- }
1348
- if (this.remoteAuthority) {
1349
- if (this.execution === "none" && (await localTrustOfSpace(this.secrets, this.space)).present)
1350
- throw new Error("remote manager-service authority cannot be combined with local space signing trust - choose one authority path, never a fallback");
1351
- // Execution is fixed for a registered instance. An older instance with no capability
1352
- // record might own retained seats/runs, so it cannot be converted to none by omission.
1353
- const remote = this.remoteAuthority;
1354
- const path = this.executionRecordPath(remote.instanceId);
1355
- if (this.execution === "none" && !existsSync(path) && remote.serveGrant.epoch !== 0)
1356
- throw new Error("execution: none refuses an existing unclassified manager instance; keep its runtime and retained state, or register a fresh control instance");
1357
- if (this.execution === "none") {
1358
- const entries = await remote.scanGoalIndex();
1359
- if (entries.some((entry) => entry.iid === remote.instanceId && (entry.allocated !== undefined || entry.note !== undefined)))
1360
- throw new Error("execution: none refuses retained seat or turn inventory before recovery; keep the execution-owning Manager");
1361
- }
1362
- if (this.execution === "none" || existsSync(path))
1363
- this.claimExecutionRecord(remote.instanceId);
1364
- }
1365
- }
1366
- async runStart() {
1367
- await this.admitExecutionState();
1368
- this.staticLifecycle.start();
1369
- await this.inspectConnectorsAtBoot();
1370
- await this.attach.start();
1371
- // In auth mode the manager is just another user in the space's account — it mints
1372
- // itself creds from the same signing key it uses for the agents it spawns. The signer comes
1373
- // through the SecretStore seam (`this.secrets` — the injected `ManagerOptions.secretStore`, or
1374
- // the local `.cotal/auth/auth.json` FS default), so a HOSTED composition mints from its KMS/Vault
1375
- // and no signing seed is ever read from the hosted disk. `this.space` cross-checks the bundle.
1376
- //
1377
- // REMOTE AUTHORITY (#1944): a manager holding host-issued remote authority mints nothing from a
1378
- // local signer, so it never composes or validates local trust. It asks ONE question of the
1379
- // store — does THIS space's own local signing trust exist (`localTrustOfSpace`) — because that
1380
- // alone is the conflict of authorities a supervisor refuses. The stock behaviour this replaces
1381
- // read the whole root's trust chain (`getSpaceAuth`): with no records for this space it fell
1382
- // back to the legacy monolith of an UNRELATED static tenant and reported that bundle as
1383
- // "corrupt or mislabeled". Other tenants' records — split (their account + the shared
1384
- // per-root broker record) or monolith — are not this space's trust and never refuse; an
1385
- // unreadable record on a key that is read refuses loud with the store's own parse message.
1386
- //
1387
- // An OPEN mesh mints nothing, also in a root that still holds a static stack's accounts. A
1388
- // credential minted there joins this instance's family in the open account, and the next open
1389
- // boot could re-register only by verify-evicting it through a delivery daemon that an open mesh
1390
- // does not run.
1391
- const recorded = loadMeshes().find((m) => m.space === this.space);
1392
- if (this.remoteAuthority) {
1393
- if ((await localTrustOfSpace(this.secrets, this.space)).present)
1394
- throw new Error("remote manager-service authority cannot be combined with local space signing trust - choose one authority path, never a fallback");
1395
- this.auth = undefined;
1396
- }
1397
- else {
1398
- this.auth = recorded?.mode === "open" ? undefined : await getSpaceAuth(this.secrets, this.space);
1399
- }
1400
- // USER-MODE detection is FAIL-CLOSED on the on-disk marker (the space-scoped state dir), never
1401
- // on the mutable mesh registry alone — registry drift/tamper must not let a user-auth space
1402
- // take the static self-mint branch. A marker/registry disagreement is a refused start with the
1403
- // repair, not a guess.
1404
- this.userMode = this.remoteAuthority !== undefined || hasUserAuthState(this.workspaceRoot, this.space);
1405
- if (!this.remoteAuthority && recorded && (recorded.mode === "user") !== this.userMode)
1406
- 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`);
1407
- if (!this.remoteAuthority && this.userMode && !recorded)
1408
- 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)}`);
1409
- if (!this.remoteAuthority && this.userMode && !this.auth)
1410
- 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`);
1411
- // SPEC 13.6 item 7: the LOGICAL instance id + serve identity PERSIST across restart
1412
- // (a space-scoped manager identity file under .cotal). A restart re-registers the SAME id with an
1413
- // ADVANCED epoch (the successor fences the predecessor); a fresh mint over a malformed file is
1414
- // refused loud (no-fallbacks - a restart never silently becomes a fresh instance). A second
1415
- // manager in a DIFFERENT workspace root is a DIFFERENT logical id by construction (its own state
1416
- // dir) - two managers in ONE space are two workspace roots.
1417
- //
1418
- // First mint on a fresh root is exclusive create (#1263). Two processes that both observe no
1419
- // file must not keep different in-memory ids: of N concurrent starts exactly one publishes the
1420
- // file by hard link and the others adopt that identity before taking a lease, or refuse with
1421
- // identity-record-create-lost. A filesystem without hard links refuses the first start with
1422
- // atomic-publish-unsupported. Atomic rename is not enough, because the loser
1423
- // of a replace would still serve under the id it minted.
1424
- {
1425
- if (this.remoteAuthority) {
1426
- this.managerInstanceId = this.remoteAuthority.instanceId;
1427
- this.managerServeIdentity = this.remoteAuthority.identities.serve;
1428
- }
1429
- else {
1430
- // Admission already resolved this identity, including the first mint. A second claim here
1431
- // would stat the same record again.
1432
- const claimed = this.admittedLocalIdentity;
1433
- if (!claimed)
1434
- throw new Error("manager start has no admitted local identity");
1435
- this.admittedLocalIdentity = undefined;
1436
- this.managerInstanceId = claimed.instanceId;
1437
- this.managerServeIdentity = claimed.serveIdentity;
1438
- }
1439
- }
1440
- await this.onServiceIdentity?.(this.serviceIdentityObservation());
1441
- let creds;
1442
- let id;
1443
- if (this.remoteAuthority) {
1444
- const remote = this.remoteAuthority;
1445
- id = remote.identities.supervisor.id;
1446
- creds = async () => this.remoteSupervisorCreds;
1447
- }
1448
- else if (this.auth) {
1449
- const identity = newIdentity();
1450
- const auth = this.auth;
1451
- id = identity.id;
1452
- // The long-lived SUPERVISOR cred (closure (ii), residual 2): serve the three control tiers, hold the
1453
- // singleton lease (open-only), publish + watch presence — and nothing else. Provisioning runs on an
1454
- // EPHEMERAL provisioner connection per spawn (withProvisioner); destructive purge mints a PURGER per
1455
- // call. So the always-on daemon holds no DM/DLV read, no consumer-create, no stream-admin tamper.
1456
- //
1457
- // STANDING RENEWAL (class 1): the manager holds the DATA signing seed, so it is its
1458
- // own renewal owner — the cred rides the endpoint's SOURCE seam and self-remints (same identity,
1459
- // pinned by the endpoint) ahead of each bounded supervisor JWT's expiry. A copied supervisor
1460
- // cred is broker-dead within the matrix TTL.
1461
- creds = () => mintCreds(auth, identity, "supervisor");
1462
- }
1463
- this.ep = new CotalEndpoint({
1464
- space: this.space,
1465
- servers: this.servers,
1466
- channels: [],
1467
- creds,
1468
- // The supervisor registers on the roster, and an authed presence-registering endpoint is
1469
- // lifecycle-keyed (SPEC 13.1, fail-before-presence). The manager process is the top of its
1470
- // own launch chain (the operator command IS its launcher): its incarnation uid is the
1471
- // per-process `managerLifecycleUid` field (also the `managerInstance` audit coordinate on
1472
- // every static activation).
1473
- lifecycleUid: this.remoteAuthority?.lifecycleUid ?? this.managerLifecycleUid,
1474
- // The supervisor serves control + watches presence; it never consumes chat/dm/task
1475
- // (no message handler). consume:false avoids binding consumers it doesn't use — and
1476
- // under auth avoids trying to bind its own DM/task durables that nothing pre-created.
1477
- // It still pre-creates OTHERS' durables via provisionDmInbox/provisionTaskQueue (lazy jsm).
1478
- consume: false,
1479
- // It also never reads the channel registry (it provisions + serves control, no channel
1480
- // pull/display), so skip the channel-registry watch — the supervisor cred (residual 2) then
1481
- // holds no channel-KV read grant. Presence (the roster) is still watched.
1482
- watchChannels: false,
1483
- // `host` says which machine runs this manager, as an agent's card does: an owner with several
1484
- // managers tells them apart by it. Advisory display metadata, never a routing input.
1485
- 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" } },
1486
- });
1487
- // Raw failures ride error; conditions the endpoint is already surviving ride warning. Both
1488
- // matter to a supervisor operator, especially a failed standing-credential renewal.
1489
- const reportEndpoint = (e) => console.error(`! manager endpoint: ${e.message}`);
1490
- this.ep.on("error", reportEndpoint);
1491
- this.ep.on("warning", reportEndpoint);
1492
- // Every roster change and every view transition, so a seat that is offline in a fresh snapshot
1493
- // (recorded with no presence event) is logged the moment the view can support the verdict.
1494
- this.ep.on("roster", () => this.logSeatMeshTransitions());
1495
- this.ep.on("presence-view", () => this.logSeatMeshTransitions());
1496
- console.error("manager startup: connecting the supervisor endpoint");
1497
- await this.ep.start();
1498
- await this.ep.setActivity(`supervisor (${this.runtimeKind})`);
1499
- // Per-instance liveness lease (the old per-space singleton is DEMOTED). Acquire
1500
- // THIS logical instance's own key (atomic CAS create). A DIFFERENT instance (a second manager in a
1501
- // second workspace root) has a distinct id ⇒ a distinct key ⇒ it coexists; the create THROWS only
1502
- // when the SAME instance id is already live (a same-root double-start, or a restart racing the
1503
- // crashed predecessor's not-yet-expired key). A double-start REFUSES loud; a restart whose
1504
- // predecessor is provably dead on this host waits for that key's bucket TTL to remove it (#4092,
1505
- // {@link acquireInstanceLease}). Losing the key LATER ends this process only when another process holds it; otherwise
1506
- // the renew loop puts it back or keeps retrying ({@link renewLease}).
1507
- this.leaseInfo = { holder: this.ep.ref().id, instanceId: this.managerInstanceId, runtime: this.runtimeKind, root: resolve(this.workspaceRoot), pid: process.pid };
1508
- try {
1509
- console.error("manager startup: acquiring the instance liveness lease");
1510
- this.leaseRevision = await this.acquireInstanceLease(this.leaseInfo);
1511
- }
1512
- catch (e) {
1513
- await this.ep.stop();
1514
- await this.attach.stop();
1515
- throw e;
1516
- }
1517
- this.leaseTimer = setInterval(() => { void this.renewLease(); }, MANAGER_LEASE_RENEW_MS);
1518
- this.leaseTimer.unref?.();
1519
- // THE PEER-READABLE LIVENESS RESPONDER for the manager plane (#1577). Bound HERE — after the
1520
- // lease, before registration — precisely so it is up during the window in which the manager is
1521
- // NOT yet serving. A responder that only appeared once everything worked could never report the
1522
- // broken state it exists to report, which is the reported defect in a new place.
1523
- //
1524
- // WHAT IT GRADES is `serviceServe`, the v0.4 service endpoint's serve handle, which is assigned
1525
- // only after `serveEndpoint` has bound this instance's rails, AND that handle's connection. A
1526
- // closed serve connection holds no subscriptions, while `onServeConnectionClosed` keeps the
1527
- // handle through its re-dial waits, so the handle alone would answer `bound` with every rail
1528
- // gone. The re-dial swaps in the fresh connection and handle together, so `bound` returns only
1529
- // once the rails are served again. A DISCONNECTED serve connection is the same fault without the
1530
- // close: it reconnects without limit, so it stays open while the broker holds none of its rails,
1531
- // and this probe arrives on the separate supervisor connection that is still up. So the grade
1532
- // also requires the serve transport to be connected. That is a RESPONDER fact. It is
1533
- // deliberately NOT "this process is alive": this process is trivially alive whenever it answers
1534
- // at all, so grading on that would make the surface a `pgrep` that also lies in both directions
1535
- // — the exact instrument the reporter's evidence table indicts. Between lease acquisition and a
1536
- // successful registration the honest answer is `unbound`, and that is what a peer is told.
1537
- //
1538
- // The lease row is never consulted and never sent: presence is the whole ask, and the row
1539
- // carries the operator's workspace root and pid.
1540
- this.ep.serveLiveness("manager", () => {
1541
- const s = this.serviceServe;
1542
- return s?.handle && !s.nc.isClosed() && !this.transportDown.has(s.nc) ? "bound" : "unbound";
1543
- });
1544
- // Static §13.1: after this instance holds its lease, collect the durable static rows
1545
- // now, but do not let their exact-op terminals make the whole space unreachable. The service
1546
- // comes up below, then the sweep overlaps the remaining registration work. Two-window
1547
- // heal-then-register is slower than one executor, but the overlap is still the no-outage
1548
- // property: `reconcilingAliases` refuses spawn or attach of THAT alias until its terminal
1549
- // attempt returns.
1550
- const startupReconcile = this.auth && !this.userMode ? this.reconcileStaticLifecycles() : undefined;
1551
- if (startupReconcile)
1552
- 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`));
1553
- // A default stop records a user-mode seat it released while the seat was still running. This
1554
- // start adopts that seat, or retires it when the runtime proves it gone. Static seats stay on
1555
- // the sweep above.
1556
- if (this.userMode)
1557
- void this.adoptReleasedSeats().catch((e) => console.error(`! a released seat was not adopted: ${rejectionText(e)}`));
1558
- // The manager serves NO ctl tiers - its whole control surface is the v0.4
1559
- // service endpoint registered below. The old three-tier rail (self/manager/admin) is deleted;
1560
- // `ctl.delivery`/`ctl.delivery-admin` (the delivery daemon) and `ctl.auth-admin` (the auth
1561
- // plane) are separate services and keep their rails.
1562
- // Class 2: the manager is the CLASS-2 RENEWAL OWNER — the one control-plane process
1563
- // that is resident in EVERY mesh mode (foreground `up`, `up --detach`, same-root refresh) and
1564
- // holds the signer. Ordered initial pass NOW (ensureControlPlane starts delivery BEFORE the
1565
- // manager, so the daemon's launch-time creds write always precedes this — no write race), then
1566
- // every half-TTL: re-sign the daemon creds files for their EXISTING nkeys, request the explicit
1567
- // `reloadCreds` adoption on the delivery-admin rail, and persist the audit record doctor renders.
1568
- if (this.auth) {
1569
- // #1634: a space may be served by several managers, so ownership of the daemon's credential
1570
- // renewal is decided here rather than by being the only manager able to start. #871: a daemon
1571
- // that is still binding or re-acquiring its lease leaves this challenge unanswered for a few
1572
- // seconds, so boot waits that out instead of exiting over a daemon about to answer.
1573
- await this.claimDaemonRenewalOwnership(DELIVERY_ADMIN_BOOT_WAIT_MS);
1574
- // ARMED BEFORE the first remint, not after. That first `renewDaemonCreds()` re-signs through
1575
- // the SecretStore, and a slow or contended store makes the one pass outlast the lease's
1576
- // MANAGER_LEASE_TTL_MS. Arming afterwards leaves the whole first remint unprotected: the lease
1577
- // expires mid-pass, a second manager's CAS create succeeds, and both remint into one store.
1578
- this.daemonRenewalLeaseTimer = setInterval(() => { void this.keepDaemonRenewalLease(); }, MANAGER_LEASE_RENEW_MS);
1579
- this.daemonRenewalLeaseTimer.unref?.();
1580
- await this.renewDaemonCreds();
1581
- this.credRenewTimer = setInterval(() => { void this.renewDaemonCreds(); }, credRenewIntervalMs(STANDING_RENEWABLE_TTL_SEC));
1582
- this.credRenewTimer.unref?.();
1583
- }
1584
- else if (this.remoteAuthority) {
1585
- if (this.remoteAuthority.renewStandingBundle)
1586
- await this.renewRemoteStandingBundle();
1587
- else
1588
- await this.renewRemoteExecutor();
1589
- let standingTtl = STANDING_RENEWABLE_TTL_SEC;
1590
- if (this.remoteSupervisorCreds) {
1591
- try {
1592
- const claims = credsClaims(this.remoteSupervisorCreds);
1593
- if (typeof claims.exp === "number" && typeof claims.iat === "number" && claims.exp > claims.iat) {
1594
- standingTtl = claims.exp - claims.iat;
1595
- }
1596
- }
1597
- catch { }
1598
- }
1599
- // A refused family needs another pass inside the final quarter of its lifetime.
1600
- const intervalMs = Math.min(credRenewIntervalMs(5 * 60), Math.max(1, Math.floor(standingTtl * 1000 / 8)));
1601
- this.resumeCredRenewal = () => {
1602
- if (this.credRenewTimer || this.leaseStopping)
1603
- return;
1604
- this.credRenewTimer = setInterval(async () => {
1605
- try {
1606
- if (this.remoteAuthority?.renewStandingBundle)
1607
- await this.renewRemoteStandingBundle();
1608
- else
1609
- await this.renewRemoteExecutor();
1610
- }
1611
- catch (e) {
1612
- console.error(`! remote manager renewal pass failed: ${rejectionText(e)}`);
1613
- }
1614
- try {
1615
- await this.runHosting?.renew();
1616
- }
1617
- catch (e) {
1618
- console.error(`! remote run-hosting renewal pass failed: ${rejectionText(e)}`);
1619
- }
1620
- }, intervalMs);
1621
- this.credRenewTimer.unref?.();
1622
- };
1623
- this.resumeCredRenewal();
1624
- }
1625
- // stop() fences before it waits for an accepted startup reconciliation terminal. Once that
1626
- // terminal drains, start() and stop() resume from the same await boundary; start must observe
1627
- // the fence before it can publish a fresh service registration after shutdown.
1628
- if (this.staticLifecycle.stopping)
1629
- return;
1630
- // Register the manager as an ordinary v0.4 `service` endpoint (SPEC §13.7/§13.9)
1631
- // and serve its typed command surface on the ep rails - the ONLY control door, in
1632
- // EVERY mesh mode. Static + user meshes mint the scoped executor + endpoint-serve credential;
1633
- // an open mesh runs the same gate/registration ceremony over bare connections and never mints
1634
- // (there is no credential system - the broker enforces nothing, matching the old open-mesh ctl
1635
- // trust). Fail-loud: a manager that cannot register does not start half-registered.
1636
- console.error("manager startup: binding the service endpoint");
1637
- await this.registerManagerService();
1638
- if (this.staticLifecycle.stopping)
1639
- return;
1640
- // Stand up the standing goal-writer connection for spawn-as-action — AFTER
1641
- // registration (it writes this endpoint's goal facts/records), disjoint from the serve cred.
1642
- await this.startGoalWriter();
1643
- // Stand up the ONE §13.6 session plane for `attach` — AFTER registration too (it
1644
- // rides the serve grant's epoch + the family-staged session-ledger cred), on its own standing
1645
- // connection disjoint from both the serve and goal-writer creds.
1646
- await this.startSessionPlane();
1647
- // Reconcile any accepted-but-unterminal goals inherited from a predecessor
1648
- // BEFORE spawn-as-action begins accepting (the goalReconcileDone gate) — a fresh incarnation
1649
- // never drops a goal a dead predecessor accepted. Never fatal; the gate opens either way.
1650
- console.error("manager startup: reconciling predecessor goals");
1651
- await this.reconcileGoalIndex();
1652
- // SPEC 14.3: the manager hosts workflow runs. Stood up AFTER registration (it names this
1653
- // instance's coordinates) and reconciled AFTER the goal index, for the same reason: a fresh
1654
- // incarnation takes back every run a dead predecessor was driving before it accepts new ones.
1655
- // The serve surface is already live by here, so the family itself holds the gate: `runHost()`
1656
- // refuses `run-start`/`run-resume` as `unavailable` until the host exists and `RunHosting`
1657
- // refuses them until its reconcile has returned. A remote user-auth manager uses its four
1658
- // registered issuer callbacks instead of holding a signer; a local user mesh stands none up.
1659
- const remoteRuns = this.remoteAuthority?.runHosting;
1660
- if (this.execution !== "none" && this.remoteAuthority && remoteRuns) {
1661
- this.runHosting = new RunHosting({
1662
- space: this.space,
1663
- servers: this.servers,
1664
- endpoint: MANAGER_ENDPOINT,
1665
- instanceId: this.managerInstanceId,
1666
- holder: { id: this.remoteAuthority.identities.supervisor.id, lifecycleUid: this.managerLifecycleUid },
1667
- auth: undefined,
1668
- log: (line) => console.error(line),
1669
- admitRun: remoteRuns.admitRun,
1670
- submitRun: remoteRuns.submitRun,
1671
- revokeRun: remoteRuns.revokeRun,
1672
- cancelRun: remoteRuns.cancelRun,
1673
- issueAttempt: remoteRuns.issueAttempt,
1674
- issueOperator: remoteRuns.issueOperator,
1675
- renewRun: remoteRuns.renewRun,
1676
- });
1677
- await this.runHosting.reconcile();
1678
- }
1679
- else if (!this.remoteAuthority && !this.userMode) {
1680
- this.runHosting = new RunHosting({
1681
- space: this.space,
1682
- servers: this.servers,
1683
- endpoint: MANAGER_ENDPOINT,
1684
- instanceId: this.managerInstanceId,
1685
- holder: { id: this.ep.ref().id, lifecycleUid: this.managerLifecycleUid },
1686
- auth: this.auth,
1687
- log: (line) => console.error(line),
1688
- });
1689
- await this.runHosting.reconcile();
1690
- }
1691
- // A carried resume (#1499) needs this instance's transfer reader: minted from the space's signing
1692
- // seed, issued by the host to a remote manager, or none on an open mesh.
1693
- if (this.execution !== "none" && (!this.remoteAuthority || this.remoteAuthority.mintTransferReader)) {
1694
- this.transcripts = new TranscriptReceiver({
1695
- space: this.space,
1696
- instanceId: this.managerInstanceId,
1697
- workspaceRoot: this.workspaceRoot,
1698
- withReader: (fn) => this.withTransferReader(fn),
1699
- log: (line) => console.error(line),
1700
- });
1701
- await this.transcripts.start();
1702
- }
1703
- for (const note of this.bootNotes.splice(0))
1704
- console.error(note);
1705
- // Plane-3 (durable backstop) is NOT the manager's job — the manager only manages agent lifecycle.
1706
- // The server-side delivery daemon hosts the fan-out writer + trusted reader, owns the durable
1707
- // membership registry, and serves the runtime durable join/leave/list ops (on `ctl.delivery`). The
1708
- // manager records each agent's read ACL at spawn (`commitAcl`, in provisionAgent) so the daemon can
1709
- // re-authorize it; that is the only Plane-3 state the manager touches, and it rides minting.
1710
- }
705
+ /** {@link ManagerBoot.claimExecutionRecord}. */
706
+ claimExecutionRecord(...args) { return this.bootComponent.claimExecutionRecord(...args); }
707
+ /** {@link ManagerBoot.runStart}. */
708
+ runStart(...args) { return this.bootComponent.runStart(...args); }
1711
709
  /** The delivery shard whose lease names the process that reloads the standing credentials.
1712
710
  * Delivery is single-shard today and the endpoint's own responder reads row 0; naming it here
1713
711
  * keeps the manager's binding check and that reply arguing about the same row. */
@@ -1771,581 +769,35 @@ export class Manager {
1771
769
  return `manager is waiting for resume attempt ${this.resumeAttemptId}; ordinary lifecycle/control work is fenced`;
1772
770
  return `manager is in ${this.maintenanceState} mode; new lifecycle/control work is fenced`;
1773
771
  }
1774
- /** Fence and build the inventory without stopping a child. The coordinator must durably persist
1775
- * this exact plan before calling commitPreservation with the same attempt id. */
1776
- preparePreservation(attemptId) {
1777
- if (this.execution === "none")
1778
- return Promise.reject(new EpEnvelopeError("unimplemented", this.executionRefusal()));
1779
- if (!attemptId.trim())
1780
- return Promise.reject(new Error("preservation attemptId is required"));
1781
- if (this.preservationAttemptId && this.preservationAttemptId !== attemptId)
1782
- return Promise.reject(new Error(`manager is fenced for preservation attempt ${this.preservationAttemptId}; refusing different attempt ${attemptId}`));
1783
- if (this.maintenanceState === "preserved" && this.preservationInventory)
1784
- return Promise.resolve({ ok: true, attemptId, state: "preserved", inventory: this.preservationInventory, failures: [] });
1785
- if (this.preparationTask)
1786
- return this.preparationTask;
1787
- if (this.maintenanceState === "active") {
1788
- // The fence lands before any await. Accepted work has already incremented lifecycleInFlight.
1789
- this.maintenanceState = "preserving";
1790
- this.preservationAttemptId = attemptId;
1791
- this.preservationGeneration++;
1792
- if (this.credRenewTimer) {
1793
- clearInterval(this.credRenewTimer);
1794
- this.credRenewTimer = undefined;
1795
- }
1796
- }
1797
- const generation = this.preservationGeneration;
1798
- const task = this.runPreparation(attemptId, generation);
1799
- let wrapped;
1800
- wrapped = task.finally(() => {
1801
- if (this.preservationGeneration === generation && this.preparationTask === wrapped)
1802
- this.preparationTask = undefined;
1803
- });
1804
- this.preparationTask = wrapped;
1805
- return wrapped;
1806
- }
1807
- assertPreservationGeneration(attemptId, generation) {
1808
- if (this.preservationAttemptId !== attemptId || this.preservationGeneration !== generation)
1809
- throw new Error(`preservation attempt ${attemptId} was abandoned before preparation completed`);
1810
- }
1811
- async runPreparation(attemptId, generation) {
1812
- await this.awaitLifecycleDrain();
1813
- this.assertPreservationGeneration(attemptId, generation);
1814
- // Read the chat frontier BEFORE any child stops (issue #545): a message posted between this
1815
- // read and the child's stop is delivered live now and again as `historical` on resume, a
1816
- // duplicate bounded to the cut window that the seat's own id dedup on `durable` channels
1817
- // absorbs, whereas a read taken after the stops would instead skip messages the seat never
1818
- // actually saw.
1819
- const backfillFloor = await this.chatFrontierForPreservation();
1820
- const inventory = this.preservationInventory ?? {
1821
- version: "cotal-manager-resume/v2",
1822
- space: this.space,
1823
- createdAt: new Date().toISOString(),
1824
- agents: [...this.agents.values()].map((a) => this.resumeEntry(a, backfillFloor)),
1825
- };
1826
- const failures = [];
1827
- for (const entry of inventory.agents) {
1828
- const error = this.inventoryReferenceError(entry);
1829
- if (error)
1830
- failures.push({
1831
- name: entry.name,
1832
- id: entry.identity.mode === "user" ? principalKey(entry.identity.owner, entry.identity.actor).key : entry.identity.id,
1833
- error,
1834
- });
1835
- }
1836
- // A later manager does not resume a delegated seat, and its close runs only inside its
1837
- // retirement, so a cut that holds one is refused before any child stops. A carried resume seat's
1838
- // private home is removed when its slot is freed, so a later manager would find nothing to fork.
1839
- for (const a of this.agents.values()) {
1840
- if (a.handedOff)
1841
- failures.push({ name: a.name, id: a.id, error: "a delegated seat is not resumed by a later manager; stop it before preserving" });
1842
- if (a.seatHome)
1843
- failures.push({ name: a.name, id: a.id, error: "a carried resume seat's private home is not kept for a later manager; stop it before preserving" });
1844
- if (a.once)
1845
- failures.push({ name: a.name, id: a.id, error: "a once seat runs its one task in this process, and a later manager would start it again; let its task end or stop it before preserving" });
1846
- }
1847
- const unverifiedStops = this.unverifiedStops.filter((stopped) => {
1848
- try {
1849
- if (!stopped.authoritative && stopped.handle.status() === "exited")
1850
- return false;
1851
- }
1852
- catch { /* fail closed below */ }
1853
- failures.push({
1854
- name: stopped.name,
1855
- id: stopped.id,
1856
- error: stopped.error ?? `an earlier stop on runtime "${stopped.handle.kind}" cannot prove the child is gone`,
1857
- });
1858
- return true;
1859
- });
1860
- this.assertPreservationGeneration(attemptId, generation);
1861
- // The prepared inventory must round-trip through the EXACT resume control parser (schema and
1862
- // byte cap) NOW, before any child stops: a cut that cannot resume must fail at prepare time,
1863
- // never after listener exposure.
1864
- try {
1865
- parseResumeControlArgs({ attemptId, inventory });
1866
- }
1867
- catch (e) {
1868
- failures.push({ name: "<inventory>", id: attemptId, error: `prepared inventory would be rejected at resume: ${rejectionText(e)}` });
1869
- }
1870
- this.preservationInventory = inventory;
1871
- this.preservationFailures = failures;
1872
- this.unverifiedStops = unverifiedStops;
1873
- return {
1874
- ok: failures.length === 0,
1875
- attemptId,
1876
- state: "prepared",
1877
- inventory,
1878
- failures: [...failures],
1879
- };
1880
- }
1881
- /** Stop children only after the coordinator has persisted the prepared inventory. Same-attempt
1882
- * retries are idempotent; a different attempt is refused. */
1883
- commitPreservation(attemptId) {
1884
- if (this.execution === "none")
1885
- return Promise.reject(new EpEnvelopeError("unimplemented", this.executionRefusal()));
1886
- if (!this.preservationAttemptId || this.preservationAttemptId !== attemptId)
1887
- return Promise.reject(new Error(`preservation attempt ${attemptId} was not prepared by this manager`));
1888
- if (!this.preservationInventory)
1889
- return Promise.reject(new Error(`preservation attempt ${attemptId} has no prepared inventory`));
1890
- if (this.preservationFailures.length)
1891
- return Promise.resolve({
1892
- ok: false,
1893
- attemptId,
1894
- state: "preserving",
1895
- inventory: this.preservationInventory,
1896
- failures: [...this.preservationFailures],
1897
- });
1898
- if (this.maintenanceState === "preserved")
1899
- return Promise.resolve({ ok: true, attemptId, state: "preserved", inventory: this.preservationInventory, failures: [] });
1900
- if (this.preservationTask)
1901
- return this.preservationTask;
1902
- this.preservationStarted = true;
1903
- this.preservationTask = this.runPreservation(attemptId).finally(() => {
1904
- this.preservationTask = undefined;
1905
- });
1906
- return this.preservationTask;
1907
- }
1908
- /** Recover an abandoned prepare before any child stop. Once commit begins, preservation is
1909
- * irreversible and remains fenced until the coordinator records failure/recourse. */
1910
- abortPreservation(attemptId) {
1911
- if (this.execution === "none")
1912
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
1913
- if (this.preservationAttemptId !== attemptId)
1914
- throw new Error(`preservation attempt ${attemptId} is not the active manager attempt`);
1915
- if (this.preparationTask || this.lifecycleInFlight > 0)
1916
- throw new Error(`preservation attempt ${attemptId} is still preparing or draining accepted lifecycle work and cannot be aborted`);
1917
- if (this.preservationStarted || this.preservationTask || this.maintenanceState === "preserved")
1918
- throw new Error(`preservation attempt ${attemptId} has begun stopping children and cannot return to active mode`);
1919
- this.preservationGeneration++;
1920
- this.maintenanceState = "active";
1921
- this.preservationAttemptId = undefined;
1922
- this.preservationInventory = undefined;
1923
- this.preservationFailures = [];
1924
- if (this.auth && !this.credRenewTimer) {
1925
- this.credRenewTimer = setInterval(() => { void this.renewDaemonCreds(); }, credRenewIntervalMs(STANDING_RENEWABLE_TTL_SEC));
1926
- this.credRenewTimer.unref?.();
1927
- }
1928
- this.resumeCredRenewal?.();
1929
- // Exit watchers were suppressed while the fence stood: reconcile every child that died during
1930
- // preparation now, or its slot/credential footprint would linger unreaped after the abort.
1931
- for (const agent of [...this.agents.values()]) {
1932
- try {
1933
- if (agent.handle.status() === "exited")
1934
- this.onAgentExit(agent);
1935
- }
1936
- catch { /* status unavailable - the exit watcher fires again on real exit */ }
1937
- }
1938
- }
1939
- /** In-process convenience that preserves the crash barrier by awaiting durable persistence between
1940
- * prepare and commit. Wire callers use the explicit two-phase admin operations. */
1941
- async preserveState(opts) {
1942
- const plan = await this.preparePreservation(opts.attemptId);
1943
- if (!plan.ok)
1944
- return { ok: false, attemptId: opts.attemptId, state: "preserving", inventory: plan.inventory, failures: plan.failures };
1945
- await opts.persistInventory(plan.inventory);
1946
- return this.commitPreservation(opts.attemptId);
1947
- }
1948
- async runPreservation(attemptId) {
1949
- const failures = [];
1950
- for (const a of [...this.agents.values()])
1951
- a.suppressCleanup = true;
1952
- await Promise.all([...this.agents.values()].map(async (a) => {
1953
- try {
1954
- // A preservation cut must not run the connector's logical leave/cleanup hooks.
1955
- a.handle.stop({ graceful: false });
1956
- }
1957
- catch (e) {
1958
- failures.push({ name: a.name, id: a.id, error: `stop failed: ${rejectionText(e)}` });
1959
- return;
1960
- }
1961
- try {
1962
- await this.awaitHandleExit(a.handle);
1963
- if (this.agents.get(a.name) === a)
1964
- this.agents.delete(a.name);
1965
- }
1966
- catch (e) {
1967
- failures.push({ name: a.name, id: a.id, error: rejectionText(e) });
1968
- }
1969
- }));
1970
- if (failures.length === 0)
1971
- this.maintenanceState = "preserved";
1972
- return {
1973
- ok: failures.length === 0,
1974
- attemptId,
1975
- state: this.maintenanceState === "preserved" ? "preserved" : "preserving",
1976
- inventory: this.preservationInventory,
1977
- failures,
1978
- };
1979
- }
1980
- async awaitHandleExit(handle) {
1981
- if (!handle.waitForExit)
1982
- throw new Error(`runtime "${handle.kind}" cannot prove child exit (AgentHandle.waitForExit is not implemented)`);
1983
- await withTimeout(handle.waitForExit(), this.preserveStopTimeoutMs, `child did not exit within ${this.preserveStopTimeoutMs}ms`);
1984
- if (handle.status() !== "exited")
1985
- throw new Error(`runtime "${handle.kind}" reported exit completion but status is still running`);
1986
- }
1987
- inventoryReferenceError(entry) {
1988
- if (entry.launch.source.kind === "manifest" && !entry.launch.source.runId)
1989
- return "resolved manifest launch has no retained runId";
1990
- if (entry.launch.unresolvedLaunchOptionKeys?.length)
1991
- return `imperative launch options have no non-secret durable source (${entry.launch.unresolvedLaunchOptionKeys.join(", ")})`;
1992
- if (!entry.dependencies.some((path) => resolve(path) === resolve(entry.launch.source.configPath)))
1993
- return `launch config is not declared as a retained dependency: ${entry.launch.source.configPath}`;
1994
- if (entry.launch.source.kind === "inline" && resolve(entry.launch.source.configPath) !== resolve(inlineSnapshotPath(this.workspaceRoot, entry.identity.lifecycleUid)))
1995
- return `inline persona snapshot ${entry.launch.source.configPath} is not this lifecycle's snapshot path`;
1996
- if (entry.launch.source.kind === "manifest" && entry.launch.source.runId) {
1997
- const specPath = join(this.workspaceRoot, ".cotal", "run", `${entry.launch.source.runId}.json`);
1998
- if (!entry.dependencies.some((path) => resolve(path) === resolve(specPath)))
1999
- return `manifest source is not declared as a retained dependency: ${specPath}`;
2000
- }
2001
- const required = [...entry.dependencies];
2002
- if (entry.identity.mode === "static")
2003
- required.push(entry.identity.credential.path);
2004
- if (entry.identity.mode === "user") {
2005
- required.push(entry.identity.actorToken.path, entry.identity.sentinelCredential.path);
2006
- }
2007
- for (const path of required) {
2008
- try {
2009
- const st = lstatSync(path);
2010
- if (!st.isFile() || st.isSymbolicLink())
2011
- return `retained reference is not a regular non-symlink file: ${path}`;
2012
- }
2013
- catch (e) {
2014
- return `retained reference unavailable: ${path} (${rejectionText(e)})`;
2015
- }
2016
- }
2017
- if (process.platform !== "win32") {
2018
- const secrets = entry.identity.mode === "static"
2019
- ? [entry.identity.credential.path]
2020
- : entry.identity.mode === "user"
2021
- ? [entry.identity.actorToken.path, entry.identity.sentinelCredential.path]
2022
- : [];
2023
- for (const path of secrets)
2024
- if ((lstatSync(path).mode & 0o077) !== 0)
2025
- return `retained identity file is not private (expected 0600): ${path}`;
2026
- }
2027
- try {
2028
- if (this.fileDigest(entry.launch.source.configPath) !== entry.launch.source.configSha256)
2029
- return `launch config changed since it became effective: ${entry.launch.source.configPath}`;
2030
- if (entry.identity.mode === "static" && this.fileDigest(entry.identity.credential.path) !== entry.identity.credential.sha256)
2031
- return `retained credential changed after the cut: ${entry.identity.credential.path}`;
2032
- if (entry.identity.mode === "user" &&
2033
- (this.fileDigest(entry.identity.actorToken.path) !== entry.identity.actorToken.sha256 ||
2034
- this.fileDigest(entry.identity.sentinelCredential.path) !== entry.identity.sentinelCredential.sha256))
2035
- return `retained user identity files changed after the cut for ${entry.name}`;
2036
- if (entry.launch.source.kind === "manifest" && entry.launch.source.runId) {
2037
- const specPath = join(this.workspaceRoot, ".cotal", "run", `${entry.launch.source.runId}.json`);
2038
- if (!entry.launch.source.manifestSha256 || this.fileDigest(specPath) !== entry.launch.source.manifestSha256)
2039
- return `manifest source changed since it became effective: ${specPath}`;
2040
- }
2041
- }
2042
- catch (e) {
2043
- return `retained reference cannot be hashed: ${rejectionText(e)}`;
2044
- }
2045
- return undefined;
2046
- }
772
+ /** {@link Preservation.preparePreservation}. */
773
+ preparePreservation(...args) { return this.preservationComponent.preparePreservation(...args); }
774
+ /** {@link Preservation.runPreparation}. */
775
+ runPreparation(...args) { return this.preservationComponent.runPreparation(...args); }
776
+ /** {@link Preservation.commitPreservation}. */
777
+ commitPreservation(...args) { return this.preservationComponent.commitPreservation(...args); }
778
+ /** {@link Preservation.abortPreservation}. */
779
+ abortPreservation(...args) { return this.preservationComponent.abortPreservation(...args); }
780
+ /** {@link Preservation.preserveState}. */
781
+ preserveState(...args) { return this.preservationComponent.preserveState(...args); }
782
+ /** {@link Preservation.awaitHandleExit}. */
783
+ awaitHandleExit(...args) { return this.preservationComponent.awaitHandleExit(...args); }
784
+ /** {@link Preservation.inventoryReferenceError}. */
785
+ inventoryReferenceError(...args) { return this.preservationComponent.inventoryReferenceError(...args); }
2047
786
  fileDigest(path) { return fileDigest(path); }
2048
- fileDigestOrEmpty(path) {
2049
- try {
2050
- return this.fileDigest(path);
2051
- }
2052
- catch {
2053
- return "";
2054
- }
2055
- }
2056
- resumeEntry(a, backfillFloor) {
2057
- // A preservation cut is a stop boundary too, so a manifest launch after it reopens what a resume would.
2058
- this.recordContinuityAtStop(a, "preservation");
2059
- return this.resumeEntryOf(a, backfillFloor);
2060
- }
2061
- /** The resume entry of one live seat, with no side effect: a preservation cut and a supervised
2062
- * seat's record both build it. The entry is its own copy, so a caller's write to the plan it was
2063
- * handed cannot change the launch the manager keeps supervising (#3241). */
2064
- resumeEntryOf(a, backfillFloor) {
2065
- const principal = a.userOwner
2066
- ? parsePrincipalKey(a.id)
2067
- : { owner: DEV_OWNER, actor: a.id };
2068
- if (!principal)
2069
- throw new Error(`managed agent ${a.name} has an invalid principal ${a.id}`);
2070
- // The RECORDED secret-family paths (set at spawn or adoption) — never a re-derivation by name:
2071
- // under mixed generations (a name-keyed pre-split incarnation adopted by this manager) the
2072
- // recorded path is the only truth, and re-deriving would preserve a family that isn't there.
2073
- const files = a.secretPaths;
2074
- const identity = a.userOwner
2075
- ? (() => {
2076
- if (!files?.actorToken || !files.sentinelCreds || !files.health)
2077
- throw new Error(`managed agent ${a.name} is user-mode but its secret-family paths were not recorded`);
2078
- return {
2079
- mode: "user",
2080
- owner: principal.owner,
2081
- actor: principal.actor,
2082
- lifecycleUid: a.lifecycleUid,
2083
- actorToken: { kind: "file", path: files.actorToken, sha256: this.fileDigestOrEmpty(files.actorToken) },
2084
- sentinelCredential: { kind: "file", path: files.sentinelCreds, sha256: this.fileDigestOrEmpty(files.sentinelCreds) },
2085
- health: { kind: "file", path: files.health },
2086
- };
2087
- })()
2088
- : this.auth
2089
- ? (() => {
2090
- if (!files?.creds)
2091
- throw new Error(`managed agent ${a.name} is static-auth but its credential path was not recorded`);
2092
- 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 } : {}) };
2093
- })()
2094
- : { mode: "open", id: principal.actor, lifecycleUid: a.lifecycleUid };
2095
- const dependencies = [a.launch.source.configPath];
2096
- if (a.launch.source.kind === "manifest" && a.launch.source.runId)
2097
- dependencies.unshift(join(this.workspaceRoot, ".cotal", "run", `${a.launch.source.runId}.json`));
2098
- return structuredClone({
2099
- space: this.space,
2100
- name: a.name,
2101
- role: a.role,
2102
- identity,
2103
- launch: {
2104
- connector: a.agent,
2105
- runtime: a.handle.kind,
2106
- cwd: a.launch.cwd,
2107
- source: a.launch.source,
2108
- model: a.launch.model,
2109
- variant: a.launch.variant,
2110
- subscribe: a.launch.subscribe,
2111
- allowSubscribe: a.launch.allowSubscribe,
2112
- allowPublish: a.launch.allowPublish,
2113
- capabilities: a.launch.capabilities,
2114
- ...(a.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(a.launch.endpoints) } : {}),
2115
- events: a.launch.events,
2116
- eventPayloads: a.launch.eventPayloads,
2117
- shareTools: a.launch.shareTools,
2118
- forkSource: a.launch.forkSource,
2119
- ...(this.forkProvenance(a) ? { resumed: this.forkProvenance(a) } : {}),
2120
- // A supervised seat whose connector keeps no session state is armed with no state file to read.
2121
- sessionId: a.restart?.armed && a.restart.sessionStatePath ? this.readManagedSession(a) : a.launch.sessionId,
2122
- // Additive and only when the connector supplied one. A seat with no pointer records no
2123
- // field, which is what keeps an older inventory and a fresh one the same document shape.
2124
- ...(a.restart?.sessionStatePath ? { sessionStatePath: a.restart.sessionStatePath } : {}),
2125
- unresolvedLaunchOptionKeys: a.launch.unresolvedLaunchOptionKeys,
2126
- },
2127
- dependencies,
2128
- spawner: a.spawner,
2129
- authorityParent: a.authorityParent,
2130
- startedAt: new Date(a.startedAt).toISOString(),
2131
- ...(backfillFloor !== undefined ? { backfillFloor } : {}),
2132
- });
2133
- }
2134
- /** Tear down every managed agent's footprint on an explicit destructive {@link stop}, or only the
2135
- * in-process seats a default stop cannot detach. A manager exit is
2136
- * a mass agent-exit, and without this its agents' footprints (creds files + `dm_`/`dlv_` durables + ACL
2137
- * rows) would orphan exactly as the per-agent exit path prevents. Stop each child gracefully, so its
2138
- * own shutdown runs before the runtime escalates, and AWAIT its deprovision — bounded per agent (`withTimeout`) and
2139
- * best-effort (`allSettled` + a loud log), so one slow/failed teardown can neither hang nor abort exit.
2140
- * The creds file is dropped even if the broker teardown fails (see {@link deprovision}). Deliberately
2141
- * touches NEITHER the lease NOR the endpoints — the caller owns those. */
2142
- async teardownManagedAgents(managed = [...this.agents.values()]) {
2143
- const failures = [];
2144
- const stopped = [];
2145
- for (const a of managed) {
2146
- // Free the slot and stop each the way an operator stop does. `stopHandle` is best-effort (never
2147
- // throws — see it), so one bad stop can't strand the rest, and every snapshot entry is
2148
- // deprovisioned below regardless. A hard kill never runs the seat's shutdown, so a helper that
2149
- // has left the process group keeps running after `cotal down`. The runtime still escalates to
2150
- // SIGKILL after its grace.
2151
- this.recordContinuityAtStop(a, "shutdown");
2152
- if (process.platform !== "win32" || a.handle.kind !== "pty") {
2153
- this.agents.delete(a.name);
2154
- this.dropSeatRecord(a);
2155
- }
2156
- const refused = this.stopHandle(a, true, { kind: "stopped-shutdown" });
2157
- if (refused === undefined)
2158
- stopped.push(a);
2159
- else
2160
- failures.push(`${a.name}: stop failed: ${refused}`);
2161
- }
2162
- // A runtime stop request is not exit proof. Do not release the manager lease or registration
2163
- // while any seat may still hold this instance's broker rails: that creates the exact orphan
2164
- // window where a successor sees a dead manager but live predecessor authority. Every shipped
2165
- // runtime now supplies waitForExit; absence or timeout is a failed shutdown, never a clean one.
2166
- // The slot delete above bypasses freeSlot, which is where the reap line lives, so say it
2167
- // here once this shutdown has proved the seat exited. A seat whose stop was refused, or
2168
- // whose exit wait did not prove it gone, is named only by the shutdown error below (#1423, #3404).
2169
- await Promise.all(stopped.map(async (a) => {
2170
- try {
2171
- await this.awaitHandleExit(a.handle);
2172
- if (process.platform === "win32" && a.handle.kind === "pty") {
2173
- this.agents.delete(a.name);
2174
- this.dropSeatRecord(a);
2175
- }
2176
- this.logSeatReaped(a, { kind: "stopped-shutdown" });
2177
- }
2178
- catch (e) {
2179
- failures.push(`${a.name}: ${rejectionText(e)}`);
2180
- }
2181
- }));
2182
- // Deprovision EVERY snapshot entry regardless of whether its stop failed (allSettled + a loud log).
2183
- await Promise.allSettled(managed.filter((a) => !a.suppressCleanup).map((a) => {
2184
- // Retired here on every mesh, the open mesh included, which runs no teardown of its own.
2185
- const settled = a.launch.source.kind !== "inline" || this.dropInlineSnapshot(a.name, a.lifecycleUid);
2186
- return this.deprovision({ ...this.teardownTarget(a), ...(settled ? { snapshotSettled: true } : {}) }).catch((e) => console.error(`deprovision ${a.name} (${a.id}) on shutdown: ${rejectionText(e)}`));
2187
- }));
2188
- if (failures.length)
2189
- throw new Error(`manager shutdown could not prove every seat exited: ${failures.join("; ")}`);
2190
- }
2191
- isProcessBoundSeat(agent) {
2192
- return agent.handle.kind === "pty" && typeof agent.handle.release !== "function";
2193
- }
2194
- /** Drop local custody of every seat that can outlive this process, and leave it running. A seat
2195
- * with a runtime reference is recorded first, so the next manager on this workspace adopts it, or
2196
- * retires it once its runtime proves it gone. The stopping manager keeps no watch on a released
2197
- * seat: its endpoint is closing, and a retirement it drove afterwards would run over a dead
2198
- * connection and race the next manager's. `stop` is every seat left for the caller to stop and
2199
- * retire now: an in-process seat, a seat the runtime already reports gone, and a seat whose record
2200
- * could not be written, because a released seat nobody can find again is the leak this stop must
2201
- * not create. */
2202
- releaseManagedAgents() {
2203
- const failures = [];
2204
- const stop = [];
2205
- for (const a of [...this.agents.values()]) {
2206
- if (this.isProcessBoundSeat(a)) {
2207
- stop.push(a);
2208
- continue;
2209
- }
2210
- let exited = false;
2211
- try {
2212
- exited = a.handle.status() === "exited";
2213
- }
2214
- catch {
2215
- // Status is not proof either way; the seat is released as any running seat is.
2216
- }
2217
- if (exited) {
2218
- stop.push(a);
2219
- continue;
2220
- }
2221
- const reference = a.handle.reference;
2222
- if (reference) {
2223
- try {
2224
- // A static manager records an adoptable seat at launch and keeps that record current. A
2225
- // user-mode manager records nothing until here.
2226
- if (this.userMode)
2227
- writeSeatRecord(this.workspaceRoot, { version: "cotal-seat-record/v1", instanceId: this.managerInstanceId, crashes: a.restart?.crashes ?? [], agent: this.resumeEntryOf(a) });
2228
- writeReleasedSeatReference(this.workspaceRoot, this.space, a.name, { version: "cotal-released-seat/v1", lifecycleUid: a.lifecycleUid, kind: reference.kind, id: reference.id });
2229
- }
2230
- catch (e) {
2231
- console.error(`! ${a.name}: the released seat could not be recorded (${rejectionText(e)}); this stop retires it instead`);
2232
- stop.push(a);
2233
- continue;
2234
- }
2235
- }
2236
- try {
2237
- a.handle.release?.();
2238
- a.suppressCleanup = true;
2239
- this.agents.delete(a.name);
2240
- }
2241
- catch (e) {
2242
- failures.push(`${a.name}: ${rejectionText(e)}`);
2243
- }
2244
- }
2245
- return { failures, stop };
2246
- }
2247
- /** Take back user-mode seats a previous manager released while they were still running. A seat
2248
- * the runtime adopts is watched, and retired when that watch proves it gone. A seat the runtime
2249
- * has already reaped is retired now. Anything the runtime cannot prove is left recorded. */
2250
- async adoptReleasedSeats() {
2251
- const dir = join(this.workspaceRoot, ".cotal", "seat-records", this.space);
2252
- if (!existsSync(dir))
2253
- return;
2254
- for (const file of readdirSync(dir)) {
2255
- if (!file.endsWith(".runtime-ref"))
2256
- continue;
2257
- const name = file.slice(0, -".runtime-ref".length);
2258
- try {
2259
- await this.adoptReleasedSeat(name);
2260
- }
2261
- catch (e) {
2262
- console.error(`! ${name}: the released seat was not adopted: ${rejectionText(e)}`);
2263
- }
2264
- }
2265
- }
2266
- async adoptReleasedSeat(name) {
2267
- const reference = readReleasedSeatReference(this.workspaceRoot, this.space, name);
2268
- const record = reference ? readSeatRecord(this.workspaceRoot, this.space, name) : undefined;
2269
- const identity = record?.agent.identity;
2270
- if (!reference || !record || identity?.mode !== "user" || identity.lifecycleUid !== reference.lifecycleUid)
2271
- return;
2272
- try {
2273
- await this.validateRetainedAuthority(record.agent);
2274
- }
2275
- catch (e) {
2276
- console.error(`! ${name}: the released seat's record was not adopted: ${rejectionText(e)}`);
2277
- return;
2278
- }
2279
- const held = this.agents.get(name);
2280
- if (held?.lifecycleUid === reference.lifecycleUid)
2281
- return;
2282
- if (held)
2283
- return;
2284
- const runtime = this.runtimeFor(reference.kind);
2285
- if (typeof runtime.adopt !== "function" || reference.kind !== runtime.kind)
2286
- return;
2287
- let handle;
2288
- try {
2289
- handle = runtime.adopt(reference);
2290
- }
2291
- catch (e) {
2292
- try {
2293
- await requireRuntimeReap(runtime, reference);
2294
- }
2295
- catch {
2296
- // The runtime could not prove the seat gone. Leave the record for a later start.
2297
- return;
2298
- }
2299
- console.error(`! ${name}: the released seat is gone (${rejectionText(e)}); retiring its lifecycle`);
2300
- handle = {
2301
- name,
2302
- kind: runtime.kind,
2303
- reference: { kind: runtime.kind, id: reference.id },
2304
- status: () => "exited",
2305
- stop: () => { },
2306
- interrupt: () => { },
2307
- waitForExit: () => Promise.resolve(),
2308
- attach: () => { throw new Error(`released seat ${name} has exited`); },
2309
- };
2310
- }
2311
- const launch = record.agent.launch;
2312
- const agent = {
2313
- name,
2314
- role: record.agent.role,
2315
- agent: launch.connector,
2316
- id: principalKey(identity.owner, identity.actor).key,
2317
- lifecycleUid: identity.lifecycleUid,
2318
- userOwner: identity.owner,
2319
- secretPaths: {
2320
- actorToken: identity.actorToken.path,
2321
- sentinelCreds: identity.sentinelCredential.path,
2322
- health: identity.health.path,
2323
- },
2324
- spawner: record.agent.spawner,
2325
- authorityParent: record.agent.authorityParent,
2326
- startedAt: Date.parse(record.agent.startedAt) || Date.now(),
2327
- handle,
2328
- launch: {
2329
- source: launch.source,
2330
- runtime: launch.runtime,
2331
- cwd: launch.cwd,
2332
- model: launch.model,
2333
- variant: launch.variant,
2334
- subscribe: launch.subscribe,
2335
- allowSubscribe: launch.allowSubscribe,
2336
- allowPublish: launch.allowPublish,
2337
- capabilities: launch.capabilities,
2338
- events: launch.events,
2339
- eventPayloads: launch.eventPayloads,
2340
- shareTools: launch.shareTools,
2341
- forkSource: launch.forkSource,
2342
- sessionId: launch.sessionId,
2343
- unresolvedLaunchOptionKeys: launch.unresolvedLaunchOptionKeys,
2344
- },
2345
- };
2346
- this.agents.set(name, agent);
2347
- this.watchExit(agent);
2348
- }
787
+ /** {@link Preservation.fileDigestOrEmpty}. */
788
+ fileDigestOrEmpty(...args) { return this.preservationComponent.fileDigestOrEmpty(...args); }
789
+ /** {@link PreservedResume.resumeEntry}. */
790
+ resumeEntry(...args) { return this.preservedResumeComponent.resumeEntry(...args); }
791
+ /** {@link PreservedResume.resumeEntryOf}. */
792
+ resumeEntryOf(...args) { return this.preservedResumeComponent.resumeEntryOf(...args); }
793
+ /** {@link Preservation.teardownManagedAgents}. */
794
+ teardownManagedAgents(...args) { return this.preservationComponent.teardownManagedAgents(...args); }
795
+ /** {@link Preservation.isProcessBoundSeat}. */
796
+ isProcessBoundSeat(...args) { return this.preservationComponent.isProcessBoundSeat(...args); }
797
+ /** {@link Preservation.releaseManagedAgents}. */
798
+ releaseManagedAgents(...args) { return this.preservationComponent.releaseManagedAgents(...args); }
799
+ /** {@link Preservation.adoptReleasedSeats}. */
800
+ adoptReleasedSeats(...args) { return this.preservationComponent.adoptReleasedSeats(...args); }
2349
801
  async stopRetainedAgentsOnExit() {
2350
802
  const managed = [...this.agents.values()];
2351
803
  for (const a of managed)
@@ -2545,220 +997,37 @@ export class Manager {
2545
997
  this.serviceServe = undefined;
2546
998
  await this.retireConnection(s.nc, () => s.handle.stop());
2547
999
  }
2548
- /** Retire a dedicated connection on stop: drain it while its transport is up, close it while the
2549
- * client is reconnecting it. A drain on a reconnecting connection does not fail, it waits for the
2550
- * reconnect, so the stop would last as long as the outage; a broker this connection cannot reach
2551
- * has nothing left to flush. `flush` (the serve loop's own drain) runs only while the transport is
2552
- * up. Best-effort, so a graceful stop completes its remaining teardown even when the broker is gone. */
2553
- async retireConnection(nc, flush) {
2554
- if (this.transportDown.has(nc)) {
2555
- try {
2556
- await nc.close();
2557
- }
2558
- catch { /* best effort */ }
2559
- return;
2560
- }
2561
- if (flush)
2562
- try {
2563
- await flush();
2564
- }
2565
- catch { /* best effort */ }
1000
+ /** {@link BrokerTransport.retireConnection}. */
1001
+ retireConnection(...args) { return this.brokerTransportComponent.retireConnection(...args); }
1002
+ /** {@link BrokerTransport.discardServeCandidate}. */
1003
+ discardServeCandidate(...args) { return this.brokerTransportComponent.discardServeCandidate(...args); }
1004
+ /** {@link BrokerTransport.trackTransport}. */
1005
+ trackTransport(...args) { return this.brokerTransportComponent.trackTransport(...args); }
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); }
1014
+ /** {@link CommandDispatch.admitControl}. */
1015
+ admitControl(...args) { return this.commandDispatch.admitControl(...args); }
1016
+ /** Run one v0.4 service-command handler through the SHARED admission chokepoint
1017
+ * ({@link admitControl}) on the broker-authenticated caller principal, mapping the two fences
1018
+ * onto the §13.3 catalog: maintenance/resume → `unavailable`, membership →
1019
+ * `permission-denied`. The serve boundary publishes the structured error reply. */
1020
+ async serveGated(ctx, fn) {
1021
+ const caller = principalKey(ctx.subject.caller.owner, ctx.subject.caller.actor).key;
1022
+ const admission = this.admitControl(caller);
1023
+ // Both fences refuse before the handler runs, so nothing ran (SPEC 13.3).
1024
+ if (admission.refusal !== undefined)
1025
+ throw new EpEnvelopeError(admission.fence === "membership" ? "permission-denied" : "unavailable", admission.refusal, undefined, "not-executed");
2566
1026
  try {
2567
- await drainAndClose(nc);
1027
+ return await fn();
2568
1028
  }
2569
- catch { /* best effort */ }
2570
- }
2571
- /** A failed candidate must not extend preparation by draining subscriptions on a stalled socket.
2572
- * Close only that candidate first. Native stop still owns any already-dispatched handlers, whose
2573
- * outcomes remain unknown to callers and must not be replayed; they do not hold family adoption. */
2574
- async discardServeCandidate(nc, handle) {
2575
- await nc.close();
2576
- if (handle)
2577
- void handle.stop().catch((e) => console.error(`! remote manager discarded serve candidate cleanup: ${rejectionText(e)}`));
2578
- }
2579
- /** Track a dedicated connection's transport into {@link transportDown} from the first moment:
2580
- * nats.js reports `disconnect` when the socket drops and `reconnect` only after it has re-sent the
2581
- * connection's subscriptions. If the status stream itself fails, the transport can no longer be
2582
- * observed, so it counts as down. */
2583
- trackTransport(nc) {
2584
- void (async () => {
2585
- for await (const st of nc.status()) {
2586
- if (st.type === "disconnect")
2587
- this.transportDown.add(nc);
2588
- else if (st.type === "reconnect")
2589
- this.transportDown.delete(nc);
2590
- }
2591
- })().catch(() => this.transportDown.add(nc));
2592
- }
2593
- async opFinalizeResume(rawArgs) {
2594
- if (this.execution === "none")
2595
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2596
- {
2597
- let args;
2598
- try {
2599
- args = parseResumeFinalizeArgs(rawArgs);
2600
- }
2601
- catch (e) {
2602
- return { ok: false, error: rejectionText(e) };
2603
- }
2604
- if (!this.resumeAttemptId || this.resumeAttemptId !== args.attemptId)
2605
- return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId ?? "<none>"}, not ${args.attemptId}` };
2606
- if (!this.resumeCommitted || !this.resumeDurableCommitToken)
2607
- return { ok: false, error: `resume attempt ${args.attemptId} has no successful commit to finalize` };
2608
- if (this.resumeDurableCommitToken !== args.durableCommitToken)
2609
- return { ok: false, error: `resume attempt ${args.attemptId} durable commit token does not match` };
2610
- if (this.resumeFinalized)
2611
- return { ok: true, data: { attemptId: args.attemptId, state: "active" } };
2612
- const inventory = this.resumeInventory;
2613
- if (!inventory)
2614
- return { ok: false, error: `resume attempt ${args.attemptId} has no bound inventory` };
2615
- let inactive;
2616
- try {
2617
- inactive = this.resumeLivenessErrors(inventory, this.ep.getRoster());
2618
- }
2619
- catch (e) {
2620
- return { ok: false, error: `resume attempt ${args.attemptId} cannot verify live principals at finalize: ${rejectionText(e)}` };
2621
- }
2622
- if (inactive.length)
2623
- return { ok: false, error: `resume attempt ${args.attemptId} is not live at finalize: ${inactive.join("; ")}` };
2624
- for (const entry of this.resumeInventory?.agents ?? []) {
2625
- const managed = this.agents.get(entry.name);
2626
- if (managed)
2627
- managed.suppressCleanup = false;
2628
- }
2629
- // distsys/security CONDITIONAL @ 9e13648: the boot sweep DEFERRED every active
2630
- // slot while a resume was pending (it could not know which would be adopted). Now adoption
2631
- // is complete and `this.agents` is EXACTLY the adopted set, so re-sweep to terminalize any
2632
- // active slot the resume did NOT claim — a durable ACTIVE ORPHAN (crashed after slot->active
2633
- // before agents.set, then not in the resumed inventory). This runs while `resumeRequired` is
2634
- // still true, so no ordinary spawn can race it (beginLifecycle refuses non-resume ops), and
2635
- // it closes both the alias wedge AND the membership-gate gap (the orphan's principal enters
2636
- // retiredPrincipals, so a copied JWT is refused). Best-effort + loud: a sweep failure must
2637
- // not fail the finalize (the next non-resume boot re-drives it), but it is never swallowed.
2638
- if (this.auth && !this.userMode)
2639
- 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`));
2640
- this.resumeFinalized = true;
2641
- this.resumeRequired = false;
2642
- return { ok: true, data: { attemptId: args.attemptId, state: "active" } };
2643
- }
2644
- }
2645
- async opCommitResume(rawArgs) {
2646
- if (this.execution === "none")
2647
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2648
- {
2649
- let attemptId;
2650
- try {
2651
- attemptId = parseResumeCommitArgs(rawArgs).attemptId;
2652
- }
2653
- catch (e) {
2654
- return { ok: false, error: rejectionText(e) };
2655
- }
2656
- if (!this.resumeAttemptId || this.resumeAttemptId !== attemptId)
2657
- return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId ?? "<none>"}, not ${attemptId}` };
2658
- if (this.resumeCommitted)
2659
- return {
2660
- ok: true,
2661
- data: {
2662
- attemptId,
2663
- state: this.resumeFinalized ? "active" : "awaitingFinalize",
2664
- durableCommitToken: this.resumeDurableCommitToken,
2665
- },
2666
- };
2667
- if (this.resumeCommitTask)
2668
- return this.resumeCommitTask;
2669
- const task = this.commitResumeActivation(attemptId);
2670
- this.resumeCommitTask = task;
2671
- try {
2672
- return await task;
2673
- }
2674
- finally {
2675
- if (this.resumeCommitTask === task)
2676
- this.resumeCommitTask = undefined;
2677
- }
2678
- }
2679
- }
2680
- async opResumePreserved(rawArgs) {
2681
- if (this.execution === "none")
2682
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2683
- {
2684
- try {
2685
- const args = parseResumeControlArgs(rawArgs);
2686
- const inventoryDigest = createHash("sha256").update(JSON.stringify(args.inventory)).digest("hex");
2687
- if (!this.resumeAttemptId)
2688
- return { ok: false, error: "resumePreserved requires a manager started with --resume-attempt" };
2689
- if (this.resumeAttemptId !== args.attemptId)
2690
- return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId}, not ${args.attemptId}` };
2691
- if (this.resumeInventoryDigest && this.resumeInventoryDigest !== inventoryDigest)
2692
- return { ok: false, error: `resume attempt ${args.attemptId} is already bound to a different inventory` };
2693
- if (!this.resumeInventoryDigest) {
2694
- this.resumeInventoryDigest = inventoryDigest;
2695
- this.resumeInventory = args.inventory;
2696
- }
2697
- if (!this.resumeTask && !this.resumeResult) {
2698
- this.resumeTask = this.resumePreserved(args.inventory).then((result) => {
2699
- if (result.ok || this.resumedAgentNames.size > 0)
2700
- this.resumeResult = result;
2701
- return result;
2702
- }).finally(() => {
2703
- this.resumeTask = undefined;
2704
- });
2705
- }
2706
- const result = this.resumeResult ?? await this.resumeTask;
2707
- const data = { attemptId: args.attemptId, state: result.ok ? "awaitingCommit" : "degraded", ...result };
2708
- return result.ok
2709
- ? { ok: true, data }
2710
- : { ok: false, data, error: result.error ?? "retained-agent resume failed" };
2711
- }
2712
- catch (e) {
2713
- return { ok: false, error: rejectionText(e) };
2714
- }
2715
- }
2716
- }
2717
- async opPreservationCtl(op, rawArgs) {
2718
- if (this.execution === "none")
2719
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2720
- if (this.resumeRequired)
2721
- return { ok: false, error: this.maintenanceError() };
2722
- const attemptId = String(rawArgs?.attemptId ?? "").trim();
2723
- if (!attemptId)
2724
- return { ok: false, error: `${op} requires attemptId` };
2725
- try {
2726
- if (op === "abortPreservation") {
2727
- this.abortPreservation(attemptId);
2728
- return { ok: true, data: { attemptId, state: "active" } };
2729
- }
2730
- const result = op === "preparePreservation"
2731
- ? await this.preparePreservation(attemptId)
2732
- : await this.commitPreservation(attemptId);
2733
- return result.ok
2734
- ? { ok: true, data: result }
2735
- : {
2736
- ok: false,
2737
- data: result,
2738
- error: `preservation incomplete: ${result.failures.map((f) => `${f.name}: ${f.error}`).join("; ")}`,
2739
- };
2740
- }
2741
- catch (e) {
2742
- return { ok: false, error: rejectionText(e) };
2743
- }
2744
- }
2745
- /** {@link CommandDispatch.admitControl}. */
2746
- admitControl(...args) { return this.commandDispatch.admitControl(...args); }
2747
- /** Run one v0.4 service-command handler through the SHARED admission chokepoint
2748
- * ({@link admitControl}) on the broker-authenticated caller principal, mapping the two fences
2749
- * onto the §13.3 catalog: maintenance/resume → `unavailable`, membership →
2750
- * `permission-denied`. The serve boundary publishes the structured error reply. */
2751
- async serveGated(ctx, fn) {
2752
- const caller = principalKey(ctx.subject.caller.owner, ctx.subject.caller.actor).key;
2753
- const admission = this.admitControl(caller);
2754
- // Both fences refuse before the handler runs, so nothing ran (SPEC 13.3).
2755
- if (admission.refusal !== undefined)
2756
- throw new EpEnvelopeError(admission.fence === "membership" ? "permission-denied" : "unavailable", admission.refusal, undefined, "not-executed");
2757
- try {
2758
- return await fn();
2759
- }
2760
- finally {
2761
- admission.release();
1029
+ finally {
1030
+ admission.release();
2762
1031
  }
2763
1032
  }
2764
1033
  /** `status` only: {@link serveGated}, except that a fully preserved manager, and an active one
@@ -2932,41 +1201,6 @@ export class Manager {
2932
1201
  }
2933
1202
  /** {@link CommandDispatch.managerServiceDefs}. */
2934
1203
  managerServiceDefs(...args) { return this.commandDispatch.managerServiceDefs(...args); }
2935
- async commitResumeActivation(attemptId) {
2936
- if (!this.resumeAwaitingCommit || !this.resumeResult?.ok)
2937
- return { ok: false, error: `resume attempt ${attemptId} has no successful activation to commit` };
2938
- const inventory = this.resumeInventory;
2939
- if (!inventory)
2940
- return { ok: false, error: `resume attempt ${attemptId} has no bound inventory` };
2941
- const authority = await Promise.all(inventory.agents.map(async (entry) => {
2942
- try {
2943
- await this.validateRetainedAuthority(entry);
2944
- return undefined;
2945
- }
2946
- catch (e) {
2947
- return `${entry.name}: ${rejectionText(e)}`;
2948
- }
2949
- }));
2950
- const drift = authority.filter((error) => error !== undefined);
2951
- if (drift.length)
2952
- return { ok: false, error: `resume attempt ${attemptId} retained authority changed before commit: ${drift.join("; ")}` };
2953
- let inactive;
2954
- try {
2955
- inactive = this.resumeLivenessErrors(inventory, this.ep.getRoster());
2956
- }
2957
- catch (e) {
2958
- return { ok: false, error: `resume attempt ${attemptId} cannot verify live principals: ${rejectionText(e)}` };
2959
- }
2960
- if (inactive.length)
2961
- return { ok: false, error: `resume attempt ${attemptId} is not live at commit: ${inactive.join("; ")}` };
2962
- this.resumeAwaitingCommit = false;
2963
- this.resumeCommitted = true;
2964
- this.resumeDurableCommitToken ??= randomBytes(32).toString("hex");
2965
- return {
2966
- ok: true,
2967
- data: { attemptId, state: "awaitingFinalize", durableCommitToken: this.resumeDurableCommitToken },
2968
- };
2969
- }
2970
1204
  /** Collapsed despawn/attach authorization (P4b). The caller already reached the command's ep
2971
1205
  * row (cred-gated: owner-mode rows via the spawn capability, any-mode rows only in admin
2972
1206
  * instruments). With admin=true (any-mode) any named target is allowed (operator). Otherwise
@@ -3003,55 +1237,6 @@ export class Manager {
3003
1237
  }
3004
1238
  /** The wire principal of a managed agent: {@link managedPrincipal}. */
3005
1239
  managedPrincipal(a) { return managedPrincipal(a); }
3006
- resumeLivenessErrors(inventory, roster) {
3007
- const inactive = [];
3008
- const expectedNames = new Set(inventory.agents.map((entry) => entry.name));
3009
- for (const name of this.resumedAgentNames)
3010
- if (!expectedNames.has(name))
3011
- inactive.push(`${name} is not part of the bound inventory`);
3012
- for (const entry of inventory.agents) {
3013
- const managed = this.agents.get(entry.name);
3014
- if (!managed) {
3015
- inactive.push(`${entry.name} is no longer managed`);
3016
- continue;
3017
- }
3018
- const expectedId = entry.identity.mode === "user"
3019
- ? principalKey(entry.identity.owner, entry.identity.actor).key
3020
- : entry.identity.id;
3021
- const expectedPrincipal = entry.identity.mode === "user"
3022
- ? expectedId
3023
- : principalKey(DEV_OWNER, entry.identity.id).key;
3024
- if (managed.id !== expectedId || this.managedPrincipal(managed) !== expectedPrincipal) {
3025
- inactive.push(`${entry.name} no longer holds retained principal ${expectedPrincipal}`);
3026
- continue;
3027
- }
3028
- // The late paths (commit/finalize) must prove the SAME incarnation the incarnation-exact
3029
- // readiness fence proved (§13.1): a principal-only match lets a wrong/absent-uid presence under
3030
- // the reused alias satisfy commit/finalize after a readiness timeout, undoing the fence.
3031
- if (managed.lifecycleUid !== entry.identity.lifecycleUid) {
3032
- inactive.push(`${entry.name} manager metadata incarnation ${managed.lifecycleUid} drifted from the inventory's ${entry.identity.lifecycleUid}`);
3033
- continue;
3034
- }
3035
- if (managed.handle.name !== entry.name || managed.handle.kind !== entry.launch.runtime) {
3036
- inactive.push(`${entry.name} is not attached to its exact retained ${entry.launch.runtime} handle`);
3037
- continue;
3038
- }
3039
- try {
3040
- if (managed.handle.status() !== "running") {
3041
- inactive.push(`${entry.name} runtime is not running`);
3042
- continue;
3043
- }
3044
- }
3045
- catch (e) {
3046
- inactive.push(`${entry.name} runtime status failed: ${rejectionText(e)}`);
3047
- continue;
3048
- }
3049
- if (!roster.some((presence) => presence.card.id === expectedPrincipal && presence.card.name === entry.name && presence.status !== "offline" &&
3050
- presence.lifecycleUid === entry.identity.lifecycleUid))
3051
- inactive.push(`${entry.name} incarnation ${entry.identity.lifecycleUid} (principal ${expectedPrincipal}) is not exactly present`);
3052
- }
3053
- return inactive;
3054
- }
3055
1240
  /** {@link CommandDispatch.opStopSelf}. */
3056
1241
  opStopSelf(...args) { return this.commandDispatch.opStopSelf(...args); }
3057
1242
  // Plane-3 durable join/leave/list ops moved OFF the manager onto the server-side delivery daemon's
@@ -3183,163 +1368,17 @@ export class Manager {
3183
1368
  async waitForPresence(name, timeoutMs = 30_000) {
3184
1369
  return this.seatLaunch.waitForPresence(name, timeoutMs);
3185
1370
  }
3186
- /** Parse a served `spawn` request into {@link StartAgentOpts}. The compiled spawn input contract
3187
- * is the shape check: it already refused a non-mapping `launchOptions`, a `supervise` that is not
3188
- * the closed `{ restarts, windowMs }` pair, and a list on `subscribe`, `allowSubscribe`,
3189
- * `allowPublish`, `shareTools`, `join` or `callerAcl` that is not an array of strings. This reads
3190
- * those fields as admitted, the way it reads the string fields. The connector still validates the
3191
- * launch-option keys, and `startAgent` still refuses a supervise budget the seat record would not
3192
- * take. `once` is shape-checked by that same contract. Its omitted `deadlineMs` takes the default
3193
- * here, and a deadline past the scheduler's last instant is refused here, which the schema does
3194
- * not express. */
3195
- opStart(args, caller, admin, hooks, route = "inst", authenticatedCaller, served) {
3196
- const supervise = args.supervise;
3197
- let once;
3198
- if (args.once !== undefined) {
3199
- const rec = args.once;
3200
- // The default is applied here, so every caller of the wire gets the same one.
3201
- const d = rec.deadlineMs ?? ONCE_DEFAULT_DEADLINE_MS;
3202
- if (d !== -1 && (typeof d !== "number" || !Number.isSafeInteger(d) || d < 1 || Date.now() + d > MAX_SCHEDULE_MS))
3203
- return Promise.resolve({ ok: false, error: "once.deadlineMs: expected -1 (no deadline) or a positive whole number of milliseconds that ends by the deadline scheduler's last instant (the end of year 9999)" });
3204
- once = { deadlineMs: d === -1 ? undefined : d };
3205
- }
3206
- const callerAcl = args.callerAcl;
3207
- // #373: the event-plane admission gate. `startAgent` resolves `eventsRequired || opts.events
3208
- // !== false`, so omission ARMS the plane — a gate on the explicit bit alone is bypassed by
3209
- // omitting it. The gate is on the DECISION, and it runs before connector resolution and
3210
- // before `startAgent` (which mints credentials), so a refusal provisions nothing.
3211
- if (args.eventPayloads !== undefined && typeof args.eventPayloads !== "boolean")
3212
- return Promise.resolve({ ok: false, error: "eventPayloads must be a boolean" });
3213
- const requestedEvents = typeof args.events === "boolean" ? args.events : undefined;
3214
- let eventsNotice;
3215
- let events = requestedEvents;
3216
- // Imperative spawns have no payload-selected owner. Local provisioning derives it from
3217
- // the authenticated u_-owner caller; hosted enrollment fixes it to the manager's owner.
3218
- // Match the same owner-domain boundary as authorizeNamed, without treating the spawn's
3219
- // spawner relation as authority over a different owner's session.
3220
- const callerOwner = parsePrincipalKey(caller)?.owner;
3221
- const childOwner = this.remoteAuthority?.owner ?? (callerOwner?.startsWith("u_") ? callerOwner : undefined);
3222
- const ownsChild = this.userMode && callerOwner !== undefined && callerOwner === childOwner;
3223
- if (!admin && !ownsChild) {
3224
- if (requestedEvents === true)
3225
- return Promise.resolve({
3226
- ok: false,
3227
- error: `spawn is operator reach; the caller's current ledger grant does not carry "admin" (SPEC 13.2): events: arming the event plane needs the admin tier`,
3228
- });
3229
- if (this.eventsRequired)
3230
- return Promise.resolve({
3231
- ok: false,
3232
- error: `spawn is operator reach; the caller's current ledger grant does not carry "admin" (SPEC 13.2): space "${this.space}" requires the event plane by registration policy, which cannot be met without the admin tier`,
3233
- });
3234
- // Omission arms by default in startAgent; serve it DISARMED and say so (never a silent
3235
- // downgrade). An explicit `false` is already the opt-out — served as-is, no notice.
3236
- if (requestedEvents === undefined) {
3237
- events = false;
3238
- eventsNotice = `event plane not armed: arming it on spawn needs the admin tier; the spawn was served with events: false`;
3239
- }
3240
- }
3241
- return this.startAgent({
3242
- name: String(args.name ?? "").trim(),
3243
- agent: args.agent,
3244
- defaultAgent: args.defaultAgent,
3245
- role: args.role,
3246
- config: args.config,
3247
- identity: args.identity,
3248
- // Passed as sent: spawnPersona validates the record, the one place every door reads it.
3249
- persona: args.persona,
3250
- ...(typeof args.runId === "string" ? { runId: args.runId } : {}),
3251
- model: args.model,
3252
- variant: args.variant,
3253
- launchOptions: args.launchOptions,
3254
- resume: args.resume,
3255
- resumeClaim: args.resumeClaim,
3256
- resumeAgent: args.resumeAgent,
3257
- events,
3258
- eventPayloads: args.eventPayloads,
3259
- eventsNotice,
3260
- cwd: args.cwd,
3261
- prompt: args.prompt,
3262
- subscribe: args.subscribe,
3263
- allowSubscribe: args.allowSubscribe,
3264
- allowPublish: args.allowPublish,
3265
- join: args.join,
3266
- callerAcl,
3267
- shareTools: args.shareTools,
3268
- ...(supervise !== undefined ? { supervise } : {}),
3269
- ...(once !== undefined ? { once } : {}),
3270
- ...(typeof args.runtime === "string" ? { runtime: args.runtime.trim() } : {}),
3271
- route,
3272
- ...(served !== undefined ? { served } : {}),
3273
- }, caller, hooks, authenticatedCaller);
3274
- }
1371
+ /** {@link StartDoors.opStart}. */
1372
+ opStart(...args) { return this.startDoorsComponent.opStart(...args); }
3275
1373
  listSpawnDirectory(args) { return this.seatLaunch.listSpawnDirectory(args); }
3276
1374
  /** {@link SeatLaunch.resolveSpawnCwd}. */
3277
1375
  resolveSpawnCwd(value) { return this.seatLaunch.resolveSpawnCwd(value); }
3278
- /** Resolve a connector by agent type. Library composition (installedExtensions off) → a registry
3279
- * hit, exactly as before (the composition root imported what it wants). The published binary gates
3280
- * on MANIFEST membership FIRST — so a live `cotal ext remove` is honored even though the registry
3281
- * still holds a connector imported earlier this session — then returns the registry hit or lazily
3282
- * imports the providing package (transactional + single-flight, via the workspace primitive).
3283
- * The captured Manager generation is checked for first-party providers under that lock,
3284
- * including providers already present in the registry.
3285
- * Fail-loud with an install hint; no fallback. */
3286
- async resolveConnector(name) {
3287
- if (!this.installedExtensions)
3288
- return registry.resolve("connector", name);
3289
- if (!manifestExtensionNames("connector").includes(name))
3290
- throw new Error(connectorInstallHint(name));
3291
- return materializeFromManifest({ kind: "connector", name }, { hint: (ref) => connectorInstallHint(ref.name), expectedGeneration: this.expectedConnectorGeneration });
3292
- }
1376
+ /** {@link HarnessResolution.resolveConnector}. */
1377
+ resolveConnector(...args) { return this.harnessResolutionComponent.resolveConnector(...args); }
3293
1378
  /** {@link SeatLaunch.connectorNames}. */
3294
1379
  connectorNames() { return this.seatLaunch.connectorNames(); }
3295
- /** Resolve every installed/registered connector's declared harness binaries before the manager
3296
- * reports ready. A missing harness degrades only that connector, never unrelated lifecycle work:
3297
- * boot continues, names it once start completes and records it on both manager status surfaces. */
3298
- async inspectConnectorsAtBoot() {
3299
- this.bootNotes = [];
3300
- if (this.execution === "none") {
3301
- this.connectorStatuses = [];
3302
- return;
3303
- }
3304
- const rows = [];
3305
- let declared;
3306
- if (this.installedExtensions) {
3307
- try {
3308
- declared = loadExtensionsManifest().extensions.flatMap((ext) => extensionConnectors(ext).map((connector) => ({ ...connector, pkg: ext.pkg })));
3309
- }
3310
- catch (error) {
3311
- const reason = rejectionText(error);
3312
- this.bootNotes.push(`! manager boot: connector inventory unavailable - ${reason}`);
3313
- this.connectorStatuses = [{ agent: "(inventory)", state: "unavailable", binaries: {}, eventPlane: false, reason }];
3314
- this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
3315
- return;
3316
- }
3317
- }
3318
- else {
3319
- declared = registry.all("connector").map((connector) => ({
3320
- name: connector.name,
3321
- requires: connector.requires ?? [],
3322
- eventPlane: connector.eventChannel !== undefined,
3323
- }));
3324
- }
3325
- this.connectorRequirements = new Map(declared.map(({ name, requires, pkg }) => [name, {
3326
- requires, needsClaudeWake: !!this.machineSetupCommand && name === "claude" && pkg === OFFICIAL_CONNECTORS.claude,
3327
- }]));
3328
- for (const { name, requires, eventPlane } of declared) {
3329
- const { binaries, reason: missing } = resolveHarness(name, requires);
3330
- const reason = missing ?? (this.connectorRequirements.get(name)?.needsClaudeWake ? await this.prepareClaudeWake() : undefined);
3331
- if (reason) {
3332
- rows.push({ agent: name, state: "unavailable", binaries, eventPlane, reason });
3333
- this.bootNotes.push(`! manager boot: connector ${name} unavailable - ${reason}`);
3334
- }
3335
- else {
3336
- rows.push({ agent: name, state: "available", binaries, eventPlane });
3337
- }
3338
- }
3339
- this.connectorStatuses = rows.sort((a, b) => a.agent.localeCompare(b.agent));
3340
- if (!this.classSpawnEnabled())
3341
- this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
3342
- }
1380
+ /** {@link ConnectorInventory.inspectConnectorsAtBoot}. */
1381
+ inspectConnectorsAtBoot(...args) { return this.connectorInventoryComponent.inspectConnectorsAtBoot(...args); }
3343
1382
  /** Install and verify the hosted Claude wake channel, or report the cause and remedy. */
3344
1383
  async prepareClaudeWake() {
3345
1384
  try {
@@ -3409,218 +1448,22 @@ export class Manager {
3409
1448
  /** {@link SeatLaunch.classSpawnEnabled}. */
3410
1449
  classSpawnEnabled() { return this.seatLaunch.classSpawnEnabled(); }
3411
1450
  omitClassCommands() { return this.seatLaunch.omitClassCommands(); }
3412
- /** The harness binaries a managed launch runs, as boot resolved them, or the refusal naming what is
3413
- * missing. Spawn, resume and the model catalog all take it, so a seat launches from the same files
3414
- * whichever path starts it and the catalog never disagrees with a launch about whether the harness
3415
- * is there. Callers recheck unavailable rows first; available rows retain their resolved files.
3416
- * A connector registered after boot has no inventory row and is checked on PATH now. */
3417
- launchHarness(connector) {
3418
- const row = this.connectorStatuses.find((status) => status.agent === connector.name);
3419
- if (row?.state === "unavailable")
3420
- return { refusal: row.reason ?? `${connector.name} harness is unavailable` };
3421
- if (row)
3422
- return { binaries: row.binaries };
3423
- const { reason } = resolveHarness(connector.name, connector.requires ?? []);
3424
- return reason ? { refusal: reason } : {};
3425
- }
3426
- /** The launch fields the host supplies rather than the seat. Spawn and resume both take them from
3427
- * here, so a resumed seat launches under the same host policy, `eventsRequired` included, as the
3428
- * same seat spawned fresh. The caller passes the cotal config it judged the launch by, so the
3429
- * servers and env allowlist come from the contents its checks read. */
3430
- hostLaunchFields(cotalConfig, agent, shareTools, harness) {
3431
- return {
3432
- space: this.space,
3433
- servers: this.servers,
3434
- // Declared overrides plus the connector's native default, unless this spawn explicitly
3435
- // restricts sharing. An empty selection is deliberate isolation, not the default.
3436
- mcpServers: connectorServers(cotalConfig, agent, shareTools),
3437
- mcpServersExclusive: shareTools !== undefined,
3438
- // The operator's spawn-env policy travels the same route: absent means no extras (the OS
3439
- // allow-list + operator knobs + connector-declared inputs), present means those names too.
3440
- // A connector never reads the config itself.
3441
- envAllow: spawnEnvAllow(cotalConfig),
3442
- resolvedBinaries: harness.binaries,
3443
- eventsRequired: this.eventsRequired,
3444
- ...(this.eventPayloadsWithheld ? { eventPayloads: false } : {}),
3445
- // So a connector that keeps per-agent local state can root it at the workspace, not the
3446
- // (possibly per-agent) launch cwd.
3447
- workspaceRoot: this.workspaceRoot,
3448
- };
3449
- }
3450
- /** The refusal for a launch choice the connector cannot honour. Spawn and resume both ask before
3451
- * a seat's launch is built, so a rule changed here holds on both paths. */
3452
- capabilityRefusal(connector, launch) {
3453
- if (launch.variant && !connector.supportsModelVariant)
3454
- return `${connector.name} connector does not support model variants (variant)`;
3455
- if (launch.prompt !== undefined && !connector.supportsPrompt)
3456
- return `${connector.name} connector does not support an initial prompt (prompt)`;
3457
- if (launch.exact && (!connector.supportsSessionReopen || !connector.supportsSessionContinuation))
3458
- return `${connector.name} connector does not support exact session continuity (continuity: exact)`;
3459
- return undefined;
3460
- }
1451
+ /** {@link HarnessResolution.launchHarness}. */
1452
+ launchHarness(...args) { return this.harnessResolutionComponent.launchHarness(...args); }
1453
+ /** {@link HarnessResolution.hostLaunchFields}. */
1454
+ hostLaunchFields(...args) { return this.harnessResolutionComponent.hostLaunchFields(...args); }
1455
+ /** {@link HarnessResolution.capabilityRefusal}. */
1456
+ capabilityRefusal(...args) { return this.harnessResolutionComponent.capabilityRefusal(...args); }
3461
1457
  /** {@link SeatLaunch.onceRefusal}. */
3462
1458
  onceRefusal(connector, runtime, launch, spawner, hooks) { return this.seatLaunch.onceRefusal(connector, runtime, launch, spawner, hooks); }
3463
- /** The refusal for an event-plane choice the registration policy or the connector cannot meet.
3464
- * Spawn and resume both ask before a seat's launch is built, so a seat retained without the
3465
- * plane cannot come back on a space that now requires it. An absent choice arms supported planes. */
3466
- eventsRefusal(connector, events) {
3467
- if (this.eventsRequired && events === false)
3468
- return `space "${this.space}" requires the event plane by registration policy; --no-events (events: false on the start op) is not allowed`;
3469
- if ((this.eventsRequired || events === true) && !connector.eventChannel)
3470
- return this.eventsRequired
3471
- ? `space "${this.space}" requires the event plane by registration policy, but connector "${connector.name}" does not publish one`
3472
- : `connector "${connector.name}" does not publish an AG-UI event plane; omit --events to launch it without one`;
3473
- return undefined;
3474
- }
3475
- /** Return connector-provided model catalogs for selector UIs. Optional by connector: a host with no
3476
- * local model-list API reports `supported:false` rather than blocking the manager. A connector that
3477
- * fails to import shows an `error:` row (from manifest enumeration) and never blocks the others. */
3478
- async opModels(args) {
3479
- if (this.execution === "none")
3480
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
3481
- const requested = String(args.agent ?? "").trim();
3482
- const refresh = args.refresh === true;
3483
- const one = async (connector) => {
3484
- await this.refreshUnavailableConnectors(connector.name, true);
3485
- const harness = this.launchHarness(connector);
3486
- if (!connector.listModels)
3487
- return { agent: connector.name, supported: false, models: [] };
3488
- if ("refusal" in harness)
3489
- return { agent: connector.name, supported: true, models: [], error: harness.refusal };
3490
- try {
3491
- const catalog = await connector.listModels({ refresh, resolvedBinaries: harness.binaries });
3492
- return { agent: connector.name, supported: catalog.unavailable === undefined, ...catalog };
3493
- }
3494
- catch (e) {
3495
- return { agent: connector.name, supported: true, models: [], error: rejectionText(e) };
3496
- }
3497
- };
3498
- if (requested) {
3499
- let connector;
3500
- try {
3501
- connector = await this.resolveConnector(requested);
3502
- }
3503
- catch (e) {
3504
- return { ok: false, error: rejectionText(e) };
3505
- }
3506
- const result = await one(connector);
3507
- return result.error ? { ok: false, error: result.error } : { ok: true, data: result };
3508
- }
3509
- // Enumerate from the manifest (published binary) so a connector that fails to import still gets
3510
- // a row — `registry.all` can't list one that never registered. Each resolves lazily; an import
3511
- // failure becomes an `error:` catalog row and never blocks the healthy ones.
3512
- const catalogs = await Promise.all(this.connectorNames().map(async (name) => {
3513
- let connector;
3514
- try {
3515
- connector = await this.resolveConnector(name);
3516
- }
3517
- catch (e) {
3518
- return { agent: name, supported: false, models: [], error: rejectionText(e) };
3519
- }
3520
- return one(connector);
3521
- }));
3522
- return { ok: true, data: catalogs };
3523
- }
3524
- /** The owner-domain bound on `ps`/`status` metadata: on a USER mesh, a privileged-tier caller
3525
- * sees only agents under its OWN subject-pinned owner. Two ways to see ALL owners: the admin
3526
- * TIER (operator), or a fresh ledger `admin` SCOPE on the caller's row — the SAME authority that
3527
- * lets `stop`/`attach` reach cross-owner agents ({@link authorizeNamedControl}). Without this the
3528
- * two surfaces disagree: an admin operator could cross-owner stop an agent it could not list.
3529
- * Read fresh so a revoked admin loses visibility on its next call; a read failure and an
3530
- * unparseable caller both fall closed (own-owner / matches-nothing). Static meshes are unbounded. */
3531
- async psOwnerFilter(caller, admin) {
3532
- if (!this.userMode || admin)
3533
- return undefined;
3534
- if (this.remoteAuthority)
3535
- return (await this.epAdminReach(caller)) ? undefined : caller.owner;
3536
- try {
3537
- const scope = await resolveAuthProvider().actorScope({
3538
- dir: userAuthStateDir(this.workspaceRoot, this.space),
3539
- owner: caller.owner,
3540
- actor: caller.actor,
3541
- });
3542
- if (scope?.includes("admin"))
3543
- return undefined;
3544
- }
3545
- catch {
3546
- /* unreadable ledger authorizes nothing extra: fall through to the own-owner bound */
3547
- }
3548
- return caller.owner;
3549
- }
3550
- /** Boot one resolved agent from a mesh-manifest launch spec, for `cotal spawn -f` onto a RUNNING
3551
- * manager. The request carries `{ runId, name }` — plus, for a deploy from another checkout or
3552
- * host, the resolved `spec` itself inline (validated as untrusted input and persisted under THIS
3553
- * manager's `.cotal/run/` first) — NEVER a path: the manager derives + validates
3554
- * `.cotal/run/<runId>.json` itself ({@link launchSpecForRun} — token-safe id, no-follow,
3555
- * `loadLaunchSpec`'s untrusted-input + `validateLaunchPolicy` contract), materializes the named
3556
- * agent's transient persona, and spawns via the same `startAgent({ resolved })` path as
3557
- * `supervise --launch`. The reply is enriched for the ownership ledger: the SPAWNED
3558
- * (collision-numbered) name + nkey id creds are filed under, plus the manifest `requested` name,
3559
- * `runId`, and resolved `hash`. USER mesh: a privileged-tier launch is owner-equality-authorized
3560
- * (spec owner === caller owner) before any side effect; the admin tier keeps operator behavior. */
3561
- async opLaunch(args, caller, admin, hooks, route = "inst") {
3562
- if (this.execution === "none")
3563
- return { ok: false, error: this.executionRefusal() };
3564
- const runId = String(args.runId ?? "").trim();
3565
- const name = String(args.name ?? "").trim();
3566
- if (!runId || !name)
3567
- return { ok: false, error: "launch requires runId + name" };
3568
- let spec;
3569
- if (args.spec !== undefined) {
3570
- // REMOTE deploy: the caller pushes the resolved spec inline over the control plane instead of
3571
- // sharing this checkout's disk. Same untrusted-input contract as the file path (strict schema,
3572
- // safe names, policy re-validation), then persisted under OUR `.cotal/run/<runId>.json` so
3573
- // stale-restart and retained resume read the same on-disk source either way. Still never a
3574
- // path: the payload is the spec itself, and where it lands is derived here.
3575
- try {
3576
- spec = parseLaunchSpec(args.spec, `inline launch spec (run ${runId})`);
3577
- if (spec.runId !== runId)
3578
- return { ok: false, error: `inline launch spec runId "${spec.runId}" does not match requested "${runId}"` };
3579
- hooks?.onEffect?.();
3580
- persistLaunchSpec(this.workspaceRoot, spec);
3581
- }
3582
- catch (e) {
3583
- return { ok: false, error: rejectionText(e) };
3584
- }
3585
- }
3586
- else {
3587
- try {
3588
- spec = launchSpecForRun(this.workspaceRoot, runId);
3589
- }
3590
- catch (e) {
3591
- return { ok: false, error: rejectionText(e) };
3592
- }
3593
- }
3594
- const la = spec.agents.find((a) => a.name === name);
3595
- if (!la)
3596
- return { ok: false, error: `no agent "${name}" in launch spec for run ${runId}` };
3597
- // USER mesh: a manifest launch runs under the spec's apply-time owner, never the ctl caller —
3598
- // fail loud on a spec without one rather than guess (core `MeshLaunchSpec.owner`).
3599
- if (this.userMode && !spec.owner)
3600
- return { ok: false, error: `user-auth space "${this.space}": launch spec for run ${runId} carries no owner - re-apply the manifest as a logged-in operator` };
3601
- if (this.userMode) {
3602
- // Privileged-tier user-mode launch: owner-equality (spec owner === caller owner), decided by
3603
- // the pure policy BEFORE materializePersona or any other side effect, so a denied
3604
- // cross-owner launch writes nothing. Admin tier passes through it unchanged.
3605
- const denied = authorizeLaunch({ specOwner: spec.owner, caller, admin, runId });
3606
- if (denied)
3607
- return { ok: false, error: denied };
3608
- }
3609
- let configPath;
3610
- try {
3611
- hooks?.onEffect?.();
3612
- configPath = materializePersona(this.workspaceRoot, runId, la);
3613
- }
3614
- catch (e) {
3615
- return { ok: false, error: rejectionText(e) };
3616
- }
3617
- const reply = await this.startAgent({ ...launchAgentToStartOpts(la, configPath, spec.owner, runId), route }, caller, hooks);
3618
- if (reply.ok)
3619
- // `data.name` stays the spawned (numbered) identity — what creds are filed under and the ledger
3620
- // keys on; `requested`/`runId`/`hash` give the CLI the manifest name + drift hash for the ledger.
3621
- reply.data = { ...reply.data, requested: la.name, runId, hash: la.hash, newlyStarted: true };
3622
- return reply;
3623
- }
1459
+ /** {@link HarnessResolution.eventsRefusal}. */
1460
+ eventsRefusal(...args) { return this.harnessResolutionComponent.eventsRefusal(...args); }
1461
+ /** {@link StatusAndModels.opModels}. */
1462
+ opModels(...args) { return this.statusAndModelsComponent.opModels(...args); }
1463
+ /** {@link StatusAndModels.psOwnerFilter}. */
1464
+ psOwnerFilter(...args) { return this.statusAndModelsComponent.psOwnerFilter(...args); }
1465
+ /** {@link StartDoors.opLaunch}. */
1466
+ opLaunch(...args) { return this.startDoorsComponent.opLaunch(...args); }
3624
1467
  /** Spawn and supervise one agent. The single spawn path: both the control-plane
3625
1468
  * `start` op and declarative roster boot call this. Mints scoped creds in auth mode,
3626
1469
  * resolves the agent file, launches via the connector + runtime, and records the handle.
@@ -3650,955 +1493,21 @@ export class Manager {
3650
1493
  spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") { return this.seatLaunch.spawnBoundRefusal(bound, grant, armsEvents, door); }
3651
1494
  /** {@link SeatLaunch.managedStaticInstanceReads}. */
3652
1495
  managedStaticInstanceReads(capabilities) { return this.seatLaunch.managedStaticInstanceReads(capabilities); }
3653
- /** Preflight the whole inventory before launching its first process, then adopt each exact retained
3654
- * principal without provisioning. A later runtime launch failure is reported per-agent, but malformed
3655
- * or missing inventory material can never produce a partially resumed set. */
3656
- async resumePreserved(inventory) {
3657
- if (this.execution === "none")
3658
- return { ok: false, agents: [], error: this.executionRefusal() };
3659
- const release = this.beginLifecycle(true);
3660
- if (!release)
3661
- return { ok: false, agents: [], error: this.maintenanceError() };
3662
- const batchReservations = [];
3663
- const prepared = new Map();
3664
- try {
3665
- if (inventory.version !== "cotal-manager-resume/v2")
3666
- return { ok: false, agents: [], error: `unsupported manager resume inventory version ${String(inventory.version)}` };
3667
- if (inventory.space !== this.space)
3668
- return { ok: false, agents: [], error: `resume inventory belongs to space "${inventory.space}", not "${this.space}"` };
3669
- // The caller keeps its inventory, so it is copied before the first await: a later write to it
3670
- // cannot change what a resumed seat launches with or what the next preservation retains.
3671
- const entries = structuredClone(inventory.agents);
3672
- const seen = new Set();
3673
- const principals = new Set();
3674
- const orphans = [];
3675
- await this.ep.waitForPresenceSnapshot();
3676
- const liveRoster = this.ep.getRoster().filter((presence) => presence.status !== "offline");
3677
- const occupancy = this.occupancy();
3678
- if (occupancy.used + entries.length > MAX_AGENTS)
3679
- return { ok: false, agents: [], error: `resume inventory of ${entries.length} would exceed manager capacity (${this.occupancyText(occupancy)})` };
3680
- for (const entry of entries) {
3681
- if (seen.has(entry.name))
3682
- return { ok: false, agents: [], error: `resume inventory contains duplicate agent name "${entry.name}"` };
3683
- seen.add(entry.name);
3684
- // A manager-local retirement hold is stronger and more precise than presence. The stopped
3685
- // predecessor can remain roster-live until its TTL/offline update lands, but that stale row
3686
- // must not hide the durable teardown state the manager already owns. Refuse and re-drive the
3687
- // exact held lifecycle before consulting generic principal liveness. A confirmed terminal has
3688
- // already removed the hold, so fresh-lifecycle resume still reaches the fail-closed roster gate.
3689
- const held = this.retirement.held(entry.name);
3690
- if (held) {
3691
- void this.deprovision(held.target).catch(() => { });
3692
- return {
3693
- ok: false,
3694
- agents: [],
3695
- 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`,
3696
- };
3697
- }
3698
- let principal;
3699
- try {
3700
- principal = entry.identity.mode === "user"
3701
- ? principalKey(entry.identity.owner, entry.identity.actor).key
3702
- : principalKey(DEV_OWNER, entry.identity.id).key;
3703
- }
3704
- catch (e) {
3705
- return { ok: false, agents: [], error: `invalid retained principal for ${entry.name}: ${rejectionText(e)}` };
3706
- }
3707
- if (principals.has(principal))
3708
- return { ok: false, agents: [], error: `resume inventory contains duplicate principal "${principal}"` };
3709
- principals.add(principal);
3710
- const confirmedPredecessor = this.retirement.predecessor(entry.name);
3711
- const principalIsLive = liveRoster.some((presence) => {
3712
- if (presence.card.id !== principal)
3713
- return false;
3714
- return confirmedPredecessor === undefined ||
3715
- confirmedPredecessor.principal !== principal ||
3716
- confirmedPredecessor.lifecycleUid !== presence.lifecycleUid ||
3717
- presence.card.name !== entry.name ||
3718
- entry.identity.lifecycleUid === confirmedPredecessor.lifecycleUid;
3719
- });
3720
- if (principalIsLive) {
3721
- const orphan = await this.orphanedResumeSeat(entry, principal, liveRoster);
3722
- if (!orphan)
3723
- return { ok: false, agents: [], error: `retained principal "${principal}" is already live and this runtime cannot authoritatively adopt it` };
3724
- orphans.push({ principal, reference: orphan });
3725
- }
3726
- if (this.agents.has(entry.name) || this.namesCapacity.isReserved(entry.name))
3727
- return { ok: false, agents: [], error: `retained agent "${entry.name}" is already managed or reserved` };
3728
- }
3729
- for (const entry of entries) {
3730
- this.namesCapacity.reserve(entry.name, resumeOwner(entry));
3731
- batchReservations.push(entry.name);
3732
- }
3733
- const preflight = [];
3734
- for (const entry of entries) {
3735
- const reply = await this.resumePreservedAgent(entry, true, true, prepared);
3736
- preflight.push({ name: entry.name, reply });
3737
- }
3738
- const preflightFailures = preflight.filter(({ reply }) => !reply.ok);
3739
- if (preflightFailures.length)
3740
- return {
3741
- ok: false,
3742
- agents: preflight,
3743
- error: `${preflightFailures.length} retained agent${preflightFailures.length === 1 ? "" : "s"} failed preflight`,
3744
- };
3745
- // Only now, with the whole inventory through preflight, is an orphan reaped: a refused batch
3746
- // leaves every seat as it found it.
3747
- for (const { principal, reference } of orphans) {
3748
- const refusal = await this.reapOrphanedResumeSeat(principal, reference);
3749
- if (refusal)
3750
- return { ok: false, agents: [], error: refusal };
3751
- }
3752
- const agents = [];
3753
- for (let i = 0; i < entries.length; i++) {
3754
- const entry = entries[i];
3755
- const reply = await this.resumePreservedAgent(entry, false, true, prepared);
3756
- agents.push({ name: entry.name, reply });
3757
- if (!reply.ok) {
3758
- for (const skipped of entries.slice(i + 1))
3759
- agents.push({ name: skipped.name, reply: { ok: false, error: `not launched because ${entry.name} failed` } });
3760
- return { ok: false, agents, error: reply.error };
3761
- }
3762
- }
3763
- if (this.resumeAttemptId)
3764
- this.resumeAwaitingCommit = true;
3765
- return { ok: true, agents };
3766
- }
3767
- finally {
3768
- for (const name of batchReservations) {
3769
- this.namesCapacity.release(name);
3770
- }
3771
- // Preflight builds every launch before any child starts, so a refused batch, a failed launch,
3772
- // or the agents skipped after it leave built specs no runtime ever received.
3773
- for (const { spec, spawned } of prepared.values()) {
3774
- if (spawned)
3775
- continue;
3776
- try {
3777
- discardLaunchArtifacts(spec.artifacts);
3778
- }
3779
- catch (e) {
3780
- console.error(`! resume: ${rejectionText(e)}`);
3781
- }
3782
- }
3783
- release();
3784
- }
3785
- }
3786
- /** Re-read every retained identity input and its current authority without provisioning. This runs
3787
- * during whole-inventory preflight, immediately before each individual spawn, and at commit. */
3788
- async validateRetainedAuthority(entry) {
3789
- const referenceError = this.inventoryReferenceError(entry);
3790
- if (referenceError)
3791
- throw new Error(`retained agent ${entry.name}: ${referenceError}`);
3792
- // THE OWN-CHANNEL RULE, ON THE RESUME DOOR, and it belongs here rather than beside the launch
3793
- // because BOTH resume paths funnel through this function and neither may skip it.
3794
- //
3795
- // A resume document is admin-supplied JSON. It carries the ACLs the managed row is re-armed
3796
- // from, and `renewManagedStaticCred` re-mints the credential out of that row at half TTL, so a
3797
- // foreign event channel written into an inventory becomes a minted read on another agent's tool
3798
- // inputs and outputs one renewal later. In static mode nothing else stops it: the checks below
3799
- // pin the credential's PATH, its IDENTITY and the broker's acceptance of it, and say nothing at
3800
- // all about its ACL. User mode compares the adopted authority's ACL against the inventory's, so
3801
- // it refuses a divergence on both fields already, but it refuses it as DRIFT rather than as this
3802
- // rule, and an inventory whose record and credential agree with each other and disagree with
3803
- // this rule is exactly the document an operator would not notice.
3804
- //
3805
- // Refuses rather than strips. Silently narrowing an admin document would leave the operator
3806
- // holding a record that says one thing and a mesh that does another, and the whole reason this
3807
- // is reachable is that nobody reads the record.
3808
- {
3809
- const owner = entry.identity.mode === "user" ? entry.identity.owner : DEV_OWNER;
3810
- // The ACTOR HALF IS THE PRINCIPAL, never the display name. In user mode the row this
3811
- // document re-arms is keyed by `identity.actor` (it is what the provider adopts below and
3812
- // what every liveness check reads), and an inventory supplies `name` and `identity.actor`
3813
- // independently, so judging the channel against `name` would judge it against the half that
3814
- // does not own the plane.
3815
- const actor = entry.identity.mode === "user" ? entry.identity.actor : entry.identity.id;
3816
- const foreign = foreignEventChannels([...(entry.launch.allowSubscribe ?? []), ...(entry.launch.allowPublish ?? [])], owner, actor);
3817
- if (foreign.length)
3818
- throw new Error(`retained agent ${entry.name}: its record claims another agent's event channel ` +
3819
- `(${foreign.join(", ")}). An agent may hold its OWN event plane and no other, because that ` +
3820
- `plane carries the session's tool inputs and outputs. Remove it from the inventory and ` +
3821
- `grant the reader out of band instead: ` +
3822
- `${this.readerRemedy(owner, foreign[0])}`);
3823
- }
3824
- if (entry.identity.mode === "open") {
3825
- if (this.auth || this.userMode)
3826
- throw new Error(`retained agent ${entry.name} is open-mode but the current manager is authenticated`);
3827
- return { id: entry.identity.id };
3828
- }
3829
- if (entry.identity.mode === "static") {
3830
- if (!this.auth || this.userMode)
3831
- throw new Error(`retained agent ${entry.name} is static-auth but the current manager is not`);
3832
- // CLOSED candidate set, not an open path: the lifecycle-keyed derivation (this generation's
3833
- // layout) or the name-keyed one (a pre-split inventory being carried across the upgrade).
3834
- // Anything else is a foreign path and refused exactly as before.
3835
- const candidates = [
3836
- resolve(agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, entry.name, entry.identity.lifecycleUid).creds),
3837
- resolve(agentSecretFilePaths(this.workspaceRoot, this.space, entry.name).creds),
3838
- ];
3839
- const expected = resolve(entry.identity.credential.path);
3840
- if (!candidates.includes(expected))
3841
- throw new Error(`retained credential reference for ${entry.name} is not a manager-owned path (expected ${candidates.join(" or ")})`);
3842
- let credentialText;
3843
- try {
3844
- // The lstat guards the FS MATERIALIZATION the child will read at launch; the identity check
3845
- // runs on the store's value — the source of truth (byte-identical here, the local FS
3846
- // composition resolves the key to this same path).
3847
- const st = lstatSync(expected);
3848
- if (!st.isFile() || st.isSymbolicLink())
3849
- throw new Error("not a regular non-symlink file");
3850
- const stored = await this.secrets.get(agentSecretKeyForFile(expected, this.space));
3851
- if (stored === undefined)
3852
- throw new Error("the credential is not in the secret store");
3853
- credentialText = stored;
3854
- const actual = idFromCreds(credentialText);
3855
- if (actual !== entry.identity.id)
3856
- throw new Error(`retained credential identity ${actual} does not match inventory principal ${entry.identity.id}`);
3857
- }
3858
- catch (e) {
3859
- throw new Error(`retained credential for ${entry.name} is unusable: ${rejectionText(e)}`);
3860
- }
3861
- const accepted = await this.probeStaticCredential(credentialText);
3862
- if (!accepted.ok)
3863
- throw new Error(`retained credential for ${entry.name} is not accepted by the current broker (${accepted.reason})`);
3864
- return { id: entry.identity.id, creds: expected };
3865
- }
3866
- if (!this.userMode)
3867
- throw new Error(`retained agent ${entry.name} is user-auth but the current manager is not`);
3868
- try {
3869
- const provider = resolveAuthProvider();
3870
- // Mirror the static branch's expected-path discipline, but pin the WHOLE secret FAMILY as ONE
3871
- // unit: all three of {actorToken, sentinelCreds, health} must equal the lifecycle-keyed triple
3872
- // (this generation) OR the name-keyed triple (a pre-split inventory carried across the upgrade).
3873
- // A per-file OR-pin let a corrupt inventory MIX families (lifecycle token + legacy sentinel)
3874
- // and, worse, left `health` UNPINNED entirely — an arbitrary recorded health path flowed into
3875
- // the bearer argv and was `rmSync`'d at terminal teardown (inventory-as-delete-gadget). Pinning
3876
- // the atomic family closes both: `health` is pinned by PATH EQUALITY (never by file existence,
3877
- // so a transiently-absent health file still validates), and the store reads below key off the
3878
- // RECORDED path, so a foreign path can neither pass the pin nor address a different row.
3879
- // Both triples are derived under THIS manager's space, and the key builder is given
3880
- // `this.space` rather than reading the segment out of the recorded path: an inventory row is
3881
- // caller data, and a recorded path may not choose which tenant's material is addressed.
3882
- const lifecycleFiles = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, entry.name, entry.identity.lifecycleUid);
3883
- const legacyFiles = agentSecretFilePaths(this.workspaceRoot, this.space, entry.name);
3884
- const recordedToken = resolve(entry.identity.actorToken.path);
3885
- const recordedSentinel = resolve(entry.identity.sentinelCredential.path);
3886
- const recordedHealth = resolve(entry.identity.health.path);
3887
- const matchesFamily = (f) => recordedToken === resolve(f.actorToken) && recordedSentinel === resolve(f.sentinelCreds) && recordedHealth === resolve(f.health);
3888
- if (!matchesFamily(lifecycleFiles) && !matchesFamily(legacyFiles))
3889
- 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)`);
3890
- const secrets = this.secrets;
3891
- const actorToken = await secrets.get(agentSecretKeyForFile(recordedToken, this.space));
3892
- const sentinelCreds = await secrets.get(agentSecretKeyForFile(recordedSentinel, this.space));
3893
- if (actorToken === undefined || sentinelCreds === undefined)
3894
- throw new Error("the retained actor token / sentinel credential is not in the secret store");
3895
- const adopted = this.remoteAuthority
3896
- ? await this.remoteAuthority.validateRetainedAgent({
3897
- owner: entry.identity.owner,
3898
- actor: entry.identity.actor,
3899
- lifecycleUid: entry.identity.lifecycleUid,
3900
- actorToken,
3901
- sentinelCreds,
3902
- })
3903
- : await provider.validateRetainedAgent({
3904
- store: secrets,
3905
- dir: userAuthStateDir(this.workspaceRoot, this.space),
3906
- space: this.space,
3907
- owner: entry.identity.owner,
3908
- actor: entry.identity.actor,
3909
- actorToken,
3910
- sentinelCreds,
3911
- });
3912
- if (adopted.owner !== entry.identity.owner || adopted.actor !== entry.identity.actor)
3913
- throw new Error(`auth provider returned a replacement principal; expected ${entry.identity.owner}.${entry.identity.actor}`);
3914
- // Bind the inventory's uid to the CURRENT authority row BEFORE any spawn: a corrupt or
3915
- // admin-supplied inventory naming a different incarnation is refused at pre-effect validation,
3916
- // never left to broker-fail after the child is already running (SPEC §13.1).
3917
- if (adopted.lifecycleUid !== entry.identity.lifecycleUid)
3918
- 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)`);
3919
- if (!sameStrings(adopted.allowSubscribe, entry.launch.allowSubscribe) ||
3920
- !sameStrings(adopted.allowPublish, entry.launch.allowPublish) ||
3921
- !sameStrings(adopted.scope, entry.launch.capabilities) ||
3922
- adopted.role !== entry.role || adopted.parent !== entry.authorityParent)
3923
- throw new Error(`retained user authority for ${entry.identity.owner}.${entry.identity.actor} no longer matches the inventory`);
3924
- return {
3925
- userAuth: {
3926
- owner: entry.identity.owner,
3927
- actor: entry.identity.actor,
3928
- sentinelCredsPath: entry.identity.sentinelCredential.path,
3929
- bearerCmd: [
3930
- ...bearerEntryArgv(),
3931
- provider.agentBearerCommand,
3932
- ...(this.remoteAuthority
3933
- ? ["--exchange-url", this.remoteAuthority.agentBearerExchangeUrl]
3934
- : ["--dir", userAuthStateDir(this.workspaceRoot, this.space)]),
3935
- "--space", this.space,
3936
- "--owner", entry.identity.owner,
3937
- "--actor", entry.identity.actor,
3938
- "--token-file", entry.identity.actorToken.path,
3939
- "--health-file", entry.identity.health.path,
3940
- ],
3941
- },
3942
- };
3943
- }
3944
- catch (e) {
3945
- throw new Error(`retained user principal ${entry.identity.owner}.${entry.identity.actor} could not be reused: ${rejectionText(e)}`);
3946
- }
3947
- }
3948
- /** The seat reference behind a live retained principal, when that seat is provably one a lost
3949
- * manager of this logical instance launched for this exact incarnation. The resume binds the
3950
- * launched handle's reference to the incarnation's active slot before it waits for readiness, and
3951
- * the coordinator journals `resume-active` only after that wait, so a coordinator crash between the
3952
- * two leaves `resume-intent` behind a live seat. Undefined for everything else, which stays refused:
3953
- * another incarnation's presence, a slot another instance owns, a runtime that cannot reap the
3954
- * reference, and user or open meshes, which keep no slot. */
3955
- async orphanedResumeSeat(entry, principal, liveRoster) {
3956
- if (!this.auth || this.userMode || entry.identity.mode !== "static")
3957
- return undefined;
3958
- const runtime = this.runtimeFor(entry.launch.runtime);
3959
- if (typeof runtime.reap !== "function")
3960
- return undefined;
3961
- if (liveRoster.some((p) => p.card.id === principal && p.lifecycleUid !== entry.identity.lifecycleUid))
3962
- return undefined;
3963
- const slot = await this.readStaticReconcileSlot(entry.name);
3964
- if (slot?.phase !== "active" || slot.actor !== entry.identity.id || slot.lifecycleUid !== entry.identity.lifecycleUid)
3965
- return undefined;
3966
- if (ownedBySibling(slot, this.managerInstanceId))
3967
- return undefined;
3968
- return slot.runtime?.kind === runtime.kind ? slot.runtime : undefined;
3969
- }
3970
- /** Reap a seat {@link orphanedResumeSeat} found, then wait for its principal to leave presence so
3971
- * the relaunch's readiness cannot match the dead seat's row. Returns the refusal when the reap
3972
- * proves nothing or the principal stays live, which means another process holds it. */
3973
- async reapOrphanedResumeSeat(principal, reference) {
3974
- try {
3975
- const evidence = await requireRuntimeReap(this.runtimeFor(reference.kind), reference);
3976
- console.error(`resume: reaped orphaned seat ${reference.kind}:${reference.id} of retained principal "${principal}" (${evidence.detail})`);
3977
- }
3978
- catch (e) {
3979
- return `retained principal "${principal}" is already live and its recorded seat ${reference.kind}:${reference.id} could not be reaped: ${rejectionText(e)}`;
3980
- }
3981
- const deadline = Date.now() + ORPHAN_PRESENCE_CLEAR_MS;
3982
- while (this.ep.getRoster().some((p) => p.card.id === principal && p.status !== "offline")) {
3983
- if (Date.now() >= deadline)
3984
- 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`;
3985
- await new Promise((resolveWait) => setTimeout(resolveWait, 250));
3986
- }
3987
- return undefined;
3988
- }
3989
- /** Validate/relaunch one retained inventory entry. Called through resumePreserved so all records
3990
- * pass the same preflight before the first child is exposed, and through restartSupervisedSeat
3991
- * with the one record a crashed manager left (`supervised`). */
3992
- async resumePreservedAgent(entry, preflightOnly = false, batchReserved = false, prepared, supervised) {
3993
- if (this.execution === "none")
3994
- return { ok: false, error: this.executionRefusal() };
3995
- const release = this.beginLifecycle(batchReserved);
3996
- if (!release)
3997
- return { ok: false, error: this.maintenanceError() };
3998
- try {
3999
- if (entry.space !== this.space)
4000
- return { ok: false, error: `retained agent ${entry.name} belongs to space "${entry.space}", not "${this.space}"` };
4001
- try {
4002
- await this.loadSeatRuntime(entry.launch.runtime);
4003
- }
4004
- catch (e) {
4005
- return { ok: false, error: `retained agent ${entry.name} requires runtime "${entry.launch.runtime}", which this manager cannot resolve: ${rejectionText(e)}` };
4006
- }
4007
- if (entry.launch.runtime !== this.runtimeFor(entry.launch.runtime).kind)
4008
- return { ok: false, error: `retained agent ${entry.name} requires runtime "${entry.launch.runtime}", which this manager cannot resolve` };
4009
- const nameErr = this.nameError(entry.name);
4010
- if (nameErr)
4011
- return { ok: false, error: nameErr };
4012
- if (this.agents.has(entry.name) || (!batchReserved && this.namesCapacity.isReserved(entry.name)))
4013
- return { ok: false, error: `retained agent "${entry.name}" is already managed or reserved; same-principal resume never auto-numbers` };
4014
- const occupancy = batchReserved ? undefined : this.occupancy();
4015
- if (occupancy && occupancy.used >= MAX_AGENTS)
4016
- return { ok: false, error: `${this.capacityRefusal(occupancy)}; same-principal resume refused` };
4017
- const cached = prepared?.get(entry.name);
4018
- if (!preflightOnly && cached) {
4019
- try {
4020
- // Do not trust the earlier batch preflight across another agent's sequential readiness wait.
4021
- await this.validateRetainedAuthority(entry);
4022
- }
4023
- catch (e) {
4024
- return { ok: false, error: rejectionText(e) };
4025
- }
4026
- return this.launchPreparedResume(entry, cached, batchReserved, supervised);
4027
- }
4028
- try {
4029
- const cwd = lstatSync(entry.launch.cwd);
4030
- if (!cwd.isDirectory() || cwd.isSymbolicLink())
4031
- return { ok: false, error: `retained cwd is not a real directory: ${entry.launch.cwd}` };
4032
- }
4033
- catch (e) {
4034
- return { ok: false, error: `retained cwd unavailable: ${entry.launch.cwd} (${rejectionText(e)})` };
4035
- }
4036
- let connector;
4037
- try {
4038
- // The SAME resolver the spawn path uses. A bare `registry.resolve` here made preserve→resume
4039
- // fail for EVERY retained agent on the published binary: the resuming manager is a fresh
4040
- // process whose registry is empty (its supervise child runs with the connector seed
4041
- // skipped), so nothing is registered until something materializes it from the ext manifest.
4042
- // That is precisely what `resolveConnector` does and what every spawn path already calls.
4043
- // Resolving bare meant a preserved mesh could never come back — first-party connectors
4044
- // included, since the asymmetry is about materialization, not about which connector it is.
4045
- connector = await this.resolveConnector(entry.launch.connector);
4046
- }
4047
- catch (e) {
4048
- return { ok: false, error: rejectionText(e) };
4049
- }
4050
- await this.refreshUnavailableConnectors(connector.name, true);
4051
- const harness = this.launchHarness(connector);
4052
- if ("refusal" in harness)
4053
- return { ok: false, error: harness.refusal };
4054
- let retainedSession;
4055
- try {
4056
- retainedSession = this.retainedSessionId(entry, connector);
4057
- }
4058
- catch (error) {
4059
- return { ok: false, error: rejectionText(error) };
4060
- }
4061
- if (entry.launch.forkSource && !retainedSession && !connector.supportsResume)
4062
- return { ok: false, error: `${connector.name} connector does not support session fork (resume)` };
4063
- if (retainedSession && !connector.supportsSessionContinuation)
4064
- return { ok: false, error: `${connector.name} connector does not support exact-session continuation` };
4065
- let launchOptions;
4066
- let exact = false;
4067
- if (entry.launch.source.kind === "manifest") {
4068
- const launchSource = entry.launch.source;
4069
- if (!launchSource.runId)
4070
- return { ok: false, error: `retained manifest launch for ${entry.name} has no runId; refusing to guess a .cotal/run source` };
4071
- let spec;
4072
- try {
4073
- const source = launchSpecForRun(this.workspaceRoot, launchSource.runId);
4074
- if (source.space !== this.space)
4075
- return { ok: false, error: `retained launch spec space "${source.space}" does not match manager space "${this.space}"` };
4076
- spec = source.agents.find((a) => a.name === launchSource.requested);
4077
- }
4078
- catch (e) {
4079
- return { ok: false, error: rejectionText(e) };
4080
- }
4081
- if (!spec || spec.hash !== launchSource.hash)
4082
- return { ok: false, error: `retained manifest agent ${launchSource.requested} is missing or its hash changed; refusing same-principal resume` };
4083
- launchOptions = spec.launchOptions;
4084
- exact = spec.continuity === "exact";
4085
- }
4086
- else {
4087
- try {
4088
- launchOptions = loadAgentFile(entry.launch.source.configPath).launchOptions;
4089
- }
4090
- catch (e) {
4091
- return { ok: false, error: rejectionText(e) };
4092
- }
4093
- }
4094
- // Asked once `exact` is known: an exact seat reopens its retained session or fails, like its
4095
- // manifest launch, so the connector must honor reopenSession before the batch starts any child.
4096
- const unsupported = this.capabilityRefusal(connector, { variant: entry.launch.variant, prompt: entry.launch.prompt, exact });
4097
- if (unsupported)
4098
- return { ok: false, error: unsupported };
4099
- const eventsRefused = this.eventsRefusal(connector, entry.launch.events);
4100
- if (eventsRefused)
4101
- return { ok: false, error: eventsRefused };
4102
- let authority;
4103
- try {
4104
- authority = await this.validateRetainedAuthority(entry);
4105
- }
4106
- catch (e) {
4107
- return { ok: false, error: rejectionText(e) };
4108
- }
4109
- try {
4110
- const launchOpts = {
4111
- ...this.hostLaunchFields(loadCotalConfig(this.workspaceRoot), entry.launch.connector, entry.launch.shareTools, harness),
4112
- name: entry.name,
4113
- role: entry.role,
4114
- id: authority.id,
4115
- creds: authority.creds,
4116
- userAuth: authority.userAuth,
4117
- // Recover the ORIGINAL incarnation uid (never a fresh mint on resume): the child endpoint
4118
- // binds its lifecycle-keyed dm/dlv/chathist durables by this exact value, and its creds pin
4119
- // the same names. Omitting it here (as the pre-fix resume path did) leaves the resumed child
4120
- // with no COTAL_LIFECYCLE_UID: static/user fail the connector auth gate and open self-mints a
4121
- // fresh uid that orphans the preserved durables and never matches the readiness fence.
4122
- lifecycleUid: entry.identity.lifecycleUid,
4123
- backfillFloor: entry.backfillFloor,
4124
- acceptedToken: entry.identity.mode === "static" ? entry.identity.issued?.acceptedToken : undefined,
4125
- configPath: entry.launch.source.configPath,
4126
- model: entry.launch.model,
4127
- variant: entry.launch.variant,
4128
- launchOptions,
4129
- resume: retainedSession ? undefined : entry.launch.forkSource,
4130
- continueSession: exact ? undefined : retainedSession,
4131
- reopenSession: exact ? retainedSession : undefined,
4132
- subscribe: entry.launch.subscribe,
4133
- allowSubscribe: entry.launch.allowSubscribe,
4134
- allowPublish: entry.launch.allowPublish,
4135
- capabilities: entry.launch.capabilities,
4136
- endpoints: copyPersonaEndpoints(entry.launch.endpoints) ?? [],
4137
- events: entry.launch.events,
4138
- eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
4139
- cwd: entry.launch.cwd,
4140
- };
4141
- const spec = connector.buildLaunch(launchOpts);
4142
- spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
4143
- const value = { spec, launchOpts, ...authority, exact };
4144
- prepared?.set(entry.name, value);
4145
- if (preflightOnly)
4146
- return { ok: true, data: { name: entry.name, preflight: true } };
4147
- return this.launchPreparedResume(entry, value, batchReserved, supervised);
4148
- }
4149
- catch (e) {
4150
- return { ok: false, error: rejectionText(e) };
4151
- }
4152
- }
4153
- finally {
4154
- release();
4155
- }
4156
- }
4157
- async launchPreparedResume(entry, prepared, batchReserved, supervised) {
4158
- if (!batchReserved)
4159
- this.namesCapacity.reserve(entry.name, resumeOwner(entry));
4160
- try {
4161
- // Recover the STATIC identity's nkey seed from the adopted credential (the
4162
- // creds file embeds it) so the manager stays this incarnation's RENEWAL OWNER across a
4163
- // preserve/resume — without it the adopted cred would die loud at its TTL with no remint.
4164
- let adoptedSeed;
4165
- if (entry.identity.mode === "static") {
4166
- const stored = await this.secrets.get(agentSecretKeyForFile(resolve(entry.identity.credential.path), this.space));
4167
- // The core parser, which reads the creds format's six-dash END marker. A local pattern that
4168
- // expected five matched no real file, so every resumed seat lost its renewal.
4169
- try {
4170
- adoptedSeed = stored === undefined ? undefined : identityFromCreds(stored).seed;
4171
- }
4172
- catch {
4173
- adoptedSeed = undefined;
4174
- }
4175
- if (adoptedSeed === undefined)
4176
- console.error(`! resume ${entry.name}: the adopted credential carries no readable nkey seed - the manager cannot renew it (it dies loud at its exp)`);
4177
- }
4178
- const connector = await this.resolveConnector(entry.launch.connector);
4179
- const readinessTimeoutMs = connector.readinessTimeoutMs ?? this.readinessTimeoutMs;
4180
- if (!Number.isSafeInteger(readinessTimeoutMs) || readinessTimeoutMs <= 0)
4181
- return { ok: false, error: `connector ${connector.name} declares invalid readinessTimeoutMs ${JSON.stringify(connector.readinessTimeoutMs)}; expected a positive safe integer` };
4182
- const resumeId = entry.identity.mode === "user" ? principalKey(entry.identity.owner, entry.identity.actor).key : entry.identity.id;
4183
- const runtime = this.runtimeFor(entry.launch.runtime);
4184
- const custody = this.reserveCustody(runtime);
4185
- if (custody)
4186
- await this.recordSlotCustody({ name: entry.name, id: resumeId, lifecycleUid: entry.identity.lifecycleUid }, custody);
4187
- prepared.spawned = true;
4188
- const handle = await this.spawnCustodied(runtime, entry.name, prepared.spec, entry.launch.cwd, custody);
4189
- const managed = {
4190
- name: entry.name,
4191
- role: entry.role,
4192
- agent: entry.launch.connector,
4193
- id: resumeId,
4194
- seed: adoptedSeed,
4195
- ...(entry.identity.mode === "static" && entry.identity.issued ? { issued: entry.identity.issued } : {}),
4196
- // Recover the ORIGINAL incarnation uid the durables are keyed by (never a fresh mint on resume).
4197
- lifecycleUid: entry.identity.lifecycleUid,
4198
- // Adopt the INVENTORY's recorded family (possibly a pre-split name-keyed layout) — the
4199
- // validated paths above, so this incarnation's later teardown addresses exactly what its
4200
- // spawn materialized, never a re-derivation.
4201
- secretPaths: entry.identity.mode === "user"
4202
- ? { actorToken: entry.identity.actorToken.path, sentinelCreds: entry.identity.sentinelCredential.path, health: entry.identity.health.path }
4203
- : entry.identity.mode === "static"
4204
- ? { creds: entry.identity.credential.path }
4205
- : undefined,
4206
- userOwner: entry.identity.mode === "user" ? entry.identity.owner : undefined,
4207
- spawner: entry.spawner,
4208
- authorityParent: entry.authorityParent,
4209
- startedAt: Date.now(),
4210
- handle,
4211
- control: prepared.spec.control,
4212
- launch: {
4213
- runtime: entry.launch.runtime,
4214
- source: entry.launch.source,
4215
- cwd: entry.launch.cwd,
4216
- model: entry.launch.model,
4217
- variant: entry.launch.variant,
4218
- subscribe: entry.launch.subscribe,
4219
- allowSubscribe: entry.launch.allowSubscribe,
4220
- allowPublish: entry.launch.allowPublish,
4221
- capabilities: entry.launch.capabilities,
4222
- ...(entry.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(entry.launch.endpoints) } : {}),
4223
- events: entry.launch.events,
4224
- eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
4225
- shareTools: entry.launch.shareTools,
4226
- forkSource: entry.launch.forkSource,
4227
- ...(entry.launch.resumed ? { resumed: entry.launch.resumed } : {}),
4228
- ...(prepared.launchOpts.resume !== undefined && prepared.spec.resumeRecordPath ? { resumeRecordPath: prepared.spec.resumeRecordPath } : {}),
4229
- sessionId: entry.launch.sessionId,
4230
- },
4231
- ...(supervised
4232
- ? { restart: { opts: prepared.launchOpts, sessionStatePath: prepared.spec.sessionStatePath, crashes: supervised.crashes, recovering: false, armed: false, policy: supervised.policy } }
4233
- : prepared.spec.sessionStatePath
4234
- ? { restart: { opts: prepared.launchOpts, sessionStatePath: prepared.spec.sessionStatePath, crashes: [], recovering: false, armed: false } }
4235
- : {}),
4236
- suppressCleanup: true,
4237
- };
4238
- this.agents.set(entry.name, managed);
4239
- this.namesCapacity.placed(entry.name);
4240
- if (this.resumeAttemptId)
4241
- this.resumedAgentNames.add(entry.name);
4242
- try {
4243
- await this.recordSlotRuntime(managed);
4244
- }
4245
- catch (error) {
4246
- return await this.stopFailedResume(managed, "resume-custody-unrecorded", `${managed.name} resumed, but ${rejectionText(error)}`);
4247
- }
4248
- const readiness = await this.awaitReadiness(managed, readinessTimeoutMs, supervised ? { joinedAfter: supervised.joinedAfter } : {});
4249
- if (!readiness.ok && !readiness.uncertain)
4250
- return { ok: false, error: readiness.detail };
4251
- if (!readiness.ok) {
4252
- this.watchExit(managed);
4253
- // The restart was counted when it launched, so the record carries that crash whether or not
4254
- // the seat ever joins: a successor reads the record to decide whether another fits the budget.
4255
- if (supervised)
4256
- this.refreshSeatRecord(managed);
4257
- this.watchResumeAdoption(managed, supervised?.joinedAfter, () => this.armLateResume(managed, connector, prepared, supervised));
4258
- return { ok: false, error: readiness.detail };
4259
- }
4260
- const unbound = await this.armResumedSeat(managed, connector, prepared, supervised);
4261
- if (unbound !== undefined)
4262
- return await this.stopFailedResume(managed, "resume-session-rebind-failed", unbound);
4263
- if (!this.resumeAttemptId)
4264
- managed.suppressCleanup = false;
4265
- if (supervised)
4266
- this.refreshSeatRecord(managed);
4267
- this.watchExit(managed);
4268
- if (this.agents.get(managed.name) !== managed)
4269
- return { ok: false, error: `${managed.name} exited immediately after same-principal readiness` };
4270
- return {
4271
- ok: true,
4272
- data: { name: managed.name, role: managed.role, agent: managed.agent, id: managed.id, mode: handle.kind, resumed: true },
4273
- };
4274
- }
4275
- catch (e) {
4276
- return { ok: false, error: rejectionText(e) };
4277
- }
4278
- finally {
4279
- if (!batchReserved) {
4280
- this.namesCapacity.release(entry.name);
4281
- }
4282
- }
4283
- }
4284
- /** Arm a resumed seat's restart once it is ready, whether it joined inside the readiness window or
4285
- * after it (#4144). A supervised restart arms the way its spawn did: a connector with no session
4286
- * continuation is armed at readiness, one with it once its session is proved. Returns why the
4287
- * session could not be rebound, and the caller stops the seat. */
4288
- async armResumedSeat(managed, connector, prepared, supervised) {
4289
- if (supervised && managed.restart && !connector.supportsSessionContinuation && !prepared.exact) {
4290
- managed.restart.armed = true;
4291
- return undefined;
4292
- }
4293
- if (!managed.restart && !prepared.exact)
4294
- return undefined;
4295
- try {
4296
- await this.armSessionRecovery(managed);
4297
- // As on a manifest launch, an exact seat is recorded only at the session it asked for,
4298
- // proved over the connector's authenticated control endpoint.
4299
- if (prepared.exact && !managed.restart?.armed)
4300
- throw new Error("continuity: exact needs the connector to prove its session over an authenticated control endpoint, and it supplied none");
4301
- managed.launch.sessionId = this.readManagedSession(managed);
4302
- const asked = prepared.launchOpts.reopenSession;
4303
- if (asked !== undefined && managed.launch.sessionId !== asked)
4304
- throw new Error(`continuity: exact asked for session ${asked}, the connector bound ${managed.launch.sessionId}`);
4305
- if (prepared.exact) {
4306
- managed.continuity = { space: this.space, name: managed.name, connector: managed.agent, cwd: managed.launch.cwd };
4307
- this.recordContinuity(managed, managed.launch.sessionId);
4308
- }
4309
- return undefined;
4310
- }
4311
- catch (error) {
4312
- return `${managed.name} resumed, but its exact host session could not be rebound: ${rejectionText(error)}`;
4313
- }
4314
- }
4315
- /** A resumed seat whose readiness was uncertain gets what a ready one gets once it joins: its
4316
- * restart is armed and its record rewritten. Without this, a supervised seat restarted after a
4317
- * manager crash that joined late was retired on its next exit instead of restarted. */
4318
- async armLateResume(managed, connector, prepared, supervised) {
4319
- const current = () => this.agents.get(managed.name) === managed && !managed.terminalizing;
4320
- if (!current())
4321
- return;
4322
- const unbound = await this.armResumedSeat(managed, connector, prepared, supervised);
4323
- if (!current())
4324
- return;
4325
- if (unbound !== undefined) {
4326
- const stopped = await this.stopFailedResume(managed, "resume-session-rebind-failed", unbound);
4327
- if (!stopped.ok)
4328
- console.error(`! ${stopped.error}`);
4329
- return;
4330
- }
4331
- if (supervised)
4332
- this.refreshSeatRecord(managed);
4333
- }
4334
- /** A resumed seat keeps its retained credentials, so freeing it runs no deprovision and nothing
4335
- * would reap it: it is freed only once its exit is proved, and otherwise stays managed until it
4336
- * exits or the manager stops it. */
4337
- async stopFailedResume(managed, cause, detail) {
4338
- const refused = this.stopHandle(managed, false, cause);
4339
- const unproven = refused === undefined
4340
- ? await this.awaitHandleExit(managed.handle).then(() => undefined, rejectionText)
4341
- : `stop failed: ${refused}`;
4342
- if (unproven !== undefined) {
4343
- this.watchExit(managed);
4344
- return { ok: false, error: `${detail}; it stays managed because its stop is unproven: ${unproven}` };
4345
- }
4346
- this.freeSlot(managed, true, cause, true);
4347
- return { ok: false, error: detail };
4348
- }
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); }
4349
1502
  probeStaticCredential(creds) {
4350
1503
  return probeConnect(this.servers ?? DEFAULT_SERVER, { creds, timeoutMs: 5_000 });
4351
1504
  }
4352
- /** An uncertain resume remains non-destructive until exact-principal AND exact-incarnation presence
4353
- * arrives later, and then `adopted` runs. Same predicate as the readiness fence: a principal-only
4354
- * match would let a wrong/absent-uid presence under the reused alias clear cleanup suppression on
4355
- * another incarnation. A supervised restart keeps its principal and uid, so it also carries the
4356
- * fence's `joinedAfter` bound: the row the dead seat left must not stand in for the new process.
4357
- * A heartbeat on that row moves only its time and emits no presence event, so the bound is polled. */
4358
- watchResumeAdoption(a, joinedAfter, adopted) {
4359
- const wanted = this.managedPrincipal(a);
4360
- let poll;
4361
- const done = () => {
4362
- this.ep.off("presence", onPresence);
4363
- if (poll !== undefined)
4364
- clearInterval(poll);
4365
- };
4366
- const onPresence = () => {
4367
- if (this.agents.get(a.name) !== a) {
4368
- done();
4369
- return;
4370
- }
4371
- if (!this.ep.getRoster().some((p) => p.card.id === wanted && p.status !== "offline" && p.lifecycleUid === a.lifecycleUid && (joinedAfter === undefined || p.ts >= joinedAfter)))
4372
- return;
4373
- if (!this.resumeRequired)
4374
- a.suppressCleanup = false;
4375
- done();
4376
- adopted().catch((error) => console.error(`! ${a.name}: joined after its readiness window, but ${rejectionText(error)}`));
4377
- };
4378
- this.ep.on("presence", onPresence);
4379
- if (joinedAfter !== undefined) {
4380
- poll = setInterval(onPresence, LATE_JOIN_POLL_MS);
4381
- poll.unref?.();
4382
- }
4383
- onPresence();
4384
- }
4385
- /** #159 B1: wait for a detached launch to reach a REAL outcome before replying — never a liveness-
4386
- * inferring timer. Races three:
4387
- * • the assigned id joins presence (live) → **started** — the honest signal (the manager owns mesh
4388
- * lifecycle, not app health, so `ok:true` means "it joined the mesh", not "fully healthy");
4389
- * • the child process exits → **failed** — surface its last output and reap the slot;
4390
- * • neither within {@link readinessTimeoutMs} → **uncertain** — a non-success diagnostic that does NOT
4391
- * deprovision (it may still be booting; the caller keeps {@link watchExit} wired so a later death is
4392
- * still reaped).
4393
- * Presence is keyed on the EXACT freshly-minted id, never the name — a fresh id has no prior record, so
4394
- * any live presence for it is from THIS launch (stale/same-name records can't false-start it). The
4395
- * `"presence"` event is only a wake; the roster is re-read as the source of truth (subscribe-then-check
4396
- * catches a join/exit that landed before we subscribed). A runtime whose `attach()` throws (an external
4397
- * surface) streams no output or exit, so its exit leg polls the runtime's exit proof ({@link pollProvedExit}),
4398
- * reads it once more when the window closes, and its failure carries no last output; one that cannot prove an
4399
- * exit either races presence-vs-backstop only.
4400
- * A launch that waits for the operator at `opts.operator`, a screen its connector names, is ready once a
4401
- * process this runtime owns has run for {@link OPERATOR_READINESS_MS} without exiting. An uncertain verdict
4402
- * says whether a process this runtime owns is still running. */
4403
- async awaitReadiness(a, readinessTimeoutMs, opts = {}) {
4404
- let session;
4405
- try {
4406
- session = a.handle.attach();
4407
- }
4408
- catch {
4409
- /* external surfaces stream no output or exit; their exit is polled below */
4410
- }
4411
- const s = session;
4412
- // Presence cards carry the wire PRINCIPAL dot-form (`<owner>.<actor>`), never a raw nkey — match
4413
- // through managedPrincipal or a static launch can never be seen joining (every static spawn would
4414
- // resolve "uncertain"; caught by the lifecycle e2e).
4415
- const wanted = this.managedPrincipal(a);
4416
- // READINESS LIFECYCLE FENCE (SPEC 13.1): match the exact principal AND the exact lifecycle uid
4417
- // the manager minted for THIS spawn (presence carries it, §6). The endpoint's own
4418
- // register-only broker proof is gated on the CLIENT-authored `card.kind`, which a managed child
4419
- // holding a valid agent credential could set to "endpoint" to skip - so it is defense-in-depth,
4420
- // NOT the authority boundary. This equality is: the manager (not the child) owns the expected
4421
- // uid, so a ghost that advertises a wrong/absent uid never reports STARTED, whatever kind it
4422
- // claims. The manager threads the uid into EVERY mode's launch (open included), so the child
4423
- // adopts it over a self-mint and publishes it in presence; the uid is absent only from a peer
4424
- // the manager never launched (a pure operator/daemon connection that never registers).
4425
- // A supervised restart keeps the same principal+uid, so a SIGKILL'd child's still-live
4426
- // presence row would otherwise satisfy this equality. `joinedAfter` is one millisecond
4427
- // past that row's last heartbeat: only a later heartbeat counts as THIS replacement joining.
4428
- const joined = () => this.ep.getRoster().some((p) => p.card.id === wanted
4429
- && p.status !== "offline"
4430
- && p.lifecycleUid === a.lifecycleUid
4431
- && (opts.joinedAfter === undefined || p.ts >= opts.joinedAfter));
4432
- return await new Promise((resolve) => {
4433
- let done = false;
4434
- let timer;
4435
- let unsubExit = () => { };
4436
- let joinedPoll;
4437
- let operatorTimer;
4438
- const finish = (r) => {
4439
- if (done)
4440
- return;
4441
- done = true;
4442
- if (!r.ok && r.uncertain) {
4443
- a.joinIssue = r.detail;
4444
- console.error(`seat join degraded: ${r.detail}`);
4445
- }
4446
- else if (r.ok) {
4447
- a.joinIssue = undefined;
4448
- }
4449
- clearTimeout(timer);
4450
- clearTimeout(operatorTimer);
4451
- if (joinedPoll !== undefined)
4452
- clearInterval(joinedPoll);
4453
- this.ep.off("presence", onPresence);
4454
- this.shutdownReadiness.signal.removeEventListener("abort", onShutdown);
4455
- unsubExit();
4456
- resolve(r);
4457
- };
4458
- const onPresence = () => {
4459
- if (joined())
4460
- finish({ ok: true });
4461
- };
4462
- // Shutdown owns the seat's stop and retirement after the lifecycle ticket drains. Do not
4463
- // keep that ticket waiting on a connector's readiness window while shutdown waits on it.
4464
- const onShutdown = () => finish({ ok: false, deliberate: true, detail: `${a.name} was stopped before it reported ready` });
4465
- if (opts.joinedAfter !== undefined) {
4466
- // Heartbeats bump roster.ts without emitting "presence" (same status/uid/activity).
4467
- // A supervised restart needs that bump, so poll joined() rather than waiting on the event.
4468
- joinedPoll = setInterval(onPresence, 50);
4469
- }
4470
- // Process exit → failed. Clear the backstop FIRST (synchronously) so it can't resolve UNCERTAIN while
4471
- // the backlog reads async — the process is known dead, that's a failure, not an unknown. Reap through
4472
- // onAgentExit so a child the launcher spawned in the window is reaped too.
4473
- const onExit = () => {
4474
- if (done)
4475
- return;
4476
- clearTimeout(timer);
4477
- clearTimeout(operatorTimer);
4478
- // `stopHandle` sets `terminalizing` synchronously before it kills, and `onAgentExit` sets it
4479
- // through `freeSlot` when it retires the seat, so only a read before the await and the reap
4480
- // tells a deliberate stop from a launch failure.
4481
- const deliberate = a.terminalizing === true;
4482
- void (async () => {
4483
- // A closed stream or a reader failure must not prevent settlement, or read as empty output.
4484
- let tail = "";
4485
- try {
4486
- if (s)
4487
- tail = await this.tail(s);
4488
- }
4489
- catch (error) {
4490
- console.error(`! ${a.name}: last output unavailable: ${rejectionText(error)}`);
4491
- }
4492
- if (opts.reapOnExit !== false)
4493
- this.onAgentExit(a);
4494
- // The despawn path owns this goal's terminal (`cancel`), and this promise still settles
4495
- // as the `deliberate` variant so the caller commits none: the readiness timer is already
4496
- // cleared, and the spawn's lifecycle ticket is released only on settle.
4497
- if (deliberate) {
4498
- finish({ ok: false, deliberate: true, detail: `${a.name} was stopped before it reported ready` });
4499
- return;
4500
- }
4501
- // The screen's last row can be a dialog footer, so the exit's diagnostic is named beside it:
4502
- // it carries the runtime's own reason when it stopped the seat. A connector that ends on its
4503
- // diagnostic already shows it as the last row, and it is not repeated.
4504
- let exitDetail = "";
4505
- try {
4506
- const diagnostic = a.handle.exitInfo?.()?.diagnostic;
4507
- if (diagnostic && diagnostic !== tail)
4508
- exitDetail = `; diagnostic: ${diagnostic}`;
4509
- }
4510
- catch (e) {
4511
- // The backstop is already cleared, so a reader that throws must still let this settle.
4512
- exitDetail = `; exit detail unreadable from runtime "${a.handle.kind}": ${rejectionText(e)}`;
4513
- }
4514
- // A runtime's text can carry a lone surrogate, which is not I-JSON, and the failed terminal
4515
- // this detail becomes is refused with it.
4516
- exitDetail = exitDetail.replace(/\p{Cs}/gu, "\uFFFD");
4517
- finish({ ok: false, detail: `${a.name} exited on launch${tail ? ` - last output: ${tail}` : ""}${exitDetail}` });
4518
- })();
4519
- };
4520
- // A process this runtime owns reports its own exit, so one still running here is running.
4521
- const uncertain = () => {
4522
- const running = s !== undefined && a.handle.status() === "running";
4523
- finish({
4524
- ok: false,
4525
- uncertain: true,
4526
- running,
4527
- detail: running
4528
- ? `${a.name} (${a.id}): launch status uncertain - its process is running but did not join the mesh within ${readinessTimeoutMs}ms; it may still be starting or waiting at a prompt. Inspect with \`cotal attach ${a.name}\` / \`cotal ps\`; do not stop it solely because this bounded wait elapsed.`
4529
- : `${a.name} (${a.id}): launch status uncertain - no process exit and no mesh presence within ${readinessTimeoutMs}ms; it may still be booting or stuck before connector startup. Inspect with \`cotal attach ${a.name}\` / \`cotal ps\`; do not stop it solely because this bounded wait elapsed.`,
4530
- });
4531
- };
4532
- if (opts.operator !== undefined && s)
4533
- operatorTimer = setTimeout(() => { if (a.handle.status() === "running")
4534
- finish({ ok: true, operator: opts.operator }); }, OPERATOR_READINESS_MS);
4535
- // The exit poll read the runtime up to a poll ago, and a window can be shorter than a poll, so
4536
- // the window closes on a fresh read: a child that exited by then is reported as exited. Nothing
4537
- // bounds how long a runtime's proof takes, so it gets one more poll before the launch is uncertain.
4538
- timer = setTimeout(() => {
4539
- const proof = s ? undefined : exitProof(a.handle);
4540
- if (!proof) {
4541
- uncertain();
4542
- return;
4543
- }
4544
- timer = setTimeout(uncertain, READINESS_EXIT_POLL_MS);
4545
- proof.then(onExit, uncertain);
4546
- }, readinessTimeoutMs);
4547
- // The poll stops once the race is done, so it needs no unsubscribe.
4548
- if (s)
4549
- unsubExit = s.onExit(onExit);
4550
- else
4551
- pollProvedExit(a.handle, onExit, () => !done, READINESS_EXIT_POLL_MS);
4552
- this.ep.on("presence", onPresence);
4553
- this.shutdownReadiness.signal.addEventListener("abort", onShutdown, { once: true });
4554
- // Subscribe-then-check (TOCTOU): a join or an exit that already landed before we subscribed.
4555
- if (this.shutdownReadiness.signal.aborted)
4556
- onShutdown();
4557
- else if (s && a.handle.status() === "exited")
4558
- onExit();
4559
- else
4560
- onPresence();
4561
- });
4562
- }
4563
- /** Last non-empty line of the session's rendered backlog as a single trimmed snippet (≤160 chars)
4564
- * — a readable one-line cause for an early-exit diagnostic. The backlog repaints cells a TUI
4565
- * skipped with cursor moves, so it is rendered and the line is read off the terminal; stripping
4566
- * its escapes would glue the words those moves separate. */
4567
- async tail(session) {
4568
- const backlog = await session.backlog();
4569
- // Sized after the snapshot: a custodial seat's snapshot carries the geometry it was taken at.
4570
- // The headless build exposes `buffer` only as proposed API.
4571
- const term = new Headless.Terminal({ cols: session.cols, rows: session.rows, allowProposedApi: true });
4572
- await new Promise((done) => term.write(backlog, done));
4573
- const screen = term.buffer.active;
4574
- let text = "";
4575
- for (let y = screen.length - 1; y >= 0; y--) {
4576
- const row = screen.getLine(y);
4577
- // A line wider than the screen continues across wrapped rows, so it is read whole.
4578
- text = row.translateToString(text === "") + text;
4579
- if (row.isWrapped)
4580
- continue;
4581
- // Blanks a program painted survive the right trim, so a line of only blanks is skipped.
4582
- if (text.trim())
4583
- break;
4584
- text = "";
4585
- }
4586
- term.dispose();
4587
- text = text.trim();
4588
- // Cut on code points: half a surrogate pair is not I-JSON, and a launch terminal carrying it is refused.
4589
- const chars = [...text];
4590
- return chars.length > 160 ? `…${chars.slice(-160).join("")}` : text;
4591
- }
4592
- /** Subscribe to a managed agent's process-exit so a self-driven exit frees its slot and reaps
4593
- * its children (P4b/P4c). The watch is bound to the current handle: a restart swaps in a new one
4594
- * and watches it, so a late exit proved for the old handle must not retire the row. */
4595
- watchExit(a) {
4596
- const handle = a.handle;
4597
- const current = () => this.agents.get(a.name) === a && a.handle === handle;
4598
- const watched = watchProvedExit(handle, () => this.onAgentExit(a), current);
4599
- if (!watched)
4600
- console.error(`! ${a.name}: runtime "${handle.kind}" cannot prove a child exit (AgentHandle.waitForExit is not implemented) - it stays managed after it exits, until it is stopped`);
4601
- }
1505
+ /** {@link ReadinessWait.awaitReadiness}. */
1506
+ awaitReadiness(...args) { return this.readinessWaitComponent.awaitReadiness(...args); }
1507
+ /** {@link ReadinessWait.tail}. */
1508
+ tail(...args) { return this.readinessWaitComponent.tail(...args); }
1509
+ /** {@link ReadinessWait.watchExit}. */
1510
+ watchExit(...args) { return this.readinessWaitComponent.watchExit(...args); }
4602
1511
  occupancy() { return this.namesCapacity.occupancy(); }
4603
1512
  occupancyText(o) { return this.namesCapacity.occupancyText(o); }
4604
1513
  capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
@@ -4618,240 +1527,27 @@ export class Manager {
4618
1527
  retireDelegatedAgent(name, intentId) { return this.seatStopComponent.retireDelegatedAgent(name, intentId); }
4619
1528
  /** {@link SeatStop.findManagedByTarget}. */
4620
1529
  findManagedByTarget(...args) { return this.seatStopComponent.findManagedByTarget(...args); }
4621
- /** Run one static §13.1 lifecycle OPERATION over an ephemeral, key-pinned `lifecycle-executor`
4622
- * connection: the credential's grants name exactly ONE incarnation's head/uid/gate/
4623
- * cred-family/slot keys, so the write authority exists only for this operation's window and
4624
- * can move nothing else. The transport is the direct-KV binding the shared core saga drives. */
4625
- async withLifecycleExecutor(pin, fn) {
4626
- if (!this.auth)
4627
- throw new Error("withLifecycleExecutor: no space auth (an open mesh has no lifecycle registry)");
4628
- const identity = newIdentity();
4629
- const creds = await mintCreds(this.auth, identity, "lifecycle-executor", {
4630
- lifecycleExecutor: { owner: pin.owner, actor: pin.actor, lifecycleUid: pin.lifecycleUid, alias: pin.alias },
4631
- });
4632
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
4633
- try {
4634
- const kvm = new Kvm(nc);
4635
- const recordsKv = await kvm.open(recordsBucket(this.space));
4636
- const authKv = await kvm.open(epAuthBucket(this.space));
4637
- return await fn(staticLifecycleTransport(recordsKv, authKv));
4638
- }
4639
- finally {
4640
- await drainAndClose(nc);
4641
- }
4642
- }
4643
- /** Run one SPEC 13.15 issuance operation over an ephemeral `issuer` connection: the evidence
4644
- * stage/release of one mint, or the retirement walk of one lifecycle's issuances. The store
4645
- * handle and the accepted-row KV live only for this window; the standing supervisor holds no
4646
- * grant on either bucket. */
4647
- async withIssuer(fn) {
4648
- if (!this.auth)
4649
- throw new Error("withIssuer: no space auth (an open mesh issues nothing)");
4650
- const creds = await mintCreds(this.auth, newIdentity(), "issuer");
4651
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
4652
- try {
4653
- const kvm = new Kvm(nc);
4654
- return await fn(await bindIssuedStores(kvm, await jetstreamManager(nc), this.space));
4655
- }
4656
- finally {
4657
- await drainAndClose(nc);
4658
- }
4659
- }
4660
- /** The issuance seam of ONE static credential mint (SPEC 13.15): the evidence is bound to the
4661
- * incarnation's own `cred.<uid>` ledger family, so the family's revocation (the static
4662
- * terminal) retires every issuance that named it. The finalizer is the §13.1 ledger append
4663
- * (slot credentialId + `cred.<uid>.<credId>` row); release runs it, then activates. */
4664
- issuanceSeam(i, mode, a, exp) {
4665
- return {
4666
- mode,
4667
- store: i.store,
4668
- accepted: i.accepted,
4669
- sources: mode === "issue" ? [{ space: this.space, bucket: epAuthBucket(this.space), key: `cred.${a.lifecycleUid}` }] : [],
4670
- finalize: async (credentialId) => {
4671
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: a.id, lifecycleUid: a.lifecycleUid, alias: a.name }, async (t) => {
4672
- await recordSlotCredential(t, DEV_OWNER, a.name, a.lifecycleUid, credentialId);
4673
- await appendStaticCredentialRow(t, { lifecycleUid: a.lifecycleUid, credentialId, holderPrincipal: principalKey(DEV_OWNER, a.id).key, exp });
4674
- });
4675
- },
4676
- };
4677
- }
4678
- /** Run one §13.1 endpoint-instance maintenance operation over an ephemeral,
4679
- * key-pinned `endpoint-serve-executor` connection: the credential's grants name exactly the
4680
- * manager instance's `epgate`/`epcred` keys plus its registration's two records keys, so the
4681
- * gate CAS, mint fence, spec/governance writes, and clean deregistration ride a one-shot scoped
4682
- * authority. The remote boot goal-index sweep instead uses the authenticated host-owned scan.
4683
- * This is NEVER the manager's standing seed/supervisor connection. */
4684
- async withEndpointServeExecutor(fn) {
4685
- const identity = this.remoteAuthority?.identities.executor ?? newIdentity();
4686
- if (this.remoteAuthority && (!this.remoteExecutorCreds || inspectCredHealth(this.remoteExecutorCreds).state !== "healthy")) {
4687
- // Shutdown has drained and discarded the standing serve context. Renew only its scoped
4688
- // maintenance executor through the existing host operation; never resurrect standing duties.
4689
- if (this.leaseStopping)
4690
- await this.renewRemoteExecutor(true);
4691
- else if (this.remoteAuthority.renewStandingBundle) {
4692
- // The renewal drains old handlers after adopting. A handler waiting here must be
4693
- // released at adoption, not after its own completion is required by that drain.
4694
- const renewal = this.renewRemoteStandingBundle(true);
4695
- void renewal.catch((error) => console.error(`! remote manager standing renewal completion: ${rejectionText(error)}`));
4696
- await this.remoteBundleAdoption;
4697
- if (!this.remoteExecutorCreds || inspectCredHealth(this.remoteExecutorCreds).state !== "healthy") {
4698
- await renewal;
4699
- throw new Error("standing renewal did not adopt a healthy scoped executor");
4700
- }
4701
- }
4702
- else
4703
- await this.renewRemoteExecutor(true);
4704
- }
4705
- const creds = this.remoteExecutorCreds ?? (this.auth
4706
- ? await mintCreds(this.auth, identity, "endpoint-serve-executor", {
4707
- endpointServeExecutor: { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId },
4708
- ...(this.endpointServeExecutorExpiresInSeconds !== undefined
4709
- ? { expiresInSeconds: this.endpointServeExecutorExpiresInSeconds }
4710
- : {}),
4711
- })
4712
- : undefined);
4713
- if (!creds)
4714
- throw new Error("withEndpointServeExecutor: no scoped executor authority (an open mesh must use the bare path)");
4715
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
4716
- try {
4717
- const kvm = new Kvm(nc);
4718
- return await fn({ recordsKv: await kvm.open(recordsBucket(this.space)), authKv: await kvm.open(epAuthBucket(this.space)), nc });
4719
- }
4720
- finally {
4721
- await drainAndClose(nc);
4722
- }
4723
- }
4724
- /** The open-mesh counterpart of {@link withEndpointServeExecutor}: an OPEN mesh has no
4725
- * credential system, so there is no scoped executor to mint - the same §13.1 gate/records
4726
- * writes ride a bare one-shot connection (the broker enforces nothing on an open mesh; the
4727
- * ceremony still produces the real gate, epoch, and registration the serve rails run on). */
4728
- async withOpenServeConnection(fn) {
4729
- if (this.auth || this.remoteAuthority)
4730
- throw new Error("withOpenServeConnection: an authenticated mesh must use the scoped endpoint-serve executor");
4731
- const nc = await this.dial({ maxReconnectAttempts: 0 });
4732
- try {
4733
- const kvm = new Kvm(nc);
4734
- // An open mesh may be a RAW broker (no `cotal up` provisioning ran), and `Kvm.open` binds
4735
- // lazily without checking the stream exists — create-or-verify the §13.12 authority stores
4736
- // first (the same mode-neutral treatment {@link registerManagerService} gives the contract
4737
- // store), or the first gate write dies "stream not found".
4738
- await ensureAuthorityStores(await jetstreamManager(nc), kvm, this.space);
4739
- return await fn({ recordsKv: await kvm.open(recordsBucket(this.space)), authKv: await kvm.open(epAuthBucket(this.space)), nc });
4740
- }
4741
- finally {
4742
- await drainAndClose(nc);
4743
- }
4744
- }
4745
- /** Parent-local inventory read. It does not enter maintenance or change admission. */
4746
- hostedSeatCount() { return this.agents.size; }
4747
- /** Public local-seat facts for the owning machine daemon. No mesh or secret reads. */
4748
- hostedAgents() {
4749
- if (this.agents.size > 50)
4750
- throw new Error("local agent inventory exceeds its bound");
4751
- return [...this.agents.values()].map(a => ({
4752
- name: a.name, application: a.agent, ...(a.launch.model ? { model: a.launch.model } : {}),
4753
- cwd: a.launch.cwd, startedAt: new Date(a.startedAt).toISOString(), state: a.handle.status(),
4754
- }));
4755
- }
4756
- /** The served manager-level health summary. Given an owner, `agentCount` counts only that owner's
4757
- * seats, as `ps` lists them ({@link psOwnerFilter}), so a person reading a shared Manager does not
4758
- * learn how many seats other owners hold on it. */
4759
- managerStatusData(ownerFilter, setupClaude = false) {
4760
- this.refreshUnavailableConnectors(undefined, setupClaude);
4761
- return {
4762
- instanceId: this.managerInstanceId,
4763
- lifecycleUid: this.managerLifecycleUid,
4764
- host: hostname(),
4765
- version: MANAGER_VERSION,
4766
- execution: this.execution,
4767
- runtime: this.runtimeKind,
4768
- custody: this.execution === "none" ? "none" : this.requiredRuntime.kind === "pty" && this.requiredRuntime.supportsRelease === true ? "custodied" : "legacy",
4769
- runHosting: this.execution !== "none" && (this.remoteAuthority ? this.remoteAuthority.runHosting !== undefined : !this.userMode && this.auth !== undefined),
4770
- terminalSessions: this.execution !== "none",
4771
- agentCount: ownerFilter === undefined ? this.agents.size : [...this.agents.values()].filter((a) => a.userOwner === ownerFilter).length,
4772
- uptimeMs: Date.now() - this.startedAtMs,
4773
- connectors: this.connectorStatuses.map((row) => ({ ...row, binaries: { ...row.binaries } })),
4774
- classSpawn: this.classSpawnEnabled(),
4775
- staticReconciliation: this.staticReconciliationStatus(),
4776
- stopImpact: {
4777
- agentScope: ownerFilter === undefined ? "manager" : "owner-filtered",
4778
- observedAt: new Date().toISOString(),
4779
- maintenance: this.maintenanceState,
4780
- resumeRequired: this.resumeRequired,
4781
- stopping: this.leaseStopping,
4782
- lifecycleInFlight: this.lifecycleInFlight,
4783
- reservedLaunches: this.namesCapacity.reservedCount,
4784
- retirementsPending: this.retirement.pendingCount,
4785
- deprovisioningInFlight: this.retirement.inFlightCount,
4786
- staticReconciliationInFlight: this.staticLifecycle.sweepsInFlight,
4787
- agents: [...this.agents.values()]
4788
- .filter((a) => ownerFilter === undefined || a.userOwner === ownerFilter)
4789
- .map((a) => ({
4790
- name: a.name,
4791
- id: a.id,
4792
- lifecycleUid: a.lifecycleUid,
4793
- mode: a.handle.kind,
4794
- defaultAction: this.maintenanceState !== "active" || this.resumeRequired
4795
- ? "stop-retaining-state" : this.isProcessBoundSeat(a) ? "stop" : "release-custody",
4796
- withAgentsAction: this.maintenanceState !== "active" || this.resumeRequired ? "stop-retaining-state" : "stop",
4797
- })),
4798
- // The same digest form `opResumePreserved` binds, so a preserved-exit stop and the later
4799
- // resume name one inventory.
4800
- ...(this.maintenanceState !== "active" && this.preservationAttemptId && this.preservationInventory
4801
- ? { preservation: { attemptId: this.preservationAttemptId, inventorySha256: createHash("sha256").update(JSON.stringify(this.preservationInventory)).digest("hex") } }
4802
- : {}),
4803
- },
4804
- };
4805
- }
1530
+ /** {@link BrokerTransport.withLifecycleExecutor}. */
1531
+ withLifecycleExecutor(pin, fn) { return this.brokerTransportComponent.withLifecycleExecutor(pin, fn); }
1532
+ /** {@link BrokerTransport.withIssuer}. */
1533
+ withIssuer(fn) { return this.brokerTransportComponent.withIssuer(fn); }
1534
+ /** {@link BrokerTransport.issuanceSeam}. */
1535
+ issuanceSeam(...args) { return this.brokerTransportComponent.issuanceSeam(...args); }
1536
+ /** {@link BrokerTransport.withEndpointServeExecutor}. */
1537
+ withEndpointServeExecutor(fn) { return this.brokerTransportComponent.withEndpointServeExecutor(fn); }
1538
+ /** {@link BrokerTransport.withOpenServeConnection}. */
1539
+ withOpenServeConnection(fn) { return this.brokerTransportComponent.withOpenServeConnection(fn); }
1540
+ /** {@link StatusAndModels.hostedSeatCount}. */
1541
+ hostedSeatCount(...args) { return this.statusAndModelsComponent.hostedSeatCount(...args); }
1542
+ /** {@link StatusAndModels.hostedAgents}. */
1543
+ hostedAgents(...args) { return this.statusAndModelsComponent.hostedAgents(...args); }
1544
+ /** {@link StatusAndModels.managerStatusData}. */
1545
+ managerStatusData(...args) { return this.statusAndModelsComponent.managerStatusData(...args); }
4806
1546
  staticReconciliationStatus() {
4807
1547
  return this.staticLifecycle.staticReconciliationStatus();
4808
1548
  }
4809
- /** Complete a crashed predecessor's FROZEN registration gate before this incarnation starts a
4810
- * new one (#783 item 3 / #871). The CLI `cotal reconcile-gate` already does this; a successor
4811
- * that cannot register is exactly the state that command exists to repair, so boot must run
4812
- * the SAME composition rather than waiting for an operator.
4813
- *
4814
- * Admit only `gone` AND `sweepComplete=true` (the probe mapping already folds an incomplete
4815
- * `gone` into `unestablishable`). Live / unknown / unestablishable / wrong-op-kind stay loud
4816
- * refusals. No TTL: request-ingress has no process-epoch fence, so a clock would either let a
4817
- * superseded serve credential keep consuming ingress or just rename the freeze. An open gate
4818
- * is a no-op (the successor's own freeze comes next). A committed spec under that freeze is
4819
- * finished at the committed registrationRevision; only a definite no-commit abort-reopens. */
4820
- async healFrozenRegistrationGate(authKv, instanceId, auth, recordsKv) {
4821
- const key = epgateKey(MANAGER_ENDPOINT, instanceId);
4822
- const entry = await authKv.get(key);
4823
- if (!entry || entry.operation !== "PUT")
4824
- return;
4825
- const row = parseEndpointGate(entry.value, key);
4826
- if (row.state !== "frozen")
4827
- return;
4828
- const servers = this.servers ?? DEFAULT_SERVER;
4829
- const log = (line) => console.error(` ${line}`);
4830
- let report;
4831
- try {
4832
- report = await reconcileEndpointGate({
4833
- kv: authKv, space: this.space, endpoint: MANAGER_ENDPOINT, instanceId,
4834
- probeHolder: makeManagerHolderLivenessProbe({ space: this.space, servers, auth, log, unreachableWaitMs: DELIVERY_ADMIN_BOOT_WAIT_MS }),
4835
- evictHolders: makeManagerEndpointHolderEvictor({ space: this.space, servers, auth, log }),
4836
- log,
4837
- recordsKv,
4838
- });
4839
- }
4840
- catch (e) {
4841
- // We observed frozen, then a concurrent reconciler finished first. If the gate is now open,
4842
- // this incarnation continues the takeover. Every other refusal — including raced-but-still-
4843
- // frozen — stays loud.
4844
- if (e instanceof GateReconcileRefused && (e.condition === "not-frozen" || e.condition === "raced")) {
4845
- const latest = await authKv.get(key);
4846
- if (latest && latest.operation === "PUT" && parseEndpointGate(latest.value, key).state === "open") {
4847
- console.error(`boot self-heal: ${MANAGER_ENDPOINT}/${instanceId} is open after ${e.condition}; continuing the normal takeover`);
4848
- return;
4849
- }
4850
- }
4851
- throw e;
4852
- }
4853
- 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.`);
4854
- }
1549
+ /** {@link ManagerBoot.healFrozenRegistrationGate}. */
1550
+ healFrozenRegistrationGate(...args) { return this.bootComponent.healFrozenRegistrationGate(...args); }
4855
1551
  dialServeConnection(state, readCreds = () => state.creds, deadline) { return this.servePlane.dialServeConnection(state, readCreds, deadline); }
4856
1552
  registerManagerService() { return this.servePlane.registerManagerService(); }
4857
1553
  /** {@link GoalWriter.mintAndStageGoalWriter}. */
@@ -5110,39 +1806,10 @@ export class Manager {
5110
1806
  }
5111
1807
  /** {@link SeatStop.lifecycleMembershipRefusal}. */
5112
1808
  lifecycleMembershipRefusal(...args) { return this.seatStopComponent.lifecycleMembershipRefusal(...args); }
5113
- /** Open a short-lived PROVISIONER connection, run the onboarding ops on it, and drain it (closure (ii),
5114
- * residual 2). The DM/DLV consumer-create surface — the irreducible onboarding power — lives only for
5115
- * this window, never as a standing grant on the long-lived supervisor. A provision-only endpoint
5116
- * (no presence/consume/channel-watch) connected with memory-only `provisioner` creds; it sets its own
5117
- * `inboxPrefix` so JS-API replies land on the `_INBOX_<id>.>` the provisioner cred subscribes. */
5118
- async withProvisioner(fn) {
5119
- if (!this.auth)
5120
- throw new Error("withProvisioner: no space auth (an open mesh has no scoped creds)");
5121
- // Onboarding runs several provisioning ops, so it keeps the provisioner profile's five-minute window.
5122
- return withScopedEndpoint({ space: this.space, servers: this.servers ?? DEFAULT_SERVER, auth: this.auth }, "provisioner", "provisioner", fn, 5 * 60);
5123
- }
5124
- /** A connection holding this instance's transfer reader grants (docs/design/resume-transfer.md
5125
- * section 6) for this one receive or sweep: minted from the space's signing seed, or issued by the
5126
- * host to a remote manager. An open mesh enforces no grants, so a bare one-shot connection is that
5127
- * reader there. */
5128
- async withTransferReader(fn) {
5129
- const issue = this.remoteAuthority?.mintTransferReader;
5130
- if (this.remoteAuthority && !issue)
5131
- throw new Error("withTransferReader: this manager's remote authority issues no transfer reader");
5132
- const identity = newIdentity();
5133
- const creds = issue
5134
- ? await issue(identity)
5135
- : this.auth && await mintCreds(this.auth, identity, "transfer-reader", { transferReader: { instanceId: this.managerInstanceId } });
5136
- const nc = await this.dial(creds
5137
- ? { ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 }
5138
- : { maxReconnectAttempts: 0 });
5139
- try {
5140
- return await fn(nc);
5141
- }
5142
- finally {
5143
- await drainAndClose(nc);
5144
- }
5145
- }
1809
+ /** {@link BrokerTransport.withProvisioner}. */
1810
+ withProvisioner(fn) { return this.brokerTransportComponent.withProvisioner(fn); }
1811
+ /** {@link BrokerTransport.withTransferReader}. */
1812
+ withTransferReader(fn) { return this.brokerTransportComponent.withTransferReader(fn); }
5146
1813
  /** {@link SeatStop.opPurge}. */
5147
1814
  opPurge(...args) { return this.seatStopComponent.opPurge(...args); }
5148
1815
  /** {@link PersonaCatalog.opDefinePersona}. */
@@ -5163,103 +1830,7 @@ export class Manager {
5163
1830
  attachAuthorized(...args) { return this.terminalInputComponent.attachAuthorized(...args); }
5164
1831
  /** {@link TerminalInput.establishConsoleSession}. */
5165
1832
  establishConsoleSession(...args) { return this.terminalInputComponent.establishConsoleSession(...args); }
5166
- /** Managed agents cross-referenced with live presence (the manager sees the roster).
5167
- *
5168
- * `ownerFilter`: restrict to agents whose spawn-time stored `userOwner` equals it (the ps/status
5169
- * owner-domain bound); undefined = unbounded. {@link NO_OWNER_MATCHES} matches nothing. */
5170
- list(ownerFilter) {
5171
- const roster = new Map(this.ep.getRoster().map((p) => [p.card.name, p]));
5172
- const observedAt = Date.now();
5173
- // The roster is only evidence while THIS observer's presence watch is fresh. A stale view
5174
- // (whole-bucket silence past TTL) or an unpopulated one (snapshot not yet replayed) cannot
5175
- // support "offline" or "absent" for anyone: a live deployment on 2026-09-09 rendered every live seat as
5176
- // one of those for hours after the presence stream was recreated under a still-open watch.
5177
- // Carry the view state on the row so the renderer can say "unknown" instead of a verdict.
5178
- // An endpoint that reports no view (test doubles built on `getRoster` alone) is read as
5179
- // `current`: that is exactly what every row meant before the field existed.
5180
- const view = typeof this.ep.presenceView === "function" ? this.ep.presenceView() : { state: "current" };
5181
- return [...this.agents.values()].filter((a) => ownerFilter === undefined || a.userOwner === ownerFilter).map((a) => {
5182
- // USER MODE: a detached agent's bearer-refresh death is silent everywhere except here — its
5183
- // bearer command writes each attempt's outcome to the health file, and `ps` renders it
5184
- // FAIL-CLOSED: a failed record is the failure + repair sentence; a missing/malformed or
5185
- // stale record on a live agent is auth-unknown/auth-stale, NEVER silently healthy.
5186
- const health = a.userOwner
5187
- ? agentAuthState(a.secretPaths?.health ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, a.name, a.lifecycleUid).health)
5188
- : undefined;
5189
- // The connector-reported provider from presence (#785): the live roster card's `meta.provider`,
5190
- // when it is a non-empty string. Absent when the connector reported none — never fabricated.
5191
- const seen = roster.get(a.name);
5192
- const presenceIdentityVerified = this.isOwnPresence(a, seen);
5193
- const providerMeta = seen?.card.meta?.provider;
5194
- const provider = typeof providerMeta === "string" && providerMeta ? providerMeta : undefined;
5195
- // The harness-reported condition beside the mesh status (#618): a turn that died upstream reads
5196
- // `waiting` with `rate_limit` here, not a bare `waiting`. Absent when the connector reported none.
5197
- // Projected field by field like `provider`: a malformed peer row must not fail this reply's schema.
5198
- const reported = roster.get(a.name)?.condition;
5199
- const condition = reported && typeof reported.code === "string" && reported.code
5200
- ? {
5201
- code: reported.code,
5202
- ...(typeof reported.source === "string" ? { source: reported.source } : {}),
5203
- ...(typeof reported.message === "string" ? { message: reported.message } : {}),
5204
- ...(typeof reported.since === "number" && Number.isFinite(reported.since) ? { since: reported.since } : {}),
5205
- }
5206
- : undefined;
5207
- // The seat's last harness-reported work progress (#618). `ts` is only its heartbeat, so a turn
5208
- // that stopped advancing reads as an old `activeAt` beside a live process. Absent when none was reported.
5209
- const activeAtReported = roster.get(a.name)?.activeAt;
5210
- const activeAt = typeof activeAtReported === "number" && Number.isFinite(activeAtReported) ? activeAtReported : undefined;
5211
- // How long an offline verdict has stood (#1208): the seat's last heartbeat before it went
5212
- // offline. Only beside a verdict, since a stale or unpopulated view dates nothing, only from the
5213
- // seat's own record, since `seen` is matched by name and a same-named foreign peer or an older
5214
- // incarnation must not date this seat, and only when the seat's unvalidated `ts` fits the row
5215
- // schema, so one odd record cannot fail the reply.
5216
- const offlineSince = view.state === "current" && this.isOwnPresence(a, seen) && seen.status === "offline" && Number.isSafeInteger(seen.ts) && seen.ts >= 0
5217
- ? seen.ts
5218
- : undefined;
5219
- return {
5220
- name: a.name,
5221
- // The spawned agent's id (nkey, or the user-mode principal) — lets an operator tool (e.g.
5222
- // `cotal down -f`) match a ledger entry by name AND id before stopping, so it never stops a
5223
- // same-named foreign agent.
5224
- id: a.id,
5225
- role: a.role,
5226
- agent: a.agent,
5227
- space: this.space,
5228
- mode: a.handle.kind,
5229
- status: a.handle.status(),
5230
- uptimeMs: Date.now() - a.startedAt,
5231
- mesh: seen?.status ?? "absent",
5232
- ...(a.joinIssue ? { joinHealth: { state: "degraded", reason: a.joinIssue } } : {}),
5233
- ...(condition ? { condition } : {}),
5234
- ...(a.startupNotice !== undefined ? { startupNotice: a.startupNotice } : {}),
5235
- ...(activeAt !== undefined ? { activeAt } : {}),
5236
- // `current` is the only state in which `mesh` is a verdict; the other two are the
5237
- // observer's own condition and travel on the row (older CLIs ignore the field).
5238
- meshView: view.state,
5239
- presenceIdentityVerified,
5240
- ...(view.state === "current" && presenceIdentityVerified ? { presenceObservedAt: observedAt } : {}),
5241
- ...(offlineSince !== undefined ? { offlineSince } : {}),
5242
- // The incarnation coordinate (SPEC 13.1) — with `id`, exactly what a v0.4 caller needs to
5243
- // build a targeted (`despawn`/`attach`) request against THIS incarnation.
5244
- lifecycleUid: a.lifecycleUid,
5245
- // #651 enrichment: per-seat facts the manager ALREADY holds, carried on the row so `ps
5246
- // --wide`/`--json` can surface them without a new collection path. All optional in the row
5247
- // schema: a fact this backend did not record serializes absent, never fabricated (the
5248
- // pid is absent on runtimes that do not own a real process; a launch may pin no model).
5249
- model: a.launch.model,
5250
- variant: a.launch.variant,
5251
- ...(provider ? { provider } : {}),
5252
- cwd: a.launch.cwd,
5253
- pid: a.handle.pid,
5254
- spawner: a.spawner,
5255
- instanceId: this.managerInstanceId,
5256
- host: hostname(),
5257
- // #1500: the session a `--resume` seat forked, with its title and transcript hash once the
5258
- // seat has recorded them.
5259
- ...(a.launch.forkSource ? { resume: this.forkProvenance(a) ?? { source: a.launch.forkSource } } : {}),
5260
- ...(health && health.state !== "ok" ? { authHealth: health.state, authReason: health.reason } : {}),
5261
- };
5262
- });
5263
- }
1833
+ /** {@link StatusAndModels.list}. */
1834
+ list(...args) { return this.statusAndModelsComponent.list(...args); }
5264
1835
  }
5265
1836
  //# sourceMappingURL=manager.js.map