@cotal-ai/manager 0.171.3 → 0.171.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.js CHANGED
@@ -5,17 +5,16 @@ import { drainAndClose } from "@cotal-ai/core";
5
5
  import { hostname } from "node:os";
6
6
  import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
7
7
  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";
8
+ import { CotalEndpoint, copyPersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, injectedSecretStoreIdentity, idFromCreds, identityFromCreds, loadAgentFile, loadCotalConfig, mintCreds, mintLifecycleUid, newIdentity, oneLine, parsePrincipalKey, principalKey, probeConnect, resolveAuthProvider, } from "@cotal-ai/core";
10
9
  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";
10
+ import { logicalExecutionEntry } from "@cotal-ai/workspace";
11
+ import { agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, DEFAULT_SEAT_CAP, findCotalRoot, getSpaceAuth, hasUserAuthState, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
12
+ import { createRuntime, isCustodialRuntime, requireRuntimeAdopt, requireRuntimeReap, } from "./runtime/index.js";
14
13
  import { Retirement } from "./retirement.js";
15
14
  import { ServePlane } from "./serve-plane.js";
16
15
  import { NamesCapacity } from "./names-capacity.js";
17
16
  import { AttachEndpoint } from "./attach-endpoint.js";
18
- import { DELIVERY_ADMIN_BOOT_WAIT_MS, makeManagerEndpointHolderEvictor, withScopedEndpoint } from "./endpoint-evict.js";
17
+ import { DELIVERY_ADMIN_BOOT_WAIT_MS, makeManagerEndpointHolderEvictor } from "./endpoint-evict.js";
19
18
  import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
20
19
  import { ManagedStaticLifecycle, STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
21
20
  export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
@@ -30,22 +29,29 @@ import { CommandDispatch, participantKey } from "./command-dispatch.js";
30
29
  import { SpawnGoal } from "./spawn-goal.js";
31
30
  import { PersonaCatalog } from "./persona-catalog.js";
32
31
  import { TerminalInput } from "./terminal-input.js";
32
+ import { StatusAndModels, MANAGER_VERSION } from "./status-and-models.js";
33
+ import { ReadinessWait } from "./readiness-wait.js";
34
+ import { BrokerTransport } from "./broker-transport.js";
35
+ import { StartDoors } from "./start-doors.js";
36
+ import { HarnessResolution, resolveHarness } from "./harness-resolution.js";
37
+ import { ConnectorInventory } from "./connector-inventory.js";
38
+ import { Preservation } from "./preservation.js";
33
39
  export { PASTE_END, PASTE_START, RUNTIME_NO_TERMINAL_DETAIL } from "./terminal-input.js";
34
40
  import { CredentialRenewal, credRenewIntervalMs, REMOTE_STANDING_BUDGET_MS, remoteStandingTimeLeft, sameStrings } from "./credential-renewal.js";
35
41
  import { SeatLaunch, foreignEventChannels } from "./seat-launch.js";
36
42
  import { withTimeout } from "./manager-timeout.js";
37
43
  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";
44
+ import { inlineSnapshotPath, launchSpecForRun } from "./launch.js";
45
+ import { authorizeNamedControl } from "./authorize.js";
40
46
  import { RunHosting } from "./run-hosting.js";
41
47
  import { rejectionText, attemptCleanup } from "@cotal-ai/core";
42
- import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
48
+ import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference } from "./resume.js";
43
49
  import { TranscriptReceiver } from "./transcript-receive.js";
44
50
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
45
51
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
46
52
  import { jetstreamManager } from "@nats-io/jetstream";
47
53
  import { Kvm } from "@nats-io/kv";
48
- import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts } from "@cotal-ai/core";
54
+ import { recordsBucket, ensureAuthorityStores, standaloneConnectOpts } from "@cotal-ai/core";
49
55
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
50
56
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
51
57
  // per-session credentials on their own short-lived connections).
@@ -53,13 +59,9 @@ import { ManagerSessionPlane } from "./session/index.js";
53
59
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
54
60
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
55
61
  // 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";
