@cotal-ai/manager 0.170.0 → 0.171.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.js CHANGED
@@ -1,46 +1,47 @@
1
1
  import { UserProvision } from "./user-provision.js";
2
2
  import { TurnRelay, goalKey, caughtEnvelope, TURN_ANSWER_RETENTION_MS } from "./turn-relay.js";
3
3
  import { createHash, randomBytes } from "node:crypto";
4
- import { checkEventStartup, EventStateConflictError, isPermissionDenied, chatStream, drainAndClose, requestSafeReconnect } from "@cotal-ai/core";
4
+ import { drainAndClose } from "@cotal-ai/core";
5
5
  import { hostname } from "node:os";
6
- import { credsAuthenticator, RequestError } from "@nats-io/transport-node";
7
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
6
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
8
7
  import { join, resolve } from "node:path";
9
8
  import { parse as parseYaml } from "yaml";
10
9
  import Headless from "@xterm/headless";
11
- import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, registry, resolveAuthProvider, resolveReadAcl, saveAgentFile, eventChannelPrincipal, capabilityWithin, grantOverreach, } from "@cotal-ai/core";
10
+ import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, injectedSecretStoreIdentity, agentFilePath, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, idFromCreds, identityFromCreds, inspectCredHealth, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, mintCreds, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, parsePrincipalKey, principalKey, probeConnect, registry, resolveAuthProvider, saveAgentFile, capabilityWithin, } from "@cotal-ai/core";
12
11
  import { retainConnectorSeat } from "@cotal-ai/workspace";
13
12
  import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
14
- import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, remintDaemonCreds, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
13
+ 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";
15
14
  import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
16
15
  import { Retirement } from "./retirement.js";
17
16
  import { ServePlane } from "./serve-plane.js";
18
17
  import { NamesCapacity } from "./names-capacity.js";
19
18
  import { AttachEndpoint } from "./attach-endpoint.js";
20
- import { DELIVERY_ADMIN_BOOT_WAIT_MS, isUnansweredDeliveryAdmin, makeManagerEndpointHolderEvictor, untilDeliveryAdminAnswers, withScopedEndpoint } from "./endpoint-evict.js";
19
+ import { DELIVERY_ADMIN_BOOT_WAIT_MS, makeManagerEndpointHolderEvictor, withScopedEndpoint } from "./endpoint-evict.js";
21
20
  import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
22
21
  import { ManagedStaticLifecycle, STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
23
22
  export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
23
+ export { credRenewIntervalMs } from "./credential-renewal.js";
24
24
  import { LeaseKeeper } from "./lease-keeper.js";
25
25
  export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
26
26
  import { SessionRecovery } from "./session-recovery.js";
27
27
  import { SeatCustody, watchConnectorHolder } from "./seat-custody.js";
28
- import { SeatLaunch, ownLists, ownPersona, userMeshEndpointsRefusal } from "./seat-launch.js";
28
+ import { GoalWriter } from "./goal-writer.js";
29
+ import { CredentialRenewal, credRenewIntervalMs, REMOTE_STANDING_BUDGET_MS, remoteStandingTimeLeft, sameStrings } from "./credential-renewal.js";
30
+ import { SeatLaunch, foreignEventChannels, userMeshEndpointsRefusal } from "./seat-launch.js";
29
31
  import { withTimeout } from "./manager-timeout.js";
30
32
  import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
31
- import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, writeInlineSnapshot, parseLaunchSpec, persistLaunchSpec, readContinuityAssignment } from "./launch.js";
33
+ import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, parseLaunchSpec, persistLaunchSpec } from "./launch.js";
32
34
  import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
33
35
  import { controlShutdown } from "./control-shutdown.js";
34
36
  import { RunHosting, servedRequestSubject } from "./run-hosting.js";
35
- import { enrolledAcl } from "./remote-authority.js";
36
37
  import { rejectionText, attemptCleanup, describeCleanupFailures } from "@cotal-ai/core";
37
- import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, supervisePolicy, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
38
+ import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
38
39
  import { TranscriptReceiver } from "./transcript-receive.js";
39
40
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
40
41
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
41
42
  import { jetstreamManager } from "@nats-io/jetstream";
42
43
  import { Kvm } from "@nats-io/kv";
43
- import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts, credentialIdOf, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC, REMOTE_MANAGER_IDENTITY_NAMES } from "@cotal-ai/core";
44
+ import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts } from "@cotal-ai/core";
44
45
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
45
46
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
46
47
  // per-session credentials on their own short-lived connections).