62
+ import { epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, listGoalIndex, turnNoticeSubject, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom } from "@cotal-ai/core";
57
63
  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;
64
+ import { ownedBySibling, } from "./static-lifecycle.js";
63
65
  /** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
64
66
  * stays and the turn sweep asks again. */
65
67
  const ONCE_RETIRE_MS = 60_000;
@@ -76,18 +78,10 @@ export const READINESS_TIMEOUT_MS = 30_000;
76
78
  * from its launch: the watch's 15s for the confirm prompt and 15s for its notice, plus 5s for the
77
79
  * last read. The readiness window applies when it is longer. */
78
80
  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
81
  /** How often a resumed seat whose readiness was uncertain is checked for a join its predecessor's
84
82
  * presence row hides (see {@link Manager.watchResumeAdoption}). The wait has no end of its own, so
85
83
  * it asks less often than the readiness fence's 50 ms poll. */
86
84
  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
85
  /** At most this many retirements run at once (#4965). A retirement dials up to four fresh broker
92
86
  * connections in turn and queues an eviction and an inventory on the delivery daemon's admin rail,
93
87
  * each against a fixed deadline. A stop that started all 50 seats' retirements together lost most of
@@ -113,10 +107,6 @@ const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
113
107
  function resumeOwner(entry) {
114
108
  return entry.identity.mode === "user" ? entry.identity.owner : DEV_OWNER;
115
109
  }
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
110
  /** Why a frozen manager gate stays frozen on an open mesh. Reconciliation must prove the holder
121
111
  * gone, and an open mesh runs no delivery daemon to prove it, so neither boot self-heal nor
122
112
  * `cotal manager reconcile` can reopen the gate there. */
@@ -145,20 +135,6 @@ function bearerEntryArgv() {
145
135
  return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
146
136
  }
147
137
  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
138
  /** The refusal a control instance with `execution: none` gives every launch, hosting, model and write door. */
163
139
  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
140
  /** The sha256 hex digest of a file's bytes. */