@@ -48,11 +49,10 @@ import { ManagerSessionPlane } from "./session/index.js";
48
49
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
49
50
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
50
51
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
51
- import { serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, MAX_SCHEDULE_MS, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
52
+ import { epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, MAX_SCHEDULE_MS, goalRefOf, turnNoticeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom } from "@cotal-ai/core";
52
53
  import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
53
54
  import { measureManagerVitals } from "./vitals.js";
54
- import { staticLifecycleTransport, activateStaticLifecycle, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, observeStaticSlot, listStaticSlotObservations, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
55
- import { CHAT_ALIAS_PREFIX, } from "./chat-session.js";
55
+ import { staticLifecycleTransport, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, observeStaticSlot, listStaticSlotObservations, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
56
56
  // Capture the loaded package version before an installation can replace its files.
57
57
  const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
58
58
  /** A `once` spawn's task deadline when the caller names none: one hour from the spawn's accept. */
@@ -99,11 +99,6 @@ const DEPROVISION_TIMEOUT_MS = 15_000;
99
99
  * 1.9 s, near the 2 s limit), none at 8 with the shortest total (3.7 s, against 4.8 s at 4). At 8,
100
100
  * one manager queues at most 8 evictions on the daemon, about 3 s of its work at that load. */
101
101
  const RETIREMENT_CONCURRENCY = 8;
102
- /** The delivery-admin `reloadCreds` request bound — STRICTLY GREATER than the daemon's internal
103
- * per-component preflight bound (4s each, run in parallel) so a slow or refused proof returns the
104
- * daemon's STRUCTURED per-component failure, never a client-side timeout that the catch below would
105
- * misrecord as "no delivery-admin responder" (a false negative while the daemon is mid-proof). */
106
- const DELIVERY_ADMIN_RELOAD_TIMEOUT_MS = 15_000;
107
102
  /** A hard preservation stop should settle quickly. The manager still waits and reports a partial
108
103
  * cut rather than pretending a child is gone. Held in ManagerOptions so fake runtimes can shorten it. */
109
104
  const PRESERVE_STOP_TIMEOUT_MS = 10_000;
@@ -127,31 +122,10 @@ export const PASTE_END = "\x1b[201~";
127
122
  * stream. The message carries that runtime's own guidance, which is operator copy and changes; this
128
123
  * marker is the contract a caller keys on so it can act without reading the wording. */
129
124
  export const RUNTIME_NO_TERMINAL_DETAIL = "ai.cotal.manager.runtime-no-terminal";
130
- /** Pick a `setInterval` period for {@link Manager.renewDaemonCreds} that guarantees at least one
131
- * tick lands inside every renewal owner's `[renewAt, exp)` window.
132
- *
133
- * `inspectCredHealth` marks a credential `near-expiry` at 75% of its iat-to-exp lifetime and
134
- * `expired` at 100%, so the window width is TTL/4. Ticks TTL/4 apart therefore land at least once
135
- * inside every window; ticks TTL/2 apart (the old schedule) can miss it entirely for any TTL. That
136
- * is the cause of Cotal #457, reproduced at both TTL=86400 and TTL=20 (the compressed-ratio probe).
137
- *
138
- * Deriving from the caller's TTL keeps the schedule correct for any credential class: the 24h
139
- * `STANDING_RENEWABLE_TTL_SEC` and the 30-day `ROTATION_RENEWED_TTL_SEC` both get a tick inside
140
- * their own renewal window without a hardcoded number. Post-boot responsiveness is already
141
- * covered by the caller invoking `renewDaemonCreds` once synchronously before starting the timer,
142
- * so no separate floor is needed. The pass is idempotent, since `renewDaemonCreds` no-ops each
143
- * credential when its state is `healthy`, so a tick that lands before the window costs one health
144
- * check per owner. A managed seat's credential is judged as of the next tick instead, because the
145
- * seat re-reads its file only once a minute and nothing pushes the renewal to it: a tick that
146
- * lands in the window's last minute can come too late for the seat to adopt it. */
147
- export function credRenewIntervalMs(ttlSeconds) {
148
- return Math.max(1, Math.floor((ttlSeconds / 4) * 1000));
149
- }
150
125
  /** Startup reconciliation overlaps control-service registration. A spawn or attach for one of
151
126
  * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
152
127
  * a reuse. */
153
128
  const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
154
- const REMOTE_STANDING_BUDGET_MS = 10_000;
155
129
  /** The owner a retained seat resumes under: its inventory identity's, which is the same value the
156
130
  * adopted seat records as `userOwner`, so a resumed seat is counted against the owner that held
157
131
  * it before the restart ({@link Manager.ownerSeats}) and not against the mesh's default one. */
@@ -200,16 +174,6 @@ function failedTerminal(error, source) {
200
174
  catch { /* unreadable or not interchangeable */ }
201
175
  return { error: text };
202
176
  }
203
- /** One absolute budget across authority, preflight and adoption waits, or one closed-serve attempt. */
204
- function remoteStandingTimeLeft(deadline) {
205
- const left = deadline - performance.now();
206
- if (left <= 0)
207
- throw new Error("remote manager standing operation exceeded its 10000ms aggregate budget");
208
- return Math.ceil(left);
209
- }
210
- function sameStrings(a, b) {
211
- return JSON.stringify([...(a ?? [])].sort()) === JSON.stringify([...(b ?? [])].sort());
212
- }
213
177
  /** The start of every agent's bearer command: node, its loader flags and this manager's entry,
214
178
  * resolved through every symlink. The agent runs that command for each renewal for as long as it
215
179
  * lives, and an install can replace the bin link meanwhile: get.cotal.ai writes a shell launcher
@@ -261,38 +225,10 @@ function onceStopReason(cause) {
261
225
  default: return cause;
262
226
  }
263
227
  }
264
- class LegacyEventCountPermissionError extends Error {
265
- }
266
228
  const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
267
229
  function participantKey(owner, actor, uid) {
268
230
  return `${owner}.${actor}.${uid}`;
269
231
  }
270
- /**
271
- * Event channels in `channels` that do NOT belong to `{owner, actor}`.
272
- *
273
- * ONE HELPER FOR EVERY SEAM THAT ARMS AN ACL, and that is the whole design. The rule first existed
274
- * only at the spawn accept seam, and a security review found the hole that shape guarantees: resume
275
- * re-arms a managed row straight from the inventory document, and `renewManagedStaticCred` re-mints
276
- * the JWT from that row, so an admin-supplied inventory could carry a foreign concrete event channel
277
- * past a fence that only ever looked at spawns. A rule with one call site is a rule that covers one
278
- * door.
279
- *
280
- * IT COMPARES PRINCIPALS, NOT STRINGS. `eventChannelPrincipal` decodes the channel back to the
281
- * `{owner, actor}` it names, so this is mode-independent: static keys the actor on the allocated
282
- * nkey and user mode keys it on the alias, and neither needs its own branch here.
283
- *
284
- * STATED LIMIT, unchanged and asserted by a cell: the decode refuses anything that is not exactly
285
- * two principal tokens, so a WILDCARD is not an event channel to it. `events.<owner>.>` and
286
- * `events.>` pass untouched and are governed by ordinary ACL authority. This closes the concrete
287
- * form, which is what a caller writes when it knows which agent it wants to read, and not the
288
- * wildcard form, which is what an operator writes deliberately for an observer.
289
- */
290
- function foreignEventChannels(channels, owner, actor) {
291
- return channels.filter((ch) => {
292
- const p = eventChannelPrincipal(ch);
293
- return p !== null && !(p.owner === owner && p.actor === actor);
294
- });
295
- }
296
232
  /** One connector's declared harness binaries resolved on PATH now. The refusal sentence is built only
297
233
  * here, so the boot row and the check for a connector registered after boot can never word it apart. */
298
234
  function resolveHarness(name, requires) {
@@ -307,18 +243,6 @@ function resolveHarness(name, requires) {
307
243
  }
308
244
  return missing.length ? { binaries, reason: `${name} harness needs ${missing.join(", ")} on PATH - not found` } : { binaries };
309
245
  }
310
- /** True only when the delivery-admin rail has no bound responder. A timeout is a hung rail, not absence. */
311
- function isAbsentDeliveryAdmin(error) {
312
- return error instanceof RequestError && error.isNoResponders();
313
- }
314
- /** The store challenge went UNANSWERED while a delivery daemon exists: the rail timed out, or it had
315
- * no responder while the lease row names a holder. Both are what a daemon that is starting or
316
- * re-acquiring its lease looks like, so manager boot waits them out (#871); a renewal pass still
317
- * refuses on the first one. A reply that does not decode was answered and is never this. */
318
- class DeliveryAdminUnanswered extends Error {
319
- }
320
- /** How long one store challenge waits for the delivery daemon's answer. */
321
- const STORE_CHALLENGE_TIMEOUT_MS = 5_000;
322
246
  /** The refusal a control instance with `execution: none` gives every launch, hosting, model and write door. */
323
247
  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";
324
248
  /** The sha256 hex digest of a file's bytes. */
@@ -857,6 +781,92 @@ export class Manager {
857
781
  shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
858
782
  bearerEntryArgv,
859
783
  });
784
+ /** The goal-writer connection and the goal index it reconciles. Every dependency reads through at its use. */
785
+ goalWriterComponent = new GoalWriter({
786
+ auth: () => this.auth,
787
+ goalAcceptances: () => this.goalAcceptances,
788
+ goalWriter: () => this.goalWriter,
789
+ setGoalWriter: (value) => { this.goalWriter = value; },
790
+ goalWriterCreds: () => this.goalWriterCreds,
791
+ setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
792
+ goalWriterIdentity: () => this.goalWriterIdentity,
793
+ leaseStopping: () => this.leaseStopping,
794
+ managerInstanceId: () => this.managerInstanceId,
795
+ readinessTimeoutMs: () => this.readinessTimeoutMs,
796
+ remoteAuthority: () => this.remoteAuthority,
797
+ serviceServe: () => this.serviceServe,
798
+ space: () => this.space,
799
+ turnRelay: () => this.turnRelay,
800
+ goalReconcileDone: () => this.goalReconcileDone,
801
+ setGoalReconcileDone: (value) => { this.goalReconcileDone = value; },
802
+ adoptTurnGoal: (...args) => this.adoptTurnGoal(...args),
803
+ boundedReconnect: (...args) => this.boundedReconnect(...args),
804
+ dial: (...args) => this.dial(...args),
805
+ noticeSeatTurns: (...args) => this.noticeSeatTurns(...args),
806
+ renewRemoteBeforeRedial: (...args) => this.renewRemoteBeforeRedial(...args),
807
+ retireConnection: (...args) => this.retireConnection(...args),
808
+ trackTransport: (...args) => this.trackTransport(...args),
809
+ withEndpointServeExecutor: (fn) => this.withEndpointServeExecutor(fn),
810
+ });
811
+ /** Renewal of the manager's standing credentials. Every dependency reads through at its use. */
812
+ credentialRenewal = new CredentialRenewal({
813
+ agents: () => this.agents,
814
+ auth: () => this.auth,
815
+ credentialPushRetry: () => this.credentialPushRetry,
816
+ setCredentialPushRetry: (value) => { this.credentialPushRetry = value; },
817
+ credentialPushes: () => this.credentialPushes,
818
+ daemonRenewalEligible: () => this.daemonRenewalEligible,
819
+ setDaemonRenewalEligible: (value) => { this.daemonRenewalEligible = value; },
820
+ daemonRenewalOwner: () => this.daemonRenewalOwner,
821
+ setDaemonRenewalOwner: (value) => { this.daemonRenewalOwner = value; },
822
+ endpointServeRenewalTimer: () => this.endpointServeRenewalTimer,
823
+ setEndpointServeRenewalTimer: (value) => { this.endpointServeRenewalTimer = value; },
824
+ ep: () => this.ep,
825
+ finishRemoteBundleAdoption: () => this.finishRemoteBundleAdoption,
826
+ setFinishRemoteBundleAdoption: (value) => { this.finishRemoteBundleAdoption = value; },
827
+ goalWriter: () => this.goalWriter,
828
+ goalWriterCreds: () => this.goalWriterCreds,
829
+ setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
830
+ leaseStopping: () => this.leaseStopping,
831
+ managerInstanceId: () => this.managerInstanceId,
832
+ pendingCredentialPushes: () => this.pendingCredentialPushes,
833
+ remoteAuthority: () => this.remoteAuthority,
834
+ remoteBundleAdoption: () => this.remoteBundleAdoption,
835
+ setRemoteBundleAdoption: (value) => { this.remoteBundleAdoption = value; },
836
+ remoteBundleRenewal: () => this.remoteBundleRenewal,
837
+ setRemoteBundleRenewal: (value) => { this.remoteBundleRenewal = value; },
838
+ remoteExecutorCreds: () => this.remoteExecutorCreds,
839
+ setRemoteExecutorCreds: (value) => { this.remoteExecutorCreds = value; },
840
+ remoteRenewalDebt: () => this.remoteRenewalDebt,
841
+ setRemoteRenewalDebt: (value) => { this.remoteRenewalDebt = value; },
842
+ remoteSupervisorCreds: () => this.remoteSupervisorCreds,
843
+ setRemoteSupervisorCreds: (value) => { this.remoteSupervisorCreds = value; },
844
+ runHosting: () => this.runHosting,
845
+ secretStoreIdentity: () => this.secretStoreIdentity,
846
+ setSecretStoreIdentity: (value) => { this.secretStoreIdentity = value; },
847
+ secrets: () => this.secrets,
848
+ serviceServe: () => this.serviceServe,
849
+ sessionLedgerConn: () => this.sessionLedgerConn,
850
+ sessionLedgerCreds: () => this.sessionLedgerCreds,
851
+ setSessionLedgerCreds: (value) => { this.sessionLedgerCreds = value; },
852
+ space: () => this.space,
853
+ supervisorCredentialPush: () => this.supervisorCredentialPush,
854
+ setSupervisorCredentialPush: (value) => { this.supervisorCredentialPush = value; },
855
+ supervisorCredentialPushPending: () => this.supervisorCredentialPushPending,
856
+ setSupervisorCredentialPushPending: (value) => { this.supervisorCredentialPushPending = value; },
857
+ userMode: () => this.userMode,
858
+ workspaceRoot: () => this.workspaceRoot,
859
+ beginLifecycle: (...args) => this.beginLifecycle(...args),
860
+ dialRemoteStanding: (...args) => this.dialRemoteStanding(...args),
861
+ dialServeConnection: (...args) => this.dialServeConnection(...args),
862
+ discardServeCandidate: (...args) => this.discardServeCandidate(...args),
863
+ mintAndStageGoalWriter: (...args) => this.mintAndStageGoalWriter(...args),
864
+ mintAndStageSessionLedger: (...args) => this.mintAndStageSessionLedger(...args),
865
+ probeStaticCredential: (...args) => this.probeStaticCredential(...args),
866
+ renewManagedStaticCred: (...args) => this.renewManagedStaticCred(...args),
867
+ withEndpointServeExecutor: (fn) => this.withEndpointServeExecutor(fn),
868
+ renewRemoteStandingBundle: (...args) => this.renewRemoteStandingBundle(...args),
869
+ });
860
870
  /** The launch pipeline's leaf steps. Every dependency reads through at its use. */
861
871
  seatLaunch = new SeatLaunch({
862
872
  space: () => this.space,
@@ -878,6 +888,50 @@ export class Manager {
878
888
  canReadPersona: (owner, caller, admin) => this.canReadPersona(owner, caller, admin),
879
889
  epAdminReach: (caller) => this.epAdminReach(caller),
880
890
  startAgent: (opts) => this.startAgent(opts),
891
+ awaitReadiness: (...args) => this.awaitReadiness(...args),
892
+ awaitStartupOutcome: (...args) => this.awaitStartupOutcome(...args),
893
+ capabilityRefusal: (...args) => this.capabilityRefusal(...args),
894
+ delegatedLaunched: () => this.delegatedLaunched,
895
+ dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
896
+ endOnceBeforeServe: (...args) => this.endOnceBeforeServe(...args),
897
+ eventPayloadsWithheld: () => this.eventPayloadsWithheld,
898
+ eventsRefusal: (...args) => this.eventsRefusal(...args),
899
+ eventsRequired: () => this.eventsRequired,
900
+ fileDigest: (...args) => this.fileDigest(...args),
901
+ hostLaunchFields: (...args) => this.hostLaunchFields(...args),
902
+ issuanceSeam: (...args) => this.issuanceSeam(...args),
903
+ launchHarness: (...args) => this.launchHarness(...args),
904
+ launchOwner: (...args) => this.launchOwner(...args),
905
+ leaseStopping: () => this.leaseStopping,
906
+ loadSeatRuntime: (...args) => this.loadSeatRuntime(...args),
907
+ managerLifecycleUid: () => this.managerLifecycleUid,
908
+ namesCapacity: () => this.namesCapacity,
909
+ openOnceDelivery: (...args) => this.openOnceDelivery(...args),
910
+ personaOwner: (...args) => this.personaOwner(...args),
911
+ place: (...args) => this.place(...args),
912
+ provisionUserAgent: (...args) => this.provisionUserAgent(...args),
913
+ readerRemedy: (...args) => this.readerRemedy(...args),
914
+ readinessTimeoutMs: () => this.readinessTimeoutMs,
915
+ refreshUnavailableConnectors: (...args) => this.refreshUnavailableConnectors(...args),
916
+ remoteAuthority: () => this.remoteAuthority,
917
+ resolveConnector: (...args) => this.resolveConnector(...args),
918
+ retirement: () => this.retirement,
919
+ runtimeFor: (...args) => this.runtimeFor(...args),
920
+ seatCapRefusal: (...args) => this.seatCapRefusal(...args),
921
+ seatCustody: () => this.seatCustody,
922
+ secrets: () => this.secrets,
923
+ sessionRecovery: () => this.sessionRecovery,
924
+ shredUserSecrets: (...args) => this.shredUserSecrets(...args),
925
+ staticLifecycle: () => this.staticLifecycle,
926
+ stopAndTrack: (...args) => this.stopAndTrack(...args),
927
+ trackDeprovision: (...args) => this.trackDeprovision(...args),
928
+ transcripts: () => this.transcripts,
929
+ userProvision: () => this.userProvision,
930
+ watchExit: (...args) => this.watchExit(...args),
931
+ watchOnceExit: (...args) => this.watchOnceExit(...args),
932
+ withIssuer: (fn) => this.withIssuer(fn),
933
+ withLifecycleExecutor: (pin, fn) => this.withLifecycleExecutor(pin, fn),
934
+ withProvisioner: (fn) => this.withProvisioner(fn),
881
935
  });
882
936
  constructor(opts) {
883
937
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
@@ -1596,644 +1650,29 @@ export class Manager {
1596
1650
  * Delivery is single-shard today and the endpoint's own responder reads row 0; naming it here
1597
1651
  * keeps the manager's binding check and that reply arguing about the same row. */
1598
1652
  static DELIVERY_SHARD = 0;
1599
- /** Proof that this manager remints into the store the delivery daemon reloads from.
1600
- * Fingerprint-only `reloadCreds` is safe only after this. Two named, different stores
1601
- * refuse the pass. A daemon that is not bound yet is not a named store: start and
1602
- * remint still proceed (tests, delayed delivery), writing this manager's store. The
1603
- * challenge runs again before every remint, so a later daemon on a foreign store is
1604
- * refused then rather than certified by an earlier absence. A request timeout is not
1605
- * absence: a hung rail would skip the proof, so it fails closed.
1606
- *
1607
- * ABSENCE IS READ OFF THE LEASE ROW, never off the rail's no-responder shape alone (#1694).
1608
- * The rail is queue-grouped, so "no responder answered" is itself something the rail reports,
1609
- * and a responder that answers in a shape the client turns into that error makes the pass read
1610
- * "absent" while a holder is live on the row — certifying every later remint with no proof at
1611
- * all. So a no-responder outcome is decided by the row: a row that names a holder makes the
1612
- * pass refuse (undetermined — a live daemon went unanswered, which must not read as "no
1613
- * daemon"), and only a row that is absent or holderless settles "absent", the state start()
1614
- * treats as not-yet-bound. An unreadable row (a failed read, or a key that exists but does not
1615
- * parse) is a genuine unknown and refuses fail-closed, like a hung rail. */
1616
- async daemonStoreRelation(timeoutMs) {
1617
- let reply;
1618
- try {
1619
- reply = await this.ep.requestDeliveryAdmin("reloadStoreIdentity", {}, timeoutMs);
1620
- }
1621
- catch (e) {
1622
- const msg = rejectionText(e);
1623
- if (isAbsentDeliveryAdmin(e))
1624
- return this.absentByLeaseRow(isUnansweredDeliveryAdmin(e));
1625
- const failure = `could not challenge the delivery daemon's SecretStore: ${msg}`;
1626
- throw isUnansweredDeliveryAdmin(e) ? new DeliveryAdminUnanswered(failure) : new Error(failure);
1627
- }
1628
- if (!reply.ok)
1629
- throw new Error(reply.error ?? "delivery daemon refused to name the SecretStore it reloads from");
1630
- let answer;
1631
- try {
1632
- answer = parseDaemonStoreAnswer(reply.data);
1633
- }
1634
- catch (e) {
1635
- throw new Error(`delivery daemon named an unreadable SecretStore: ${rejectionText(e)}. Nothing reminted. ` +
1636
- `Check that delivery and manager use the same Cotal version, then restart delivery through its supervisor. ` +
1637
- `For a saved local delivery service: \`cotal down delivery --space ${this.space}\`, ` +
1638
- `then \`cotal up --space ${this.space}\``);
1639
- }
1640
- // The answerer's own claim first, so an honest non-holder is refused by its own admission and
1641
- // the operator-facing reason names that. This is the CHEAP half of the test and NOT the binding
1642
- // one: a responder that does not hold the lease can assert `true` here just as easily.
1643
- if (!answer.holdsDeliveryLease)
1644
- throw new Error("the delivery-admin rail was answered by a responder that does not hold this space's " +
1645
- "delivery lease, so its SecretStore is not the store the daemon reloads from - nothing reminted");
1646
- // THE BINDING TEST, measured by this manager rather than asserted by the answerer. The lease
1647
- // row's holder is read here under this manager's own credential; the answerer must BE that
1648
- // principal. A reply asserting the claim while some other process holds the shard fails here,
1649
- // which is the case a bare store identity could not see. An unreadable row is an unknown and
1650
- // refuses too: this test may never be satisfied by failing to run.
1651
- const holder = await this.ep.deliveryLeaseHolder(Manager.DELIVERY_SHARD);
1652
- if (holder === undefined)
1653
- throw new Error("this manager could not read the delivery lease row, so it cannot verify that the answering " +
1654
- "responder is the process that reloads the standing credentials - nothing reminted");
1655
- if (holder !== answer.responder)
1656
- throw new Error(`the delivery-admin rail was answered by ${answer.responder}, which is not the holder of ` +
1657
- `this space's delivery lease (${holder}), so its SecretStore is not the store the daemon ` +
1658
- `reloads from - nothing reminted`);
1659
- const daemon = answer.identity;
1660
- // The workspace store records its id the first time it is named, so it is named here, where
1661
- // only an auth manager reaches, rather than in a constructor every open-mode manager runs.
1662
- this.secretStoreIdentity ??= parseSecretStoreIdentity(this.secrets.identity);
1663
- if (!sameSecretStoreIdentity(this.secretStoreIdentity, daemon)) {
1664
- console.error(`! ${divergentSecretStoreNotice(this.secretStoreIdentity, daemon)}`);
1665
- return "divergent";
1666
- }
1667
- return "shared";
1668
- }
1669
- /** Settle a no-responder challenge outcome from the lease row, never from the rail's own
1670
- * reporting shape (#1694). The three cases:
1671
- *
1672
- * 1. The row READS but names a holder: a live daemon holds the shard and the rail went
1673
- * unanswered. That is undetermined, not "no daemon" — treating it as absent would let this
1674
- * manager remint with no proof while a reloading daemon runs, which is exactly what the
1675
- * challenge exists to prevent. Refuse.
1676
- * 2. The row is unreadable — a read that fails (a denied or erroring bucket) OR a key that
1677
- * exists but does not parse as a lease record (`readDeliveryLeaseEntry` throws for both):
1678
- * undetermined, and it refuses the same fail-closed way a hung rail does. Never a silent
1679
- * "absent" over a row the manager could not read.
1680
- * 3. The row is absent or holderless (no key, a DEL/PURGE tombstone, or a row that names no
1681
- * holder): today's "absent", the state start() treats as a daemon that is not bound yet.
1682
- *
1683
- * `deliveryLeaseHolder` swallows its read failures into `undefined`, which would fold case 2
1684
- * into case 3 — so this reads the entry directly and lets the read's own failure refuse. */
1685
- async absentByLeaseRow(unanswered) {
1686
- let entry;
1687
- try {
1688
- entry = await this.ep.readDeliveryLeaseEntry(Manager.DELIVERY_SHARD);
1689
- }
1690
- catch (e) {
1691
- throw new Error(`could not read the delivery lease row to settle whether the delivery daemon is absent ` +
1692
- `(${rejectionText(e)}) - absence is undetermined, nothing reminted`);
1693
- }
1694
- const holder = entry?.info.holder;
1695
- if (holder !== undefined && holder !== "") {
1696
- const refusal = `the delivery-admin rail reported no responder while the delivery lease names a holder ` +
1697
- `(${holder}) - absence cannot be read off the rail alone, and nothing reminted`;
1698
- throw unanswered ? new DeliveryAdminUnanswered(refusal) : new Error(refusal);
1699
- }
1700
- return "absent";
1701
- }
1702
- /** Keep this manager's renewal lease alive between credential passes (#1634). The manager bucket
1703
- * expires keys at MANAGER_LEASE_TTL_MS, far below the credential pass's cadence, so the lease
1704
- * needs its own heartbeat like the per-instance liveness lease. A non-owner calls this too: the
1705
- * CAS is how a survivor picks up a dead owner's expired lease with no operator step. Never
1706
- * throws; a failed heartbeat leaves ownership to the next pass rather than ending the process. */
1707
- async keepDaemonRenewalLease() {
1708
- if (!this.auth || !this.daemonRenewalEligible)
1709
- return;
1710
- try {
1711
- const held = await this.ep.holdDaemonRenewalLease(this.managerInstanceId);
1712
- if (this.daemonRenewalOwner && !held)
1713
- console.error(`! daemon credential renewal for space "${this.space}" passed to another manager (this one lost the renewal lease) - it keeps serving its seats`);
1714
- this.daemonRenewalOwner = held;
1715
- }
1716
- catch (e) {
1717
- console.error(`! could not refresh the daemon renewal lease: ${rejectionText(e)} - ownership is re-decided on the next pass`);
1718
- }
1719
- }
1720
- /** Decide whether THIS manager owns the daemon's credential renewal (#1634). Both conditions are
1721
- * required, because each answers a question the other cannot:
1722
- *
1723
- * 1. The daemon must reload from this manager's store (#1447). Reminting into a store the daemon
1724
- * never reads writes bytes nobody adopts, and fingerprint-only `reloadCreds` would then name a
1725
- * generation the daemon cannot see.
1726
- * 2. This manager must hold the per-space renewal lease. Store identity CANNOT pick one owner on
1727
- * its own: `sameSecretStoreIdentity` is pure equality with no holder and no tiebreak, so every
1728
- * manager sharing one store passes it, and two owners reminting on independent timers have no
1729
- * ordering between them - one's write lands between the other's re-sign and its adoption
1730
- * request, which is the #773 refusal the challenge exists to prevent.
1731
- *
1732
- * A manager failing either test serves the space normally and skips only the daemon remint. */
1733
- async claimDaemonRenewalOwnership(waitMs = 0) {
1734
- // EVERY refusal outcome drops a held lease, not only "divergent". The refusal paths THROW
1735
- // (#1694: a non-holder answer, an unbindable answerer, an unreadable or holder-naming row on a
1736
- // no-responder rail), and a thrown refusal caught by renewDaemonCreds would otherwise leave a
1737
- // manager that once owned the renewal still holding the lease behind its own heartbeat — the
1738
- // pass refuses, the log says so, and the space keeps a renewal owner that must not remint.
1739
- // Deciding here, inside the claim, is what keeps the release on the refusal path itself.
1740
- let relation;
1741
- try {
1742
- // Only the read-only challenge is retried, so a wait that ends mid-attempt abandons a read,
1743
- // never the lease work below.
1744
- relation = await untilDeliveryAdminAnswers(waitMs, (requestMs) => this.daemonStoreRelation(requestMs(STORE_CHALLENGE_TIMEOUT_MS)), (reason, delayMs) => console.error(`! delivery-admin rail did not answer the store challenge (${reason}); retrying in ${delayMs / 1000}s`), (e) => e instanceof DeliveryAdminUnanswered);
1745
- }
1746
- catch (e) {
1747
- this.daemonRenewalEligible = false;
1748
- if (this.daemonRenewalOwner)
1749
- await this.ep.releaseDaemonRenewalLease().catch(() => { });
1750
- this.daemonRenewalOwner = false;
1751
- throw e;
1752
- }
1753
- this.daemonRenewalEligible = relation !== "divergent";
1754
- if (relation === "divergent") {
1755
- // Not our daemon's store: drop any lease we hold rather than sit on it, so the manager that
1756
- // CAN remint is not blocked behind us.
1757
- if (this.daemonRenewalOwner)
1758
- await this.ep.releaseDaemonRenewalLease();
1759
- this.daemonRenewalOwner = false;
1760
- return;
1761
- }
1762
- await this.keepDaemonRenewalLease();
1763
- }
1764
- /** #2073: arm the `endpoint-serve` credential's own renewal from its `[renewAt, exp)` window
1765
- * instead of `credRenewTimer`'s boot-phased TTL/4 tick, which can miss that window depending on
1766
- * when the timer happened to start relative to the credential's `iat`. Called after the initial
1767
- * mint (`registerManagerService`) and after every successful re-mint in the serve branch below,
1768
- * so the schedule always tracks the CURRENT credential. `credsRenewalDelayMs` is the same 75%
1769
- * convention the endpoint's delivery renewal and the membership feed use (`@cotal-ai/core`); no
1770
- * second copy of that arithmetic lives here. */
1771
- scheduleServeRenewal(creds) {
1772
- if (this.endpointServeRenewalTimer)
1773
- clearTimeout(this.endpointServeRenewalTimer);
1774
- const delay = Math.max(1_000, credsRenewalDelayMs(creds));
1775
- const renewAt = new Date(Date.now() + delay).toISOString();
1776
- this.endpointServeRenewalTimer = setTimeout(() => { void this.renewDaemonCreds(); }, delay);
1777
- this.endpointServeRenewalTimer.unref?.();
1778
- console.error(`manager endpoint-serve renewal scheduled at ${renewAt}`);
1779
- }
1653
+ /** {@link CredentialRenewal.absentByLeaseRow}. */
1654
+ absentByLeaseRow(...args) { return this.credentialRenewal.absentByLeaseRow(...args); }
1655
+ /** {@link CredentialRenewal.keepDaemonRenewalLease}. */
1656
+ keepDaemonRenewalLease(...args) { return this.credentialRenewal.keepDaemonRenewalLease(...args); }
1657
+ /** {@link CredentialRenewal.claimDaemonRenewalOwnership}. */
1658
+ claimDaemonRenewalOwnership(...args) { return this.credentialRenewal.claimDaemonRenewalOwnership(...args); }
1659
+ /** {@link CredentialRenewal.scheduleServeRenewal}. */
1660
+ scheduleServeRenewal(...args) { return this.credentialRenewal.scheduleServeRenewal(...args); }
1780
1661
  credentialPushRetry;
1781
1662
  credentialPushes = new Map();
1782
1663
  supervisorCredentialPush;
1783
1664
  pendingCredentialPushes = new Set();
1784
1665
  supervisorCredentialPushPending = false;
1785
- scheduleCredentialPushRetry() {
1786
- if (this.credentialPushRetry || this.leaseStopping)
1787
- return;
1788
- this.credentialPushRetry = setTimeout(() => {
1789
- this.credentialPushRetry = undefined;
1790
- if (this.leaseStopping)
1791
- return;
1792
- void Promise.all([
1793
- ...[...this.pendingCredentialPushes].map((nc) => this.pushRenewedCreds(nc)),
1794
- ...(this.supervisorCredentialPushPending ? [this.pushSupervisorCreds()] : []),
1795
- ]);
1796
- }, 1_000);
1797
- this.credentialPushRetry.unref();
1798
- }
1799
- /** Retain a busy transport and retry its adopted credential without replaying requests. */
1800
- pushRenewedCreds(nc) {
1801
- const active = this.credentialPushes.get(nc);
1802
- if (active)
1803
- return active;
1804
- const push = this.pushRenewedCredsOnce(nc).finally(() => { this.credentialPushes.delete(nc); });
1805
- this.credentialPushes.set(nc, push);
1806
- return push;
1807
- }
1808
- async pushRenewedCredsOnce(nc) {
1809
- this.pendingCredentialPushes.add(nc);
1810
- try {
1811
- await requestSafeReconnect(nc);
1812
- this.pendingCredentialPushes.delete(nc);
1813
- }
1814
- catch (e) {
1815
- if (nc.isClosed())
1816
- this.pendingCredentialPushes.delete(nc);
1817
- console.error(`! manager credential push deferred: ${rejectionText(e)}`);
1818
- if (!nc.isClosed())
1819
- this.scheduleCredentialPushRetry();
1820
- }
1821
- }
1822
- pushSupervisorCreds() {
1823
- if (this.supervisorCredentialPush)
1824
- return this.supervisorCredentialPush;
1825
- const push = this.pushSupervisorCredsOnce().finally(() => { this.supervisorCredentialPush = undefined; });
1826
- this.supervisorCredentialPush = push;
1827
- return push;
1828
- }
1829
- async pushSupervisorCredsOnce() {
1830
- this.supervisorCredentialPushPending = true;
1831
- try {
1832
- await this.ep.refreshCredsRequestSafe();
1833
- this.supervisorCredentialPushPending = false;
1834
- }
1835
- catch (e) {
1836
- console.error(`! remote manager supervisor credential push deferred: ${rejectionText(e)}`);
1837
- this.scheduleCredentialPushRetry();
1838
- }
1839
- }
1840
- /** #2073: the shared bounded-retry shape for a closed standing connection: wait out each of
1841
- * {@link STATIC_RECONCILE_RETRY_DELAYS_MS}, trying `attempt` after each. Waiting does not repair
1842
- * two closes, so they skip the first delay. One that closes while an all-duty renewal is in flight,
1843
- * as one the broker expires just before adoption, tries when that renewal adopts. One whose
1844
- * credential has `expired` tries at once, because its attempt renews the credential. A stop landing
1845
- * while this loop waits is not a fault this loop reports (the caller re-checks `leaseStopping`). */
1846
- async boundedReconnect(label, attempt, expired = false) {
1847
- let first = this.remoteBundleAdoption ?? (expired ? Promise.resolve() : undefined);
1848
- for (const delayMs of STATIC_RECONCILE_RETRY_DELAYS_MS) {
1849
- await (first ?? new Promise((r) => setTimeout(r, delayMs)));
1850
- first = undefined;
1851
- if (this.leaseStopping)
1852
- return true;
1853
- try {
1854
- if (await attempt())
1855
- return true;
1856
- }
1857
- catch (e) {
1858
- console.error(`! manager ${label} re-dial attempt failed: ${rejectionText(e)}`);
1859
- }
1860
- }
1861
- return false;
1862
- }
1863
- /** One class-2 renewal pass: re-sign `.cotal/delivery.creds` + `.cotal/membership-rw.creds`
1864
- * for their existing nkeys, then request the delivery daemon's EXPLICIT `reloadCreds` adoption on the
1865
- * delivery-admin rail and persist the audit record (`.cotal/renewal.<spaceKey>.json`) that `cotal doctor auth`
1866
- * renders — so "file re-signed" and "daemon adopted" are distinguishable states. A missing daemon
1867
- * (no responder) is recorded honestly: each daemon's own 75% renewal timer remains the adoption backstop.
1868
- * Never throws — renewal failure must be LOUD (log + record), not fatal to the supervisor. */
1869
- async renewDaemonCreds() {
1870
- const release = this.beginLifecycle();
1871
- if (!release)
1872
- return;
1873
- try {
1874
- // #1634: re-decide every pass, so a daemon that moved onto this manager's store becomes
1875
- // ownable, one that moved off retires this manager's ownership, and a crashed owner's expired
1876
- // lease is taken over by a survivor.
1877
- await this.claimDaemonRenewalOwnership();
1878
- // Re-sign through the manager's ONE store — the SAME store the delivery daemon reads
1879
- // (`runDelivery(args, store)`), so a hosted remint writes the store the daemon renews from,
1880
- // never a divergent one. Locally this is the workstation FS store (`.cotal/*.creds`).
1881
- // `this.space` gates cross-space signer swaps; the `preflight` proves broker acceptance before
1882
- // overwriting from ANY signer form (full or stripped). A same-label alternate full bundle is
1883
- // self-bound, not broker-bound, so the manager-hosted path proves every re-sign before it could
1884
- // clobber the last-good with a broker-dead cred; a wrong-account signer's cred is refused here.
1885
- const results = this.daemonRenewalOwner
1886
- ? await remintDaemonCreds(this.workspaceRoot, this.space, this.secrets, {
1887
- preflight: (creds) => this.probeStaticCredential(creds).then((r) => r.ok),
1888
- })
1889
- : [];
1890
- const resigned = results.filter((r) => r.ok);
1891
- let adoption;
1892
- if (resigned.length) {
1893
- // Hand the daemon the EXPECTED generation per component (SHA-256 of the JWT we just
1894
- // re-signed) so its reply proves it adopted THIS generation, not merely re-read some file.
1895
- const expected = {};
1896
- for (const r of resigned) {
1897
- if (r.file === DELIVERY_CREDS_KIND && r.fingerprint)
1898
- expected.delivery = r.fingerprint;
1899
- else if (r.file === MEMBERSHIP_RW_CREDS_KIND && r.fingerprint)
1900
- expected.membership = r.fingerprint;
1901
- }
1902
- try {
1903
- const reply = await this.ep.requestDeliveryAdmin("reloadCreds", { expected }, DELIVERY_ADMIN_RELOAD_TIMEOUT_MS);
1904
- // Keep the per-component aggregate on BOTH outcomes: on a top-level failure `reply.data`
1905
- // still carries which component adopted and which was refused, which `doctor auth` renders.
1906
- adoption = reply.ok
1907
- ? { ok: true, detail: reply.data }
1908
- : { ok: false, error: reply.error, detail: reply.data };
1909
- }
1910
- catch (e) {
1911
- adoption = { ok: false, error: `no delivery-admin responder (${rejectionText(e)}) - the daemon's 75% re-read backstop adopts the re-signed file` };
1912
- }
1913
- }
1914
- for (const r of results.filter((x) => !x.ok && !x.skipped))
1915
- console.error(`! credential renewal: could not re-sign ${r.file}: ${r.error} - the daemon dies loud at this cred's expiry unless it is reminted`);
1916
- if (adoption && !adoption.ok)
1917
- console.error(`! credential renewal: daemon adoption failed: ${adoption.error}`);
1918
- // `writeRenewalRecord` redacts the ephemeral fingerprint at the persistence boundary (covering
1919
- // the `doctor auth --fix` writer too), so the results pass straight through.
1920
- // A non-owner (#1634) re-signed nothing, so it writes no record: an empty one renders in
1921
- // `doctor auth` as a pass that never ran.
1922
- if (this.daemonRenewalOwner)
1923
- writeRenewalRecord(this.workspaceRoot, this.space, { ts: new Date().toISOString(), owner: "manager", results, adoption });
1924
- this.warnOnSystemCredExpiry();
1925
- // The MANAGER is the renewal owner for its managed-static agent creds —
1926
- // supervisor-side PUSH remint for recorded LIVE slots (the child JWT is never proof of
1927
- // incarnation; a copied credential cannot drive this and is stranded at its own row's TTL).
1928
- // Same class-2 mechanics as the daemon creds: re-sign the file for the SAME nkey; the
1929
- // agent endpoint's 75% source re-read adopts it.
1930
- //
1931
- // Each credential is judged as of the NEXT pass, so one whose renewal point falls before it
1932
- // is re-signed now, ahead of the endpoint's re-read. Judged as of now, a credential whose
1933
- // renewal point lands just after a pass waited a whole interval: the endpoint warned every
1934
- // minute that the file still held the old generation, and when the next pass came in the
1935
- // credential's last minute, the endpoint's one-minute retry could miss it and the connection
1936
- // expired.
1937
- const nextPassSec = Math.floor(Date.now() / 1000) + Math.ceil(credRenewIntervalMs(STANDING_RENEWABLE_TTL_SEC) / 1000);
1938
- if (!this.userMode) {
1939
- for (const a of [...this.agents.values()]) {
1940
- // The `terminalizing` test here is an OPTIMISATION, NOT THE GUARD. There are awaits below
1941
- // it, so an agent can latch mid-iteration and this filter will have already let it
1942
- // through — what actually refuses is the same test at the top of
1943
- // {@link renewManagedStaticCred}, which every renewal on this path goes through.
1944
- // COUPLING: deleting or weakening that check silently promotes this line from an
1945
- // optimisation into the whole guard, and nothing fails at the moment of the change.
1946
- if (a.userOwner || a.terminalizing || !a.seed || !a.secretPaths?.creds)
1947
- continue;
1948
- try {
1949
- const stored = await this.secrets.get(agentSecretKeyForFile(a.secretPaths.creds, this.space));
1950
- if (stored === undefined)
1951
- continue; // no materialized cred (never minted here) - nothing to renew
1952
- const health = inspectCredHealth(stored, nextPassSec);
1953
- if (health.state === "healthy")
1954
- continue;
1955
- if (health.state === "unbounded" || health.state === "unreadable") {
1956
- console.error(`! managed cred renewal ${a.name}: credential is ${health.state}${health.error ? ` (${health.error})` : ""} - not renewed (a pre-TTL credential stays as minted until respawn)`);
1957
- continue;
1958
- }
1959
- await this.renewManagedStaticCred(a);
1960
- }
1961
- catch (e) {
1962
- console.error(`! managed cred renewal ${a.name}: ${rejectionText(e)} - the agent dies loud at this cred's expiry unless it is reminted`);
1963
- }
1964
- }
1965
- }
1966
- // The manager is the `endpoint-serve` renewal owner for its own
1967
- // service credential: re-mint the same serve identity with a fresh bounded exp through the
1968
- // §13.1 mint fence over a scoped one-shot executor (staging a new ledger row in a later
1969
- // second or idempotently re-staging the active row within the same second, and releasing only
1970
- // on winning the gate CAS; never the standing connection). The serve connection's
1971
- // authenticator presents the refreshed credential on its next (re)connect.
1972
- if (this.serviceServe?.creds && this.auth) {
1973
- const s = this.serviceServe;
1974
- const authRef = this.auth;
1975
- try {
1976
- const health = inspectCredHealth(this.serviceServe.creds);
1977
- if (health.state !== "healthy") {
1978
- s.creds = await this.withEndpointServeExecutor(({ authKv }) => mintCreds(authRef, s.identity, "endpoint-serve", {
1979
- serveIssuance: serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId }),
1980
- endpointServe: s.grant,
1981
- }));
1982
- // #2073: a superseded instance's re-mint fails the gate CAS above and lands in the
1983
- // catch below, not here — this re-mint already re-checks the issuance gate through
1984
- // the SAME executor a fresh registration would use, so there is no second epoch read
1985
- // to add before re-binding after a re-dial.
1986
- await this.pushRenewedCreds(s.nc);
1987
- this.scheduleServeRenewal(s.creds);
1988
- }
1989
- }
1990
- catch (e) {
1991
- console.error(`! endpoint-serve renewal: ${rejectionText(e)} - the manager's service endpoint dies loud at this cred's expiry unless it is re-registered`);
1992
- }
1993
- }
1994
- // The manager is also the goal-writer's renewal owner — re-mint the SAME
1995
- // goal-writer nkey with a fresh bounded exp AND re-stage its new credId into the §13.1 family,
1996
- // through the scoped executor (never the standing seed). Without this the standing goal-writer
1997
- // connection dies at its TTL and spawn-as-action stops accepting until a restart. The
1998
- // connection's authenticator presents the refreshed credential on its next (re)connect.
1999
- if (this.goalWriter && this.goalWriterCreds && this.auth) {
2000
- const gw = this.goalWriter;
2001
- try {
2002
- if (inspectCredHealth(this.goalWriterCreds).state !== "healthy") {
2003
- const fresh = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageGoalWriter(authKv));
2004
- this.goalWriterCreds = fresh;
2005
- gw.creds = fresh;
2006
- await this.pushRenewedCreds(gw.nc);
2007
- }
2008
- }
2009
- catch (e) {
2010
- console.error(`! goal-writer renewal: ${rejectionText(e)} - spawn-as-action stops accepting at this cred's expiry unless the manager restarts`);
2011
- }
2012
- }
2013
- // The manager is also the session-ledger's renewal owner — re-mint the SAME nkey
2014
- // with a fresh bounded exp AND re-stage its new credId into the §13.1 family, through the
2015
- // scoped executor. Without this the standing session-ledger connection dies at its TTL and
2016
- // `attach` stops establishing sessions until a restart. The connection's authenticator presents
2017
- // the refreshed credential on its next (re)connect.
2018
- // SPEC 14.6: every hosted drive's per-run `run-driver` credential is the manager's to renew
2019
- // for the same nkey; a run parked in a pause for days must not die at the credential's TTL.
2020
- await this.runHosting?.renew();
2021
- if (this.sessionLedgerConn && this.sessionLedgerCreds && this.auth) {
2022
- const sw = this.sessionLedgerConn;
2023
- try {
2024
- if (inspectCredHealth(this.sessionLedgerCreds).state !== "healthy") {
2025
- const fresh = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageSessionLedger(authKv));
2026
- this.sessionLedgerCreds = fresh;
2027
- sw.creds = fresh;
2028
- await this.pushRenewedCreds(sw.nc);
2029
- }
2030
- }
2031
- catch (e) {
2032
- console.error(`! session-ledger renewal: ${rejectionText(e)} - attach stops establishing sessions at this cred's expiry unless the manager restarts`);
2033
- }
2034
- }
2035
- }
2036
- catch (e) {
2037
- console.error(`! credential renewal pass failed: ${rejectionText(e)}`);
2038
- }
2039
- finally {
2040
- release();
2041
- }
2042
- }
2043
- /** Renew the remote registration executor through the typed host protocol. A healthy credential
2044
- * is retained; near-expiry and expired credentials are replaced for the same nkey. */
2045
- async renewRemoteExecutor(force = false) {
2046
- if (!this.remoteAuthority)
2047
- return;
2048
- const current = this.remoteExecutorCreds;
2049
- if (!force && current && inspectCredHealth(current).state === "healthy")
2050
- return;
2051
- try {
2052
- this.remoteExecutorCreds = await this.remoteAuthority.renewExecutor();
2053
- }
2054
- catch (e) {
2055
- console.error(`! remote manager executor renewal: ${rejectionText(e)} - registration maintenance and clean deregistration remain unavailable until renewal succeeds`);
2056
- if (force)
2057
- throw e;
2058
- }
2059
- }
2060
- /** An active signerless manager renews its standing duties together. The issuer stages the closed
2061
- * credential family first; broker preflight proves every JWT and existing caller-held nkey
2062
- * before any mutable holder changes. A failed candidate leaves all current creds intact. */
2063
- async renewRemoteStandingBundle(force = false) {
2064
- if (this.remoteBundleRenewal)
2065
- return this.remoteBundleRenewal;
2066
- if (this.leaseStopping)
2067
- return;
2068
- this.remoteBundleAdoption = new Promise((resolve) => { this.finishRemoteBundleAdoption = resolve; });
2069
- const renewal = this.renewRemoteStandingBundleOnce(force, performance.now() + REMOTE_STANDING_BUDGET_MS);
2070
- this.remoteBundleRenewal = renewal;
2071
- try {
2072
- await renewal;
2073
- }
2074
- finally {
2075
- this.finishRemoteBundleAdoption?.();
2076
- if (this.remoteBundleRenewal === renewal) {
2077
- this.remoteBundleRenewal = undefined;
2078
- this.remoteBundleAdoption = undefined;
2079
- this.finishRemoteBundleAdoption = undefined;
2080
- }
2081
- }
2082
- }
2083
- /** A signerless manager's closed standing connection re-dials through the all-duty family only.
2084
- * A healthy holder re-dials as is. An unhealthy one waits for the closed renewal and adoption,
2085
- * and a refusal fails this attempt with last-good and debt kept. Nothing is minted locally. */
2086
- async renewRemoteBeforeRedial(label, read) {
2087
- if (inspectCredHealth(read() ?? "").state === "healthy")
2088
- return;
2089
- await this.renewRemoteStandingBundle(true);
2090
- if (inspectCredHealth(read() ?? "").state !== "healthy")
2091
- throw new Error(`the ${label} credential is not healthy after all-duty renewal; last-good is kept and nothing is minted locally`);
2092
- }
2093
- async renewRemoteStandingBundleOnce(force, deadline) {
2094
- const remote = this.remoteAuthority;
2095
- if (!remote?.renewStandingBundle || !this.serviceServe)
2096
- return;
2097
- const current = [this.remoteSupervisorCreds, this.remoteExecutorCreds, this.serviceServe.creds,
2098
- this.goalWriterCreds, this.sessionLedgerCreds];
2099
- if (!force && current.every((cred) => cred && inspectCredHealth(cred).state === "healthy")) {
2100
- await Promise.all([
2101
- ...[...this.pendingCredentialPushes].map((nc) => this.pushRenewedCreds(nc)),
2102
- ...(this.supervisorCredentialPushPending ? [this.pushSupervisorCreds()] : []),
2103
- ]);
2104
- return;
2105
- }
2106
- const processEpoch = this.serviceServe.grant.epoch;
2107
- let candidate;
2108
- const serving = this.serviceServe;
2109
- const previous = { nc: serving.nc, handle: serving.handle };
2110
- let replacement;
2111
- let adopted = false;
2112
- try {
2113
- // Only this continuation can adopt. A host operation may still issue after this wait times
2114
- // out, but its late result cannot re-enter preflight or change any Manager holder.
2115
- candidate = await withTimeout(remote.renewStandingBundle(processEpoch), remoteStandingTimeLeft(deadline), "remote manager standing authority exceeded its 10000ms aggregate budget; issuance outcome is unknown");
2116
- if (Object.keys(candidate).sort().join(",") !== [...REMOTE_MANAGER_IDENTITY_NAMES].sort().join(","))
2117
- throw new Error("host returned an incomplete or widened standing credential family");
2118
- for (const name of REMOTE_MANAGER_IDENTITY_NAMES) {
2119
- if (typeof candidate[name] !== "string" || inspectCredHealth(candidate[name]).state === "unreadable")
2120
- throw new Error(`host returned an unreadable ${name} credential`);
2121
- if (!remote.accountPublicKey || accountFromCreds(candidate[name]) !== remote.accountPublicKey)
2122
- throw new Error(`host returned a ${name} credential for another account`);
2123
- if (credsClaims(candidate[name]).sub !== remote.identities[name].id)
2124
- throw new Error(`host returned a ${name} credential for a different nkey than the held identity`);
2125
- const staged = candidate[name];
2126
- const nc = await this.dialRemoteStanding({ authenticator: (nonce) => credsAuthenticator(new TextEncoder().encode(staged))(nonce), maxReconnectAttempts: 0 }, deadline);
2127
- await nc.close();
2128
- }
2129
- remoteStandingTimeLeft(deadline);
2130
- if (this.leaseStopping || this.serviceServe !== serving || serving.nc !== previous.nc || serving.grant.epoch !== processEpoch)
2131
- throw new Error("manager changed its active serve epoch or connection while standing renewal was in flight");
2132
- const stagedServeCreds = candidate.serve;
2133
- replacement = await this.dialServeConnection({ ...serving, creds: stagedServeCreds }, () => adopted ? serving.creds : stagedServeCreds, deadline);
2134
- remoteStandingTimeLeft(deadline);
2135
- if (this.leaseStopping || this.serviceServe !== serving || serving.nc !== previous.nc || serving.grant.epoch !== processEpoch)
2136
- throw new Error("manager changed its active serve epoch or connection while standing renewal was in flight");
2137
- if (REMOTE_MANAGER_IDENTITY_NAMES.some((name) => inspectCredHealth(candidate[name]).state !== "healthy"))
2138
- throw new Error("standing candidate is no longer healthy after broker preflight");
2139
- serving.nc = replacement.nc;
2140
- serving.handle = replacement.handle;
2141
- replacement = undefined;
2142
- this.remoteSupervisorCreds = candidate.supervisor;
2143
- this.remoteExecutorCreds = candidate.executor;
2144
- this.serviceServe.creds = candidate.serve;
2145
- adopted = true;
2146
- this.goalWriterCreds = candidate.goalWriter;
2147
- this.sessionLedgerCreds = candidate.sessionLedger;
2148
- if (this.goalWriter)
2149
- this.goalWriter.creds = candidate.goalWriter;
2150
- if (this.sessionLedgerConn)
2151
- this.sessionLedgerConn.creds = candidate.sessionLedger;
2152
- // Adoption is committed above; a connection that cannot come back yet is a push failure the
2153
- // endpoint's own reconnect loop retries with the adopted credential, not unadopted debt.
2154
- this.remoteRenewalDebt = undefined;
2155
- // Maintenance needed by admitted handlers must not wait for those same handlers to drain.
2156
- this.finishRemoteBundleAdoption?.();
2157
- await withTimeout(Promise.all([
2158
- this.pushSupervisorCreds(),
2159
- (async () => {
2160
- try {
2161
- // A handler or a lost broker PONG can keep stop/flush pending forever. Only the
2162
- // retired transport is expendable: never retry its requests or close the replacement.
2163
- await withTimeout((async () => {
2164
- await previous.handle.stop();
2165
- await previous.nc.flush();
2166
- })(), 5_000, "old serve drain unfinished after 5000ms; closing retired transport, in-flight request outcomes are unknown and must not be retried");
2167
- }
2168
- finally {
2169
- await previous.nc.close();
2170
- }
2171
- })().catch((e) => console.error(`! remote manager retired serve drainage after renewal: ${rejectionText(e)}`)),
2172
- ...(this.goalWriter ? [this.pushRenewedCreds(this.goalWriter.nc)] : []),
2173
- ...(this.sessionLedgerConn ? [this.pushRenewedCreds(this.sessionLedgerConn.nc)] : []),
2174
- ]), remoteStandingTimeLeft(deadline), "remote manager standing reconnect exceeded its 10000ms aggregate budget; adopted transports keep their native reconnect ownership");
2175
- }
2176
- catch (e) {
2177
- if (replacement) {
2178
- await this.discardServeCandidate(replacement.nc, replacement.handle);
2179
- }
2180
- if (adopted) {
2181
- console.error(`! remote manager adopted standing family: ${rejectionText(e)}`);
2182
- return;
2183
- }
2184
- const unadoptedSubjects = candidate && typeof candidate === "object"
2185
- ? Object.values(candidate).flatMap((cred) => { try {
2186
- return typeof cred === "string" && credsClaims(cred).sub ? [credsClaims(cred).sub] : [];
2187
- }
2188
- catch {
2189
- return [];
2190
- } })
2191
- : REMOTE_MANAGER_IDENTITY_NAMES.map((name) => remote.identities[name].id);
2192
- this.remoteRenewalDebt = { at: Date.now(), processEpoch, reason: rejectionText(e), unadoptedSubjects };
2193
- console.error(`! remote manager all-duty renewal: ${this.remoteRenewalDebt.reason} - no unsigned or local replacement is available`);
2194
- if (force)
2195
- throw e;
2196
- }
2197
- }
2198
- /** Warn, on every renewal pass, when a $SYS credential is at or past its renewal point.
2199
- *
2200
- * The manager is the renewal owner for every credential it CAN re-sign, and these two are the ones
2201
- * it cannot: they are `rotation-renewed`, so no resident process re-mints them and they simply die
2202
- * on their 30-day horizon. Before this, a mesh that never ran `doctor auth` got no signal at all,
2203
- * it discovered the expiry as an "Authorization Violation" in the delivery log and a refused
2204
- * membership adoption, weeks after the warning would have been actionable (#338). The pass runs
2205
- * every half-TTL of the 24h class, so this repeats about twice a day for the ~7 days between the
2206
- * renewal point and expiry: loud enough to be seen, bounded enough not to be noise.
2207
- *
2208
- * Diagnostic only, and deliberately non-fatal: renewal is an operator action (`cotal down` then
2209
- * `cotal up --rotate-sys`, which needs a broker restart), so the manager must report it, never
2210
- * attempt it. An absent file is the unprovisioned space, reported by the daemon that needs it. */
2211
- warnOnSystemCredExpiry() {
2212
- for (const file of SYSTEM_CREDS_FILES) {
2213
- let health;
2214
- try {
2215
- // The pair is PER-SPACE, so the location comes from the resolver and never from a
2216
- // path built here (§2 rule 1). Building `.cotal/<kind>` instead would not warn on a wrong
2217
- // file — it would silently warn on NOTHING, for every provisioned root, forever, which is
2218
- // exactly the signal #338 added this for. The resolver may also refuse (§2 rules 3, 4); that
2219
- // refusal is caught with the unreadable case for the reason on the tin — the daemon that
2220
- // NEEDS the pair resolves it through the same function and reports it loudly there, so a
2221
- // diagnostic pass has nothing to add by crashing renewal.
2222
- const path = join(this.workspaceRoot, ".cotal", spaceMaterialKey(file, this.space, { injected: false, root: this.workspaceRoot }));
2223
- if (!existsSync(path))
2224
- continue;
2225
- health = inspectCredHealth(readFileSync(path, "utf8"));
2226
- }
2227
- catch {
2228
- continue; // an unreadable $SYS file is the daemon's loud failure, not a renewal-pass crash
2229
- }
2230
- const when = health.exp ? new Date(health.exp * 1000).toISOString() : "an unknown date";
2231
- if (health.state === "expired")
2232
- console.error(`! $SYS credential ${file} EXPIRED ${when} - the broker denies it, and NOTHING renews it in place (it is rotation-renewed). Live eviction and the membership feed stay down until: \`cotal down\` then \`cotal up --rotate-sys\` (agents, creds and data survive)`);
2233
- else if (health.state === "near-expiry")
2234
- console.error(`! $SYS credential ${file} expires ${when} and nothing renews it in place (it is rotation-renewed) - schedule: \`cotal down\` then \`cotal up --rotate-sys\` (agents, creds and data survive)`);
2235
- }
2236
- }
1666
+ /** {@link CredentialRenewal.boundedReconnect}. */
1667
+ boundedReconnect(...args) { return this.credentialRenewal.boundedReconnect(...args); }
1668
+ /** {@link CredentialRenewal.renewDaemonCreds}. */
1669
+ renewDaemonCreds(...args) { return this.credentialRenewal.renewDaemonCreds(...args); }
1670
+ /** {@link CredentialRenewal.renewRemoteExecutor}. */
1671
+ renewRemoteExecutor(...args) { return this.credentialRenewal.renewRemoteExecutor(...args); }
1672
+ /** {@link CredentialRenewal.renewRemoteStandingBundle}. */
1673
+ renewRemoteStandingBundle(...args) { return this.credentialRenewal.renewRemoteStandingBundle(...args); }
1674
+ /** {@link CredentialRenewal.renewRemoteBeforeRedial}. */
1675
+ renewRemoteBeforeRedial(...args) { return this.credentialRenewal.renewRemoteBeforeRedial(...args); }
2237
1676
  /** Admit one lifecycle/control operation while active. The synchronous increment is the fence:
2238
1677
  * preserveState and stop close it before their first await, so work is either counted or rejected. */
2239
1678
  beginLifecycle(resumeOperation = false) {
@@ -4409,8 +3848,6 @@ export class Manager {
4409
3848
  ...(served !== undefined ? { served } : {}),
4410
3849
  }, caller, hooks, authenticatedCaller);
4411
3850
  }
4412
- /** {@link SeatLaunch.checkSpawnCwd}. */
4413
- checkSpawnCwd(resolved) { return this.seatLaunch.checkSpawnCwd(resolved); }
4414
3851
  listSpawnDirectory(args) { return this.seatLaunch.listSpawnDirectory(args); }
4415
3852
  /** {@link SeatLaunch.resolveSpawnCwd}. */
4416
3853
  resolveSpawnCwd(value) { return this.seatLaunch.resolveSpawnCwd(value); }
@@ -4548,8 +3985,6 @@ export class Manager {
4548
3985
  /** {@link SeatLaunch.classSpawnEnabled}. */
4549
3986
  classSpawnEnabled() { return this.seatLaunch.classSpawnEnabled(); }
4550
3987
  omitClassCommands() { return this.seatLaunch.omitClassCommands(); }
4551
- /** {@link SeatLaunch.harnessUnavailableError}. */
4552
- harnessUnavailableError(reason, route) { return this.seatLaunch.harnessUnavailableError(reason, route); }
4553
3988
  /** The harness binaries a managed launch runs, as boot resolved them, or the refusal naming what is
4554
3989
  * missing. Spawn, resume and the model catalog all take it, so a seat launches from the same files
4555
3990
  * whichever path starts it and the catalog never disagrees with a launch about whether the harness
@@ -4601,8 +4036,6 @@ export class Manager {
4601
4036
  }
4602
4037
  /** {@link SeatLaunch.onceRefusal}. */
4603
4038
  onceRefusal(connector, runtime, launch, spawner, hooks) { return this.seatLaunch.onceRefusal(connector, runtime, launch, spawner, hooks); }
4604
- /** {@link SeatLaunch.spawnerName}. */
4605
- spawnerName(spawner) { return this.seatLaunch.spawnerName(spawner); }
4606
4039
  /** The refusal for an event-plane choice the registration policy or the connector cannot meet.
4607
4040
  * Spawn and resume both ask before a seat's launch is built, so a seat retained without the
4608
4041
  * plane cannot come back on a space that now requires it. An absent choice arms supported planes. */
@@ -4777,7 +4210,7 @@ export class Manager {
4777
4210
  if (!release)
4778
4211
  return { ok: false, error: this.maintenanceError() };
4779
4212
  try {
4780
- return await this.startAgentActive(opts, spawner, hooks, authenticatedCaller);
4213
+ return await this.seatLaunch.startActive(opts, spawner, hooks, authenticatedCaller);
4781
4214
  }
4782
4215
  finally {
4783
4216
  release();
@@ -4793,1125 +4226,6 @@ export class Manager {
4793
4226
  spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") { return this.seatLaunch.spawnBoundRefusal(bound, grant, armsEvents, door); }
4794
4227
  /** {@link SeatLaunch.managedStaticInstanceReads}. */
4795
4228
  managedStaticInstanceReads(capabilities) { return this.seatLaunch.managedStaticInstanceReads(capabilities); }
4796
- async startAgentActive(opts, spawner, hooks, authenticatedCaller) {
4797
- // Before the first await, so the grant, the launch, the retained form and the restart slot all read
4798
- // the lists and the restart policy as admitted.
4799
- opts = ownLists(opts);
4800
- if (opts.resolved)
4801
- opts.resolved = ownLists(opts.resolved);
4802
- if (opts.persona !== undefined)
4803
- opts.persona = ownPersona(opts.persona);
4804
- if (opts.supervise) {
4805
- opts.supervise = { restarts: opts.supervise.restarts, windowMs: opts.supervise.windowMs };
4806
- // The budget is checked here, where it is held, not only at the wire: an in-process caller of
4807
- // this export is refused before anything launches, rather than getting a seat that joins and is
4808
- // torn down when its seat record will not take the policy (#3298).
4809
- const policy = supervisePolicy.safeParse(opts.supervise);
4810
- if (!policy.success)
4811
- return { ok: false, error: `supervise.${policy.error.issues[0]?.path.join(".")}: expected a positive integer` };
4812
- }
4813
- if (opts.once)
4814
- opts.once = { deadlineMs: opts.once.deadlineMs };
4815
- let runtime;
4816
- try {
4817
- await this.loadSeatRuntime(opts.runtime);
4818
- runtime = this.runtimeFor(opts.runtime);
4819
- }
4820
- catch (e) {
4821
- return { ok: false, error: rejectionText(e) };
4822
- }
4823
- if (opts.delegatedIntent) {
4824
- if (!this.remoteAuthority?.executeDelegatedUserIntent)
4825
- return { ok: false, error: `"${opts.name}" names a delegated user intent, and this manager has no host execution for one` };
4826
- if (opts.supervise)
4827
- return { ok: false, error: `"${opts.name}" names a delegated user intent, and a delegated agent is never restarted (SPEC 13.16)` };
4828
- // A delegated launch's spawner is the user's principal, never the composition root's call.
4829
- spawner = opts.delegatedIntent.parent;
4830
- }
4831
- const persona = await this.spawnPersona(opts, spawner, authenticatedCaller);
4832
- if ("error" in persona)
4833
- return { ok: false, error: persona.error, ...(persona.code ? { code: persona.code } : {}) };
4834
- const { ref, def, agent, inline } = persona;
4835
- // An inline persona's file is its snapshot, written once the lifecycle uid is final; until then
4836
- // a refusal names the persona instead of a path.
4837
- let configPath = persona.configPath;
4838
- const where = configPath ?? `inline persona "${ref}"`;
4839
- // Materialize the requested connector before the capacity/reserve span so its lazy import
4840
- // cannot interleave that synchronous allocation. On the manifest binary this also honors a
4841
- // live `cotal ext remove`: a removed connector is rejected here even if an earlier spawn already
4842
- // imported it. A broken/missing connector fails loud here with a clear name + install hint.
4843
- let connector;
4844
- try {
4845
- connector = await this.resolveConnector(agent);
4846
- }
4847
- catch (e) {
4848
- const error = rejectionText(e);
4849
- // An action refusal here precedes capacity, allocation and onAccepted. Preserve that proof
4850
- // through serveSpawnGoal without changing the direct startAgent ControlReply contract.
4851
- if (hooks?.onAccepted)
4852
- throw new EpEnvelopeError("failed-precondition", error, undefined, "not-executed");
4853
- return { ok: false, error };
4854
- }
4855
- // Read here, beside the connector, so the capacity check and the reserve below take no new await.
4856
- const run = await this.spawnRun(authenticatedCaller, opts.runId);
4857
- if (run !== undefined && "refused" in run)
4858
- return { ok: false, error: `spawn: ${run.refused}` };
4859
- const bound = await this.staticSpawnBound(authenticatedCaller, run);
4860
- const readinessTimeoutMs = connector.readinessTimeoutMs ?? this.readinessTimeoutMs;
4861
- if (!Number.isSafeInteger(readinessTimeoutMs) || readinessTimeoutMs <= 0)
4862
- return { ok: false, error: `connector ${connector.name} declares invalid readinessTimeoutMs ${JSON.stringify(connector.readinessTimeoutMs)}; expected a positive safe integer` };
4863
- // Fail fast when full. If hosted Claude has to await wake setup, resample capacity after it.
4864
- // The final capacity check and the reserve below stay in the same tick or two concurrent
4865
- // spawns could overshoot the ceiling or pick the same name.
4866
- let occupancy = this.namesCapacity.occupancy(); // prunes expired cooling stamps; counts each name once
4867
- if (occupancy.used >= MAX_AGENTS)
4868
- return { ok: false, error: this.namesCapacity.capacityRefusal(occupancy) };
4869
- const recheck = this.refreshUnavailableConnectors(connector.name, true);
4870
- if (recheck) {
4871
- await recheck;
4872
- occupancy = this.namesCapacity.occupancy();
4873
- if (occupancy.used >= MAX_AGENTS)
4874
- return { ok: false, error: this.namesCapacity.capacityRefusal(occupancy) };
4875
- }
4876
- // Harness preflight before reserving a slot or minting — a missing `claude`/`opencode` binary
4877
- // fails here with a clear name, not obscurely at process spawn. No fallback. All synchronous, so
4878
- // the reserve gate stays atomic. (The connector itself was resolved up top, before the capacity gate.)
4879
- const harness = this.launchHarness(connector);
4880
- if ("refusal" in harness)
4881
- return { ok: false, error: this.harnessUnavailableError(harness.refusal, opts.route ?? "inst") };
4882
- // Resume is a connector capability: reject an unsupported resume HERE, before the reserve/mint, so
4883
- // it can never provision creds + durables and then throw at buildLaunch (mint-then-orphan). Same
4884
- // reject-before-side-effects window as the harness preflight above; buildLaunch stays the backstop.
4885
- if (opts.resume && !connector.supportsResume)
4886
- return { ok: false, error: `${agent} connector does not support resuming an existing session (resume)` };
4887
- // A carried resume (#1499) is checked here too, before anything is minted. The claim is only
4888
- // looked at: the connector may still refuse the launch, and a refused launch leaves it unspent.
4889
- let carried;
4890
- if (opts.resumeClaim !== undefined) {
4891
- if (opts.resume === undefined)
4892
- return { ok: false, error: "resumeClaim: names carried bytes of a resume; the launch carries no resume" };
4893
- if (!connector.resumeTranscript)
4894
- return { ok: false, error: `${agent} connector does not take a carried transcript (resumeClaim)` };
4895
- if (opts.resumeAgent !== agent)
4896
- return { ok: false, error: `resumeClaim: the session was carried for agent "${opts.resumeAgent ?? "<none>"}", and this launch resolves agent "${agent}"` };
4897
- if (!this.transcripts)
4898
- return { ok: false, error: "resumeClaim: this manager does not receive carried transcripts" };
4899
- try {
4900
- carried = this.transcripts.peek(opts.resumeClaim, opts.resume);
4901
- }
4902
- catch (e) {
4903
- return { ok: false, error: rejectionText(e) };
4904
- }
4905
- }
4906
- // A restart policy this host cannot honour is refused at accept, never accepted and ignored.
4907
- // External runtimes (tmux/cmux/orca/herdr) attach to a process they do not own and stream no
4908
- // exit, so a name cannot be respawned in place. User-mode seats have no static slot that
4909
- // keeps the incarnation owned across a process death, so the same refusal applies there.
4910
- if (opts.supervise !== undefined) {
4911
- if (runtime.kind !== "pty")
4912
- return { ok: false, error: `supervise is a restart policy this host cannot enforce: runtime "${runtime.kind}" cannot respawn a name in place` };
4913
- if (this.userMode)
4914
- return { ok: false, error: "supervise is a restart policy this host cannot enforce: a user-mode seat has no static slot to keep the incarnation owned across a process death" };
4915
- if (runtime.supportsWorkClosure !== true)
4916
- return { ok: false, error: `supervise is a restart policy this host cannot enforce: runtime "${runtime.kind}" cannot prove prior local work ended` };
4917
- }
4918
- // One read of the cotal config per spawn: the delegated refusal, the model policy and the launch
4919
- // fields below all take this value, so the awaits between the policy check and the launch cannot
4920
- // admit the seat under one file and launch it with another's servers and env allowlist. Read per
4921
- // spawn, so a policy edit reaches the next spawn without a restart. The launch fields are resolved
4922
- // here too, before the spawn is accepted, so a sharing selection that names an undeclared server
4923
- // is refused while there is nothing to roll back.
4924
- let cotalConfig;
4925
- let hostFields;
4926
- try {
4927
- cotalConfig = loadCotalConfig(this.workspaceRoot);
4928
- hostFields = this.hostLaunchFields(cotalConfig, agent, opts.shareTools, harness);
4929
- }
4930
- catch (e) {
4931
- const error = rejectionText(e);
4932
- // An input refusal here precedes allocation and onAccepted, like a connector refusal above:
4933
- // a hosted run proves it not-executed instead of binding a goal to a spawn that never starts.
4934
- if (hooks?.onAccepted)
4935
- throw new EpEnvelopeError("failed-precondition", error, undefined, "not-executed");
4936
- return { ok: false, error };
4937
- }
4938
- // A delegated seat starts outside this host from values alone, so a choice only this host can
4939
- // honour is refused here, before enrollment, and named rather than dropped.
4940
- if (runtime.spawnDelegated) {
4941
- const delegatedBy = `runtime "${runtime.kind}" starts seats outside this host`;
4942
- if (!this.remoteAuthority?.enrollManagedAgent)
4943
- return { ok: false, error: `${delegatedBy}, which needs a host that enrolls managed agents (remoteAuthority.enrollManagedAgent); a delegated seat has no local grant path` };
4944
- try {
4945
- this.userProvision.delegatedMeshRecord();
4946
- }
4947
- catch (e) {
4948
- return { ok: false, error: rejectionText(e) };
4949
- }
4950
- if (opts.resume)
4951
- return { ok: false, error: `${delegatedBy}, so it cannot resume a session held on this host (resume)` };
4952
- if (opts.resolved?.continuity === "exact")
4953
- return { ok: false, error: `${delegatedBy}, so it cannot reopen a session held on this host (continuity: exact)` };
4954
- if (typeof opts.cwd === "string" && opts.cwd !== "")
4955
- return { ok: false, error: `${delegatedBy}, so it cannot run in a directory on this host's filesystem (cwd); the seat runs in its runtime resource's own directory` };
4956
- const shared = Object.keys(hostFields.mcpServers);
4957
- if (shared.length)
4958
- return { ok: false, error: `${delegatedBy}, so it cannot share MCP servers that run on this host (${shared.join(", ")}); pass --share-tools none` };
4959
- }
4960
- // A placed spawn's cwd is checked on this host BEFORE anything is minted or reserved: an absolute
4961
- // path this manager cannot realpath, or one that is not a directory, is refused here with the
4962
- // asked path, the reason and this host, so a misplaced spawn in a multi-manager space is
4963
- // diagnosable at the moment it happens (#385 item 2) instead of failing inside the pty launch.
4964
- // The resolved realpath is threaded to the launch cwd below (`resolvedCwd`) so it is computed once.
4965
- let resolvedCwd;
4966
- if (typeof opts.cwd === "string" && opts.cwd !== "") {
4967
- const asked = opts.cwd;
4968
- const target = resolve(this.workspaceRoot, asked);
4969
- const checked = this.checkSpawnCwd(target);
4970
- if ("refusal" in checked)
4971
- return { ok: false, error: `spawn: cwd does not resolve on this host (${hostname()}): ${JSON.stringify(asked)} (${checked.refusal}); the seat was not launched` };
4972
- resolvedCwd = checked.cwd;
4973
- }
4974
- // Resolve the launch profile: IDENTITY (free-form `name:`) + role + read/post ACL + capabilities
4975
- // + model/variant. Either from a fully-resolved manifest launch object (`opts.resolved`, whose `config`
4976
- // is a materialized transient persona — the file is NOT the access authority), or from the
4977
- // persona file. The number rides the IDENTITY (socrates → socrates_2), not the file ref — a
4978
- // redelivered identical spawn yields a fresh numbered agent (MAX_AGENTS bounds the blast radius).
4979
- let identityName;
4980
- let role;
4981
- let subscribe;
4982
- let allowSubscribe;
4983
- let allowPublish;
4984
- let capabilities;
4985
- // The endpoint commands the persona hands on (SPEC 13.15), as the persona names them and as the
4986
- // mint grants them. A manifest launch carries none: its schema has no slot for them.
4987
- let personaEndpoints;
4988
- let endpoints = [];
4989
- let model = opts.model;
4990
- let variant = opts.variant;
4991
- let launchOptions = opts.launchOptions;
4992
- let prompt = opts.prompt;
4993
- // The read set the persona and the overrides name, before `join` adds to it: what a saved copy keeps.
4994
- let ownSubscribe;
4995
- if (opts.resolved) {
4996
- // A manifest launch is the access + identity authority: imperative overrides arriving
4997
- // alongside `resolved` are a caller contract error, not something to merge (no fallbacks).
4998
- if (opts.subscribe || opts.allowSubscribe || opts.allowPublish || opts.join || opts.callerAcl || opts.prompt || opts.shareTools || opts.identity)
4999
- return { ok: false, error: "a manifest launch (resolved) rejects imperative overrides (identity/subscribe/allow*/join/callerAcl/prompt/shareTools)" };
5000
- const r = opts.resolved;
5001
- identityName = r.name;
5002
- role = opts.role ?? r.role;
5003
- subscribe = r.subscribe;
5004
- allowSubscribe = r.allowSubscribe;
5005
- allowPublish = r.allowPublish;
5006
- capabilities = r.capabilities;
5007
- model = opts.model ?? r.model;
5008
- variant = opts.variant ?? r.variant;
5009
- launchOptions = mergeLaunchOptions(r.launchOptions, opts.launchOptions);
5010
- prompt = r.prompt; // the guard above rejected an imperative prompt — one source
5011
- }
5012
- else {
5013
- // `def` was loaded once above the connector resolution (#869 ordering); consume it here.
5014
- // `resolved` is the only path that skips the load, and this is its opposite branch.
5015
- if (!def)
5016
- return { ok: false, error: "internal: persona definition missing at launch profile" };
5017
- // Identity: the `--name` override wins over the file's `name:` — foreground parity (there,
5018
- // `requested = values.name ?? def.name`). The override is minted into the creds and rides
5019
- // COTAL_NAME below, so the presence identity and its credential can't diverge.
5020
- identityName = opts.identity ?? def.name;
5021
- role = opts.role ?? def.role;
5022
- // Flags > persona file — the same precedence as foreground `cotal spawn`, so the two launch
5023
- // paths of the merged grammar can't diverge. One source feeds BOTH the minted creds and the
5024
- // connector env below.
5025
- // A persona that names no channel field at all is scoped to its spawner's ACL (`callerAcl`,
5026
- // when the door sent one). The spawner's own event channel is dropped from it: that plane is
5027
- // foreign to the child, and the guard below refuses any spawn that asks for one. The joined
5028
- // set is never copied from the spawner: a helper starts on what its persona lists plus what
5029
- // the caller passes in `join`, and nothing else. The ACL is the caller's own report, so on a
5030
- // static mesh it is clamped to what the caller's evidence shows it holds, and a caller with
5031
- // no evidence gets no default at all.
5032
- const personaNamesChannels = def.subscribe !== undefined || def.allowSubscribe !== undefined || def.allowPublish !== undefined;
5033
- const heldChannels = (field, channels) => {
5034
- const own = channels.filter((ch) => eventChannelPrincipal(ch) === null);
5035
- return bound.kind === "bounded" ? own.filter((ch) => grantOverreach(this.space, bound.caller, bound.ceiling, { [field]: [ch] }).length === 0) : own;
5036
- };
5037
- let scoped;
5038
- try {
5039
- scoped = !personaNamesChannels && opts.callerAcl && bound.kind !== "none" ? {
5040
- allowSubscribe: heldChannels("allowSubscribe", opts.callerAcl.allowSubscribe),
5041
- allowPublish: heldChannels("allowPublish", opts.callerAcl.allowPublish),
5042
- } : undefined;
5043
- }
5044
- catch (e) {
5045
- return { ok: false, error: `callerAcl: ${rejectionText(e)}` };
5046
- }
5047
- const base = opts.subscribe ?? def.subscribe;
5048
- ownSubscribe = base;
5049
- subscribe = opts.join?.length ? [...new Set([...(base ?? []), ...opts.join])] : base;
5050
- allowSubscribe = opts.allowSubscribe ?? def.allowSubscribe ?? scoped?.allowSubscribe ?? [];
5051
- allowPublish = opts.allowPublish ?? def.allowPublish ?? scoped?.allowPublish;
5052
- capabilities = def.capabilities;
5053
- personaEndpoints = copyPersonaEndpoints(def.endpoints);
5054
- // A user-auth mesh grants endpoint access through the service owner's records, which a spawn
5055
- // cannot write (SPEC 13.15), so a persona that names the field is refused there, `[]` included,
5056
- // before any bound or exemption reads it.
5057
- if (personaEndpoints !== undefined && this.meshMode === "user")
5058
- return { ok: false, error: userMeshEndpointsRefusal("spawn") };
5059
- endpoints = lowerPersonaEndpoints(personaEndpoints);
5060
- // #651: fold the persona's model into the launch record, mirroring the variant line below
5061
- // and the manifest branch above. Without this, a persona-file model (the common pin source)
5062
- // never reaches `launch.model`, so the connector runs the seat on it while `ps --wide`/`--json`
5063
- // reports the model ABSENT - a false "no model pinned" for a seat that has one.
5064
- model = opts.model ?? def.model;
5065
- variant = opts.variant ?? def.variant;
5066
- launchOptions = mergeLaunchOptions(def.launchOptions, opts.launchOptions);
5067
- }
5068
- // Resolved once for both branches, because this one list is granted, minted, recorded on the
5069
- // launch and forwarded to the session, and each of those must read the list the provisioner does.
5070
- try {
5071
- allowSubscribe = resolveReadAcl(subscribe ?? [], allowSubscribe);
5072
- }
5073
- catch (e) {
5074
- return { ok: false, error: opts.resolved ? `launch agent: ${rejectionText(e)}` : `persona ${where}: ${rejectionText(e)}` };
5075
- }
5076
- // Default events on where the connector supports them, unless the launch explicitly opts out.
5077
- const events = this.eventsRequired || opts.events === true || (opts.events !== false && !!connector.eventChannel);
5078
- if (this.eventPayloadsWithheld && opts.eventPayloads === true)
5079
- return { ok: false, error: "space policy withholds event payloads" };
5080
- const eventPayloads = !this.eventPayloadsWithheld && (opts.eventPayloads ?? def?.eventPayloads) !== false;
5081
- if (run === undefined) {
5082
- const reads = this.managedStaticInstanceReads(capabilities);
5083
- if (bound.kind === "exempt" || (bound.kind === "bounded" && !grantOverreach(this.space, bound.caller, bound.ceiling, { endpoints: reads }).length))
5084
- endpoints.push(...reads);
5085
- }
5086
- // THE DELEGATION BOUND, on the grant as it will be minted: every channel and capability the
5087
- // helper gets, from the persona, the raw overrides and the `callerAcl` default alike, and its own
5088
- // event plane, so no door reaches the mint around it. Before any reserve or mint, so a refusal
5089
- // leaves nothing.
5090
- const boundRefusal = this.spawnBoundRefusal(bound, {
5091
- allowSubscribe,
5092
- ...(allowPublish !== undefined ? { allowPublish } : {}),
5093
- ...(role !== undefined ? { role } : {}),
5094
- ...(capabilities !== undefined ? { capabilities } : {}),
5095
- ...(endpoints.length ? { endpoints } : {}),
5096
- }, events);
5097
- if (boundRefusal)
5098
- return { ok: false, error: boundRefusal };
5099
- // A run saves for the caller it was admitted for, whose catalog reads then find the copy.
5100
- const savedBy = authenticatedCaller === undefined ? undefined : this.runHosting?.admittedCaller(authenticatedCaller);
5101
- // What a saved copy keeps: the grant just checked, without the helper's own event row, which each
5102
- // later spawn derives for its own helper. The file names every channel field, so no later caller's
5103
- // default fills one, and each later spawn of it is still bounded against that caller.
5104
- const catalogCopy = inline?.save
5105
- ? {
5106
- name: ref,
5107
- owner: savedBy !== undefined ? this.personaOwner(principalKey(savedBy.owner, savedBy.actor).key) : spawner === undefined ? undefined : this.personaOwner(spawner),
5108
- role,
5109
- model,
5110
- variant,
5111
- description: def?.description,
5112
- persona: def?.persona,
5113
- subscribe: [...(ownSubscribe ?? [])],
5114
- allowSubscribe: [...allowSubscribe],
5115
- allowPublish: [...(allowPublish ?? [])],
5116
- capabilities: capabilities?.length ? [...capabilities] : undefined,
5117
- endpoints: copyPersonaEndpoints(personaEndpoints?.length ? personaEndpoints : undefined),
5118
- }
5119
- : undefined;
5120
- // Checked after every path has resolved its selectors: a direct `startAgent` call skips the
5121
- // `start` op's checks, and no connector may receive a blank one (#2862).
5122
- if (model !== undefined && !model.trim())
5123
- return { ok: false, error: "model: must not be empty" };
5124
- if (variant !== undefined && !variant.trim())
5125
- return { ok: false, error: "variant: must not be empty" };
5126
- const idErr = this.namesCapacity.nameError(identityName);
5127
- if (idErr)
5128
- return { ok: false, error: opts.resolved ? `launch agent: ${idErr}` : `persona ${where}: ${idErr}` };
5129
- // #966: a seat labelled `manager` that cannot spawn is a worker wearing a label, and the label
5130
- // is what other agents ROUTE on (role is the anycast address). The gap is silent today because
5131
- // the mismatch is only discovered minutes in, when the seat first reaches for a worker. Refuse
5132
- // at accept, before any reserve/mint, naming the remediation for each author: an operator edits
5133
- // the file to add the grant, and the persona's owner may redefine it with the grant only if the
5134
- // owner holds spawn, because define-persona bounds capabilities against the definer. The
5135
- // check keys on the EFFECTIVE role (a spawn-time role: override wins
5136
- // over the file, mirroring the resolution above), not the file's, so the label other agents
5137
- // will actually see is the label that is held to account. `manager` is the label that MEANS
5138
- // spawn-holding: naming it literally keeps this the narrow guard for the observed harm, not a
5139
- // vocabulary any caller can trigger with a synonym (roles are free-form and mostly
5140
- // non-manager: this workspace's own catalog carries worker/reviewer/orchestrator seats with no
5141
- // spawn grant, all legitimate).
5142
- if (role === "manager" && !capabilities?.includes("spawn") && inline)
5143
- return {
5144
- ok: false,
5145
- error: `inline persona "${ref}" would join with role "manager" but no spawn capability: it presents as a manager ` +
5146
- `while being unable to seat workers. Add \`capabilities: [spawn]\` to the inline persona (a spawner hands on only what it holds), or give it another role.`,
5147
- };
5148
- if (role === "manager" && !capabilities?.includes("spawn"))
5149
- return {
5150
- ok: false,
5151
- error: `persona "${ref}" would join with role "manager" but no spawn capability: it presents as a manager ` +
5152
- `while being unable to seat workers, and it would discover that only on first use. ` +
5153
- `An operator adds \`capabilities: [spawn]\` to ${configPath}, or the persona's owner redefines it ` +
5154
- `with \`capabilities: [spawn]\` (cotal_persona) if the owner holds spawn.`,
5155
- };
5156
- // #581: the operator's per-role model allowlist, judged on the EFFECTIVE role and model resolved
5157
- // above, before any reserve or mint. This is where the launch is performed, so no caller can
5158
- // skip it, and a definition pinned to a stale model (or to none) is refused here instead of
5159
- // serving on it.
5160
- const policyRefusal = modelPolicyRefusal(cotalConfig, {
5161
- persona: opts.resolved ? `manifest agent "${ref}"` : configPath ? `persona "${ref}" (${configPath})` : where,
5162
- role, model, variant,
5163
- // A manifest launch carries its own declared model/variant in these options
5164
- // (launchAgentToStartOpts), so there they are the definition's field, never a flag.
5165
- modelFlag: !opts.resolved && opts.model !== undefined,
5166
- variantFlag: !opts.resolved && opts.variant !== undefined,
5167
- launchOptions,
5168
- });
5169
- if (policyRefusal)
5170
- return { ok: false, error: policyRefusal };
5171
- // The alias-reuse gate: a name whose previous agent is still retiring REFUSES
5172
- // legibly (never a silent suffix), and the refusal re-drives the FULL durable teardown so
5173
- // "retry the spawn" is also the nudge. It routes through `deprovision` (not `requestRetirement`
5174
- // alone) so a retry re-drives the standing-authority revoke (INT-2) AND the broker cleanup before
5175
- // any hold-clear (C): the alias must not free while the durable teardown or the revoke is still
5176
- // outstanding. All the teardown ops are idempotent, and the rail request is single-flighted.
5177
- if (this.staticLifecycle.isReconciling(identityName))
5178
- return { ok: false, error: `the name "${identityName}" is still reconciling at manager startup; its prior lifecycle terminal owns this alias until it completes. Retry shortly.` };
5179
- const held = this.retirement.held(identityName);
5180
- if (held !== undefined) {
5181
- hooks?.onEffect?.();
5182
- void this.retirement.deprovision(held.target).catch(() => { });
5183
- const err = lifecycleBlocked("failed-precondition", `the name "${identityName}" is reserved pending retirement: its previous agent's despawn started that lifecycle's teardown (footprint + standing-authority revoke + auth-side retirement), and the name frees only when all of it completes${held.lastError !== undefined ? ` (last attempt: ${held.lastError})` : ""}. NEXT: wait a moment and retry this spawn (retrying re-drives the whole teardown), or pick another name.`, { blockedOp: "retirement", opId: held.opId, remedy: "retry" });
5184
- return { ok: false, error: renderLifecycleBlocked(err.message, err), details: err.details };
5185
- }
5186
- // A manifest `continuity: exact` agent reopens the session this manager last bound to its
5187
- // declared name. Refused before any reserve or mint when the connector cannot reopen an exact
5188
- // session or the recorded assignment does not match this declaration.
5189
- const exact = opts.resolved?.continuity === "exact";
5190
- const unsupported = this.capabilityRefusal(connector, { variant, prompt, exact });
5191
- if (unsupported)
5192
- return { ok: false, error: unsupported };
5193
- const onceRefused = opts.once && this.onceRefusal(connector, runtime, { ...opts, launchOptions, prompt }, spawner, hooks);
5194
- if (onceRefused)
5195
- return { ok: false, error: onceRefused };
5196
- let reopenSession;
5197
- if (exact) {
5198
- try {
5199
- reopenSession = readContinuityAssignment(this.workspaceRoot, { space: this.space, name: identityName, connector: agent, cwd: resolvedCwd ?? this.workspaceRoot });
5200
- }
5201
- catch (e) {
5202
- return { ok: false, error: rejectionText(e) };
5203
- }
5204
- }
5205
- // The child takes launch options as `--opt k=v`, so only string values can cross to it.
5206
- const unportable = runtime.spawnDelegated ? Object.keys(launchOptions ?? {}).filter((k) => typeof launchOptions[k] !== "string") : [];
5207
- if (unportable.length)
5208
- return { ok: false, error: `runtime "${runtime.kind}" starts seats outside this host, so it cannot pass non-string launch options (${unportable.join(", ")})` };
5209
- // An event plane the connector cannot emit is refused HERE, before anything is minted: a
5210
- // connector that cannot emit must fail before provisioning rather than after, as an
5211
- // unsupported `resume` does.
5212
- // The GRANT itself cannot be derived yet. It is keyed on the agent's PRINCIPAL, and in user mode
5213
- // the principal's owner is resolved further down, so deriving it from anything in scope here
5214
- // would mean guessing at the identity the child will actually connect as. It is added at the
5215
- // accept seam below, where the allocated triple exists.
5216
- const eventsRefused = this.eventsRefusal(connector, opts.events);
5217
- if (eventsRefused)
5218
- return { ok: false, error: eventsRefused };
5219
- // The roster the allocation consults must reflect the initial presence snapshot,
5220
- // or a spawn immediately after manager boot races an already-live unmanaged peer and re-opens the
5221
- // very collision black-hole this closes. Await the snapshot (bounded internally, fail-safe on an
5222
- // empty mesh) before allocating; the broker/auth remain the authority downstream. Deliberately
5223
- // unconditional: a half-wired endpoint without the seam must fail loud here, not silently
5224
- // allocate off a pre-snapshot roster.
5225
- await this.ep.waitForPresenceSnapshot();
5226
- // Spawn-as-action: a HARD-PINNED name — an imperative `--name`/identity override
5227
- // or a manifest-declared name (opts.resolved) — that collides with a LIVE/provisioning/reserved
5228
- // incarnation REFUSES loud at accept, BEFORE any reserve/mint/bind, never a silent `_2`
5229
- // suffix (so an address-by-triple caller's pinned name can't be re-pointed). A PERSONA-DERIVED
5230
- // base name (no pin) keeps uniqueName's collision numbering, so multi-peer `spawn reviewer` twice
5231
- // still yields reviewer + reviewer_2. The alias-reuse gate above is orthogonal and already fired.
5232
- const hardPinned = opts.identity !== undefined || opts.resolved !== undefined;
5233
- const owner = this.launchOwner(opts, spawner);
5234
- const unavailable = new Set();
5235
- let name;
5236
- for (;;) {
5237
- if (hardPinned) {
5238
- if (this.namesCapacity.nameInUse(identityName))
5239
- return { ok: false, code: "already-exists", error: `the name "${identityName}" is hard-pinned (${opts.resolved ? "manifest-declared" : "--name/identity override"}) but is already held by a live incarnation (managed here, an unmanaged foreground/connector session, or another manager's agent); a pinned same-name collision refuses at accept - pick another name or despawn the existing one` };
5240
- name = identityName;
5241
- }
5242
- else {
5243
- try {
5244
- name = this.namesCapacity.uniqueName(identityName, unavailable);
5245
- }
5246
- catch (e) {
5247
- return { ok: false, error: rejectionText(e) };
5248
- }
5249
- }
5250
- // In user mode the name is the principal's actor. A fresh nkey in static/open mode
5251
- // cannot collide with an earlier transcript. Use the connector's own startup proof.
5252
- const eventOwner = opts.owner ?? (spawner === undefined ? undefined : parsePrincipalKey(spawner)?.owner);
5253
- if (events && this.userMode && !runtime.spawnDelegated && eventOwner?.startsWith("u_")) {
5254
- try {
5255
- await checkEventStartup({
5256
- workspaceRoot: this.workspaceRoot,
5257
- space: this.space,
5258
- principal: { owner: eventOwner, actor: name },
5259
- retainedMessages: async () => {
5260
- try {
5261
- return (await this.ep.chatRetention()).senders;
5262
- }
5263
- catch (e) {
5264
- // Older hosts do not issue this metadata grant. Do not infer that the name is
5265
- // free or renumber it: preserve the requested candidate and let the launched
5266
- // agent's existing startup check decide. Every other read failure stays loud.
5267
- if (!isPermissionDenied(e))
5268
- throw e;
5269
- console.error(`! event startup name check: missing $JS.API.STREAM.INFO.${chatStream(this.space)} permission; launching "${name}" unchanged so the agent checks its transcript state`);
5270
- throw new LegacyEventCountPermissionError();
5271
- }
5272
- },
5273
- });
5274
- }
5275
- catch (e) {
5276
- if (e instanceof EventStateConflictError && !hardPinned) {
5277
- unavailable.add(name);
5278
- continue;
5279
- }
5280
- if (!(e instanceof LegacyEventCountPermissionError))
5281
- return { ok: false, code: "failed-precondition", error: `cannot check event startup for ${eventOwner}.${name}: ${rejectionText(e)}` };
5282
- }
5283
- // Another spawn may have reserved the candidate while the disk/broker proof awaited.
5284
- // Recheck in the same synchronous window as the cap and reservation below.
5285
- if (this.namesCapacity.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
5286
- if (!hardPinned)
5287
- continue;
5288
- return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
5289
- }
5290
- }
5291
- break;
5292
- }
5293
- // The `chat_` prefix belongs to static chat sessions, whose aliases only `chat-session-open`
5294
- // draws. Checked once the name is fixed by either branch above, so a persona name, a numbered
5295
- // collision, a manifest name and a `--name` override all meet it, and before the reservation.
5296
- if (name.startsWith(CHAT_ALIAS_PREFIX))
5297
- return { ok: false, error: `the name "${name}" starts with "${CHAT_ALIAS_PREFIX}", which is reserved for chat sessions; pick another name` };
5298
- // THE PER-OWNER CEILING, read in the same synchronous window as the reserve below rather than
5299
- // beside the host capacity gate higher up: the count it takes must be the one the reservation
5300
- // lands against, or a burst of concurrent launches for one owner each reads a count taken
5301
- // before any of the others reserved, and they all pass. Nothing between here and the reserve
5302
- // awaits. It refuses BEFORE `onEffect`, so the launch states `not-executed` and leaves no
5303
- // name, no mint and no footprint behind.
5304
- const overCap = this.seatCapRefusal(owner);
5305
- if (overCap)
5306
- return { ok: false, code: overCap.code, error: overCap.message, ...(overCap.details ? { details: overCap.details } : {}) };
5307
- // Set once the agent's footprint (durables + creds, or the user-mode grant + secret files)
5308
- // exists; cleared when a live slot takes ownership. If it survives to `finally`, the spawn threw
5309
- // AFTER provisioning (buildLaunch / runtime.spawn) — the orphan-rollback tears it down. Carries
5310
- // `userOwner` for a user-mode spawn so that rollback runs the revoke+shred branch, not just the
5311
- // static durable teardown, which would leak the managed grant + files.
5312
- // The RESERVED custody reference rides the rollback object: a spawn that launched the seat and
5313
- // then threw (the activation CAS refuses a slot that is not this spawn's intent) reaches the
5314
- // `finally` with the handle only in a local, so without this the terminal has nothing to reap
5315
- // and retires over a live process. The slot row holds the same reference; this is the copy the
5316
- // in-process rollback can actually read.
5317
- let provisioned;
5318
- // A carried resume's seat-private home, removed by the finally unless a live seat took it.
5319
- let seatHome;
5320
- // The lifecycle whose inline snapshot this spawn wrote: removed by the finally unless a live seat
5321
- // took it. A write that failed sets nothing, so the finally never removes a file it did not make.
5322
- let snapshotUid;
5323
- // Taken right before the try so its finally is the only release; a refusal belongs above the
5324
- // allocation, where there is no name to give back.
5325
- hooks?.onEffect?.();
5326
- if (!hardPinned && name !== identityName)
5327
- this.namesCapacity.rememberNumbered(name);
5328
- this.namesCapacity.reserve(name, owner);
5329
- try {
5330
- // A stable nkey identity assigned at spawn: the public key is the agent's card.id (threaded via
5331
- // COTAL_ID); the seed is retained to mint matching creds later.
5332
- const identity = newIdentity();
5333
- // The incarnation's lifecycle UID (SPEC 13.1), minted ONCE per spawn: every lifecycle-keyed
5334
- // broker resource (dm_/dlv_/chathist_ durables, ACL row, memberships) and the teardown
5335
- // credential carry it, so a same-name successor's footprint is name-disjoint by construction.
5336
- //
5337
- // On the HOSTED enrollment arm (#1972) this value is PROVISIONAL. The host selects the
5338
- // authoritative uid, because it alone reads the retirement tombstones that make a uid
5339
- // permanently unusable, and the enrollment below rebinds this binding to what the host
5340
- // returned before anything durable is keyed by it.
5341
- let lifecycleUid = mintLifecycleUid();
5342
- // Reserve the seat's custody reference NOW, before any durable row and long before the
5343
- // launch. Minting it inside `runtime.spawn` (as it used to be) put the processes on disk
5344
- // before anything recorded how to address them, so a crash in that window left a live seat
5345
- // outside every manager and the successor retired the slot over it.
5346
- const custody = this.seatCustody.reserveCustody(runtime);
5347
- // ACCEPT SEAM (spawn-as-action): the incarnation identity is minted and NOTHING has
5348
- // been provisioned yet — the action serve path binds the goal + replies the acceptance HERE. A
5349
- // throw (bind conflict / duplicate goalId) aborts the spawn before provisioning: the catch below
5350
- // returns the failure and the finally releases the reserve, so a refused accept leaves zero
5351
- // footprint. The hosted enrollment arm is the exception, below. Blocking callers
5352
- // (roster boot) pass no hooks and this is a no-op.
5353
- // The ALLOCATED agent's addressing triple (the acceptance floor names what was actually
5354
- // allocated, never the requested-but-unallocated name). Static/open key on DEV_OWNER + the
5355
- // freshly-minted nkey; user mode keys on the derived owner (opts.owner, else a u_-owner spawner)
5356
- // + the alias — derived HERE where the mode and owner source are in scope.
5357
- const agentTriple = this.userMode
5358
- ? { owner, actor: name, uid: lifecycleUid }
5359
- : { owner, actor: identity.id, uid: lifecycleUid };
5360
- // THE EVENT GRANT, derived from the principal that was actually ALLOCATED and never from the
5361
- // display name. A display name is UI convenience: this mesh permits two live agents to carry
5362
- // one, so a name-keyed channel fuses two principals onto one subject and, in auth mode,
5363
- // authorizes both onto it from the same name-only value. `agentTriple` is the triple the child
5364
- // will connect as in both modes, so the grant and the subject the session derives from its own
5365
- // endpoint are the same derivation. Placed here rather than beside the refusal above
5366
- // because this is the first point at which that triple exists, and still before every
5367
- // provisioning call that consumes `allowPublish`.
5368
- // THE OWN-CHANNEL RULE FOR THE EVENT PLANE, and it is the first thing this seam does.
5369
- //
5370
- // An event channel carries a session's tool inputs and outputs, which makes it the most
5371
- // valuable read on the mesh, and `subscribe` / `allowSubscribe` / `allowPublish` are
5372
- // caller-supplied on every spawn door. On a per-user-auth mesh the ledger's spawner envelope
5373
- // already refuses a delegation wider than the spawner's own grant. On a STATIC mesh there is
5374
- // no ledger, so nothing attenuates a caller-supplied ACL at all, and a caller that may spawn
5375
- // may mint its child a read on any subject.
5376
- //
5377
- // What this rule asks is NOT who the caller is. That question has no answer on a static mesh:
5378
- // an untargeted spawn carries no authorization mode, and the admin reach a static caller
5379
- // holds is true by construction for everyone who can reach the handler. It asks whether the
5380
- // event channel being minted BELONGS TO THE AGENT BEING CREATED, which the manager knows
5381
- // because it has just allocated the principal.
5382
- //
5383
- // STATED LIMIT, because a fence whose gap is discovered later is worse than one whose gap is
5384
- // written down. `eventChannelPrincipal` decodes a principal and refuses anything that is not exactly
5385
- // two principal tokens, so a WILDCARD is not an event channel to it: `events.<owner>.>` and
5386
- // `events.>` pass this rule untouched and are governed by ordinary ACL authority, which on a
5387
- // user mesh is the envelope and on a static mesh is the spawn credential itself. So this
5388
- // closes the concrete form and not the wildcard form. It is worth having anyway: it is the
5389
- // form a caller writes when it knows which agent it wants to read, and the wildcard form is
5390
- // the one an operator writes deliberately for an observer.
5391
- const foreign = foreignEventChannels([...allowSubscribe, ...(allowPublish ?? [])], agentTriple.owner, agentTriple.actor);
5392
- if (foreign.length) {
5393
- // Throws rather than returning, because this seam is inside the accept body: the throw
5394
- // unwinds before `onAccepted`, so no goal is bound and no identity is minted, and the
5395
- // enclosing `finally` releases the reserved name. Returning here would be a value nobody
5396
- // reads.
5397
- throw new Error(`this spawn asks for another agent's event channel: ${foreign.join(", ")}. An ` +
5398
- `agent may be granted its OWN event plane and no other, because that plane carries the ` +
5399
- `session's tool inputs and outputs. Grant a reader out of band rather than through a ` +
5400
- `spawn: ${this.readerRemedy(agentTriple.owner, foreign[0])}`);
5401
- }
5402
- if (events)
5403
- allowPublish = [...(allowPublish ?? []), connector.eventChannel({ owner: agentTriple.owner, actor: agentTriple.actor })];
5404
- await hooks?.onReadinessWindow?.(readinessTimeoutMs);
5405
- // The hosted enrollment arm accepts only once the host has answered: the floor names the uid
5406
- // the agent runs at, and before the host picks it there is no such uid to name.
5407
- const hostedEnrollment = this.userMode && (opts.delegatedIntent !== undefined || this.remoteAuthority?.enrollManagedAgent !== undefined);
5408
- // A once spawn's task is accepted with the spawn, before anything launches.
5409
- let onceTask;
5410
- const acceptOnce = async (seat) => {
5411
- if (opts.once === undefined)
5412
- return;
5413
- onceTask = await hooks.onOnce({
5414
- seat: { name, ...seat }, prompt: prompt, spawner: this.spawnerName(spawner), deadlineMs: opts.once.deadlineMs, readinessDeadlineMs: readinessTimeoutMs,
5415
- ...(connector.retireAfterExit ? { retire: connector.name } : {}),
5416
- });
5417
- };
5418
- if (!hostedEnrollment) {
5419
- await hooks?.onAccepted?.({ name, identity, lifecycleUid, agentTriple });
5420
- await acceptOnce(agentTriple);
5421
- }
5422
- // In auth mode, mint the agent's creds from the space signing key and write them where the
5423
- // spawned session reads them (COTAL_CREDS path). Open mesh → no creds. Scope = the resolved
5424
- // subscribe/allowSubscribe (read) + allowPublish (post, default-deny).
5425
- let credsPath;
5426
- let issued;
5427
- let userLaunch;
5428
- let userOwner;
5429
- let enrolled;
5430
- if (this.userMode) {
5431
- const prep = await this.provisionUserAgent(name, {
5432
- eventPayloads,
5433
- spawner,
5434
- specOwner: opts.owner,
5435
- subscribe,
5436
- allowSubscribe,
5437
- allowPublish,
5438
- role,
5439
- capabilities,
5440
- label: ref,
5441
- lifecycleUid,
5442
- enrollmentCaller: authenticatedCaller ? { owner: authenticatedCaller.owner, actor: authenticatedCaller.actor } : undefined,
5443
- delegatedIntent: opts.delegatedIntent,
5444
- ...(opts.served !== undefined ? { spawnRequest: this.userProvision.servedSpawnRequest(opts.served, authenticatedCaller) } : {}),
5445
- // Hold the name at the UID the host enrolled for the intent's user before any later local
5446
- // step runs, so no later failure, its refusal included, releases a lifecycle that only that
5447
- // user's retirement intent retires.
5448
- onEnrolled: opts.delegatedIntent
5449
- ? (enrolled) => {
5450
- provisioned = { id: principalKey(enrolled.owner, name).key, name, lifecycleUid: enrolled.lifecycleUid, userOwner: enrolled.owner, delegated: true, secretPaths: enrolled.files };
5451
- }
5452
- : undefined,
5453
- });
5454
- if ("error" in prep) {
5455
- if (prep.refused !== undefined)
5456
- hooks?.onUndone?.(prep.refused);
5457
- return { ok: false, error: prep.error, ...(prep.refused !== undefined ? { code: prep.refused } : {}), ...(prep.details ? { details: prep.details } : {}) };
5458
- }
5459
- // THE HOST'S UID WINS (#1972). On the local arm this is the value passed in, unchanged. On
5460
- // the hosted enrollment arm the host selected it, and from here every lifecycle-keyed thing
5461
- // this spawn records — the slot, the launch, the managed row, the teardown credential — must
5462
- // carry that value and not the provisional one, or the manager would address a footprint the
5463
- // host never created.
5464
- lifecycleUid = prep.lifecycleUid;
5465
- userLaunch = prep.launch;
5466
- userOwner = prep.owner;
5467
- enrolled = prep.enrolled;
5468
- provisioned = { id: principalKey(prep.owner, name).key, name, lifecycleUid, userOwner: prep.owner, ...(opts.delegatedIntent ? { delegated: true } : {}), secretPaths: prep.files, ...(custody ? { runtime: custody } : {}) };
5469
- if (hostedEnrollment) {
5470
- try {
5471
- await hooks?.onAccepted?.({ name, identity, lifecycleUid, agentTriple: { owner: prep.owner, actor: name, uid: lifecycleUid } });
5472
- await acceptOnce({ owner: prep.owner, actor: name, uid: lifecycleUid });
5473
- }
5474
- catch (e) {
5475
- // A refused accept rolls the enrollment back: the host's grant through `provisioned`, and
5476
- // this participant's secret family here, before the refusal returns. The hosted retirement
5477
- // removes it too, but only once the host's release completes.
5478
- const unshredded = [];
5479
- await this.shredUserSecrets(unshredded, prep.files);
5480
- if (unshredded.length)
5481
- throw new Error(`${rejectionText(e)}; cleanup failed: ${describeCleanupFailures(unshredded)}`, { cause: e });
5482
- throw e;
5483
- }
5484
- }
5485
- }
5486
- else if (this.auth) {
5487
- // §13.1: reserve + activate this incarnation's DURABLE identity BEFORE any
5488
- // broker footprint — the outer spawn intent first (slot row, phase `provisioning`),
5489
- // then the SHARED core activation saga (reserve uid -> gate frozen -> head CAS -> reopen
5490
- // LAST) over the key-pinned executor. The wire AUTHORITY principal is the incarnation-
5491
- // unique nkey; the alias is protected by the name-keyed slot + freeSlot hold.
5492
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: identity.id, lifecycleUid, alias: name }, (t) => activateStaticLifecycle(t, { owner: DEV_OWNER, alias: name, actor: identity.id, lifecycleUid, managerInstance: this.managerLifecycleUid, ownerInstanceId: this.managerInstanceId, runtime: custody }));
5493
- // From here the DURABLE registration exists: arm the rollback BEFORE minting, so a throw
5494
- // between activation and provisioning still drives the exact-op static terminal (the
5495
- // finally's deprovision tolerates absent files; the broker teardown is idempotent).
5496
- provisioned = { id: identity.id, name, lifecycleUid, ...(custody ? { runtime: custody } : {}) };
5497
- // Pre-create the agent's bind-only chat (+ DM + role TASK) durables and mint its scoped creds
5498
- // — the shared onboarding step (provisionAgent). It runs on a short-lived PROVISIONER connection
5499
- // (NOT the supervisor's long-lived endpoint), so the DM/DLV consumer-create surface exists only
5500
- // for the provisioning window, never as a standing grant on the always-on daemon (residual 2).
5501
- // The credential is BOUNDED (`expiresAt`) — the manager push-renews it ahead of expiry.
5502
- const now = Math.floor(Date.now() / 1000);
5503
- const exp = now + MANAGED_STATIC_TTL_SEC;
5504
- // The credential is an ISSUANCE (SPEC 13.15): its caller rails carry a fresh generation
5505
- // and its ceiling is recorded as evidence bound to this incarnation's ledger family. The
5506
- // §13.1 ledger append (ledger BEFORE materialization) is the release's finalizer, so the
5507
- // evidence activates only once the row exists, and the row exists only after the evidence
5508
- // was staged. The agent learns the generation by reading the accepted row under its token.
5509
- // The generation's horizon bounds every renewal of this incarnation's credential.
5510
- issued = { generation: mintGeneration(now + STATIC_GENERATION_HORIZON_SEC), acceptedToken: mintAcceptedToken(), listing: true };
5511
- const issuedAgent = { name, id: identity.id, lifecycleUid };
5512
- const creds = await this.withIssuer((i) => this.withProvisioner((prov) => provisionAgent(prov, this.auth, identity, {
5513
- eventPayloads,
5514
- subscribe,
5515
- allowSubscribe,
5516
- allowPublish,
5517
- role,
5518
- capabilities,
5519
- ...(endpoints.length ? { endpointCapabilities: endpoints } : {}),
5520
- lifecycleUid,
5521
- expiresAt: exp,
5522
- issued,
5523
- issuance: this.issuanceSeam(i, "issue", issuedAgent, exp),
5524
- })));
5525
- // Store first (the source of truth), then materialize: `buildLaunch` hands the CHILD this
5526
- // file path, so the cred must exist as a file regardless of the store behind the seam. The
5527
- // manager's ONE store (injected for hosted, workstation FS locally).
5528
- const secrets = this.secrets;
5529
- // LIFECYCLE-KEYED (SPEC 13.1 on the FS): the incarnation's cred file embeds its uid, so a
5530
- // replayed/stale teardown can never address a same-name successor's credential.
5531
- credsPath = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, lifecycleUid).creds;
5532
- await secrets.put(agentSecretKeyForFile(credsPath, this.space), creds);
5533
- await materializeSecretToFile(secrets, agentSecretKeyForFile(credsPath, this.space), credsPath);
5534
- provisioned = { id: identity.id, name, lifecycleUid, secretPaths: { creds: credsPath }, ...(custody ? { runtime: custody } : {}) }; // footprint now exists — the finally rolls it back if the spawn throws
5535
- }
5536
- // Per-agent cwd overrides the manager's shared workspace root, so agents can be rooted at
5537
- // arbitrary folders/repos. A relative path resolves against the workspace root; omitted → the
5538
- // agent shares the workspace root (the prior, unchanged behavior).
5539
- // The realpath the admission check above already resolved (#385 item 2) — never re-resolved here,
5540
- // so the admission refusal and the launch cwd can never disagree on the same request.
5541
- const cwd = resolvedCwd ?? this.workspaceRoot;
5542
- // An inline persona's snapshot, and its catalog copy when saved, are written here: after the
5543
- // grant (the static issuance, the user-auth ledger, a hosted enrollment that may replace the
5544
- // uid) and before launch, so a refused grant leaves neither file and the snapshot carries the
5545
- // final uid. A copy that loses a create race throws, and the finally rolls the grant back.
5546
- if (inline) {
5547
- configPath = writeInlineSnapshot(this.workspaceRoot, lifecycleUid, { name, role, model, variant, description: def.description, body: def.persona });
5548
- snapshotUid = lifecycleUid;
5549
- if (catalogCopy)
5550
- saveAgentFile(agentFilePath(this.workspaceRoot, ref), catalogCopy, { createOnly: true });
5551
- }
5552
- if (configPath === undefined)
5553
- throw new Error("internal: the persona file is missing at launch");
5554
- const configSha256 = this.fileDigest(configPath);
5555
- const manifestPath = opts.launchRef
5556
- ? join(this.workspaceRoot, ".cotal", "run", `${opts.launchRef.runId}.json`)
5557
- : undefined;
5558
- const manifestSha256 = manifestPath ? this.fileDigest(manifestPath) : undefined;
5559
- const launchOpts = {
5560
- ...hostFields,
5561
- name,
5562
- role,
5563
- // User mode: the principal IS the identity (the endpoint derives card.id from owner+actor);
5564
- // no nkey id, no static creds.
5565
- id: userLaunch ? undefined : identity.id,
5566
- creds: credsPath,
5567
- userAuth: userLaunch,
5568
- // The incarnation's lifecycle UID: the agent endpoint binds its lifecycle-keyed dm/dlv/
5569
- // chathist durables by this exact value (its creds pin the same names, so a mismatch fails
5570
- // at the broker, never silently).
5571
- lifecycleUid,
5572
- acceptedToken: issued?.acceptedToken,
5573
- configPath,
5574
- model,
5575
- variant,
5576
- launchOptions,
5577
- // Fork an existing session into the mesh. Taken straight from `opts.resume` (the imperative
5578
- // control arg), never from `opts.resolved` — so the manifest launch path carries no resume by
5579
- // construction. An unsupported connector throws here before any process is spawned.
5580
- resume: opts.resume,
5581
- reopenSession,
5582
- // Initial prompt: the `--prompt` flag, or the manifest entry's `prompt:` on a resolved launch.
5583
- // A reopened session already had its kickoff turn, so it is not submitted again. A once
5584
- // seat gets its prompt as its one relayed task instead.
5585
- prompt: reopenSession === undefined && opts.once === undefined ? prompt : undefined,
5586
- ...(opts.once !== undefined ? { once: true } : {}),
5587
- // The SAME access set the creds were minted from (above) — forwarded so the session's
5588
- // runtime read/post set matches its credentials. Without this a manifest-spawned agent
5589
- // (materialized persona has no access frontmatter) has no channel set to read and joins
5590
- // nothing, even though its creds authorize the manifest's channels.
5591
- subscribe,
5592
- allowSubscribe,
5593
- allowPublish,
5594
- capabilities,
5595
- // Always the list the launch resolved, `[]` included, so the session never reads a persona
5596
- // file that may have changed since.
5597
- endpoints: copyPersonaEndpoints(personaEndpoints) ?? [],
5598
- events,
5599
- eventPayloads,
5600
- cwd,
5601
- };
5602
- // A delegated seat gets no local launch at all: no launch-material file, control token or
5603
- // manager path is produced for it, only the handoff its runtime writes into the child.
5604
- let spec;
5605
- let handle;
5606
- if (runtime.spawnDelegated) {
5607
- const handoff = this.userProvision.composeManagedHandoff(enrolled.material, enrolled.actorToken);
5608
- if (this.delegatedLaunched.has(lifecycleUid))
5609
- throw new Error(`lifecycle ${lifecycleUid} was already handed to runtime "${runtime.kind}"; a lifecycle is handed off at most once`);
5610
- this.delegatedLaunched.add(lifecycleUid);
5611
- const holder = retainConnectorSeat(this.managerInstanceId, name);
5612
- handle = runtime.spawnDelegated({ agent, persona: readFileSync(configPath, "utf8"), managerInstanceId: this.managerInstanceId, role, model, variant, prompt, launchOptions: launchOptions, events, eventPayloads }, handoff);
5613
- watchConnectorHolder(handle, holder);
5614
- }
5615
- else {
5616
- if (carried) {
5617
- seatHome = join(this.workspaceRoot, ".cotal", "seat-homes", lifecycleUid);
5618
- mkdirSync(seatHome, { recursive: true, mode: 0o700 });
5619
- launchOpts.carried = { home: seatHome, transcript: carried.path, cwd };
5620
- }
5621
- spec = connector.buildLaunch(launchOpts);
5622
- if (carried)
5623
- this.transcripts.consume(opts.resumeClaim, opts.resume);
5624
- spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
5625
- handle = await this.seatCustody.spawnCustodied(runtime, name, spec, cwd, custody);
5626
- }
5627
- if (onceTask && !handle.waitForExit)
5628
- throw new Error(`once: runtime "${handle.kind}" cannot prove the seat's exit, which is what ends its task when the seat goes first`);
5629
- const launchedAt = Date.now();
5630
- hooks?.onLaunched?.(); // The "launched" progress edge (process spawned, pre-presence)
5631
- const managed = {
5632
- name,
5633
- role,
5634
- agent,
5635
- ...(seatHome ? { seatHome } : {}),
5636
- id: userLaunch ? principalKey(userLaunch.owner, name).key : identity.id,
5637
- lifecycleUid,
5638
- // The lifecycle-keyed family this spawn just materialized (absent on an open mesh) — the
5639
- // recorded truth teardown/preservation/health consume, never re-derived by name.
5640
- secretPaths: provisioned?.secretPaths,
5641
- ...(userLaunch ? { userOwner } : { seed: identity.seed }),
5642
- ...(opts.delegatedIntent ? { delegated: true } : {}),
5643
- ...(issued ? { issued } : {}),
5644
- spawner: spawner ?? this.ep.ref().id,
5645
- authorityParent: userLaunch && spawner && parsePrincipalKey(spawner) ? spawner : undefined,
5646
- startedAt: Date.now(),
5647
- handle,
5648
- control: spec?.control,
5649
- ...(spec ? {} : { handedOff: true }),
5650
- launch: {
5651
- runtime: runtime.kind,
5652
- source: opts.resolved
5653
- ? {
5654
- kind: "manifest",
5655
- runId: opts.launchRef?.runId,
5656
- requested: opts.launchRef?.requested ?? opts.resolved.name,
5657
- hash: opts.launchRef?.hash ?? opts.resolved.hash,
5658
- configPath,
5659
- configSha256,
5660
- manifestSha256,
5661
- }
5662
- : inline
5663
- ? { kind: "inline", ref, configPath, configSha256 }
5664
- : { kind: "persona", ref: opts.config ? identityName : ref, configPath, configSha256 },
5665
- cwd,
5666
- model,
5667
- variant,
5668
- // The kickoff prompt is part of the launch form: a stale-restart re-submits it, so the
5669
- // recorded launch must carry it for the restart gate (and preserve) to see it. A once
5670
- // seat's prompt is its task, which no relaunch may submit again.
5671
- prompt: onceTask ? undefined : prompt,
5672
- subscribe,
5673
- allowSubscribe,
5674
- allowPublish,
5675
- capabilities,
5676
- ...(personaEndpoints?.length ? { endpoints: copyPersonaEndpoints(personaEndpoints) } : {}),
5677
- events,
5678
- eventPayloads,
5679
- shareTools: opts.shareTools,
5680
- forkSource: opts.resume,
5681
- ...(opts.resume !== undefined && spec?.resumeRecordPath ? { resumeRecordPath: spec.resumeRecordPath } : {}),
5682
- ...(carried ? { carried: { transcriptSha256: carried.sha256, host: carried.sourceHost, transferredAt: carried.stagedAt } } : {}),
5683
- // Opaque values may contain secrets. Preserve only their keys and require the referenced
5684
- // persona/manifest to resolve the values again; imperative overrides have no safe payload.
5685
- unresolvedLaunchOptionKeys: opts.launchOptions && Object.keys(opts.launchOptions).length
5686
- ? Object.keys(opts.launchOptions).sort()
5687
- : undefined,
5688
- },
5689
- // A delegated agent is never restarted (SPEC 13.16), and a once seat never runs its task
5690
- // twice, so neither slot arms recovery.
5691
- ...(onceTask ? { once: { ref: onceTask.ref, ...(connector.retireAfterExit ? { retire: connector.name } : {}) } } : {}),
5692
- ...(spec && (connector.supportsSessionContinuation || opts.supervise !== undefined) && !opts.delegatedIntent && !onceTask
5693
- ? {
5694
- restart: {
5695
- opts: launchOpts,
5696
- sessionStatePath: spec.sessionStatePath,
5697
- crashes: [],
5698
- recovering: false,
5699
- armed: false,
5700
- ...(opts.supervise !== undefined ? { policy: opts.supervise } : {}),
5701
- },
5702
- }
5703
- : {}),
5704
- };
5705
- // The DURABLE slot takes the `active` phase before the in-memory row takes the
5706
- // name — a crash between the two leaves an active-but-unadopted slot the boot sweep
5707
- // terminalizes (never an untracked orphan). Static auth only; a failed CAS fails the spawn
5708
- // (the finally's rollback then drives the exact-op terminal).
5709
- if (this.auth && !this.userMode) {
5710
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: managed.id, lifecycleUid, alias: name }, async (t) => {
5711
- const slot = await readStaticSlot(t, DEV_OWNER, name);
5712
- if (slot === undefined || slot.row.lifecycleUid !== lifecycleUid || slot.row.phase !== "provisioning")
5713
- throw new Error(`the static slot for "${name}" is ${slot === undefined ? "absent" : `${slot.row.phase} at uid ${slot.row.lifecycleUid}`}, not this spawn's provisioning intent; refusing to take the slot`);
5714
- // The custody reference rides the SAME CAS as activation: a crash after this write leaves
5715
- // an active slot a successor can reap by reference, never a live seat nobody addresses.
5716
- await casStaticSlot(t, { ...slot.row, phase: "active", ...(handle.reference ? { runtime: handle.reference } : {}) }, slot.revision);
5717
- });
5718
- }
5719
- this.place(name, managed);
5720
- if (managed.once)
5721
- this.watchOnceExit(managed);
5722
- // The live slot now owns teardown — freeSlot deprovisions this identity on exit — so the
5723
- // orphan-rollback in `finally` no longer applies to it.
5724
- provisioned = undefined;
5725
- seatHome = undefined;
5726
- snapshotUid = undefined;
5727
- // #159 B1: reply on a REAL outcome, not a timer. Wait for the agent to actually join the mesh
5728
- // (presence) → started, the child to exit → failed (with its last output; already reaped), or
5729
- // neither in time → uncertain. `✓ started` therefore means "it joined", never just "a process
5730
- // launched", except for a launch whose options make the harness wait for the operator first: that
5731
- // one is ready once its process runs, and its reply names the screen it waits at.
5732
- const operator = connector.waitsForOperator?.(launchOptions);
5733
- const readiness = await this.awaitReadiness(managed, readinessTimeoutMs, operator === undefined ? {} : { operator });
5734
- // Deliberately stopped mid-launch: reaped by onExit, and the despawn/stop path owns the
5735
- // goal terminal. Return BEFORE the failed/uncertain arms so this emits no competing
5736
- // outcome and does not re-arm an exit watcher on an agent already gone.
5737
- if (!readiness.ok && readiness.deliberate) {
5738
- hooks?.onTerminalDeferred?.();
5739
- return { ok: false, error: readiness.detail };
5740
- }
5741
- if (!readiness.ok && !readiness.uncertain) { // failed → already reaped
5742
- // A reopen fails before readiness when the host no longer has the recorded session, which
5743
- // is refused rather than replaced by an empty one; name the record that pins it.
5744
- const error = reopenSession === undefined ? readiness.detail
5745
- : `${readiness.detail} (continuity: exact was reopening recorded session ${reopenSession}; if the harness no longer has it, ` +
5746
- `remove ${join(this.workspaceRoot, ".cotal", "continuity", `${name}.json`)} to start a new session)`;
5747
- if (managed.once)
5748
- managed.once.stopReason ??= "launch-failed";
5749
- await hooks?.onOutcome?.({ kind: "failed", data: { error } });
5750
- return { ok: false, error };
5751
- }
5752
- // Started OR uncertain: the agent stays managed, so wire the ongoing exit reaper (it reaps a later
5753
- // death — including one that follows an `uncertain` verdict, which deliberately does NOT deprovision).
5754
- if (!readiness.ok) {
5755
- this.watchExit(managed);
5756
- if (managed.launch.carried)
5757
- void this.sessionRecovery.refuseLateCarriedFork(managed, readinessTimeoutMs);
5758
- // A once seat is never left running with nothing to do, and its stop does not wait on the
5759
- // spawn's terminal, whose write can stall. The spawn keeps that terminal: the stop lets go
5760
- // of the spawn goal first. Its task was never served and is cancelled with the verdict.
5761
- if (managed.once) {
5762
- this.endOnceBeforeServe(managed, "readiness-timeout");
5763
- }
5764
- await hooks?.onOutcome?.({ kind: "uncertain", data: { reason: readiness.detail, ...(readiness.running ? { running: true } : {}) } });
5765
- return { ok: false, error: readiness.detail };
5766
- }
5767
- // A once seat whose connector needs a confirmed startup is served only on that outcome. Any
5768
- // other ends it like a seat that never joined: stopped before the failed terminal, and its
5769
- // task, never served, cancelled with the verdict.
5770
- if (onceTask && connector.onceNeedsConfirmed !== undefined) {
5771
- const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
5772
- if (managed.terminalizing || this.leaseStopping) {
5773
- hooks?.onTerminalDeferred?.();
5774
- return { ok: false, error: `${name} was stopped before its startup ended` };
5775
- }
5776
- if (startup !== "confirmed") {
5777
- const watch = { ready: "opened its input screen without the prompt", failed: "failed", exited: "saw the seat exit", pending: "had not ended" }[startup];
5778
- const error = `${name} joined, but ${connector.onceNeedsConfirmed}: its startup watch ${watch}, so it cannot take a once task`;
5779
- this.watchExit(managed);
5780
- this.endOnceBeforeServe(managed, "launch-failed", "launch-failed");
5781
- await hooks?.onOutcome?.({ kind: "failed", data: { error } });
5782
- return { ok: false, error };
5783
- }
5784
- }
5785
- // A plain seat on such a connector starts whatever its startup showed. One whose watch opened the
5786
- // input screen without the prompt is not woken by mesh traffic, and the spawn says so instead of
5787
- // starting it silently without push (#5737).
5788
- if (!onceTask && connector.idleWakeNeedsConfirmed !== undefined && runtime.reportsStartupOutcome) {
5789
- const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
5790
- if (managed.terminalizing || this.leaseStopping) {
5791
- hooks?.onTerminalDeferred?.();
5792
- return { ok: false, error: `${name} was stopped before its startup ended` };
5793
- }
5794
- if (startup === "ready") {
5795
- managed.startupNotice = connector.idleWakeNeedsConfirmed;
5796
- console.error(`! ${name}: ${connector.idleWakeNeedsConfirmed}`);
5797
- }
5798
- }
5799
- if (managed.launch.carried) {
5800
- const refused = await this.sessionRecovery.refuseCarriedFork(managed, readinessTimeoutMs);
5801
- if (refused !== undefined && managed.terminalizing) {
5802
- hooks?.onTerminalDeferred?.();
5803
- return { ok: false, error: refused };
5804
- }
5805
- if (refused !== undefined) {
5806
- this.stopAndTrack(managed, "carried-fork-refused");
5807
- await hooks?.onOutcome?.({ kind: "failed", data: { error: refused } });
5808
- return { ok: false, error: refused };
5809
- }
5810
- }
5811
- if (managed.restart) {
5812
- if (connector.supportsSessionContinuation) {
5813
- try {
5814
- await this.sessionRecovery.armSessionRecovery(managed);
5815
- // The capability flags are only a claim. An exact seat is recorded once the connector
5816
- // has proved its session over its authenticated control endpoint, never before.
5817
- if (exact && !managed.restart.armed)
5818
- throw new Error("continuity: exact needs the connector to prove its session over an authenticated control endpoint, and it supplied none");
5819
- managed.launch.sessionId = this.sessionRecovery.readManagedSession(managed);
5820
- if (reopenSession !== undefined && managed.launch.sessionId !== reopenSession)
5821
- throw new Error(`continuity: exact asked for session ${reopenSession}, the connector bound ${managed.launch.sessionId}`);
5822
- if (exact) {
5823
- managed.continuity = { space: this.space, name, connector: agent, cwd };
5824
- this.sessionRecovery.recordContinuity(managed, managed.launch.sessionId);
5825
- }
5826
- }
5827
- catch (error) {
5828
- const detail = `${managed.name} joined, but its exact host session could not be bound for supervised recovery: ${rejectionText(error)}`;
5829
- this.stopAndTrack(managed, "session-bind-failed");
5830
- await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
5831
- return { ok: false, error: detail };
5832
- }
5833
- }
5834
- else {
5835
- managed.restart.armed = true;
5836
- }
5837
- if (managed.restart.policy) {
5838
- try {
5839
- this.seatCustody.recordSeat(managed);
5840
- }
5841
- catch (error) {
5842
- const detail = `${managed.name} joined, but supervise cannot cover a manager restart for it: ${rejectionText(error)}`;
5843
- this.stopAndTrack(managed, "supervise-record-failed");
5844
- await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
5845
- return { ok: false, error: detail };
5846
- }
5847
- }
5848
- }
5849
- // An unsupervised seat a successor could adopt keeps a record too; one that cannot be written
5850
- // costs only that adoption, so the spawn stands and the line says so.
5851
- if (!managed.restart?.policy)
5852
- this.seatCustody.refreshSeatRecord(managed);
5853
- this.watchExit(managed);
5854
- // Reply with the id the slot actually carries (user-mode: the owner.actor principal —
5855
- // presence, ps, and the manifest ownership ledger all key on it; the throwaway static nkey
5856
- // would never match and down -f would treat the agent as foreign).
5857
- // `lifecycleUid` rides the reply so callers that record this spawn (the manifest ledger) can
5858
- // later address the incarnation's lifecycle-keyed artifacts without re-deriving by name.
5859
- // OMIT an absent role: the goal terminal commits this data through the strict
5860
- // canonicalJson (undefined never coerces to null, SPEC 13.6), so a role-less spawn would
5861
- // otherwise fail its succeeded terminal. The CLI/connector already render an absent role as
5862
- // "no role", so dropping the key preserves the reply (surfaced by readiness:live).
5863
- // A host that granted other channels than this spawn asked for: the receipt carries both.
5864
- const acl = enrolled ? enrolledAcl({ allowSubscribe, allowPublish }, enrolled.material) : undefined;
5865
- const okData = { name, agent, id: managed.id, mode: handle.kind, streamsTerminal: runtime.streamsTerminal, lifecycleUid, ...(role !== undefined ? { role } : {}), ...(opts.eventsNotice !== undefined ? { eventsNotice: opts.eventsNotice } : {}), ...(managed.startupNotice !== undefined ? { startupNotice: managed.startupNotice } : {}), ...(acl ? { acl } : {}), ...(readiness.operator !== undefined ? { waitingFor: readiness.operator } : {}), ...(onceTask ? { once: { goalId: onceTask.ref.goalId, ...(onceTask.deadlineAt !== undefined ? { deadlineAt: onceTask.deadlineAt } : {}) } } : {}) };
5866
- // The task is served once the succeeded terminal is written, so a served task always has it
5867
- // and a successor reads it as the readiness verdict. Every failure arm above ran before it. A
5868
- // terminal this call did not commit never served the task: the seat is stopped, which cancels it.
5869
- const committed = await hooks?.onOutcome?.({ kind: "succeeded", data: okData });
5870
- if (onceTask && committed === true)
5871
- this.openOnceDelivery(onceTask.ref);
5872
- else if (onceTask) {
5873
- this.endOnceBeforeServe(managed, "launch-failed", "launch-failed");
5874
- }
5875
- return { ok: true, data: okData };
5876
- }
5877
- catch (e) {
5878
- // Failure after reserve (provision / launch threw): the slot was never live, so no cold-start
5879
- // was paid — the reserved rollback (finally) is enough, no cooling stamp.
5880
- // Keep the envelope's code and lifecycle details on the ControlReply so the serve boundary
5881
- // can carry the refusal's classification and barrier to the caller. An extension can throw
5882
- // any value, and an envelope's `message` is only typed as a string, so the refusal text always
5883
- // comes from rejectionText; telling an envelope apart is guarded because a thrown Proxy can
5884
- // throw from `instanceof` or from its own fields.
5885
- const error = rejectionText(e);
5886
- try {
5887
- if (e instanceof EpEnvelopeError)
5888
- return controlReplyFromThrown(e, error);
5889
- }
5890
- catch { /* not a readable envelope */ }
5891
- return { ok: false, error };
5892
- }
5893
- finally {
5894
- this.namesCapacity.release(name);
5895
- if (seatHome)
5896
- rmSync(seatHome, { recursive: true, force: true });
5897
- // A failed removal is logged, never thrown, so the grant's teardown below is still scheduled.
5898
- const snapshotGone = snapshotUid === undefined || this.dropInlineSnapshot(name, snapshotUid);
5899
- // Minted but never handed to a live slot (buildLaunch / runtime.spawn threw after mint) → tear the
5900
- // orphan down (detached, fail-loud) so a failed spawn leaves no creds/durables behind (#159 B).
5901
- if (provisioned) {
5902
- // Settled when this spawn wrote no snapshot or removed the one it wrote. A file its write
5903
- // refused is not this lifecycle's, so the terminal leaves the uid's path alone; a removal
5904
- // that failed is the terminal's to retry and report.
5905
- const orphan = { ...provisioned, ...(snapshotGone ? { snapshotSettled: true } : {}) };
5906
- // The host enrolled this UID for the intent's user, so only that user's retirement intent
5907
- // retires it, and its name stays held for retireDelegatedAgent.
5908
- const p = orphan.delegated ? parsePrincipalKey(orphan.id) : null;
5909
- if (p)
5910
- this.retirement.hold(orphan.name, { opId: managedRetirementOpId(orphan.lifecycleUid), owner: p.owner, actor: p.actor, target: orphan, startedAt: Date.now() });
5911
- this.trackDeprovision(orphan, "(orphaned spawn)");
5912
- }
5913
- }
5914
- }
5915
4229
  /** Preflight the whole inventory before launching its first process, then adopt each exact retained
5916
4230
  * principal without provisioning. A later runtime launch failure is reported per-agent, but malformed
5917
4231
  * or missing inventory material can never produce a partially resumed set. */