@@ -538,12 +514,8 @@ export class Manager {
538
514
  maintenanceState = "active";
539
515
  lifecycleInFlight = 0;
540
516
  lifecycleDrainWaiters = [];
541
- preservationTask;
542
- preparationTask;
543
517
  preservationGeneration = 0;
544
518
  preservationAttemptId;
545
- preservationStarted = false;
546
- preservationFailures = [];
547
519
  unverifiedStops = [];
548
520
  preservationInventory;
549
521
  resumeAttemptId;
@@ -567,36 +539,10 @@ export class Manager {
567
539
  /** A refused or failed standing candidate is cleanup debt, never a silent loss: the last-good
568
540
  * family stays live and this records what the host may have signed but the manager never adopted. */
569
541
  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
- }
542
+ /** {@link BrokerTransport.dial}. */
543
+ dial(...args) { return this.brokerTransportComponent.dial(...args); }
544
+ /** {@link BrokerTransport.dialRemoteStanding}. */
545
+ dialRemoteStanding(...args) { return this.brokerTransportComponent.dialRemoteStanding(...args); }
600
546
  seatCustody = new SeatCustody({
601
547
  staticAuth: () => !!this.auth && !this.userMode,
602
548
  workspaceRoot: () => this.workspaceRoot,
@@ -843,6 +789,147 @@ export class Manager {
843
789
  wsPort: () => this.wsPort,
844
790
  runtimeFor: (...args) => this.runtimeFor(...args),
845
791
  });
792
+ /** Status, seat list and model catalog reads. Every dependency reads through at its use. */
793
+ statusAndModelsComponent = new StatusAndModels({
794
+ agents: () => this.agents,
795
+ auth: () => this.auth,
796
+ connectorStatuses: () => this.connectorStatuses,
797
+ ep: () => this.ep,
798
+ execution: () => this.execution,
799
+ leaseStopping: () => this.leaseStopping,
800
+ lifecycleInFlight: () => this.lifecycleInFlight,
801
+ maintenanceState: () => this.maintenanceState,
802
+ managerInstanceId: () => this.managerInstanceId,
803
+ managerLifecycleUid: () => this.managerLifecycleUid,
804
+ namesCapacity: () => this.namesCapacity,
805
+ preservationAttemptId: () => this.preservationAttemptId,
806
+ preservationInventory: () => this.preservationInventory,
807
+ remoteAuthority: () => this.remoteAuthority,
808
+ requiredRuntime: () => this.requiredRuntime,
809
+ resumeRequired: () => this.resumeRequired,
810
+ retirement: () => this.retirement,
811
+ runtimeKind: () => this.runtimeKind,
812
+ space: () => this.space,
813
+ startedAtMs: () => this.startedAtMs,
814
+ staticLifecycle: () => this.staticLifecycle,
815
+ userMode: () => this.userMode,
816
+ workspaceRoot: () => this.workspaceRoot,
817
+ classSpawnEnabled: (...args) => this.classSpawnEnabled(...args),
818
+ connectorNames: (...args) => this.connectorNames(...args),
819
+ epAdminReach: (...args) => this.epAdminReach(...args),
820
+ executionRefusal: (...args) => this.executionRefusal(...args),
821
+ forkProvenance: (...args) => this.forkProvenance(...args),
822
+ isOwnPresence: (a, p) => this.isOwnPresence(a, p),
823
+ isProcessBoundSeat: (...args) => this.isProcessBoundSeat(...args),
824
+ launchHarness: (...args) => this.launchHarness(...args),
825
+ refreshUnavailableConnectors: (...args) => this.refreshUnavailableConnectors(...args),
826
+ resolveConnector: (...args) => this.resolveConnector(...args),
827
+ staticReconciliationStatus: (...args) => this.staticReconciliationStatus(...args),
828
+ });
829
+ /** The launch readiness race and exit watch. Every dependency reads through at its use. */
830
+ readinessWaitComponent = new ReadinessWait({
831
+ agents: () => this.agents,
832
+ ep: () => this.ep,
833
+ shutdownReadiness: () => this.shutdownReadiness,
834
+ managedPrincipal: (...args) => this.managedPrincipal(...args),
835
+ onAgentExit: (...args) => this.onAgentExit(...args),
836
+ });
837
+ /** Broker dials and scoped executor connections. Every dependency reads through at its use. */
838
+ brokerTransportComponent = new BrokerTransport({
839
+ auth: () => this.auth,
840
+ endpointServeExecutorExpiresInSeconds: () => this.endpointServeExecutorExpiresInSeconds,
841
+ leaseStopping: () => this.leaseStopping,
842
+ managerInstanceId: () => this.managerInstanceId,
843
+ remoteAuthority: () => this.remoteAuthority,
844
+ remoteBundleAdoption: () => this.remoteBundleAdoption,
845
+ remoteExecutorCreds: () => this.remoteExecutorCreds,
846
+ servers: () => this.servers,
847
+ space: () => this.space,
848
+ transportDown: () => this.transportDown,
849
+ renewRemoteExecutor: (...args) => this.renewRemoteExecutor(...args),
850
+ renewRemoteStandingBundle: (...args) => this.renewRemoteStandingBundle(...args),
851
+ });
852
+ /** The start and launch control doors. Every dependency reads through at its use. */
853
+ startDoorsComponent = new StartDoors({
854
+ eventsRequired: () => this.eventsRequired,
855
+ execution: () => this.execution,
856
+ remoteAuthority: () => this.remoteAuthority,
857
+ space: () => this.space,
858
+ userMode: () => this.userMode,
859
+ workspaceRoot: () => this.workspaceRoot,
860
+ executionRefusal: (...args) => this.executionRefusal(...args),
861
+ startAgent: (...args) => this.startAgent(...args),
862
+ });
863
+ /** Connector and harness resolution for a launch. Every dependency reads through at its use. */
864
+ harnessResolutionComponent = new HarnessResolution({
865
+ connectorStatuses: () => this.connectorStatuses,
866
+ eventPayloadsWithheld: () => this.eventPayloadsWithheld,
867
+ eventsRequired: () => this.eventsRequired,
868
+ expectedConnectorGeneration: () => this.expectedConnectorGeneration,
869
+ installedExtensions: () => this.installedExtensions,
870
+ servers: () => this.servers,
871
+ space: () => this.space,
872
+ workspaceRoot: () => this.workspaceRoot,
873
+ });
874
+ /** The boot connector inventory. Every dependency reads through at its use. */
875
+ connectorInventoryComponent = new ConnectorInventory({
876
+ bootNotes: () => this.bootNotes,
877
+ setBootNotes: (value) => { this.bootNotes = value; },
878
+ connectorRequirements: () => this.connectorRequirements,
879
+ setConnectorRequirements: (value) => { this.connectorRequirements = value; },
880
+ connectorStatuses: () => this.connectorStatuses,
881
+ setConnectorStatuses: (value) => { this.connectorStatuses = value; },
882
+ execution: () => this.execution,
883
+ installedExtensions: () => this.installedExtensions,
884
+ machineSetupCommand: () => this.machineSetupCommand,
885
+ classSpawnEnabled: (...args) => this.classSpawnEnabled(...args),
886
+ prepareClaudeWake: (...args) => this.prepareClaudeWake(...args),
887
+ });
888
+ /** Manager preservation and released-seat adoption. Every dependency reads through at its use. */
889
+ preservationComponent = new Preservation({
890
+ agents: () => this.agents,
891
+ auth: () => this.auth,
892
+ credRenewTimer: () => this.credRenewTimer,
893
+ setCredRenewTimer: (value) => { this.credRenewTimer = value; },
894
+ ep: () => this.ep,
895
+ execution: () => this.execution,
896
+ lifecycleInFlight: () => this.lifecycleInFlight,
897
+ maintenanceState: () => this.maintenanceState,
898
+ setMaintenanceState: (value) => { this.maintenanceState = value; },
899
+ managerInstanceId: () => this.managerInstanceId,
900
+ meshMode: () => this.meshMode,
901
+ preservationAttemptId: () => this.preservationAttemptId,
902
+ setPreservationAttemptId: (value) => { this.preservationAttemptId = value; },
903
+ preservationGeneration: () => this.preservationGeneration,
904
+ setPreservationGeneration: (value) => { this.preservationGeneration = value; },
905
+ preservationInventory: () => this.preservationInventory,
906
+ setPreservationInventory: (value) => { this.preservationInventory = value; },
907
+ preserveStopTimeoutMs: () => this.preserveStopTimeoutMs,
908
+ resumeCredRenewal: () => this.resumeCredRenewal,
909
+ space: () => this.space,
910
+ unverifiedStops: () => this.unverifiedStops,
911
+ setUnverifiedStops: (value) => { this.unverifiedStops = value; },
912
+ userMode: () => this.userMode,
913
+ workspaceRoot: () => this.workspaceRoot,
914
+ awaitLifecycleDrain: (...args) => this.awaitLifecycleDrain(...args),
915
+ deprovision: (...args) => this.deprovision(...args),
916
+ dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
917
+ dropSeatRecord: (...args) => this.dropSeatRecord(...args),
918
+ executionRefusal: (...args) => this.executionRefusal(...args),
919
+ fileDigest: (...args) => this.fileDigest(...args),
920
+ logSeatReaped: (...args) => this.logSeatReaped(...args),
921
+ onAgentExit: (...args) => this.onAgentExit(...args),
922
+ recordContinuityAtStop: (...args) => this.recordContinuityAtStop(...args),
923
+ renewDaemonCreds: (...args) => this.renewDaemonCreds(...args),
924
+ resumeEntry: (...args) => this.resumeEntry(...args),
925
+ resumeEntryOf: (...args) => this.resumeEntryOf(...args),
926
+ runtimeFor: (...args) => this.runtimeFor(...args),
927
+ stopHandle: (...args) => this.stopHandle(...args),
928
+ teardownTarget: (...args) => this.teardownTarget(...args),
929
+ validateRetainedAuthority: (...args) => this.validateRetainedAuthority(...args),
930
+ watchExit: (...args) => this.watchExit(...args),
931
+ withProvisioner: (fn) => this.withProvisioner(fn),
932
+ });
846
933
  /** The goal-writer connection and the goal index it reconciles. Every dependency reads through at its use. */
847
934
  goalWriterComponent = new GoalWriter({
848
935
  auth: () => this.auth,
@@ -1235,28 +1322,6 @@ export class Manager {
1235
1322
  return "static";
1236
1323
  return "open";
1237
1324
  }
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
1325
  readerRemedy(owner, channel) {
1261
1326
  switch (this.meshMode) {
1262
1327
  case "user":
@@ -1771,288 +1836,23 @@ export class Manager {
1771
1836
  return `manager is waiting for resume attempt ${this.resumeAttemptId}; ordinary lifecycle/control work is fenced`;
1772
1837
  return `manager is in ${this.maintenanceState} mode; new lifecycle/control work is fenced`;
1773
1838
  }
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
- }
1839
+ /** {@link Preservation.preparePreservation}. */
1840
+ preparePreservation(...args) { return this.preservationComponent.preparePreservation(...args); }
1841
+ /** {@link Preservation.runPreparation}. */
1842
+ runPreparation(...args) { return this.preservationComponent.runPreparation(...args); }
1843
+ /** {@link Preservation.commitPreservation}. */
1844
+ commitPreservation(...args) { return this.preservationComponent.commitPreservation(...args); }
1845
+ /** {@link Preservation.abortPreservation}. */
1846
+ abortPreservation(...args) { return this.preservationComponent.abortPreservation(...args); }
1847
+ /** {@link Preservation.preserveState}. */
1848
+ preserveState(...args) { return this.preservationComponent.preserveState(...args); }
1849
+ /** {@link Preservation.awaitHandleExit}. */
1850
+ awaitHandleExit(...args) { return this.preservationComponent.awaitHandleExit(...args); }
1851
+ /** {@link Preservation.inventoryReferenceError}. */
1852
+ inventoryReferenceError(...args) { return this.preservationComponent.inventoryReferenceError(...args); }
2047
1853
  fileDigest(path) { return fileDigest(path); }
2048
- fileDigestOrEmpty(path) {
2049
- try {
2050
- return this.fileDigest(path);
2051
- }
2052
- catch {
2053
- return "";
2054
- }
2055
- }
1854
+ /** {@link Preservation.fileDigestOrEmpty}. */
1855
+ fileDigestOrEmpty(...args) { return this.preservationComponent.fileDigestOrEmpty(...args); }
2056
1856
  resumeEntry(a, backfillFloor) {
2057
1857
  // A preservation cut is a stop boundary too, so a manifest launch after it reopens what a resume would.
2058
1858
  this.recordContinuityAtStop(a, "preservation");
@@ -2131,221 +1931,14 @@ export class Manager {
2131
1931
  ...(backfillFloor !== undefined ? { backfillFloor } : {}),
2132
1932
  });
2133
1933
  }
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
- }
1934
+ /** {@link Preservation.teardownManagedAgents}. */
1935
+ teardownManagedAgents(...args) { return this.preservationComponent.teardownManagedAgents(...args); }
1936
+ /** {@link Preservation.isProcessBoundSeat}. */
1937
+ isProcessBoundSeat(...args) { return this.preservationComponent.isProcessBoundSeat(...args); }
1938
+ /** {@link Preservation.releaseManagedAgents}. */
1939
+ releaseManagedAgents(...args) { return this.preservationComponent.releaseManagedAgents(...args); }
1940
+ /** {@link Preservation.adoptReleasedSeats}. */
1941
+ adoptReleasedSeats(...args) { return this.preservationComponent.adoptReleasedSeats(...args); }
2349
1942
  async stopRetainedAgentsOnExit() {
2350
1943
  const managed = [...this.agents.values()];
2351
1944
  for (const a of managed)
@@ -2545,51 +2138,12 @@ export class Manager {
2545
2138
  this.serviceServe = undefined;
2546
2139
  await this.retireConnection(s.nc, () => s.handle.stop());
2547
2140
  }
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 */ }
2566
- try {
2567
- await drainAndClose(nc);
2568
- }
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
- }
2141
+ /** {@link BrokerTransport.retireConnection}. */
2142
+ retireConnection(...args) { return this.brokerTransportComponent.retireConnection(...args); }
2143
+ /** {@link BrokerTransport.discardServeCandidate}. */
2144
+ discardServeCandidate(...args) { return this.brokerTransportComponent.discardServeCandidate(...args); }
2145
+ /** {@link BrokerTransport.trackTransport}. */
2146
+ trackTransport(...args) { return this.brokerTransportComponent.trackTransport(...args); }
2593
2147
  async opFinalizeResume(rawArgs) {
2594
2148
  if (this.execution === "none")
2595
2149
  throw new EpEnvelopeError("unimplemented", this.executionRefusal());
@@ -3183,163 +2737,17 @@ export class Manager {
3183
2737
  async waitForPresence(name, timeoutMs = 30_000) {
3184
2738
  return this.seatLaunch.waitForPresence(name, timeoutMs);
3185
2739
  }
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
- }
2740
+ /** {@link StartDoors.opStart}. */
2741
+ opStart(...args) { return this.startDoorsComponent.opStart(...args); }
3275
2742
  listSpawnDirectory(args) { return this.seatLaunch.listSpawnDirectory(args); }
3276
2743
  /** {@link SeatLaunch.resolveSpawnCwd}. */
3277
2744
  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
- }
2745
+ /** {@link HarnessResolution.resolveConnector}. */
2746
+ resolveConnector(...args) { return this.harnessResolutionComponent.resolveConnector(...args); }
3293
2747
  /** {@link SeatLaunch.connectorNames}. */
3294
2748
  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
- }
2749
+ /** {@link ConnectorInventory.inspectConnectorsAtBoot}. */
2750
+ inspectConnectorsAtBoot(...args) { return this.connectorInventoryComponent.inspectConnectorsAtBoot(...args); }
3343
2751
  /** Install and verify the hosted Claude wake channel, or report the cause and remedy. */
3344
2752
  async prepareClaudeWake() {
3345
2753
  try {
@@ -3409,218 +2817,22 @@ export class Manager {
3409
2817
  /** {@link SeatLaunch.classSpawnEnabled}. */
3410
2818
  classSpawnEnabled() { return this.seatLaunch.classSpawnEnabled(); }
3411
2819
  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
- }
2820
+ /** {@link HarnessResolution.launchHarness}. */
2821
+ launchHarness(...args) { return this.harnessResolutionComponent.launchHarness(...args); }
2822
+ /** {@link HarnessResolution.hostLaunchFields}. */
2823
+ hostLaunchFields(...args) { return this.harnessResolutionComponent.hostLaunchFields(...args); }
2824
+ /** {@link HarnessResolution.capabilityRefusal}. */
2825
+ capabilityRefusal(...args) { return this.harnessResolutionComponent.capabilityRefusal(...args); }
3461
2826
  /** {@link SeatLaunch.onceRefusal}. */
3462
2827
  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
- }
2828
+ /** {@link HarnessResolution.eventsRefusal}. */
2829
+ eventsRefusal(...args) { return this.harnessResolutionComponent.eventsRefusal(...args); }
2830
+ /** {@link StatusAndModels.opModels}. */
2831
+ opModels(...args) { return this.statusAndModelsComponent.opModels(...args); }
2832
+ /** {@link StatusAndModels.psOwnerFilter}. */
2833
+ psOwnerFilter(...args) { return this.statusAndModelsComponent.psOwnerFilter(...args); }
2834
+ /** {@link StartDoors.opLaunch}. */
2835
+ opLaunch(...args) { return this.startDoorsComponent.opLaunch(...args); }
3624
2836
  /** Spawn and supervise one agent. The single spawn path: both the control-plane
3625
2837
  * `start` op and declarative roster boot call this. Mints scoped creds in auth mode,
3626
2838
  * resolves the agent file, launches via the connector + runtime, and records the handle.
@@ -4382,223 +3594,12 @@ export class Manager {
4382
3594
  }
4383
3595
  onPresence();
4384
3596
  }
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
- }
3597
+ /** {@link ReadinessWait.awaitReadiness}. */
3598
+ awaitReadiness(...args) { return this.readinessWaitComponent.awaitReadiness(...args); }
3599
+ /** {@link ReadinessWait.tail}. */
3600
+ tail(...args) { return this.readinessWaitComponent.tail(...args); }
3601
+ /** {@link ReadinessWait.watchExit}. */
3602
+ watchExit(...args) { return this.readinessWaitComponent.watchExit(...args); }
4602
3603
  occupancy() { return this.namesCapacity.occupancy(); }
4603
3604
  occupancyText(o) { return this.namesCapacity.occupancyText(o); }
4604
3605
  capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
@@ -4618,191 +3619,22 @@ export class Manager {
4618
3619
  retireDelegatedAgent(name, intentId) { return this.seatStopComponent.retireDelegatedAgent(name, intentId); }
4619
3620
  /** {@link SeatStop.findManagedByTarget}. */
4620
3621
  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
- }
3622
+ /** {@link BrokerTransport.withLifecycleExecutor}. */
3623
+ withLifecycleExecutor(pin, fn) { return this.brokerTransportComponent.withLifecycleExecutor(pin, fn); }
3624
+ /** {@link BrokerTransport.withIssuer}. */
3625
+ withIssuer(fn) { return this.brokerTransportComponent.withIssuer(fn); }
3626
+ /** {@link BrokerTransport.issuanceSeam}. */
3627
+ issuanceSeam(...args) { return this.brokerTransportComponent.issuanceSeam(...args); }
3628
+ /** {@link BrokerTransport.withEndpointServeExecutor}. */
3629
+ withEndpointServeExecutor(fn) { return this.brokerTransportComponent.withEndpointServeExecutor(fn); }
3630
+ /** {@link BrokerTransport.withOpenServeConnection}. */
3631
+ withOpenServeConnection(fn) { return this.brokerTransportComponent.withOpenServeConnection(fn); }
3632
+ /** {@link StatusAndModels.hostedSeatCount}. */
3633
+ hostedSeatCount(...args) { return this.statusAndModelsComponent.hostedSeatCount(...args); }
3634
+ /** {@link StatusAndModels.hostedAgents}. */
3635
+ hostedAgents(...args) { return this.statusAndModelsComponent.hostedAgents(...args); }
3636
+ /** {@link StatusAndModels.managerStatusData}. */
3637
+ managerStatusData(...args) { return this.statusAndModelsComponent.managerStatusData(...args); }
4806
3638
  staticReconciliationStatus() {
4807
3639
  return this.staticLifecycle.staticReconciliationStatus();
4808
3640
  }
@@ -5110,39 +3942,10 @@ export class Manager {
5110
3942
  }
5111
3943
  /** {@link SeatStop.lifecycleMembershipRefusal}. */
5112
3944
  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
- }
3945
+ /** {@link BrokerTransport.withProvisioner}. */
3946
+ withProvisioner(fn) { return this.brokerTransportComponent.withProvisioner(fn); }
3947
+ /** {@link BrokerTransport.withTransferReader}. */
3948
+ withTransferReader(fn) { return this.brokerTransportComponent.withTransferReader(fn); }
5146
3949
  /** {@link SeatStop.opPurge}. */
5147
3950
  opPurge(...args) { return this.seatStopComponent.opPurge(...args); }
5148
3951
  /** {@link PersonaCatalog.opDefinePersona}. */
@@ -5163,103 +3966,7 @@ export class Manager {
5163
3966
  attachAuthorized(...args) { return this.terminalInputComponent.attachAuthorized(...args); }
5164
3967
  /** {@link TerminalInput.establishConsoleSession}. */
5165
3968
  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
- }
3969
+ /** {@link StatusAndModels.list}. */
3970
+ list(...args) { return this.statusAndModelsComponent.list(...args); }
5264
3971
  }
5265
3972
  //# sourceMappingURL=manager.js.map