@@ -7219,311 +5533,21 @@ export class Manager {
7219
5533
  }
7220
5534
  dialServeConnection(state, readCreds = () => state.creds, deadline) { return this.servePlane.dialServeConnection(state, readCreds, deadline); }
7221
5535
  registerManagerService() { return this.servePlane.registerManagerService(); }
7222
- /** Mint the standing `goal-writer` credential and STAGE it into this
7223
- * instance's §13.1 revocation family (`epcred.<e>.<iid>`), over the passed executor's `authKv`
7224
- * (the scoped `endpoint-serve-executor`, which holds the epcred write grant). The GRANT profile
7225
- * stays goal-writer-only (Q2, disjoint from the serve credential); only the FAMILY membership
7226
- * is shared, so the registration barrier's existing enumerate+revoke+evict catches the
7227
- * goal-writer on takeover/retire with NO barrier code change. Used both at registration (the run
7228
- * block's `authKv`) and at renewal (a fresh executor's), re-minting the SAME stable nkey with a
7229
- * fresh bounded exp: `mintCreds` stamps a random `issuance:` tag on `goal-writer` (`userTags`),
7230
- * so each issuance signs distinct bytes and stages a distinct ledger row (per-JWT `credentialId`
7231
- * digest) even within one second. */
7232
- async mintAndStageGoalWriter(authKv) {
7233
- const auth = this.auth;
7234
- const identity = this.goalWriterIdentity;
7235
- // The issuance gate + §13.1 revocation family are keyed by the REGISTRATION instanceId
7236
- // (the persisted logical id), NOT the per-process lifecycleUid — the barrier
7237
- // enumerates `epcred.<e>.<managerInstanceId>`, so the goal-writer must stage into that family.
7238
- const iid = this.managerInstanceId;
7239
- const creds = await mintCreds(auth, identity, "goal-writer", { goalWriter: { endpoint: MANAGER_ENDPOINT } });
7240
- const exp = inspectCredHealth(creds).exp;
7241
- if (exp === undefined)
7242
- throw new Error(`the goal-writer credential for ${MANAGER_ENDPOINT}/${iid} is unbounded; the §13.1 ledger row requires an expiry`);
7243
- const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
7244
- const observed = await fence.observe();
7245
- if (observed === null)
7246
- throw new Error(`the issuance gate for ${MANAGER_ENDPOINT}/${iid} vanished; the goal-writer cannot join its §13.1 revocation family`);
7247
- // The §13.1 open-and-commit fence, the SAME one the serve credential's own mint runs: a frozen
7248
- // gate refuses, and a gate that moved under us loses the CAS and revokes the staged row. Without
7249
- // it a barrier mid-takeover (already past its enumeration) would let this credential land
7250
- // ACTIVE in a family nothing revokes again.
7251
- await commitSiblingIssuance(fence, observed, {
7252
- credentialId: credentialIdOf(creds),
7253
- credentialKey: identity.id,
7254
- holderPrincipal: principalKey(DEV_OWNER, identity.id).key,
7255
- endpoint: MANAGER_ENDPOINT, lifecycleUid: iid, sourceChain: ["root"], state: "active", exp,
7256
- generation: observed.generation, processEpoch: observed.processEpoch,
7257
- registrationRevision: observed.registrationRevision, nameAuthorityRevision: observed.nameAuthorityRevision,
7258
- });
7259
- return creds;
7260
- }
7261
- /** #2073: dial the goal-writer's ONE standing connection and rebuild everything derived from it
7262
- * (the fence-resolving action context, the issuance-gate reader) — shared by the initial start
7263
- * and the closed-connection recovery ({@link onGoalWriterConnectionClosed}), so a redial never
7264
- * leaves the context bound to a dead socket. */
7265
- async dialGoalWriter(gw) {
7266
- const nc = await this.dial({
7267
- ...((this.auth || this.remoteAuthority) ? standaloneConnectOpts({ creds: () => gw.creds, tls: false }) : {}),
7268
- inboxPrefix: `_INBOX_${gw.identity.id}`,
7269
- maxReconnectAttempts: -1,
7270
- });
7271
- nc.closed().then((err) => { void this.onGoalWriterConnectionClosed(err ?? undefined); });
7272
- this.trackTransport(nc);
7273
- gw.nc = nc;
7274
- // The (i) fence resolver (SPEC 13.6): resolve an executing instance's CURRENT gate
7275
- // epoch. This manager reconciles only ITS OWN goals, so it resolves its own
7276
- // registration instanceId to this incarnation's serve-grant epoch; a foreign/retired instance
7277
- // is `null` (no current terminal to surface). A successor incarnation carries an ADVANCED epoch
7278
- // here, so its reads pick the current-epoch subject and the predecessor's terminal is fenced out.
7279
- gw.ctx = await actionContext(nc, this.space);
7280
- // The own-issuance-gate READER for the currency belt, on BOTH mesh modes. Reads
7281
- // `epgate.<e>.<iid>` over this connection; observe-only (stage/commit/revoke are never called
7282
- // through it — the goal-writer holds no gate/epcred WRITE grant, so a mis-call would
7283
- // broker-deny anyway).
7284
- //
7285
- // OPEN MESH IS NOT EXEMPT, and this is load-bearing. An open-mesh registration mints no
7286
- // credentials, so the §13.1 takeover barrier's revoke-and-evict loop enumerates an EMPTY family
7287
- // and is VACUOUS — yet it still advances processEpoch. The gate row itself DOES exist there
7288
- // (`provisionEndpointGateOpen`, over the authority stores the open serve path ensures), and a
7289
- // bare connection CAN read it (executed probe). So this belt is the ONLY thing standing between
7290
- // a deposed open-mesh incarnation and a wrong terminal on the one create-only result subject.
7291
- //
7292
- // NAME IT HONESTLY: on an open mesh this is a COOPERATIVE fence. The broker enforces nothing, so
7293
- // a hostile or non-conformant process can simply not run the check — the same guarantee class as
7294
- // every other open-mesh property. It is also a read-then-CAS, so it NARROWS the commit window
7295
- // rather than closing it. An AUTH mesh gets durable closure from the §13.1 barrier (revoke +
7296
- // cluster-verified eviction BEFORE the epoch advance); an open mesh gets none.
7297
- gw.gate = serveIssuanceGateKv(await new Kvm(nc).open(epAuthBucket(this.space)), this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId });
7298
- }
7299
- /** #2073: the goal-writer rail's closed-connection fault, the same bounded shape the serve rail
7300
- * uses ({@link onServeConnectionClosed}) through the same {@link boundedReconnect} helper:
7301
- * re-dial with the current credential (a transport blip needs nothing new), re-mint through the
7302
- * existing goal-writer renewal branch when the credential itself has expired, then re-attach.
7303
- * Unlike the serve rail this never exits the process on exhaustion (brief step 4: only the serve
7304
- * rail is the control plane the report lost) — it logs and leaves the credential to the next
7305
- * scheduled renewal pass. */
7306
- async onGoalWriterConnectionClosed(err) {
7307
- if (this.leaseStopping)
7308
- return;
7309
- console.error(`! manager goal-writer connection closed: ${err?.message ?? "unknown reason"}`);
7310
- const gw = this.goalWriter;
7311
- const recovered = await this.boundedReconnect("goal-writer", async () => {
7312
- if (!gw)
7313
- return false;
7314
- if (this.remoteAuthority)
7315
- await this.renewRemoteBeforeRedial("goal-writer", () => gw.creds);
7316
- else if (gw.creds !== undefined && inspectCredHealth(gw.creds).state !== "healthy") {
7317
- gw.creds = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageGoalWriter(authKv));
7318
- this.goalWriterCreds = gw.creds;
7319
- }
7320
- await this.dialGoalWriter(gw);
7321
- console.error("manager goal-writer re-dialed");
7322
- return true;
7323
- }, inspectCredHealth(gw?.creds ?? "").state === "expired");
7324
- if (this.leaseStopping || recovered)
7325
- return;
7326
- console.error("! manager goal-writer could not be re-dialed; leaving the credential to the next renewal pass");
7327
- }
7328
- /** Spawn-as-action: stand up the standing self-mediated goal-writer connection +
7329
- * ActionContext. Mode-dual, mirroring {@link registerManagerService}: an AUTH mesh uses the
7330
- * scoped `goal-writer` credential already minted + family-STAGED inside registration's run block
7331
- * ({@link mintAndStageGoalWriter} — DISJOINT grant from the serve cred, SHARED §13.1 revocation
7332
- * family); an OPEN mesh uses a bare connection (no credential system to mint from - the broker
7333
- * enforces nothing). The connection presents the CURRENT credential on every (re)connect (a
7334
- * renewal is adopted without reconnecting the whole endpoint); the ActionContext bonds its
7335
- * KV + JS + JSM to this one connection and space (SPEC 13.4), so a composition mixup cannot splice
7336
- * goal state across brokers. */
7337
- async startGoalWriter() {
7338
- const identity = (this.auth || this.remoteAuthority) ? this.goalWriterIdentity : newIdentity();
7339
- // The mutable holder captured by the authenticator (mirrors the serve connection): a half-TTL
7340
- // renewal updates `gw.creds` and the next (re)connect presents the refreshed credential.
7341
- const gw = { nc: undefined, ctx: undefined, creds: (this.auth || this.remoteAuthority) ? this.goalWriterCreds : undefined, identity };
7342
- await this.dialGoalWriter(gw);
7343
- this.goalWriter = gw;
7344
- console.error(`manager goal-writer standing (endpoint ${MANAGER_ENDPOINT}, ${(this.auth || this.remoteAuthority) ? "scoped cred, §13.1 family-staged" : "open/bare"})`);
7345
- }
7346
- /** Retire the goal-writer connection (best-effort, both exit paths). */
7347
- async stopGoalWriter() {
7348
- const gw = this.goalWriter;
7349
- if (!gw)
7350
- return;
7351
- this.goalWriter = undefined;
7352
- await this.retireConnection(gw.nc);
7353
- }
5536
+ /** {@link GoalWriter.mintAndStageGoalWriter}. */
5537
+ mintAndStageGoalWriter(...args) { return this.goalWriterComponent.mintAndStageGoalWriter(...args); }
5538
+ /** {@link GoalWriter.startGoalWriter}. */
5539
+ startGoalWriter(...args) { return this.goalWriterComponent.startGoalWriter(...args); }
5540
+ /** {@link GoalWriter.stopGoalWriter}. */
5541
+ stopGoalWriter(...args) { return this.goalWriterComponent.stopGoalWriter(...args); }
7354
5542
  mintAndStageSessionLedger(authKv) { return this.servePlane.mintAndStageSessionLedger(authKv); }
7355
5543
  startSessionPlane() { return this.servePlane.startSessionPlane(); }
7356
5544
  stopSessionPlane() { return this.servePlane.stopSessionPlane(); }
7357
- /** The boot reconcile: a fresh incarnation (a manager restart takes a NEW
7358
- * instanceId, so the in-memory acceptance map starts empty) inherits the endpoint's accepted-but-
7359
- * unterminal goals from any predecessor. The local signer enumerates with an ephemeral PROVISIONER.
7360
- * A remote manager calls the authenticated host-owned scan, which keeps the sealed consumer and its
7361
- * lifecycle authority on the host; the instance executor, goal-writer, and supervisor hold NO records
7362
- * consumer grant. Settle each orphan so an accepted goal is NEVER dropped across a restart. Open mesh:
7363
- * a bare connection (the broker enforces nothing). Runs ONCE at start, BEFORE spawn-as-action begins
7364
- * accepting (the `goalReconcileDone` gate), so it never races a live goal's acceptance. Never
7365
- * fatal — a reconcile failure is logged and the gate opens either way. */
7366
- async reconcileGoalIndex() {
7367
- const gw = this.goalWriter;
7368
- if (!gw) {
7369
- this.goalReconcileDone = true;
7370
- return;
7371
- }
7372
- try {
7373
- let entries = [];
7374
- if (this.remoteAuthority) {
7375
- entries = (await this.remoteAuthority.scanGoalIndex()).map((entry) => ({
7376
- ref: { endpoint: entry.endpoint, caller: { owner: entry.owner, actor: entry.actor, uid: entry.uid }, goalId: entry.goalId },
7377
- iid: entry.iid,
7378
- ...(entry.allocated !== undefined ? { allocated: entry.allocated } : {}),
7379
- ...(entry.note !== undefined ? { note: entry.note } : {}),
7380
- }));
7381
- }
7382
- else {
7383
- const nc = this.auth
7384
- ? await this.dial({ ...standaloneConnectOpts({ creds: await mintCreds(this.auth, newIdentity(), "provisioner"), /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 })
7385
- : await this.dial({ maxReconnectAttempts: 0 });
7386
- try {
7387
- const kvm = new Kvm(nc);
7388
- await ensureAuthorityStores(await jetstreamManager(nc), kvm, this.space);
7389
- entries = await listGoalIndex(await kvm.open(recordsBucket(this.space)), MANAGER_ENDPOINT);
7390
- }
7391
- finally {
7392
- await drainAndClose(nc);
7393
- }
7394
- }
7395
- // Single-manager: EVERY inherited entry belongs to a DEAD predecessor (only one manager
7396
- // at a time), so all are reconciled. The `iid` field is the hook the multi-instance sweep
7397
- // filters on (skip a goal whose accepting `iid` is a still-LIVE sibling — never settle its goal).
7398
- for (const entry of entries) {
7399
- const key = goalKey(entry.ref);
7400
- if (this.goalAcceptances.has(key) || this.turnRelay.hasAcceptance(key))
7401
- continue; // never settle a goal THIS incarnation drives
7402
- try {
7403
- // A note marks a TURN entry: its relay is rebuilt (the hold is its bounded ending), never
7404
- // settled uncertain — the spawn arm's readiness window is the wrong ending for a relay.
7405
- if (entry.note !== undefined)
7406
- await this.adoptTurnGoal(entry);
7407
- else
7408
- await this.reconcileOneGoal(entry.ref, entry.iid);
7409
- }
7410
- catch (e) {
7411
- console.error(`! goal reconcile for ${entry.ref.goalId}: ${rejectionText(e)}`);
7412
- }
7413
- }
7414
- if (entries.length)
7415
- console.error(`goal-index boot reconcile: swept ${entries.length} inherited goal(s)`);
7416
- }
7417
- catch (e) {
7418
- console.error(`! goal-index boot reconcile failed: ${rejectionText(e)} - accepted goals from a predecessor may stay unsettled until the next restart`);
7419
- }
7420
- finally {
7421
- this.goalReconcileDone = true;
7422
- this.turnRelay.markReconciled(Date.now());
7423
- // A seat that pulled during the window was refused, and a predecessor may have died before
7424
- // its notice went out, so every seat holding a rebuilt turn is told once.
7425
- const seats = this.turnRelay.pendingSeats();
7426
- for (const seat of seats)
7427
- this.noticeSeatTurns(seat);
7428
- }
7429
- }
7430
- /** Settle ONE inherited goal by evidence: no goal record (a crash between the index write and the
7431
- * goal-record create) leaves the pointer untouched (never settle a goal that was never accepted,
7432
- * and clearing it would race a live goal mid-creation); a TERMINAL goal clears the index
7433
- * (converged — the predecessor committed but died before clearing); a NON-TERMINAL goal settles
7434
- * `uncertain` (the accepting incarnation is gone, so the success signal will never reach us — the
7435
- * bounded readiness outcome the plan maps the window to). Within the readiness window it arms a
7436
- * bounded, unref'd timer to settle at the deadline (an early uncertain would steal a still-possible
7437
- * success the substrate guards against). */
7438
- async reconcileOneGoal(ref, acceptedByIid) {
7439
- const gw = this.goalWriter;
7440
- if (!gw)
7441
- return;
7442
- const status = await readGoalStatus(gw.ctx, ref);
7443
- if (status === undefined)
7444
- return; // index points at no goal record: a dead pointer, left for honesty
7445
- if (GOAL_TERMINAL_STATES.includes(status.value.state)) {
7446
- await clearGoalIndex(gw.ctx, ref);
7447
- return;
7448
- }
7449
- const spec = await readGoalSpec(gw.ctx, ref);
7450
- if (spec === undefined)
7451
- return; // a status without its spec is garbled — leave for the next boot
7452
- // NEVER A CROSS-INSTANCE SETTLE. The accepting incarnation is recorded on the INDEX ENTRY
7453
- // itself (`iid`, written at accept), which is the honest coordinate: a same-instanceId restart
7454
- // inherits its predecessor's orphans, and a goal accepted by a DIFFERENT (possibly still-live)
7455
- // sibling is left for its owner. This replaces the goal spec's `executor` pin, which existed
7456
- // only to epoch-scope the terminal subject and is gone with it (§13.2 reserved subjects).
7457
- if (acceptedByIid !== this.managerInstanceId) {
7458
- console.error(`goal reconcile ${ref.goalId}: accepted by instance "${acceptedByIid}", not this incarnation "${this.managerInstanceId}"; left for its owner (never a cross-instance settle)`);
7459
- return;
7460
- }
7461
- const settle = async () => {
7462
- // A SUCCESSOR settling work it inherited: the committer is THIS incarnation at its CURRENT
7463
- // serve epoch, which is strictly greater than the goal's acceptedEpoch — the `committed >
7464
- // accepted` arm of the attribution rule, and the reason that arm has to exist.
7465
- await settleGoalUncertain(gw.ctx, { ref, now: Date.now(), committer: { instanceId: this.managerInstanceId, epoch: this.serviceServe?.grant.epoch ?? 0 } }); // first-terminal-wins: a racing terminal returns the winner, no throw
7466
- await clearGoalIndex(gw.ctx, ref);
7467
- };
7468
- const remaining = spec.value.acceptedAt + (spec.value.readinessDeadlineMs ?? this.readinessTimeoutMs) - Date.now();
7469
- if (remaining <= 0) {
7470
- await settle();
7471
- return;
7472
- }
7473
- console.error(`goal reconcile ${ref.goalId}: within the readiness window (${remaining}ms) - arming a bounded settle`);
7474
- const t = setTimeout(() => { settle().catch((e) => console.error(`! goal reconcile settle ${ref.goalId}: ${rejectionText(e)}`)); }, remaining + 100);
7475
- t.unref?.();
7476
- }
7477
- /** Publish a goal PROGRESS event on the caller-scoped epe subtree, over the SERVE
7478
- * connection (which holds the `epe.<e>.<iid>.<epoch>.>` egress grant; the goal-writer deliberately
7479
- * does not). The terminal rides a final event `phase:"terminal"` (the caller follows epe to
7480
- * the terminal; the durable result fact + inspect/ps are the reconcile authority). A dropped event
7481
- * is non-fatal (the terminal is authoritative in the journal). */
7482
- emitGoalProgress(ref, epoch, event) {
7483
- const nc = this.serviceServe?.nc;
7484
- if (!nc)
7485
- return;
7486
- try {
7487
- nc.publish(epeSubject(this.space, MANAGER_ENDPOINT, this.managerInstanceId, epoch, goalProgressTopic(ref)), new TextEncoder().encode(JSON.stringify({ v: 1, goalId: ref.goalId, ...event })));
7488
- }
7489
- catch (e) {
7490
- console.error(`! goal progress emit for ${ref.goalId} failed: ${rejectionText(e)}`);
7491
- }
7492
- }
7493
- /** The own-gate currency belt: before the goal-writer commits a terminal fact, the manager reads
7494
- * its OWN issuance gate epoch and REFUSES the commit if superseded. This NARROWS the window; it
7495
- * is not the fence. Layer 1 below is closed by the sibling-mint fence; layers 2 and 3 are not
7496
- * closed by any planned slice and must not be described as temporary.
7497
- *
7498
- * THE RESIDUAL, STACKED:
7499
- * 1. SIBLING-MINT INJECTION. A §13.1 barrier's revoke/evict loop closes only over the family
7500
- * SNAPSHOT IT ENUMERATED, so a sibling mint that observes the gate and stages a ledger row
7501
- * WITHOUT the observe/open/commit fence can be staged and released AFTER that enumerate and
7502
- * never be revoked. This layer is closed exactly where BOTH sibling mint sites
7503
- * ({@link mintAndStageGoalWriter}, {@link mintAndStageSessionLedger}) route their stage
7504
- * through `commitSiblingIssuance` (the revision-pinned CAS that makes a losing mint release
7505
- * nothing), and open exactly where they do not — state the mechanism, never the branch.
7506
- * 2. THE BARRIER WINDOW. A gate FREEZE neither kills this connection nor advances the epoch,
7507
- * and this belt compares `processEpoch` alone, so it still PASSES from barrier start until
7508
- * the reopen. A ledger revoke marks a row; it does not re-check a live JWT mid-publish. The
7509
- * durable kill is the CLUSTER-VERIFIED EVICTION, so a deposed manager can INITIATE new
7510
- * terminal publishes from barrier start until eviction is verified — not merely finish bytes
7511
- * already on the wire. Successor EXISTENCE and corpse DEATH are different phases, so the
7512
- * barrier's ordering licenses no conclusion about when the corpse stops being able to write.
7513
- * 3. OPEN MESH. No credential family exists, so the revoke/evict loop is vacuous and this belt
7514
- * is COOPERATIVE only: a non-conformant process simply does not run it.
7515
- * The named follow-up that would close 2 and 3 is the gate-linearized commit (routing the
7516
- * terminal through the issuance gate's own CAS), deliberately deferred as substrate territory. */
7517
- async assertGoalWriterEpochCurrent(epoch) {
7518
- const gate = this.goalWriter?.gate;
7519
- if (!gate)
7520
- return; // no goal-writer standing yet
7521
- const observed = await gate.observe();
7522
- if (observed === null)
7523
- throw new EpEnvelopeError("expired", `the manager's issuance gate for ${MANAGER_ENDPOINT}/${this.managerInstanceId} is gone; a retired incarnation never commits a goal terminal (SPEC 13.1/13.6)`);
7524
- if (observed.processEpoch !== epoch)
7525
- throw new EpEnvelopeError("expired", `the manager's issuance gate epoch is ${observed.processEpoch} but this goal was accepted under epoch ${epoch}; a superseded incarnation never commits a goal terminal (SPEC 13.6)`);
7526
- }
5545
+ /** {@link GoalWriter.reconcileGoalIndex}. */
5546
+ reconcileGoalIndex(...args) { return this.goalWriterComponent.reconcileGoalIndex(...args); }
5547
+ /** {@link GoalWriter.emitGoalProgress}. */
5548
+ emitGoalProgress(...args) { return this.goalWriterComponent.emitGoalProgress(...args); }
5549
+ /** {@link GoalWriter.assertGoalWriterEpochCurrent}. */
5550
+ assertGoalWriterEpochCurrent(...args) { return this.goalWriterComponent.assertGoalWriterEpochCurrent(...args); }
7527
5551
  /** A spawn's refusal reaches only its caller's terminal, so the manager also writes one line for it
7528
5552
  * to its own log, naming the request ID the caller printed, the persona and the reason. */
7529
5553
  async loggedSpawnRefusal(ctx, serve) {