@cotal-ai/manager 0.169.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
- import { TurnRelay, goalKey, caughtEnvelope, TURN_ANSWER_RETENTION_MS, onceTurnNote, turnHoldToken } from "./turn-relay.js";
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";
5
- import { hostname, homedir } from "node:os";
6
- import { listDirectory } from "./list-dir.js";
7
- import { credsAuthenticator, RequestError } from "@nats-io/transport-node";
8
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
9
- import { isAbsolute, join, resolve, sep } from "node:path";
4
+ import { drainAndClose } from "@cotal-ai/core";
5
+ import { hostname } from "node:os";
6
+ import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
7
+ import { join, resolve } from "node:path";
10
8
  import { parse as parseYaml } from "yaml";
11
9
  import Headless from "@xterm/headless";
12
- import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, assertLifecycleToken, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, assertValidChannel, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, registry, resolveAuthProvider, resolveReadAcl, runDriverCaller, saveAgentFile, eventChannel, eventChannelPrincipal, digestIdToken, capabilityWithin, grantOverreach, grantParts, isIssuedCaller, issuedSpawnerStanding, withIssuerSession, renderOnceTask, shownSpawner, } from "@cotal-ai/core";
13
- import { loadLaunchPersonaFile, PersonaSourceError, retainConnectorSeat } from "@cotal-ai/workspace";
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";
11
+ import { retainConnectorSeat } from "@cotal-ai/workspace";
14
12
  import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
15
- import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, remintDaemonCreds, resolveAgentType, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, SEAT_CAP_UNLIMITED, spaceKey, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
13
+ 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";
16
14
  import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
17
15
  import { Retirement } from "./retirement.js";
18
16
  import { ServePlane } from "./serve-plane.js";
19
17
  import { NamesCapacity } from "./names-capacity.js";
20
18
  import { AttachEndpoint } from "./attach-endpoint.js";
21
- 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";
22
20
  import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
23
21
  import { ManagedStaticLifecycle, STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
24
22
  export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
23
+ export { credRenewIntervalMs } from "./credential-renewal.js";
25
24
  import { LeaseKeeper } from "./lease-keeper.js";
26
25
  export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
27
26
  import { SessionRecovery } from "./session-recovery.js";
28
- import { SeatCustody } from "./seat-custody.js";
27
+ import { SeatCustody, watchConnectorHolder } from "./seat-custody.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 { inlinePersonaDir, 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, seatCapRefused, 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. */
@@ -60,9 +60,6 @@ const ONCE_DEFAULT_DEADLINE_MS = 60 * 60_000;
60
60
  /** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
61
61
  * stays and the turn sweep asks again. */
62
62
  const ONCE_RETIRE_MS = 60_000;
63
- /** The goal index's bound on a relay note (core `GOAL_INDEX_NOTE_MAX`). A once task's note must
64
- * fit it, and is refused at admission when it cannot. */
65
- const TURN_NOTE_MAX = 65536;
66
63
  /** Backstop for the detached-launch readiness race (#159 B1). `startAgent` waits on two REAL outcomes —
67
64
  * the assigned id joining the mesh (presence) = started, the child process exiting = failed — NOT a
68
65
  * liveness-inferring timer. This is only the last-resort bound for "neither happened in time": the launch
@@ -102,11 +99,6 @@ const DEPROVISION_TIMEOUT_MS = 15_000;
102
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,
103
100
  * one manager queues at most 8 evictions on the daemon, about 3 s of its work at that load. */
104
101
  const RETIREMENT_CONCURRENCY = 8;
105
- /** The delivery-admin `reloadCreds` request bound — STRICTLY GREATER than the daemon's internal
106
- * per-component preflight bound (4s each, run in parallel) so a slow or refused proof returns the
107
- * daemon's STRUCTURED per-component failure, never a client-side timeout that the catch below would
108
- * misrecord as "no delivery-admin responder" (a false negative while the daemon is mid-proof). */
109
- const DELIVERY_ADMIN_RELOAD_TIMEOUT_MS = 15_000;
110
102
  /** A hard preservation stop should settle quickly. The manager still waits and reports a partial
111
103
  * cut rather than pretending a child is gone. Held in ManagerOptions so fake runtimes can shorten it. */
112
104
  const PRESERVE_STOP_TIMEOUT_MS = 10_000;
@@ -130,31 +122,10 @@ export const PASTE_END = "\x1b[201~";
130
122
  * stream. The message carries that runtime's own guidance, which is operator copy and changes; this
131
123
  * marker is the contract a caller keys on so it can act without reading the wording. */
132
124
  export const RUNTIME_NO_TERMINAL_DETAIL = "ai.cotal.manager.runtime-no-terminal";
133
- /** Pick a `setInterval` period for {@link Manager.renewDaemonCreds} that guarantees at least one
134
- * tick lands inside every renewal owner's `[renewAt, exp)` window.
135
- *
136
- * `inspectCredHealth` marks a credential `near-expiry` at 75% of its iat-to-exp lifetime and
137
- * `expired` at 100%, so the window width is TTL/4. Ticks TTL/4 apart therefore land at least once
138
- * inside every window; ticks TTL/2 apart (the old schedule) can miss it entirely for any TTL. That
139
- * is the cause of Cotal #457, reproduced at both TTL=86400 and TTL=20 (the compressed-ratio probe).
140
- *
141
- * Deriving from the caller's TTL keeps the schedule correct for any credential class: the 24h
142
- * `STANDING_RENEWABLE_TTL_SEC` and the 30-day `ROTATION_RENEWED_TTL_SEC` both get a tick inside
143
- * their own renewal window without a hardcoded number. Post-boot responsiveness is already
144
- * covered by the caller invoking `renewDaemonCreds` once synchronously before starting the timer,
145
- * so no separate floor is needed. The pass is idempotent, since `renewDaemonCreds` no-ops each
146
- * credential when its state is `healthy`, so a tick that lands before the window costs one health
147
- * check per owner. A managed seat's credential is judged as of the next tick instead, because the
148
- * seat re-reads its file only once a minute and nothing pushes the renewal to it: a tick that
149
- * lands in the window's last minute can come too late for the seat to adopt it. */
150
- export function credRenewIntervalMs(ttlSeconds) {
151
- return Math.max(1, Math.floor((ttlSeconds / 4) * 1000));
152
- }
153
125
  /** Startup reconciliation overlaps control-service registration. A spawn or attach for one of
154
126
  * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
155
127
  * a reuse. */
156
128
  const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
157
- const REMOTE_STANDING_BUDGET_MS = 10_000;
158
129
  /** The owner a retained seat resumes under: its inventory identity's, which is the same value the
159
130
  * adopted seat records as `userOwner`, so a resumed seat is counted against the owner that held
160
131
  * it before the restart ({@link Manager.ownerSeats}) and not against the mesh's default one. */
@@ -203,16 +174,6 @@ function failedTerminal(error, source) {
203
174
  catch { /* unreadable or not interchangeable */ }
204
175
  return { error: text };
205
176
  }
206
- /** One absolute budget across authority, preflight and adoption waits, or one closed-serve attempt. */
207
- function remoteStandingTimeLeft(deadline) {
208
- const left = deadline - performance.now();
209
- if (left <= 0)
210
- throw new Error("remote manager standing operation exceeded its 10000ms aggregate budget");
211
- return Math.ceil(left);
212
- }
213
- function sameStrings(a, b) {
214
- return JSON.stringify([...(a ?? [])].sort()) === JSON.stringify([...(b ?? [])].sort());
215
- }
216
177
  /** The start of every agent's bearer command: node, its loader flags and this manager's entry,
217
178
  * resolved through every symlink. The agent runs that command for each renewal for as long as it
218
179
  * lives, and an install can replace the bin link meanwhile: get.cotal.ai writes a shell launcher
@@ -220,37 +181,6 @@ function sameStrings(a, b) {
220
181
  function bearerEntryArgv() {
221
182
  return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
222
183
  }
223
- /** The caller keeps the arrays it passed, so a launch form is admitted with its own copies: a later
224
- * write to the caller's array cannot change what the manager grants, shares or preserves. */
225
- function ownLists(form) {
226
- return {
227
- ...form,
228
- ...(form.subscribe && { subscribe: [...form.subscribe] }),
229
- ...(form.allowSubscribe && { allowSubscribe: [...form.allowSubscribe] }),
230
- ...(form.allowPublish && { allowPublish: [...form.allowPublish] }),
231
- ...(form.capabilities && { capabilities: [...form.capabilities] }),
232
- ...(form.shareTools && { shareTools: [...form.shareTools] }),
233
- };
234
- }
235
- /** The inline record is admitted the same way, one level deeper: the record itself, its lists, and
236
- * each `endpoints` entry with its commands. It is still untrusted here, so a shape the validator
237
- * will refuse is copied as far as it goes and refused where it is read. */
238
- function ownPersona(record) {
239
- if (record === null || typeof record !== "object" || Array.isArray(record))
240
- return record;
241
- const owned = ownLists({ ...record });
242
- const endpoints = owned.endpoints;
243
- if (Array.isArray(endpoints))
244
- owned.endpoints = endpoints.map((e) => {
245
- if (e === null || typeof e !== "object" || Array.isArray(e))
246
- return e;
247
- const entry = { ...e };
248
- if (Array.isArray(entry.commands))
249
- entry.commands = [...entry.commands];
250
- return entry;
251
- });
252
- return owned;
253
- }
254
184
  /** Operator-facing phrasing per cause. Kept beside the union so adding a member without a sentence
255
185
  * is a type error rather than a blank in the log. The stop family's sentences carry the principal
256
186
  * from the cause, so they render through {@link STOP_CAUSE_TEXT} under the same exhaustive-Record
@@ -295,103 +225,10 @@ function onceStopReason(cause) {
295
225
  default: return cause;
296
226
  }
297
227
  }
298
- /** Why a revoked run starts no helper, the same words wherever the marker is read. */
299
- function revokedRunRefusal(runId, revoked) {
300
- return `run ${runId} was revoked by ${revoked.by} (${revoked.reason}); a revoked run starts no helper (SPEC 14.8)`;
301
- }
302
- const INLINE_PERSONA_KEYS = ["prompt", "role", "model", "variant", "description", "subscribe", "allowSubscribe", "allowPublish", "capabilities", "endpoints", "save"];
303
- /** Read an inline persona into the definition a catalog file would load as, refusing what a file
304
- * load refuses plus any shape the closed record does not take. The body is literal text: nothing in
305
- * it becomes a field, so a body that starts with `---` stays body. */
306
- function inlinePersonaDef(name, raw) {
307
- if (raw === null || typeof raw !== "object" || Array.isArray(raw))
308
- throw new Error("persona: expected an object");
309
- const rec = raw;
310
- const extra = Object.keys(rec).filter((k) => !INLINE_PERSONA_KEYS.includes(k));
311
- if (extra.length)
312
- throw new Error(`persona: unknown key ${extra[0]}; it takes ${INLINE_PERSONA_KEYS.join(", ")}`);
313
- const text = (k) => {
314
- const v = rec[k];
315
- if (v === undefined)
316
- return undefined;
317
- if (typeof v !== "string" || !v.trim())
318
- throw new Error(`persona.${k}: expected a non-blank string`);
319
- return v;
320
- };
321
- const list = (k) => {
322
- const v = rec[k];
323
- if (v === undefined)
324
- return undefined;
325
- if (!Array.isArray(v) || v.some((x) => typeof x !== "string"))
326
- throw new Error(`persona.${k}: expected an array of strings`);
327
- return [...v];
328
- };
329
- const prompt = text("prompt");
330
- if (prompt === undefined)
331
- throw new Error("persona.prompt: required; it is the persona body");
332
- if (rec.save !== undefined && typeof rec.save !== "boolean")
333
- throw new Error("persona.save: expected a boolean");
334
- const def = {
335
- name,
336
- persona: prompt.trim(),
337
- role: text("role"),
338
- model: text("model"),
339
- variant: text("variant"),
340
- description: text("description"),
341
- subscribe: list("subscribe"),
342
- allowSubscribe: list("allowSubscribe"),
343
- allowPublish: list("allowPublish"),
344
- capabilities: list("capabilities"),
345
- endpoints: parsePersonaEndpoints(rec.endpoints, "persona"),
346
- };
347
- // The checks a file load makes on these fields: channel names, and the read set within the read ACL.
348
- try {
349
- for (const ch of [...(def.subscribe ?? []), ...(def.allowSubscribe ?? []), ...(def.allowPublish ?? [])])
350
- assertValidChannel(ch);
351
- resolveReadAcl(def.subscribe ?? [], def.allowSubscribe);
352
- }
353
- catch (e) {
354
- throw new Error(`persona: ${rejectionText(e)}`);
355
- }
356
- return { def, save: rec.save === true };
357
- }
358
- /** The refusal a user-auth mesh gives a persona that names `endpoints`. */
359
- function userMeshEndpointsRefusal(door) {
360
- return `${door}: this mesh has per-user auth, where endpoint access comes from the service owner's grants and a persona cannot hand it on (SPEC 13.15). ` +
361
- "Drop `endpoints` from the persona, and ask the operator to grant the helper with `cotal service-endpoint grant` once it runs.";
362
- }
363
- class LegacyEventCountPermissionError extends Error {
364
- }
365
228
  const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
366
229
  function participantKey(owner, actor, uid) {
367
230
  return `${owner}.${actor}.${uid}`;
368
231
  }
369
- /**
370
- * Event channels in `channels` that do NOT belong to `{owner, actor}`.
371
- *
372
- * ONE HELPER FOR EVERY SEAM THAT ARMS AN ACL, and that is the whole design. The rule first existed
373
- * only at the spawn accept seam, and a security review found the hole that shape guarantees: resume
374
- * re-arms a managed row straight from the inventory document, and `renewManagedStaticCred` re-mints
375
- * the JWT from that row, so an admin-supplied inventory could carry a foreign concrete event channel
376
- * past a fence that only ever looked at spawns. A rule with one call site is a rule that covers one
377
- * door.
378
- *
379
- * IT COMPARES PRINCIPALS, NOT STRINGS. `eventChannelPrincipal` decodes the channel back to the
380
- * `{owner, actor}` it names, so this is mode-independent: static keys the actor on the allocated
381
- * nkey and user mode keys it on the alias, and neither needs its own branch here.
382
- *
383
- * STATED LIMIT, unchanged and asserted by a cell: the decode refuses anything that is not exactly
384
- * two principal tokens, so a WILDCARD is not an event channel to it. `events.<owner>.>` and
385
- * `events.>` pass untouched and are governed by ordinary ACL authority. This closes the concrete
386
- * form, which is what a caller writes when it knows which agent it wants to read, and not the
387
- * wildcard form, which is what an operator writes deliberately for an observer.
388
- */
389
- function foreignEventChannels(channels, owner, actor) {
390
- return channels.filter((ch) => {
391
- const p = eventChannelPrincipal(ch);
392
- return p !== null && !(p.owner === owner && p.actor === actor);
393
- });
394
- }
395
232
  /** One connector's declared harness binaries resolved on PATH now. The refusal sentence is built only
396
233
  * here, so the boot row and the check for a connector registered after boot can never word it apart. */
397
234
  function resolveHarness(name, requires) {
@@ -406,18 +243,31 @@ function resolveHarness(name, requires) {
406
243
  }
407
244
  return missing.length ? { binaries, reason: `${name} harness needs ${missing.join(", ")} on PATH - not found` } : { binaries };
408
245
  }
409
- /** True only when the delivery-admin rail has no bound responder. A timeout is a hung rail, not absence. */
410
- function isAbsentDeliveryAdmin(error) {
411
- return error instanceof RequestError && error.isNoResponders();
246
+ /** The refusal a control instance with `execution: none` gives every launch, hosting, model and write door. */
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";
248
+ /** The sha256 hex digest of a file's bytes. */
249
+ function fileDigest(path) {
250
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
251
+ }
252
+ /** The wire PRINCIPAL dot-form a managed agent's presence/control identity carries: user-mode
253
+ * entries already store it in `id`; static mints store the raw nkey there (the durable/teardown
254
+ * key), so the wire form derives under DEV_OWNER. Every comparison against an AUTHENTICATED wire
255
+ * id (presence card.id, control from.id) must go through this, never raw `a.id`. */
256
+ function managedPrincipal(a) {
257
+ return a.userOwner ? a.id : principalKey(DEV_OWNER, a.id).key;
412
258
  }
413
- /** The store challenge went UNANSWERED while a delivery daemon exists: the rail timed out, or it had
414
- * no responder while the lease row names a holder. Both are what a daemon that is starting or
415
- * re-acquiring its lease looks like, so manager boot waits them out (#871); a renewal pass still
416
- * refuses on the first one. A reply that does not decode was answered and is never this. */
417
- class DeliveryAdminUnanswered extends Error {
259
+ /** How a once seat's startup watch ended, waited for until {@link STARTUP_OUTCOME_MS} after its
260
+ * launch or the readiness window, whichever is longer. A watch that has not ended by then, or a
261
+ * seat being stopped, answers what the handle reports at that moment. */
262
+ async function awaitStartupOutcome(a, launchedAt, readinessTimeoutMs, stopping) {
263
+ const until = launchedAt + Math.max(readinessTimeoutMs, STARTUP_OUTCOME_MS);
264
+ for (;;) {
265
+ const outcome = a.handle.startupOutcome?.() ?? "pending";
266
+ if (outcome !== "pending" || a.terminalizing || stopping() || Date.now() >= until)
267
+ return outcome;
268
+ await new Promise((resolve) => setTimeout(resolve, 250));
269
+ }
418
270
  }
419
- /** How long one store challenge waits for the delivery daemon's answer. */
420
- const STORE_CHALLENGE_TIMEOUT_MS = 5_000;
421
271
  /**
422
272
  * The agent supervisor: a long-lived mesh node that owns agent process lifecycle.
423
273
  * It serves control requests on the "manager" service and spawns/kills agents
@@ -579,10 +429,11 @@ export class Manager {
579
429
  onceWatched = new Set();
580
430
  /** Process start, for the served `status` uptime. */
581
431
  startedAtMs = Date.now();
582
- /** Connector harness inventory. Available paths stay pinned; missing binaries are retried when
432
+ /** Connector harness inventory. Available paths stay pinned; unavailable rows are retried when
583
433
  * launch, model lookup or status asks, without stopping unrelated Manager work. */
584
434
  connectorStatuses = [];
585
435
  connectorRequirements = new Map();
436
+ claudeWakeRecheck;
586
437
  /** The boot inventory's warnings, printed once start completes, so a refused start prints none. */
587
438
  bootNotes = [];
588
439
  /** The complete boot task. stop() joins it after fencing static reconciliation, so a registration
@@ -615,6 +466,9 @@ export class Manager {
615
466
  userMode = false;
616
467
  namesCapacity = new NamesCapacity({
617
468
  userMode: () => this.userMode,
469
+ seatCap: () => this.seatCap,
470
+ managerInstanceId: () => this.managerInstanceId,
471
+ agents: () => this.agents.values(),
618
472
  authEnabled: () => this.auth !== undefined,
619
473
  maintenanceActive: () => this.maintenanceState === "active",
620
474
  roster: () => this.ep.getRoster(),
@@ -927,6 +781,158 @@ export class Manager {
927
781
  shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
928
782
  bearerEntryArgv,
929
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
+ });
870
+ /** The launch pipeline's leaf steps. Every dependency reads through at its use. */
871
+ seatLaunch = new SeatLaunch({
872
+ space: () => this.space,
873
+ servers: () => this.servers,
874
+ workspaceRoot: () => this.workspaceRoot,
875
+ installedExtensions: () => this.installedExtensions,
876
+ ep: () => this.ep,
877
+ auth: () => this.auth,
878
+ userMode: () => this.userMode,
879
+ managerInstanceId: () => this.managerInstanceId,
880
+ serviceServe: () => this.serviceServe,
881
+ runHosting: () => this.runHosting,
882
+ connectorStatuses: () => this.connectorStatuses,
883
+ execution: () => this.execution,
884
+ requiredRuntime: () => this.requiredRuntime,
885
+ meshMode: () => this.meshMode,
886
+ executionRefusal: () => this.executionRefusal(),
887
+ nameError: (name) => this.nameError(name),
888
+ canReadPersona: (owner, caller, admin) => this.canReadPersona(owner, caller, admin),
889
+ epAdminReach: (caller) => this.epAdminReach(caller),
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),
935
+ });
930
936
  constructor(opts) {
931
937
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
932
938
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -1027,7 +1033,7 @@ export class Manager {
1027
1033
  return this.executionState.kind;
1028
1034
  }
1029
1035
  executionRefusal() {
1030
- return "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";
1036
+ return EXECUTION_NONE_REFUSAL;
1031
1037
  }
1032
1038
  /** A defensive last barrier, not a substitute Runtime. Entry admission runs before effects. */
1033
1039
  get requiredRuntime() {
@@ -1644,644 +1650,29 @@ export class Manager {
1644
1650
  * Delivery is single-shard today and the endpoint's own responder reads row 0; naming it here
1645
1651
  * keeps the manager's binding check and that reply arguing about the same row. */
1646
1652
  static DELIVERY_SHARD = 0;
1647
- /** Proof that this manager remints into the store the delivery daemon reloads from.
1648
- * Fingerprint-only `reloadCreds` is safe only after this. Two named, different stores
1649
- * refuse the pass. A daemon that is not bound yet is not a named store: start and
1650
- * remint still proceed (tests, delayed delivery), writing this manager's store. The
1651
- * challenge runs again before every remint, so a later daemon on a foreign store is
1652
- * refused then rather than certified by an earlier absence. A request timeout is not
1653
- * absence: a hung rail would skip the proof, so it fails closed.
1654
- *
1655
- * ABSENCE IS READ OFF THE LEASE ROW, never off the rail's no-responder shape alone (#1694).
1656
- * The rail is queue-grouped, so "no responder answered" is itself something the rail reports,
1657
- * and a responder that answers in a shape the client turns into that error makes the pass read
1658
- * "absent" while a holder is live on the row — certifying every later remint with no proof at
1659
- * all. So a no-responder outcome is decided by the row: a row that names a holder makes the
1660
- * pass refuse (undetermined — a live daemon went unanswered, which must not read as "no
1661
- * daemon"), and only a row that is absent or holderless settles "absent", the state start()
1662
- * treats as not-yet-bound. An unreadable row (a failed read, or a key that exists but does not
1663
- * parse) is a genuine unknown and refuses fail-closed, like a hung rail. */
1664
- async daemonStoreRelation(timeoutMs) {
1665
- let reply;
1666
- try {
1667
- reply = await this.ep.requestDeliveryAdmin("reloadStoreIdentity", {}, timeoutMs);
1668
- }
1669
- catch (e) {
1670
- const msg = rejectionText(e);
1671
- if (isAbsentDeliveryAdmin(e))
1672
- return this.absentByLeaseRow(isUnansweredDeliveryAdmin(e));
1673
- const failure = `could not challenge the delivery daemon's SecretStore: ${msg}`;
1674
- throw isUnansweredDeliveryAdmin(e) ? new DeliveryAdminUnanswered(failure) : new Error(failure);
1675
- }
1676
- if (!reply.ok)
1677
- throw new Error(reply.error ?? "delivery daemon refused to name the SecretStore it reloads from");
1678
- let answer;
1679
- try {
1680
- answer = parseDaemonStoreAnswer(reply.data);
1681
- }
1682
- catch (e) {
1683
- throw new Error(`delivery daemon named an unreadable SecretStore: ${rejectionText(e)}. Nothing reminted. ` +
1684
- `Check that delivery and manager use the same Cotal version, then restart delivery through its supervisor. ` +
1685
- `For a saved local delivery service: \`cotal down delivery --space ${this.space}\`, ` +
1686
- `then \`cotal up --space ${this.space}\``);
1687
- }
1688
- // The answerer's own claim first, so an honest non-holder is refused by its own admission and
1689
- // the operator-facing reason names that. This is the CHEAP half of the test and NOT the binding
1690
- // one: a responder that does not hold the lease can assert `true` here just as easily.
1691
- if (!answer.holdsDeliveryLease)
1692
- throw new Error("the delivery-admin rail was answered by a responder that does not hold this space's " +
1693
- "delivery lease, so its SecretStore is not the store the daemon reloads from - nothing reminted");
1694
- // THE BINDING TEST, measured by this manager rather than asserted by the answerer. The lease
1695
- // row's holder is read here under this manager's own credential; the answerer must BE that
1696
- // principal. A reply asserting the claim while some other process holds the shard fails here,
1697
- // which is the case a bare store identity could not see. An unreadable row is an unknown and
1698
- // refuses too: this test may never be satisfied by failing to run.
1699
- const holder = await this.ep.deliveryLeaseHolder(Manager.DELIVERY_SHARD);
1700
- if (holder === undefined)
1701
- throw new Error("this manager could not read the delivery lease row, so it cannot verify that the answering " +
1702
- "responder is the process that reloads the standing credentials - nothing reminted");
1703
- if (holder !== answer.responder)
1704
- throw new Error(`the delivery-admin rail was answered by ${answer.responder}, which is not the holder of ` +
1705
- `this space's delivery lease (${holder}), so its SecretStore is not the store the daemon ` +
1706
- `reloads from - nothing reminted`);
1707
- const daemon = answer.identity;
1708
- // The workspace store records its id the first time it is named, so it is named here, where
1709
- // only an auth manager reaches, rather than in a constructor every open-mode manager runs.
1710
- this.secretStoreIdentity ??= parseSecretStoreIdentity(this.secrets.identity);
1711
- if (!sameSecretStoreIdentity(this.secretStoreIdentity, daemon)) {
1712
- console.error(`! ${divergentSecretStoreNotice(this.secretStoreIdentity, daemon)}`);
1713
- return "divergent";
1714
- }
1715
- return "shared";
1716
- }
1717
- /** Settle a no-responder challenge outcome from the lease row, never from the rail's own
1718
- * reporting shape (#1694). The three cases:
1719
- *
1720
- * 1. The row READS but names a holder: a live daemon holds the shard and the rail went
1721
- * unanswered. That is undetermined, not "no daemon" — treating it as absent would let this
1722
- * manager remint with no proof while a reloading daemon runs, which is exactly what the
1723
- * challenge exists to prevent. Refuse.
1724
- * 2. The row is unreadable — a read that fails (a denied or erroring bucket) OR a key that
1725
- * exists but does not parse as a lease record (`readDeliveryLeaseEntry` throws for both):
1726
- * undetermined, and it refuses the same fail-closed way a hung rail does. Never a silent
1727
- * "absent" over a row the manager could not read.
1728
- * 3. The row is absent or holderless (no key, a DEL/PURGE tombstone, or a row that names no
1729
- * holder): today's "absent", the state start() treats as a daemon that is not bound yet.
1730
- *
1731
- * `deliveryLeaseHolder` swallows its read failures into `undefined`, which would fold case 2
1732
- * into case 3 — so this reads the entry directly and lets the read's own failure refuse. */
1733
- async absentByLeaseRow(unanswered) {
1734
- let entry;
1735
- try {
1736
- entry = await this.ep.readDeliveryLeaseEntry(Manager.DELIVERY_SHARD);
1737
- }
1738
- catch (e) {
1739
- throw new Error(`could not read the delivery lease row to settle whether the delivery daemon is absent ` +
1740
- `(${rejectionText(e)}) - absence is undetermined, nothing reminted`);
1741
- }
1742
- const holder = entry?.info.holder;
1743
- if (holder !== undefined && holder !== "") {
1744
- const refusal = `the delivery-admin rail reported no responder while the delivery lease names a holder ` +
1745
- `(${holder}) - absence cannot be read off the rail alone, and nothing reminted`;
1746
- throw unanswered ? new DeliveryAdminUnanswered(refusal) : new Error(refusal);
1747
- }
1748
- return "absent";
1749
- }
1750
- /** Keep this manager's renewal lease alive between credential passes (#1634). The manager bucket
1751
- * expires keys at MANAGER_LEASE_TTL_MS, far below the credential pass's cadence, so the lease
1752
- * needs its own heartbeat like the per-instance liveness lease. A non-owner calls this too: the
1753
- * CAS is how a survivor picks up a dead owner's expired lease with no operator step. Never
1754
- * throws; a failed heartbeat leaves ownership to the next pass rather than ending the process. */
1755
- async keepDaemonRenewalLease() {
1756
- if (!this.auth || !this.daemonRenewalEligible)
1757
- return;
1758
- try {
1759
- const held = await this.ep.holdDaemonRenewalLease(this.managerInstanceId);
1760
- if (this.daemonRenewalOwner && !held)
1761
- console.error(`! daemon credential renewal for space "${this.space}" passed to another manager (this one lost the renewal lease) - it keeps serving its seats`);
1762
- this.daemonRenewalOwner = held;
1763
- }
1764
- catch (e) {
1765
- console.error(`! could not refresh the daemon renewal lease: ${rejectionText(e)} - ownership is re-decided on the next pass`);
1766
- }
1767
- }
1768
- /** Decide whether THIS manager owns the daemon's credential renewal (#1634). Both conditions are
1769
- * required, because each answers a question the other cannot:
1770
- *
1771
- * 1. The daemon must reload from this manager's store (#1447). Reminting into a store the daemon
1772
- * never reads writes bytes nobody adopts, and fingerprint-only `reloadCreds` would then name a
1773
- * generation the daemon cannot see.
1774
- * 2. This manager must hold the per-space renewal lease. Store identity CANNOT pick one owner on
1775
- * its own: `sameSecretStoreIdentity` is pure equality with no holder and no tiebreak, so every
1776
- * manager sharing one store passes it, and two owners reminting on independent timers have no
1777
- * ordering between them - one's write lands between the other's re-sign and its adoption
1778
- * request, which is the #773 refusal the challenge exists to prevent.
1779
- *
1780
- * A manager failing either test serves the space normally and skips only the daemon remint. */
1781
- async claimDaemonRenewalOwnership(waitMs = 0) {
1782
- // EVERY refusal outcome drops a held lease, not only "divergent". The refusal paths THROW
1783
- // (#1694: a non-holder answer, an unbindable answerer, an unreadable or holder-naming row on a
1784
- // no-responder rail), and a thrown refusal caught by renewDaemonCreds would otherwise leave a
1785
- // manager that once owned the renewal still holding the lease behind its own heartbeat — the
1786
- // pass refuses, the log says so, and the space keeps a renewal owner that must not remint.
1787
- // Deciding here, inside the claim, is what keeps the release on the refusal path itself.
1788
- let relation;
1789
- try {
1790
- // Only the read-only challenge is retried, so a wait that ends mid-attempt abandons a read,
1791
- // never the lease work below.
1792
- 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);
1793
- }
1794
- catch (e) {
1795
- this.daemonRenewalEligible = false;
1796
- if (this.daemonRenewalOwner)
1797
- await this.ep.releaseDaemonRenewalLease().catch(() => { });
1798
- this.daemonRenewalOwner = false;
1799
- throw e;
1800
- }
1801
- this.daemonRenewalEligible = relation !== "divergent";
1802
- if (relation === "divergent") {
1803
- // Not our daemon's store: drop any lease we hold rather than sit on it, so the manager that
1804
- // CAN remint is not blocked behind us.
1805
- if (this.daemonRenewalOwner)
1806
- await this.ep.releaseDaemonRenewalLease();
1807
- this.daemonRenewalOwner = false;
1808
- return;
1809
- }
1810
- await this.keepDaemonRenewalLease();
1811
- }
1812
- /** #2073: arm the `endpoint-serve` credential's own renewal from its `[renewAt, exp)` window
1813
- * instead of `credRenewTimer`'s boot-phased TTL/4 tick, which can miss that window depending on
1814
- * when the timer happened to start relative to the credential's `iat`. Called after the initial
1815
- * mint (`registerManagerService`) and after every successful re-mint in the serve branch below,
1816
- * so the schedule always tracks the CURRENT credential. `credsRenewalDelayMs` is the same 75%
1817
- * convention the endpoint's delivery renewal and the membership feed use (`@cotal-ai/core`); no
1818
- * second copy of that arithmetic lives here. */
1819
- scheduleServeRenewal(creds) {
1820
- if (this.endpointServeRenewalTimer)
1821
- clearTimeout(this.endpointServeRenewalTimer);
1822
- const delay = Math.max(1_000, credsRenewalDelayMs(creds));
1823
- const renewAt = new Date(Date.now() + delay).toISOString();
1824
- this.endpointServeRenewalTimer = setTimeout(() => { void this.renewDaemonCreds(); }, delay);
1825
- this.endpointServeRenewalTimer.unref?.();
1826
- console.error(`manager endpoint-serve renewal scheduled at ${renewAt}`);
1827
- }
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); }
1828
1661
  credentialPushRetry;
1829
1662
  credentialPushes = new Map();
1830
1663
  supervisorCredentialPush;
1831
1664
  pendingCredentialPushes = new Set();
1832
1665
  supervisorCredentialPushPending = false;
1833
- scheduleCredentialPushRetry() {
1834
- if (this.credentialPushRetry || this.leaseStopping)
1835
- return;
1836
- this.credentialPushRetry = setTimeout(() => {
1837
- this.credentialPushRetry = undefined;
1838
- if (this.leaseStopping)
1839
- return;
1840
- void Promise.all([
1841
- ...[...this.pendingCredentialPushes].map((nc) => this.pushRenewedCreds(nc)),
1842
- ...(this.supervisorCredentialPushPending ? [this.pushSupervisorCreds()] : []),
1843
- ]);
1844
- }, 1_000);
1845
- this.credentialPushRetry.unref();
1846
- }
1847
- /** Retain a busy transport and retry its adopted credential without replaying requests. */
1848
- pushRenewedCreds(nc) {
1849
- const active = this.credentialPushes.get(nc);
1850
- if (active)
1851
- return active;
1852
- const push = this.pushRenewedCredsOnce(nc).finally(() => { this.credentialPushes.delete(nc); });
1853
- this.credentialPushes.set(nc, push);
1854
- return push;
1855
- }
1856
- async pushRenewedCredsOnce(nc) {
1857
- this.pendingCredentialPushes.add(nc);
1858
- try {
1859
- await requestSafeReconnect(nc);
1860
- this.pendingCredentialPushes.delete(nc);
1861
- }
1862
- catch (e) {
1863
- if (nc.isClosed())
1864
- this.pendingCredentialPushes.delete(nc);
1865
- console.error(`! manager credential push deferred: ${rejectionText(e)}`);
1866
- if (!nc.isClosed())
1867
- this.scheduleCredentialPushRetry();
1868
- }
1869
- }
1870
- pushSupervisorCreds() {
1871
- if (this.supervisorCredentialPush)
1872
- return this.supervisorCredentialPush;
1873
- const push = this.pushSupervisorCredsOnce().finally(() => { this.supervisorCredentialPush = undefined; });
1874
- this.supervisorCredentialPush = push;
1875
- return push;
1876
- }
1877
- async pushSupervisorCredsOnce() {
1878
- this.supervisorCredentialPushPending = true;
1879
- try {
1880
- await this.ep.refreshCredsRequestSafe();
1881
- this.supervisorCredentialPushPending = false;
1882
- }
1883
- catch (e) {
1884
- console.error(`! remote manager supervisor credential push deferred: ${rejectionText(e)}`);
1885
- this.scheduleCredentialPushRetry();
1886
- }
1887
- }
1888
- /** #2073: the shared bounded-retry shape for a closed standing connection: wait out each of
1889
- * {@link STATIC_RECONCILE_RETRY_DELAYS_MS}, trying `attempt` after each. Waiting does not repair
1890
- * two closes, so they skip the first delay. One that closes while an all-duty renewal is in flight,
1891
- * as one the broker expires just before adoption, tries when that renewal adopts. One whose
1892
- * credential has `expired` tries at once, because its attempt renews the credential. A stop landing
1893
- * while this loop waits is not a fault this loop reports (the caller re-checks `leaseStopping`). */
1894
- async boundedReconnect(label, attempt, expired = false) {
1895
- let first = this.remoteBundleAdoption ?? (expired ? Promise.resolve() : undefined);
1896
- for (const delayMs of STATIC_RECONCILE_RETRY_DELAYS_MS) {
1897
- await (first ?? new Promise((r) => setTimeout(r, delayMs)));
1898
- first = undefined;
1899
- if (this.leaseStopping)
1900
- return true;
1901
- try {
1902
- if (await attempt())
1903
- return true;
1904
- }
1905
- catch (e) {
1906
- console.error(`! manager ${label} re-dial attempt failed: ${rejectionText(e)}`);
1907
- }
1908
- }
1909
- return false;
1910
- }
1911
- /** One class-2 renewal pass: re-sign `.cotal/delivery.creds` + `.cotal/membership-rw.creds`
1912
- * for their existing nkeys, then request the delivery daemon's EXPLICIT `reloadCreds` adoption on the
1913
- * delivery-admin rail and persist the audit record (`.cotal/renewal.<spaceKey>.json`) that `cotal doctor auth`
1914
- * renders — so "file re-signed" and "daemon adopted" are distinguishable states. A missing daemon
1915
- * (no responder) is recorded honestly: each daemon's own 75% renewal timer remains the adoption backstop.
1916
- * Never throws — renewal failure must be LOUD (log + record), not fatal to the supervisor. */
1917
- async renewDaemonCreds() {
1918
- const release = this.beginLifecycle();
1919
- if (!release)
1920
- return;
1921
- try {
1922
- // #1634: re-decide every pass, so a daemon that moved onto this manager's store becomes
1923
- // ownable, one that moved off retires this manager's ownership, and a crashed owner's expired
1924
- // lease is taken over by a survivor.
1925
- await this.claimDaemonRenewalOwnership();
1926
- // Re-sign through the manager's ONE store — the SAME store the delivery daemon reads
1927
- // (`runDelivery(args, store)`), so a hosted remint writes the store the daemon renews from,
1928
- // never a divergent one. Locally this is the workstation FS store (`.cotal/*.creds`).
1929
- // `this.space` gates cross-space signer swaps; the `preflight` proves broker acceptance before
1930
- // overwriting from ANY signer form (full or stripped). A same-label alternate full bundle is
1931
- // self-bound, not broker-bound, so the manager-hosted path proves every re-sign before it could
1932
- // clobber the last-good with a broker-dead cred; a wrong-account signer's cred is refused here.
1933
- const results = this.daemonRenewalOwner
1934
- ? await remintDaemonCreds(this.workspaceRoot, this.space, this.secrets, {
1935
- preflight: (creds) => this.probeStaticCredential(creds).then((r) => r.ok),
1936
- })
1937
- : [];
1938
- const resigned = results.filter((r) => r.ok);
1939
- let adoption;
1940
- if (resigned.length) {
1941
- // Hand the daemon the EXPECTED generation per component (SHA-256 of the JWT we just
1942
- // re-signed) so its reply proves it adopted THIS generation, not merely re-read some file.
1943
- const expected = {};
1944
- for (const r of resigned) {
1945
- if (r.file === DELIVERY_CREDS_KIND && r.fingerprint)
1946
- expected.delivery = r.fingerprint;
1947
- else if (r.file === MEMBERSHIP_RW_CREDS_KIND && r.fingerprint)
1948
- expected.membership = r.fingerprint;
1949
- }
1950
- try {
1951
- const reply = await this.ep.requestDeliveryAdmin("reloadCreds", { expected }, DELIVERY_ADMIN_RELOAD_TIMEOUT_MS);
1952
- // Keep the per-component aggregate on BOTH outcomes: on a top-level failure `reply.data`
1953
- // still carries which component adopted and which was refused, which `doctor auth` renders.
1954
- adoption = reply.ok
1955
- ? { ok: true, detail: reply.data }
1956
- : { ok: false, error: reply.error, detail: reply.data };
1957
- }
1958
- catch (e) {
1959
- adoption = { ok: false, error: `no delivery-admin responder (${rejectionText(e)}) - the daemon's 75% re-read backstop adopts the re-signed file` };
1960
- }
1961
- }
1962
- for (const r of results.filter((x) => !x.ok && !x.skipped))
1963
- 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`);
1964
- if (adoption && !adoption.ok)
1965
- console.error(`! credential renewal: daemon adoption failed: ${adoption.error}`);
1966
- // `writeRenewalRecord` redacts the ephemeral fingerprint at the persistence boundary (covering
1967
- // the `doctor auth --fix` writer too), so the results pass straight through.
1968
- // A non-owner (#1634) re-signed nothing, so it writes no record: an empty one renders in
1969
- // `doctor auth` as a pass that never ran.
1970
- if (this.daemonRenewalOwner)
1971
- writeRenewalRecord(this.workspaceRoot, this.space, { ts: new Date().toISOString(), owner: "manager", results, adoption });
1972
- this.warnOnSystemCredExpiry();
1973
- // The MANAGER is the renewal owner for its managed-static agent creds —
1974
- // supervisor-side PUSH remint for recorded LIVE slots (the child JWT is never proof of
1975
- // incarnation; a copied credential cannot drive this and is stranded at its own row's TTL).
1976
- // Same class-2 mechanics as the daemon creds: re-sign the file for the SAME nkey; the
1977
- // agent endpoint's 75% source re-read adopts it.
1978
- //
1979
- // Each credential is judged as of the NEXT pass, so one whose renewal point falls before it
1980
- // is re-signed now, ahead of the endpoint's re-read. Judged as of now, a credential whose
1981
- // renewal point lands just after a pass waited a whole interval: the endpoint warned every
1982
- // minute that the file still held the old generation, and when the next pass came in the
1983
- // credential's last minute, the endpoint's one-minute retry could miss it and the connection
1984
- // expired.
1985
- const nextPassSec = Math.floor(Date.now() / 1000) + Math.ceil(credRenewIntervalMs(STANDING_RENEWABLE_TTL_SEC) / 1000);
1986
- if (!this.userMode) {
1987
- for (const a of [...this.agents.values()]) {
1988
- // The `terminalizing` test here is an OPTIMISATION, NOT THE GUARD. There are awaits below
1989
- // it, so an agent can latch mid-iteration and this filter will have already let it
1990
- // through — what actually refuses is the same test at the top of
1991
- // {@link renewManagedStaticCred}, which every renewal on this path goes through.
1992
- // COUPLING: deleting or weakening that check silently promotes this line from an
1993
- // optimisation into the whole guard, and nothing fails at the moment of the change.
1994
- if (a.userOwner || a.terminalizing || !a.seed || !a.secretPaths?.creds)
1995
- continue;
1996
- try {
1997
- const stored = await this.secrets.get(agentSecretKeyForFile(a.secretPaths.creds, this.space));
1998
- if (stored === undefined)
1999
- continue; // no materialized cred (never minted here) - nothing to renew
2000
- const health = inspectCredHealth(stored, nextPassSec);
2001
- if (health.state === "healthy")
2002
- continue;
2003
- if (health.state === "unbounded" || health.state === "unreadable") {
2004
- 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)`);
2005
- continue;
2006
- }
2007
- await this.renewManagedStaticCred(a);
2008
- }
2009
- catch (e) {
2010
- console.error(`! managed cred renewal ${a.name}: ${rejectionText(e)} - the agent dies loud at this cred's expiry unless it is reminted`);
2011
- }
2012
- }
2013
- }
2014
- // The manager is the `endpoint-serve` renewal owner for its own
2015
- // service credential: re-mint the same serve identity with a fresh bounded exp through the
2016
- // §13.1 mint fence over a scoped one-shot executor (staging a new ledger row in a later
2017
- // second or idempotently re-staging the active row within the same second, and releasing only
2018
- // on winning the gate CAS; never the standing connection). The serve connection's
2019
- // authenticator presents the refreshed credential on its next (re)connect.
2020
- if (this.serviceServe?.creds && this.auth) {
2021
- const s = this.serviceServe;
2022
- const authRef = this.auth;
2023
- try {
2024
- const health = inspectCredHealth(this.serviceServe.creds);
2025
- if (health.state !== "healthy") {
2026
- s.creds = await this.withEndpointServeExecutor(({ authKv }) => mintCreds(authRef, s.identity, "endpoint-serve", {
2027
- serveIssuance: serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId }),
2028
- endpointServe: s.grant,
2029
- }));
2030
- // #2073: a superseded instance's re-mint fails the gate CAS above and lands in the
2031
- // catch below, not here — this re-mint already re-checks the issuance gate through
2032
- // the SAME executor a fresh registration would use, so there is no second epoch read
2033
- // to add before re-binding after a re-dial.
2034
- await this.pushRenewedCreds(s.nc);
2035
- this.scheduleServeRenewal(s.creds);
2036
- }
2037
- }
2038
- catch (e) {
2039
- console.error(`! endpoint-serve renewal: ${rejectionText(e)} - the manager's service endpoint dies loud at this cred's expiry unless it is re-registered`);
2040
- }
2041
- }
2042
- // The manager is also the goal-writer's renewal owner — re-mint the SAME
2043
- // goal-writer nkey with a fresh bounded exp AND re-stage its new credId into the §13.1 family,
2044
- // through the scoped executor (never the standing seed). Without this the standing goal-writer
2045
- // connection dies at its TTL and spawn-as-action stops accepting until a restart. The
2046
- // connection's authenticator presents the refreshed credential on its next (re)connect.
2047
- if (this.goalWriter && this.goalWriterCreds && this.auth) {
2048
- const gw = this.goalWriter;
2049
- try {
2050
- if (inspectCredHealth(this.goalWriterCreds).state !== "healthy") {
2051
- const fresh = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageGoalWriter(authKv));
2052
- this.goalWriterCreds = fresh;
2053
- gw.creds = fresh;
2054
- await this.pushRenewedCreds(gw.nc);
2055
- }
2056
- }
2057
- catch (e) {
2058
- console.error(`! goal-writer renewal: ${rejectionText(e)} - spawn-as-action stops accepting at this cred's expiry unless the manager restarts`);
2059
- }
2060
- }
2061
- // The manager is also the session-ledger's renewal owner — re-mint the SAME nkey
2062
- // with a fresh bounded exp AND re-stage its new credId into the §13.1 family, through the
2063
- // scoped executor. Without this the standing session-ledger connection dies at its TTL and
2064
- // `attach` stops establishing sessions until a restart. The connection's authenticator presents
2065
- // the refreshed credential on its next (re)connect.
2066
- // SPEC 14.6: every hosted drive's per-run `run-driver` credential is the manager's to renew
2067
- // for the same nkey; a run parked in a pause for days must not die at the credential's TTL.
2068
- await this.runHosting?.renew();
2069
- if (this.sessionLedgerConn && this.sessionLedgerCreds && this.auth) {
2070
- const sw = this.sessionLedgerConn;
2071
- try {
2072
- if (inspectCredHealth(this.sessionLedgerCreds).state !== "healthy") {
2073
- const fresh = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageSessionLedger(authKv));
2074
- this.sessionLedgerCreds = fresh;
2075
- sw.creds = fresh;
2076
- await this.pushRenewedCreds(sw.nc);
2077
- }
2078
- }
2079
- catch (e) {
2080
- console.error(`! session-ledger renewal: ${rejectionText(e)} - attach stops establishing sessions at this cred's expiry unless the manager restarts`);
2081
- }
2082
- }
2083
- }
2084
- catch (e) {
2085
- console.error(`! credential renewal pass failed: ${rejectionText(e)}`);
2086
- }
2087
- finally {
2088
- release();
2089
- }
2090
- }
2091
- /** Renew the remote registration executor through the typed host protocol. A healthy credential
2092
- * is retained; near-expiry and expired credentials are replaced for the same nkey. */
2093
- async renewRemoteExecutor(force = false) {
2094
- if (!this.remoteAuthority)
2095
- return;
2096
- const current = this.remoteExecutorCreds;
2097
- if (!force && current && inspectCredHealth(current).state === "healthy")
2098
- return;
2099
- try {
2100
- this.remoteExecutorCreds = await this.remoteAuthority.renewExecutor();
2101
- }
2102
- catch (e) {
2103
- console.error(`! remote manager executor renewal: ${rejectionText(e)} - registration maintenance and clean deregistration remain unavailable until renewal succeeds`);
2104
- if (force)
2105
- throw e;
2106
- }
2107
- }
2108
- /** An active signerless manager renews its standing duties together. The issuer stages the closed
2109
- * credential family first; broker preflight proves every JWT and existing caller-held nkey
2110
- * before any mutable holder changes. A failed candidate leaves all current creds intact. */
2111
- async renewRemoteStandingBundle(force = false) {
2112
- if (this.remoteBundleRenewal)
2113
- return this.remoteBundleRenewal;
2114
- if (this.leaseStopping)
2115
- return;
2116
- this.remoteBundleAdoption = new Promise((resolve) => { this.finishRemoteBundleAdoption = resolve; });
2117
- const renewal = this.renewRemoteStandingBundleOnce(force, performance.now() + REMOTE_STANDING_BUDGET_MS);
2118
- this.remoteBundleRenewal = renewal;
2119
- try {
2120
- await renewal;
2121
- }
2122
- finally {
2123
- this.finishRemoteBundleAdoption?.();
2124
- if (this.remoteBundleRenewal === renewal) {
2125
- this.remoteBundleRenewal = undefined;
2126
- this.remoteBundleAdoption = undefined;
2127
- this.finishRemoteBundleAdoption = undefined;
2128
- }
2129
- }
2130
- }
2131
- /** A signerless manager's closed standing connection re-dials through the all-duty family only.
2132
- * A healthy holder re-dials as is. An unhealthy one waits for the closed renewal and adoption,
2133
- * and a refusal fails this attempt with last-good and debt kept. Nothing is minted locally. */
2134
- async renewRemoteBeforeRedial(label, read) {
2135
- if (inspectCredHealth(read() ?? "").state === "healthy")
2136
- return;
2137
- await this.renewRemoteStandingBundle(true);
2138
- if (inspectCredHealth(read() ?? "").state !== "healthy")
2139
- throw new Error(`the ${label} credential is not healthy after all-duty renewal; last-good is kept and nothing is minted locally`);
2140
- }
2141
- async renewRemoteStandingBundleOnce(force, deadline) {
2142
- const remote = this.remoteAuthority;
2143
- if (!remote?.renewStandingBundle || !this.serviceServe)
2144
- return;
2145
- const current = [this.remoteSupervisorCreds, this.remoteExecutorCreds, this.serviceServe.creds,
2146
- this.goalWriterCreds, this.sessionLedgerCreds];
2147
- if (!force && current.every((cred) => cred && inspectCredHealth(cred).state === "healthy")) {
2148
- await Promise.all([
2149
- ...[...this.pendingCredentialPushes].map((nc) => this.pushRenewedCreds(nc)),
2150
- ...(this.supervisorCredentialPushPending ? [this.pushSupervisorCreds()] : []),
2151
- ]);
2152
- return;
2153
- }
2154
- const processEpoch = this.serviceServe.grant.epoch;
2155
- let candidate;
2156
- const serving = this.serviceServe;
2157
- const previous = { nc: serving.nc, handle: serving.handle };
2158
- let replacement;
2159
- let adopted = false;
2160
- try {
2161
- // Only this continuation can adopt. A host operation may still issue after this wait times
2162
- // out, but its late result cannot re-enter preflight or change any Manager holder.
2163
- candidate = await withTimeout(remote.renewStandingBundle(processEpoch), remoteStandingTimeLeft(deadline), "remote manager standing authority exceeded its 10000ms aggregate budget; issuance outcome is unknown");
2164
- if (Object.keys(candidate).sort().join(",") !== [...REMOTE_MANAGER_IDENTITY_NAMES].sort().join(","))
2165
- throw new Error("host returned an incomplete or widened standing credential family");
2166
- for (const name of REMOTE_MANAGER_IDENTITY_NAMES) {
2167
- if (typeof candidate[name] !== "string" || inspectCredHealth(candidate[name]).state === "unreadable")
2168
- throw new Error(`host returned an unreadable ${name} credential`);
2169
- if (!remote.accountPublicKey || accountFromCreds(candidate[name]) !== remote.accountPublicKey)
2170
- throw new Error(`host returned a ${name} credential for another account`);
2171
- if (credsClaims(candidate[name]).sub !== remote.identities[name].id)
2172
- throw new Error(`host returned a ${name} credential for a different nkey than the held identity`);
2173
- const staged = candidate[name];
2174
- const nc = await this.dialRemoteStanding({ authenticator: (nonce) => credsAuthenticator(new TextEncoder().encode(staged))(nonce), maxReconnectAttempts: 0 }, deadline);
2175
- await nc.close();
2176
- }
2177
- remoteStandingTimeLeft(deadline);
2178
- if (this.leaseStopping || this.serviceServe !== serving || serving.nc !== previous.nc || serving.grant.epoch !== processEpoch)
2179
- throw new Error("manager changed its active serve epoch or connection while standing renewal was in flight");
2180
- const stagedServeCreds = candidate.serve;
2181
- replacement = await this.dialServeConnection({ ...serving, creds: stagedServeCreds }, () => adopted ? serving.creds : stagedServeCreds, deadline);
2182
- remoteStandingTimeLeft(deadline);
2183
- if (this.leaseStopping || this.serviceServe !== serving || serving.nc !== previous.nc || serving.grant.epoch !== processEpoch)
2184
- throw new Error("manager changed its active serve epoch or connection while standing renewal was in flight");
2185
- if (REMOTE_MANAGER_IDENTITY_NAMES.some((name) => inspectCredHealth(candidate[name]).state !== "healthy"))
2186
- throw new Error("standing candidate is no longer healthy after broker preflight");
2187
- serving.nc = replacement.nc;
2188
- serving.handle = replacement.handle;
2189
- replacement = undefined;
2190
- this.remoteSupervisorCreds = candidate.supervisor;
2191
- this.remoteExecutorCreds = candidate.executor;
2192
- this.serviceServe.creds = candidate.serve;
2193
- adopted = true;
2194
- this.goalWriterCreds = candidate.goalWriter;
2195
- this.sessionLedgerCreds = candidate.sessionLedger;
2196
- if (this.goalWriter)
2197
- this.goalWriter.creds = candidate.goalWriter;
2198
- if (this.sessionLedgerConn)
2199
- this.sessionLedgerConn.creds = candidate.sessionLedger;
2200
- // Adoption is committed above; a connection that cannot come back yet is a push failure the
2201
- // endpoint's own reconnect loop retries with the adopted credential, not unadopted debt.
2202
- this.remoteRenewalDebt = undefined;
2203
- // Maintenance needed by admitted handlers must not wait for those same handlers to drain.
2204
- this.finishRemoteBundleAdoption?.();
2205
- await withTimeout(Promise.all([
2206
- this.pushSupervisorCreds(),
2207
- (async () => {
2208
- try {
2209
- // A handler or a lost broker PONG can keep stop/flush pending forever. Only the
2210
- // retired transport is expendable: never retry its requests or close the replacement.
2211
- await withTimeout((async () => {
2212
- await previous.handle.stop();
2213
- await previous.nc.flush();
2214
- })(), 5_000, "old serve drain unfinished after 5000ms; closing retired transport, in-flight request outcomes are unknown and must not be retried");
2215
- }
2216
- finally {
2217
- await previous.nc.close();
2218
- }
2219
- })().catch((e) => console.error(`! remote manager retired serve drainage after renewal: ${rejectionText(e)}`)),
2220
- ...(this.goalWriter ? [this.pushRenewedCreds(this.goalWriter.nc)] : []),
2221
- ...(this.sessionLedgerConn ? [this.pushRenewedCreds(this.sessionLedgerConn.nc)] : []),
2222
- ]), remoteStandingTimeLeft(deadline), "remote manager standing reconnect exceeded its 10000ms aggregate budget; adopted transports keep their native reconnect ownership");
2223
- }
2224
- catch (e) {
2225
- if (replacement) {
2226
- await this.discardServeCandidate(replacement.nc, replacement.handle);
2227
- }
2228
- if (adopted) {
2229
- console.error(`! remote manager adopted standing family: ${rejectionText(e)}`);
2230
- return;
2231
- }
2232
- const unadoptedSubjects = candidate && typeof candidate === "object"
2233
- ? Object.values(candidate).flatMap((cred) => { try {
2234
- return typeof cred === "string" && credsClaims(cred).sub ? [credsClaims(cred).sub] : [];
2235
- }
2236
- catch {
2237
- return [];
2238
- } })
2239
- : REMOTE_MANAGER_IDENTITY_NAMES.map((name) => remote.identities[name].id);
2240
- this.remoteRenewalDebt = { at: Date.now(), processEpoch, reason: rejectionText(e), unadoptedSubjects };
2241
- console.error(`! remote manager all-duty renewal: ${this.remoteRenewalDebt.reason} - no unsigned or local replacement is available`);
2242
- if (force)
2243
- throw e;
2244
- }
2245
- }
2246
- /** Warn, on every renewal pass, when a $SYS credential is at or past its renewal point.
2247
- *
2248
- * The manager is the renewal owner for every credential it CAN re-sign, and these two are the ones
2249
- * it cannot: they are `rotation-renewed`, so no resident process re-mints them and they simply die
2250
- * on their 30-day horizon. Before this, a mesh that never ran `doctor auth` got no signal at all,
2251
- * it discovered the expiry as an "Authorization Violation" in the delivery log and a refused
2252
- * membership adoption, weeks after the warning would have been actionable (#338). The pass runs
2253
- * every half-TTL of the 24h class, so this repeats about twice a day for the ~7 days between the
2254
- * renewal point and expiry: loud enough to be seen, bounded enough not to be noise.
2255
- *
2256
- * Diagnostic only, and deliberately non-fatal: renewal is an operator action (`cotal down` then
2257
- * `cotal up --rotate-sys`, which needs a broker restart), so the manager must report it, never
2258
- * attempt it. An absent file is the unprovisioned space, reported by the daemon that needs it. */
2259
- warnOnSystemCredExpiry() {
2260
- for (const file of SYSTEM_CREDS_FILES) {
2261
- let health;
2262
- try {
2263
- // The pair is PER-SPACE, so the location comes from the resolver and never from a
2264
- // path built here (§2 rule 1). Building `.cotal/<kind>` instead would not warn on a wrong
2265
- // file — it would silently warn on NOTHING, for every provisioned root, forever, which is
2266
- // exactly the signal #338 added this for. The resolver may also refuse (§2 rules 3, 4); that
2267
- // refusal is caught with the unreadable case for the reason on the tin — the daemon that
2268
- // NEEDS the pair resolves it through the same function and reports it loudly there, so a
2269
- // diagnostic pass has nothing to add by crashing renewal.
2270
- const path = join(this.workspaceRoot, ".cotal", spaceMaterialKey(file, this.space, { injected: false, root: this.workspaceRoot }));
2271
- if (!existsSync(path))
2272
- continue;
2273
- health = inspectCredHealth(readFileSync(path, "utf8"));
2274
- }
2275
- catch {
2276
- continue; // an unreadable $SYS file is the daemon's loud failure, not a renewal-pass crash
2277
- }
2278
- const when = health.exp ? new Date(health.exp * 1000).toISOString() : "an unknown date";
2279
- if (health.state === "expired")
2280
- 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)`);
2281
- else if (health.state === "near-expiry")
2282
- 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)`);
2283
- }
2284
- }
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); }
2285
1676
  /** Admit one lifecycle/control operation while active. The synchronous increment is the fence:
2286
1677
  * preserveState and stop close it before their first await, so work is either counted or rejected. */
2287
1678
  beginLifecycle(resumeOperation = false) {
@@ -2591,9 +1982,7 @@ export class Manager {
2591
1982
  }
2592
1983
  return undefined;
2593
1984
  }
2594
- fileDigest(path) {
2595
- return createHash("sha256").update(readFileSync(path)).digest("hex");
2596
- }
1985
+ fileDigest(path) { return fileDigest(path); }
2597
1986
  fileDigestOrEmpty(path) {
2598
1987
  try {
2599
1988
  return this.fileDigest(path);
@@ -3333,7 +2722,7 @@ export class Manager {
3333
2722
  * readiness reads the same status; the maintenance fence refuses every other command in both
3334
2723
  * states. The read is counted in `lifecycleInFlight` like any admitted operation and released in
3335
2724
  * `finally`, so a drain waits at most for one status snapshot; the membership gate still
3336
- * applies. `preserving` and a stopping manager stay fenced. Status writes nothing. */
2725
+ * applies. `preserving` and a stopping manager stay fenced. */
3337
2726
  async serveObservation(ctx, fn) {
3338
2727
  const preserved = this.maintenanceState === "preserved" && !this.resumeRequired;
3339
2728
  const resumePending = this.maintenanceState === "active" && this.resumeRequired;
@@ -3604,7 +2993,12 @@ export class Manager {
3604
2993
  vitals: (ctx) => this.serveGated(ctx, () => measureManagerVitals()),
3605
2994
  // A remote Manager files every seat under its own owner, so only a user mesh's shared local
3606
2995
  // Manager narrows the count, and status never waits on a remote admin check.
3607
- status: (ctx) => this.serveObservation(ctx, async () => this.managerStatusData(this.remoteAuthority ? undefined : await this.psOwnerFilter(ctx.subject.caller, false))),
2996
+ status: (ctx) => this.serveObservation(ctx, async () => {
2997
+ const ownerFilter = this.remoteAuthority ? undefined : await this.psOwnerFilter(ctx.subject.caller, false);
2998
+ // The daemon's status deadline is shorter than an install. Report the current inventory
2999
+ // without waiting for the install, which has its own lifecycle admission below.
3000
+ return this.managerStatusData(ownerFilter, !this.resumeRequired);
3001
+ }),
3608
3002
  ps: (ctx) => this.serveGated(ctx, async () => this.list(await this.psOwnerFilter(ctx.subject.caller, false))),
3609
3003
  inspect: (ctx) => this.serveGated(ctx, async () => {
3610
3004
  const name = String(args(ctx).name ?? "").trim();
@@ -3910,13 +3304,8 @@ export class Manager {
3910
3304
  scopeOf: (owner, actor) => resolveAuthProvider().actorScope({ dir: userAuthStateDir(this.workspaceRoot, this.space), owner, actor }),
3911
3305
  });
3912
3306
  }
3913
- /** The wire PRINCIPAL dot-form a managed agent's presence/control identity carries: user-mode
3914
- * entries already store it in `id`; static mints store the raw nkey there (the durable/teardown
3915
- * key), so the wire form derives under DEV_OWNER. Every comparison against an AUTHENTICATED wire
3916
- * id (presence card.id, control from.id) must go through this, never raw `a.id`. */
3917
- managedPrincipal(a) {
3918
- return a.userOwner ? a.id : principalKey(DEV_OWNER, a.id).key;
3919
- }
3307
+ /** The wire principal of a managed agent: {@link managedPrincipal}. */
3308
+ managedPrincipal(a) { return managedPrincipal(a); }
3920
3309
  resumeLivenessErrors(inventory, roster) {
3921
3310
  const inactive = [];
3922
3311
  const expectedNames = new Set(inventory.agents.map((entry) => entry.name));
@@ -4103,7 +3492,6 @@ export class Manager {
4103
3492
  })
4104
3493
  .finally(() => this.releaseLifecycle());
4105
3494
  }
4106
- servedSpawnRequest(served, caller) { return this.userProvision.servedSpawnRequest(served, caller); }
4107
3495
  provisionUserAgent(name, opts) { return this.userProvision.provisionUserAgent(name, opts); }
4108
3496
  /** Shred a user agent's secret family from the store and from disk. Every removal is attempted,
4109
3497
  * and each failure joins `unshredded`, so one fault cannot leave the rest of the family behind. */
@@ -4115,8 +3503,6 @@ export class Manager {
4115
3503
  if (path)
4116
3504
  await attemptCleanup(unshredded, `file ${path}`, () => rmSync(path, { force: true }));
4117
3505
  }
4118
- delegatedMeshRecord() { return this.userProvision.delegatedMeshRecord(); }
4119
- composeManagedHandoff(enrolled, actorToken) { return this.userProvision.composeManagedHandoff(enrolled, actorToken); }
4120
3506
  /**
4121
3507
  * WHY A SEAT LEFT — one line, at the one place every free path passes through.
4122
3508
  *
@@ -4280,12 +3666,6 @@ export class Manager {
4280
3666
  forkProvenance(a) {
4281
3667
  return this.sessionRecovery.forkProvenance(a);
4282
3668
  }
4283
- refuseCarriedFork(a, timeoutMs) {
4284
- return this.sessionRecovery.refuseCarriedFork(a, timeoutMs);
4285
- }
4286
- refuseLateCarriedFork(a, timeoutMs) {
4287
- return this.sessionRecovery.refuseLateCarriedFork(a, timeoutMs);
4288
- }
4289
3669
  readManagedSession(a) {
4290
3670
  return this.sessionRecovery.readManagedSession(a);
4291
3671
  }
@@ -4365,13 +3745,11 @@ export class Manager {
4365
3745
  this.reapChildrenOf(this.managedPrincipal(a));
4366
3746
  }
4367
3747
  nameError(name) { return this.namesCapacity.nameError(name); }
4368
- nameInUse(name, live) { return this.namesCapacity.nameInUse(name, live); }
4369
- uniqueName(base, unavailable = new Set()) { return this.namesCapacity.uniqueName(base, unavailable); }
4370
3748
  /** Spawn a teammate by persona ref (`name` loads `.cotal/agents/<name>.md`; the peer presents
4371
3749
  * under that file's own `name:`), as if a peer asked via the control plane. Used to pre-spawn the
4372
3750
  * demo's experts at startup so the manager owns them. */
4373
3751
  async startByName(name) {
4374
- return this.startAgent({ name });
3752
+ return this.seatLaunch.startByName(name);
4375
3753
  }
4376
3754
  /** Resolve once `name` shows up on the mesh roster (presence registered), or after `timeoutMs`.
4377
3755
  * Lets the pre-spawn loop stagger heavy agent cold-starts so they don't all boot at once.
@@ -4379,13 +3757,7 @@ export class Manager {
4379
3757
  * resolution: a same-named *unmanaged* peer already present could satisfy this early. That's
4380
3758
  * acceptable for cold-start staggering; it never routes anything. */
4381
3759
  async waitForPresence(name, timeoutMs = 30_000) {
4382
- const deadline = Date.now() + timeoutMs;
4383
- while (Date.now() < deadline) {
4384
- if (this.ep.getRoster().some((p) => p.card.name === name))
4385
- return true;
4386
- await new Promise((r) => setTimeout(r, 1_000));
4387
- }
4388
- return false;
3760
+ return this.seatLaunch.waitForPresence(name, timeoutMs);
4389
3761
  }
4390
3762
  /** Parse a served `spawn` request into {@link StartAgentOpts}. The compiled spawn input contract
4391
3763
  * is the shape check: it already refused a non-mapping `launchOptions`, a `supervise` that is not
@@ -4476,57 +3848,9 @@ export class Manager {
4476
3848
  ...(served !== undefined ? { served } : {}),
4477
3849
  }, caller, hooks, authenticatedCaller);
4478
3850
  }
4479
- /** The realpath + directory checks a placed spawn directory must pass on this manager's host,
4480
- * shared by the served `resolve-cwd` command and the `spawn` admission check (#385 item 2): one
4481
- * function, so the two doors never drift. Creates nothing and never substitutes the workspace root. */
4482
- checkSpawnCwd(resolved) {
4483
- let cwd = resolved;
4484
- try {
4485
- cwd = realpathSync(resolved);
4486
- }
4487
- catch (error) {
4488
- return { refusal: `path cannot be resolved: ${rejectionText(error)}` };
4489
- }
4490
- try {
4491
- if (!statSync(cwd).isDirectory())
4492
- return { refusal: "path is not a directory" };
4493
- }
4494
- catch (error) {
4495
- return { refusal: rejectionText(error) };
4496
- }
4497
- return { cwd, host: hostname() };
4498
- }
4499
- /** Refuse host directory reads before lookup when seats cannot use this host. */
4500
- assertHostDirectoryExecution() {
4501
- if (this.execution === "none")
4502
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
4503
- if (this.execution === "runtime" && this.requiredRuntime.spawnDelegated)
4504
- throw new EpEnvelopeError("failed-precondition", `runtime "${this.requiredRuntime.kind}" starts seats outside this host, so it cannot resolve a directory on this host's filesystem (cwd); the seat runs in its runtime resource's own directory`);
4505
- }
4506
- async listSpawnDirectory(args) {
4507
- this.assertHostDirectoryExecution();
4508
- const { cwd } = this.resolveSpawnCwd(args.path ?? homedir());
4509
- try {
4510
- return await listDirectory(cwd, args.includeHidden === true, typeof args.limit === "number" ? args.limit : 200);
4511
- }
4512
- catch (error) {
4513
- throw new EpEnvelopeError("failed-precondition", `directory cannot be listed on this host: ${JSON.stringify(cwd)} (${rejectionText(error)})`);
4514
- }
4515
- }
4516
- /** Resolve a placed spawn directory without creating or substituting a workspace. */
4517
- resolveSpawnCwd(value) {
4518
- this.assertHostDirectoryExecution();
4519
- const asked = typeof value === "string" ? value : String(value ?? "");
4520
- const refuse = (reason) => {
4521
- throw new EpEnvelopeError("failed-precondition", `cwd does not resolve on this host: ${JSON.stringify(asked)} (${reason})`);
4522
- };
4523
- if (!isAbsolute(asked))
4524
- refuse("expected an absolute path");
4525
- const result = this.checkSpawnCwd(asked);
4526
- if ("refusal" in result)
4527
- return refuse(result.refusal);
4528
- return result;
4529
- }
3851
+ listSpawnDirectory(args) { return this.seatLaunch.listSpawnDirectory(args); }
3852
+ /** {@link SeatLaunch.resolveSpawnCwd}. */
3853
+ resolveSpawnCwd(value) { return this.seatLaunch.resolveSpawnCwd(value); }
4530
3854
  /** Resolve a connector by agent type. Library composition (installedExtensions off) → a registry
4531
3855
  * hit, exactly as before (the composition root imported what it wants). The published binary gates
4532
3856
  * on MANIFEST membership FIRST — so a live `cotal ext remove` is honored even though the registry
@@ -4542,11 +3866,8 @@ export class Manager {
4542
3866
  throw new Error(connectorInstallHint(name));
4543
3867
  return materializeFromManifest({ kind: "connector", name }, { hint: (ref) => connectorInstallHint(ref.name), expectedGeneration: this.expectedConnectorGeneration });
4544
3868
  }
4545
- /** Connector names the manager can spawn WITHOUT importing: the manifest on the published binary,
4546
- * else whatever a composition root registered. Drives the `models` catalog enumeration. */
4547
- connectorNames() {
4548
- return this.installedExtensions ? manifestExtensionNames("connector") : registry.all("connector").map((c) => c.name);
4549
- }
3869
+ /** {@link SeatLaunch.connectorNames}. */
3870
+ connectorNames() { return this.seatLaunch.connectorNames(); }
4550
3871
  /** Resolve every installed/registered connector's declared harness binaries before the manager
4551
3872
  * reports ready. A missing harness degrades only that connector, never unrelated lifecycle work:
4552
3873
  * boot continues, names it once start completes and records it on both manager status surfaces. */
@@ -4577,27 +3898,12 @@ export class Manager {
4577
3898
  eventPlane: connector.eventChannel !== undefined,
4578
3899
  }));
4579
3900
  }
4580
- this.connectorRequirements = new Map(declared.map(({ name, requires }) => [name, requires]));
4581
- for (const { name, requires, eventPlane, pkg } of declared) {
3901
+ this.connectorRequirements = new Map(declared.map(({ name, requires, pkg }) => [name, {
3902
+ requires, needsClaudeWake: !!this.machineSetupCommand && name === "claude" && pkg === OFFICIAL_CONNECTORS.claude,
3903
+ }]));
3904
+ for (const { name, requires, eventPlane } of declared) {
4582
3905
  const { binaries, reason: missing } = resolveHarness(name, requires);
4583
- let reason = missing;
4584
- if (!reason && this.machineSetupCommand && name === "claude" && pkg === OFFICIAL_CONNECTORS.claude) {
4585
- try {
4586
- const connector = await this.resolveConnector(name);
4587
- if (!connector.setup)
4588
- throw new Error("Claude connector has no setup provider");
4589
- const provider = await materializeFromManifest(connector.setup, { expectedGeneration: this.expectedConnectorGeneration });
4590
- if (!provider.connector)
4591
- throw new Error("Claude connector has no install action");
4592
- const cotal = bearerEntryArgv();
4593
- cotal[cotal.length - 1] = logicalExecutionEntry() ?? cotal.at(-1);
4594
- await provider.connector.run({ cotal, machineHost: true });
4595
- }
4596
- catch (error) {
4597
- const detail = oneLine(rejectionText(error).replace(/eyJ[A-Za-z0-9_.-]*/g, "<redacted>").slice(0, 800));
4598
- reason = `Claude wake channel setup failed: ${detail}. Correct the cause and run \`${this.machineSetupCommand}\` on this computer.`;
4599
- }
4600
- }
3906
+ const reason = missing ?? (this.connectorRequirements.get(name)?.needsClaudeWake ? await this.prepareClaudeWake() : undefined);
4601
3907
  if (reason) {
4602
3908
  rows.push({ agent: name, state: "unavailable", binaries, eventPlane, reason });
4603
3909
  this.bootNotes.push(`! manager boot: connector ${name} unavailable - ${reason}`);
@@ -4610,55 +3916,81 @@ export class Manager {
4610
3916
  if (!this.classSpawnEnabled())
4611
3917
  this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
4612
3918
  }
4613
- /** Retry missing applications on the Manager's PATH without changing resolved available rows. */
4614
- refreshUnavailableConnectors(name) {
3919
+ /** Install and verify the hosted Claude wake channel, or report the cause and remedy. */
3920
+ async prepareClaudeWake() {
3921
+ try {
3922
+ const connector = await this.resolveConnector("claude");
3923
+ if (!connector.setup)
3924
+ throw new Error("Claude connector has no setup provider");
3925
+ const provider = await materializeFromManifest(connector.setup, { expectedGeneration: this.expectedConnectorGeneration });
3926
+ if (!provider.connector)
3927
+ throw new Error("Claude connector has no install action");
3928
+ const cotal = bearerEntryArgv();
3929
+ cotal[cotal.length - 1] = logicalExecutionEntry() ?? cotal.at(-1);
3930
+ await provider.connector.run({ cotal, machineHost: true });
3931
+ }
3932
+ catch (error) {
3933
+ const detail = oneLine(rejectionText(error).replace(/eyJ[A-Za-z0-9_.-]*/g, "<redacted>").slice(0, 800));
3934
+ return `Claude wake channel setup failed: ${detail}. Correct the cause and run \`${this.machineSetupCommand}\` on this computer.`;
3935
+ }
3936
+ }
3937
+ /** Retry unavailable applications without changing resolved available rows. Claude launches
3938
+ * join the status or launch that started wake setup, before any name or capacity is reserved. */
3939
+ refreshUnavailableConnectors(name, setupClaude = false) {
4615
3940
  const wasEnabled = this.classSpawnEnabled();
3941
+ let pending;
4616
3942
  for (const row of this.connectorStatuses) {
4617
3943
  if (row.state !== "unavailable" || (name !== undefined && row.agent !== name))
4618
3944
  continue;
4619
- const requires = this.connectorRequirements.get(row.agent);
4620
- if (!requires)
3945
+ const requirements = this.connectorRequirements.get(row.agent);
3946
+ if (!requirements)
4621
3947
  continue;
4622
- const { binaries, reason } = resolveHarness(row.agent, requires);
4623
- row.binaries = binaries;
4624
- if (reason)
4625
- row.reason = reason;
4626
- else {
3948
+ if (requirements.needsClaudeWake && this.claudeWakeRecheck) {
3949
+ pending = this.claudeWakeRecheck;
3950
+ continue;
3951
+ }
3952
+ const { binaries, reason } = resolveHarness(row.agent, requirements.requires);
3953
+ if (reason) {
3954
+ row.binaries = binaries;
3955
+ row.reason = reason;
3956
+ }
3957
+ else if (requirements.needsClaudeWake) {
3958
+ const release = setupClaude ? this.beginLifecycle(true) : undefined;
3959
+ if (!release)
3960
+ continue;
3961
+ pending = this.claudeWakeRecheck = this.prepareClaudeWake().then((failure) => {
3962
+ row.binaries = binaries;
3963
+ if (failure) {
3964
+ row.reason = failure;
3965
+ return;
3966
+ }
3967
+ const alreadyEnabled = this.classSpawnEnabled();
3968
+ row.state = "available";
3969
+ delete row.reason;
3970
+ if (!alreadyEnabled)
3971
+ this.servePlane.enableClassSpawn();
3972
+ }).finally(() => { this.claudeWakeRecheck = undefined; release(); });
3973
+ void pending.catch((error) => console.error(`! manager: Claude recheck failed: ${rejectionText(error)}`));
3974
+ }
3975
+ else {
3976
+ row.binaries = binaries;
4627
3977
  row.state = "available";
4628
3978
  delete row.reason;
4629
3979
  }
4630
3980
  }
4631
3981
  if (!wasEnabled && this.classSpawnEnabled())
4632
3982
  this.servePlane.enableClassSpawn();
3983
+ return pending;
4633
3984
  }
4634
- /** True when at least one declared connector is available. Empty inventory (or a failed
4635
- * inventory load) skips the class `one` subscribe for spawn/launch so this member cannot
4636
- * consume an unpinned request a sibling could serve. */
4637
- classSpawnEnabled() {
4638
- if (this.execution === "none")
4639
- return false;
4640
- return this.connectorStatuses.some((row) => row.state === "available");
4641
- }
4642
- omitClassCommands() {
4643
- return this.classSpawnEnabled() ? undefined : ["spawn", "launch"];
4644
- }
4645
- /** Named harness-unavailable refusal. On the class rail a partial inventory must not look
4646
- * like the space cannot launch: name `--on` so the caller can pin a sibling. The standing
4647
- * serve credential cannot enumerate sibling `svc.*.status` inventories, so the residual
4648
- * is the flag, not a list of capable instance ids. Instance-pinned calls keep the local
4649
- * reason only. */
4650
- harnessUnavailableError(reason, route) {
4651
- if (route !== "one")
4652
- return reason;
4653
- return `${reason}. This manager cannot launch that harness. The space may have other managers; pin one with --on <instance> (the whole id, as ps prints it)`;
4654
- }
3985
+ /** {@link SeatLaunch.classSpawnEnabled}. */
3986
+ classSpawnEnabled() { return this.seatLaunch.classSpawnEnabled(); }
3987
+ omitClassCommands() { return this.seatLaunch.omitClassCommands(); }
4655
3988
  /** The harness binaries a managed launch runs, as boot resolved them, or the refusal naming what is
4656
3989
  * missing. Spawn, resume and the model catalog all take it, so a seat launches from the same files
4657
3990
  * whichever path starts it and the catalog never disagrees with a launch about whether the harness
4658
- * is there. Unavailable rows are checked again on PATH; available rows retain their resolved files.
3991
+ * is there. Callers recheck unavailable rows first; available rows retain their resolved files.
4659
3992
  * A connector registered after boot has no inventory row and is checked on PATH now. */
4660
3993
  launchHarness(connector) {
4661
- this.refreshUnavailableConnectors(connector.name);
4662
3994
  const row = this.connectorStatuses.find((status) => status.agent === connector.name);
4663
3995
  if (row?.state === "unavailable")
4664
3996
  return { refusal: row.reason ?? `${connector.name} harness is unavailable` };
@@ -4702,49 +4034,8 @@ export class Manager {
4702
4034
  return `${connector.name} connector does not support exact session continuity (continuity: exact)`;
4703
4035
  return undefined;
4704
4036
  }
4705
- /** The refusal for a `once` spawn this manager cannot run as one task: every check is made before
4706
- * anything is allocated, so a refused spawn leaves nothing behind. */
4707
- onceRefusal(connector, runtime, launch, spawner, hooks) {
4708
- if (!hooks?.onOnce)
4709
- return "once: a once task rides the spawn action, which this launch door is not";
4710
- if (launch.prompt === undefined || launch.prompt.trim() === "")
4711
- return "once: needs a prompt, which is the task";
4712
- if (launch.supervise !== undefined)
4713
- return "once: a once seat is never restarted, so it cannot carry supervise";
4714
- if (!connector.supportsTurnRelay)
4715
- return `once: the ${connector.name} connector cannot take a once task${connector.turnRelayRefusal ? `: ${connector.turnRelayRefusal}` : ""}`;
4716
- if (connector.onceNeedsConfirmed !== undefined && !runtime.reportsStartupOutcome)
4717
- return `once: runtime "${runtime.kind}" does not report how a seat's startup ended, which a once seat on the ${connector.name} connector needs`;
4718
- if (runtime.spawnDelegated)
4719
- return `once: runtime "${runtime.kind}" starts seats outside this host, where this manager cannot prove the seat's exit`;
4720
- const operator = connector.waitsForOperator?.(launch.launchOptions);
4721
- if (operator !== undefined)
4722
- return `once: these launch options make the seat wait at ${operator} before it starts, so nothing could take its task`;
4723
- // The task's relay record, measured with the widest deadline it could carry.
4724
- const { note, payload } = onceTurnNote({
4725
- prompt: launch.prompt, spawner: this.spawnerName(spawner),
4726
- ...(launch.once.deadlineMs !== undefined ? { deadlineAt: MAX_SCHEDULE_MS, holdToken: turnHoldToken("") } : {}),
4727
- holdEpoch: this.serviceServe?.grant.epoch ?? 0,
4728
- ...(connector.retireAfterExit ? { retire: connector.name } : {}),
4729
- // The longest id token core accepts (endpoint-subjects `assertIdToken`).
4730
- spawn: "x".repeat(64),
4731
- });
4732
- if (note.length > TURN_NOTE_MAX)
4733
- return `once: the prompt is too long for one task (its relay record is ${note.length} characters, over ${TURN_NOTE_MAX})`;
4734
- if (connector.turnFrameLimit !== undefined) {
4735
- // The text the seat shows, rendered by the seat's own function with the widest values it could
4736
- // carry: the task's goal id is a digest token, and a deadline renders as one ISO instant.
4737
- const text = renderOnceTask({ goalId: digestIdToken("once"), payload, spawner: this.spawnerName(spawner), ...(launch.once.deadlineMs !== undefined ? { deadlineAt: MAX_SCHEDULE_MS } : {}) });
4738
- if (text.length > connector.turnFrameLimit)
4739
- return `once: the prompt is too long for one ${connector.name} turn (the task renders to ${text.length} characters, over ${connector.turnFrameLimit})`;
4740
- }
4741
- return undefined;
4742
- }
4743
- /** How a once task names who sent it: the spawner's roster name, or its principal when that name is missing or only whitespace. */
4744
- spawnerName(spawner) {
4745
- const id = spawner ?? this.ep.ref().id;
4746
- return shownSpawner(this.ep.getRoster().find((p) => p.card.id === id)?.card.name, id);
4747
- }
4037
+ /** {@link SeatLaunch.onceRefusal}. */
4038
+ onceRefusal(connector, runtime, launch, spawner, hooks) { return this.seatLaunch.onceRefusal(connector, runtime, launch, spawner, hooks); }
4748
4039
  /** The refusal for an event-plane choice the registration policy or the connector cannot meet.
4749
4040
  * Spawn and resume both ask before a seat's launch is built, so a seat retained without the
4750
4041
  * plane cannot come back on a space that now requires it. An absent choice arms supported planes. */
@@ -4766,6 +4057,7 @@ export class Manager {
4766
4057
  const requested = String(args.agent ?? "").trim();
4767
4058
  const refresh = args.refresh === true;
4768
4059
  const one = async (connector) => {
4060
+ await this.refreshUnavailableConnectors(connector.name, true);
4769
4061
  const harness = this.launchHarness(connector);
4770
4062
  if (!connector.listModels)
4771
4063
  return { agent: connector.name, supported: false, models: [] };
@@ -4918,1399 +4210,22 @@ export class Manager {
4918
4210
  if (!release)
4919
4211
  return { ok: false, error: this.maintenanceError() };
4920
4212
  try {
4921
- return await this.startAgentActive(opts, spawner, hooks, authenticatedCaller);
4213
+ return await this.seatLaunch.startActive(opts, spawner, hooks, authenticatedCaller);
4922
4214
  }
4923
4215
  finally {
4924
4216
  release();
4925
4217
  }
4926
4218
  }
4927
- /** The persona file a spawn loads and the harness it resolves, shared by `spawn` and the served
4928
- * `resolve-agent` read: a detached resume locates the session it carries with the connector this
4929
- * names, so the two doors must not drift (#2899). */
4930
- async spawnPersona(opts, spawner, authenticatedCaller) {
4931
- // Both config-taking wire commands and direct/roster starts enter here before interpreting
4932
- // a path. A resolved manifest is host-built authority over its own materialized resource,
4933
- // never a wire-supplied config override (the public schemas accept no `resolved` field).
4934
- if (this.execution === "runtime" && this.requiredRuntime.spawnDelegated && opts.config !== undefined && !opts.resolved)
4935
- return { error: "delegated execution cannot use a manager-host persona config path; select a named persona" };
4936
- // The spawn argument is a persona REF — a filename in `.cotal/agents` (the unique spawn KEY), or
4937
- // a path via `--config`. It is NOT the mesh identity: the identity comes from inside the file
4938
- // (`name:`), so a persona can be filed descriptively (review-critic.md) yet present under a
4939
- // free-form name (socrates) — the same model `cotal spawn` already uses. You always spawn by
4940
- // filename (unique on disk); two files can't collide on the key.
4941
- const ref = opts.name.trim();
4942
- if (!ref)
4943
- return { error: "name required" };
4944
- // An inline persona is its own definition, read here like a file so every later check sees a
4945
- // def. It has no file until its snapshot is written, once the seat's lifecycle uid is final.
4946
- if (opts.persona !== undefined) {
4947
- if (opts.resolved || opts.config !== undefined || opts.identity !== undefined)
4948
- return { error: "persona: an inline persona names the helper itself, so it takes no config, identity or manifest launch", code: "bad-request" };
4949
- const refErr = this.nameError(ref);
4950
- if (refErr)
4951
- return { error: refErr };
4952
- let inline;
4953
- try {
4954
- inline = inlinePersonaDef(ref, opts.persona);
4955
- }
4956
- catch (e) {
4957
- return { error: rejectionText(e), code: "bad-request" };
4958
- }
4959
- // A save under a name the catalog already holds is refused here, before anything is allocated,
4960
- // so the refusal starts nothing. The create-only write after the grant settles a race.
4961
- if (inline.save) {
4962
- const target = agentFilePath(this.workspaceRoot, ref);
4963
- let taken = true;
4964
- try {
4965
- lstatSync(target);
4966
- }
4967
- catch (e) {
4968
- if (e.code !== "ENOENT")
4969
- return { error: `persona.save: ${rejectionText(e)}` };
4970
- taken = false;
4971
- }
4972
- if (taken)
4973
- return { error: `persona.save: the catalog already holds a persona named "${ref}" (${target}). Spawn that persona by name, or pick another name to save this one under` };
4974
- }
4975
- return { ref, def: inline.def, agent: resolveAgentType({ flag: opts.agent, pin: undefined, callerDefault: opts.defaultAgent }), inline: { save: inline.save } };
4976
- }
4977
- // A bare ref maps to `.cotal/agents/<ref>.md`, so it must be a safe token (no path traversal); a
4978
- // `--config` path is validated by existsSync below instead.
4979
- if (!opts.config) {
4980
- const refErr = this.nameError(ref);
4981
- if (refErr)
4982
- return { error: refErr };
4983
- }
4984
- // Resolve the persona file (fail loud — NO silent default-ACL fallback). A missing persona used
4985
- // to mint DEFAULT creds (read `general` only, default-deny publish, no capabilities), so a
4986
- // typo'd / renamed / spawned-by-display-name agent became live with silently-wrong ACLs — a
4987
- // behavioral/security bug. Fail loud instead, matching `cotal spawn` (loadAgentFile throws).
4988
- // This runs BEFORE the spawn path resolves its connector: the file's `agent:` pin participates in
4989
- // the harness choice (flag > file > COTAL_DEFAULT_AGENT > default, #869), which is impossible if
4990
- // the connector is materialized first.
4991
- let configPath;
4992
- if (opts.config) {
4993
- configPath = agentFilePath(this.workspaceRoot, opts.config);
4994
- if (!existsSync(configPath))
4995
- return { error: `agent file not found: ${configPath}` };
4996
- }
4997
- else {
4998
- configPath = agentFilePath(this.workspaceRoot, ref);
4999
- if (!existsSync(configPath))
5000
- return { error: `no persona "${ref}" in the catalog of manager ${this.managerInstanceId} on host ${hostname()}: ${configPath} not found; create it there` };
5001
- }
5002
- // An inline snapshot belongs to its own seat's lifecycle, which removes it at retirement and
5003
- // refuses a restart once it changed, so no other launch may read it. Compared after symlinks
5004
- // resolve, for a config path and a catalog entry alike.
5005
- if (!opts.resolved && this.insideInlineDir(configPath))
5006
- return { error: `${configPath} is an inline persona's snapshot, which belongs to the seat it was written for; spawn a saved persona by name, or pass the persona inline` };
5007
- // Load the persona ONCE, here, ahead of the connector choice. The file's `agent:` pin feeds the
5008
- // harness resolution below; the spawn path's identity/ACL profile block consumes the SAME def (no
5009
- // second load). A manifest launch (`resolved`) materializes its own transient persona and the
5010
- // file is NOT its authority, so its def (and its agent pin) is deliberately not consulted here —
5011
- // the manifest's own `agent:` field drove the launch object already.
5012
- let def;
5013
- if (!opts.resolved) {
5014
- try {
5015
- def = loadLaunchPersonaFile(configPath);
5016
- }
5017
- catch (e) {
5018
- return { error: rejectionText(e), ...(e instanceof PersonaSourceError ? { code: "bad-request" } : {}) };
5019
- }
5020
- // Shared operator files remain launchable. Owned content follows the catalog's visibility
5021
- // decision before connector loading or any allocation. A hosted run acts for its admission;
5022
- // only a complete authenticated caller can request the current ledger's admin decision.
5023
- if (this.userMode && def.owner !== undefined) {
5024
- const acting = authenticatedCaller === undefined ? undefined
5025
- : this.runHosting?.admittedCaller(authenticatedCaller) ?? authenticatedCaller;
5026
- const personaCaller = acting === undefined ? spawner ?? "" : principalKey(acting.owner, acting.actor).key;
5027
- const admin = authenticatedCaller !== undefined && await this.epAdminReach(authenticatedCaller);
5028
- if (!this.canReadPersona(def.owner, personaCaller, admin))
5029
- return { error: `no persona "${ref}"` };
5030
- }
5031
- }
5032
- return { ref, configPath, def, agent: resolveAgentType({ flag: opts.agent, pin: def?.agent, callerDefault: opts.defaultAgent }) };
5033
- }
5034
- /** Whether a persona path resolves into the inline snapshot directory, the directory itself
5035
- * included. A directory that does not exist holds nothing. */
5036
- insideInlineDir(path) {
5037
- const dir = inlinePersonaDir(this.workspaceRoot);
5038
- if (!existsSync(dir))
5039
- return false;
5040
- const real = realpathSync(path);
5041
- const realDir = realpathSync(dir);
5042
- return real === realDir || real.startsWith(realDir + sep);
5043
- }
5044
- /** The run a spawn acts for (SPEC 14.8). The run this manager drives under `caller` answers from
5045
- * memory. On a static mesh, a spawn from a run hosted elsewhere names its run, whether the program
5046
- * placed it here or the class queue delivered it, and its caller must be that run's driver, whose
5047
- * triple derives from the run id; the run's admission and revocation marker are then read
5048
- * leader-served, so the helper is bounded as the hosting manager bounds it. Elsewhere the run id
5049
- * is not read: a user-auth run's issuing host bounds the helper, and an open mesh bounds none.
5050
- * `undefined` for a spawn that acts for no run. */
5051
- async spawnRun(caller, runId) {
5052
- const hosted = caller !== undefined ? this.runHosting?.runAdmission(caller) : undefined;
5053
- if (hosted !== undefined) {
5054
- if (runId !== undefined && runId !== hosted.runId)
5055
- return { refused: `it names run ${runId}, but its caller drives run ${hosted.runId}` };
5056
- return { admission: hosted, hosted: true };
5057
- }
5058
- if (runId === undefined || this.meshMode !== "static")
5059
- return undefined;
5060
- let driver;
5061
- try {
5062
- driver = caller !== undefined ? runDriverCaller(runId, caller.owner) : undefined;
5063
- }
5064
- catch (e) {
5065
- return { refused: `runId ${JSON.stringify(runId)} is not a run id (${rejectionText(e)})` };
5066
- }
5067
- if (driver === undefined || driver.actor !== caller.actor || driver.uid !== caller.uid)
5068
- return { refused: `it names run ${runId}, but its caller is not that run's driver` };
5069
- if (this.runHosting === undefined)
5070
- return { refused: `run ${runId} asked this manager for a helper, but this manager hosts no runs, so it cannot read the run's admission` };
5071
- let view;
5072
- try {
5073
- view = await this.runHosting.admission(runId);
5074
- }
5075
- catch (e) {
5076
- return { refused: `run ${runId}'s admission and revocation marker could not be read (${rejectionText(e)}), so it starts no helper (SPEC 14.8)` };
5077
- }
5078
- if (view.revoked !== undefined)
5079
- return { refused: revokedRunRefusal(runId, view.revoked) };
5080
- return { admission: view.admission, hosted: false };
5081
- }
5082
- /**
5083
- * Resolve what bounds a spawn's grant on a STATIC mesh: the caller's issued evidence, read the way
5084
- * keyed runs read it. A user-auth mesh bounds the mint on its ledger instead, and an open mesh
5085
- * mints no grant, so both return `exempt`. So does a call with no authenticated caller, which is
5086
- * the manager's own composition root (roster boot, a manifest `launch`, which a static mesh mints
5087
- * only into operator instruments). A workflow run's spawn, whether this manager hosts the run or
5088
- * its spawn reached this manager from another host ({@link spawnRun}), is bounded by the run's admission (SPEC 14.8):
5089
- * the ceiling it recorded, at the starter's coordinate, unless the starter was exempt then. That
5090
- * ceiling is the starter's evidence as resolved at admission, or for a local run the channels the
5091
- * operator named. Any other caller with no issued generation, or whose evidence does not resolve,
5092
- * hands on no grant. The evidence's own standing decides the rest.
5093
- */
5094
- async staticSpawnBound(caller, run) {
5095
- if (this.meshMode !== "static" || caller === undefined)
5096
- return { kind: "exempt" };
5097
- // The driver's own credential is not the run's authority, and the starter's evidence may have
5098
- // expired or changed since: the admission recorded both the ceiling and the verdict.
5099
- if (run !== undefined) {
5100
- const admission = run.admission;
5101
- // Read leader-served before each of the run's spawns, so a run revoked mid-step starts no
5102
- // helper, and a marker this manager cannot read refuses the spawn too. The marker of a run
5103
- // hosted elsewhere was read with its admission.
5104
- let refusal;
5105
- if (run.hosted)
5106
- try {
5107
- const revoked = (await this.runHosting.admission(admission.runId)).revoked;
5108
- if (revoked !== undefined)
5109
- refusal = revokedRunRefusal(admission.runId, revoked);
5110
- }
5111
- catch (e) {
5112
- refusal = `run ${admission.runId}'s revocation marker could not be read (${rejectionText(e)}), so it starts no helper (SPEC 14.8)`;
5113
- }
5114
- if (refusal !== undefined)
5115
- return { kind: "refused", reason: refusal };
5116
- if (admission.spawnExempt)
5117
- return { kind: "exempt" };
5118
- // The helper is projected at the admitted coordinate, which needs a lifecycle token. A local
5119
- // admission written before its uid was one records the CLI's own holder id, and bounds nothing.
5120
- try {
5121
- assertLifecycleToken(admission.caller.uid);
5122
- }
5123
- catch {
5124
- return { kind: "refused", reason: `run ${admission.runId}'s admission records caller uid ${JSON.stringify(admission.caller.uid)}, which is not a lifecycle token, so its helpers cannot be measured and it starts none. Start the run again (SPEC 14.8)` };
5125
- }
5126
- return { kind: "bounded", caller: admission.caller, ceiling: admission.ceiling, run: admission.runId };
5127
- }
5128
- if (!isIssuedCaller(caller))
5129
- return { kind: "none", reason: "its credential carries no issued generation (an unissued mint or a legacy rail)" };
5130
- const ref = { space: this.space, owner: caller.owner, actor: caller.actor, uid: caller.uid, generation: caller.generation };
5131
- try {
5132
- const { evidence } = await withIssuerSession({ servers: this.servers ?? DEFAULT_SERVER, space: this.space, auth: this.auth, tls: false }, (s) => s.store.resolve(ref, s.sourceIsLive));
5133
- return issuedSpawnerStanding(evidence) === "bounded" ? { kind: "bounded", caller, ceiling: evidence.permissions } : { kind: "exempt" };
5134
- }
5135
- catch (e) {
5136
- return { kind: "none", reason: `its issued evidence does not resolve: ${rejectionText(e)}` };
5137
- }
5138
- }
5139
- /** The refusal for a grant its static spawner does not hold, or `undefined` when it holds all of
5140
- * it. Each part is named, so the caller can drop exactly what overreached. `armsEvents` is whether
5141
- * the helper's own event plane will be minted: that row is keyed on a principal allocated later,
5142
- * so it is measured as the spawner's own, the rule the ledger applies. `door` names the command
5143
- * being bounded: a persona definition is bounded against its definer as a spawn is. */
5144
- spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") {
5145
- if (bound.kind === "exempt")
5146
- return undefined;
5147
- if (bound.kind === "refused")
5148
- return `${door}: ${bound.reason}`;
5149
- let over;
5150
- let eventsOver;
5151
- try {
5152
- over = bound.kind === "none" ? grantParts(grant) : grantOverreach(this.space, bound.caller, bound.ceiling, grant);
5153
- eventsOver = armsEvents && (bound.kind === "none"
5154
- || grantOverreach(this.space, bound.caller, bound.ceiling, { allowPublish: [eventChannel({ owner: bound.caller.owner, actor: bound.caller.actor })] }).length > 0);
5155
- }
5156
- catch (e) {
5157
- return `${door}: ${rejectionText(e)}`;
5158
- }
5159
- if (!over.length && !eventsOver)
5160
- return undefined;
5161
- const named = [
5162
- // A role is handed on by a spawner whose credential binds that role's task queue: its own
5163
- // role, or a `role:<r>` token in its capabilities.
5164
- ...over.map((o) => o.field === "role" ? `role ${o.value} (a spawner hands on a role it was given as its own or as the \`role:${o.value}\` capability)` : `${o.field} ${o.value}`),
5165
- ...(eventsOver ? ["events (the helper's own event plane; pass events: false to spawn without it)"] : []),
5166
- ].join(", ");
5167
- if (door === "define-persona")
5168
- return bound.kind === "none"
5169
- ? `define-persona: the definer holds no issued evidence (SPEC 13.15), so its persona can grant nothing: ${bound.reason}. This persona asks for ${named}. ` +
5170
- `Define it without these, or start the definer under a manager (\`cotal spawn --detach\`), whose seats carry issued evidence.`
5171
- : `define-persona: this persona grants more than the definer holds: ${named}. A definer hands on only what its own issued credential carries (SPEC 13.15). ` +
5172
- `Drop these from the persona, or have the operator widen the definer's own persona.`;
5173
- if (bound.kind === "bounded" && bound.run !== undefined)
5174
- return `spawn: this spawn hands its helper more than run ${bound.run}'s starter held when the run was admitted: ${named}. ` +
5175
- `A run hands on only what its admission recorded: its starter's issued credential, or for a \`--local\` run the channels named by \`--admit-read\` and \`--admit-publish\` (SPEC 14.8). ` +
5176
- `Drop these from the persona or the spawn, or start the run from a caller that holds them.`;
5177
- return bound.kind === "none"
5178
- ? `spawn: the spawner holds no issued evidence (SPEC 13.15), so it hands on no grant: ${bound.reason}. This spawn asks for ${named}. ` +
5179
- `Spawn a persona that names none of these, or start the spawner under a manager (\`cotal spawn --detach\`), whose seats carry issued evidence.`
5180
- : `spawn: this spawn hands its helper more than the spawner holds: ${named}. A spawner hands on only what its own issued credential carries (SPEC 13.15). ` +
5181
- `Drop these from the persona or the spawn, or have the operator widen the spawner's own persona.`;
5182
- }
5183
- /** Ordinary static control seats can read their holding instance. A run's recorded ceiling is
5184
- * authoritative, so its helpers receive no additional instance reads. */
5185
- managedStaticInstanceReads(capabilities) {
5186
- if (this.meshMode !== "static" || !this.managerInstanceId || !capabilities?.some(c => c === "spawn" || c === "run" || c === "admin"))
5187
- return [];
5188
- return ["describe", "inspect"].map(command => ({
5189
- endpoint: MANAGER_ENDPOINT, command, instanceId: this.managerInstanceId, instanceOnly: true,
5190
- }));
5191
- }
5192
- async startAgentActive(opts, spawner, hooks, authenticatedCaller) {
5193
- // Before the first await, so the grant, the launch, the retained form and the restart slot all read
5194
- // the lists and the restart policy as admitted.
5195
- opts = ownLists(opts);
5196
- if (opts.resolved)
5197
- opts.resolved = ownLists(opts.resolved);
5198
- if (opts.persona !== undefined)
5199
- opts.persona = ownPersona(opts.persona);
5200
- if (opts.supervise) {
5201
- opts.supervise = { restarts: opts.supervise.restarts, windowMs: opts.supervise.windowMs };
5202
- // The budget is checked here, where it is held, not only at the wire: an in-process caller of
5203
- // this export is refused before anything launches, rather than getting a seat that joins and is
5204
- // torn down when its seat record will not take the policy (#3298).
5205
- const policy = supervisePolicy.safeParse(opts.supervise);
5206
- if (!policy.success)
5207
- return { ok: false, error: `supervise.${policy.error.issues[0]?.path.join(".")}: expected a positive integer` };
5208
- }
5209
- if (opts.once)
5210
- opts.once = { deadlineMs: opts.once.deadlineMs };
5211
- let runtime;
5212
- try {
5213
- await this.loadSeatRuntime(opts.runtime);
5214
- runtime = this.runtimeFor(opts.runtime);
5215
- }
5216
- catch (e) {
5217
- return { ok: false, error: rejectionText(e) };
5218
- }
5219
- if (opts.delegatedIntent) {
5220
- if (!this.remoteAuthority?.executeDelegatedUserIntent)
5221
- return { ok: false, error: `"${opts.name}" names a delegated user intent, and this manager has no host execution for one` };
5222
- if (opts.supervise)
5223
- return { ok: false, error: `"${opts.name}" names a delegated user intent, and a delegated agent is never restarted (SPEC 13.16)` };
5224
- // A delegated launch's spawner is the user's principal, never the composition root's call.
5225
- spawner = opts.delegatedIntent.parent;
5226
- }
5227
- const persona = await this.spawnPersona(opts, spawner, authenticatedCaller);
5228
- if ("error" in persona)
5229
- return { ok: false, error: persona.error, ...(persona.code ? { code: persona.code } : {}) };
5230
- const { ref, def, agent, inline } = persona;
5231
- // An inline persona's file is its snapshot, written once the lifecycle uid is final; until then
5232
- // a refusal names the persona instead of a path.
5233
- let configPath = persona.configPath;
5234
- const where = configPath ?? `inline persona "${ref}"`;
5235
- // Materialize the requested connector before the capacity/reserve span so its lazy import
5236
- // cannot interleave that synchronous allocation. On the manifest binary this also honors a
5237
- // live `cotal ext remove`: a removed connector is rejected here even if an earlier spawn already
5238
- // imported it. A broken/missing connector fails loud here with a clear name + install hint.
5239
- let connector;
5240
- try {
5241
- connector = await this.resolveConnector(agent);
5242
- }
5243
- catch (e) {
5244
- const error = rejectionText(e);
5245
- // An action refusal here precedes capacity, allocation and onAccepted. Preserve that proof
5246
- // through serveSpawnGoal without changing the direct startAgent ControlReply contract.
5247
- if (hooks?.onAccepted)
5248
- throw new EpEnvelopeError("failed-precondition", error, undefined, "not-executed");
5249
- return { ok: false, error };
5250
- }
5251
- // Read here, beside the connector, so the capacity check and the reserve below take no new await.
5252
- const run = await this.spawnRun(authenticatedCaller, opts.runId);
5253
- if (run !== undefined && "refused" in run)
5254
- return { ok: false, error: `spawn: ${run.refused}` };
5255
- const bound = await this.staticSpawnBound(authenticatedCaller, run);
5256
- const readinessTimeoutMs = connector.readinessTimeoutMs ?? this.readinessTimeoutMs;
5257
- if (!Number.isSafeInteger(readinessTimeoutMs) || readinessTimeoutMs <= 0)
5258
- return { ok: false, error: `connector ${connector.name} declares invalid readinessTimeoutMs ${JSON.stringify(connector.readinessTimeoutMs)}; expected a positive safe integer` };
5259
- // Capacity check first (cheap, fail-fast). Everything from here to the reserve below is
5260
- // SYNCHRONOUS (existsSync / registry / accessSync / readFileSync — no await), so the gate stays
5261
- // atomic: the capacity snapshot and the reserve land in one tick (P4a/P4c), and two concurrent
5262
- // spawns can't overshoot the ceiling or pick the same name.
5263
- const occupancy = this.occupancy(); // prunes expired cooling stamps; counts each name once
5264
- if (occupancy.used >= MAX_AGENTS)
5265
- return { ok: false, error: this.capacityRefusal(occupancy) };
5266
- // Harness preflight before reserving a slot or minting — a missing `claude`/`opencode` binary
5267
- // fails here with a clear name, not obscurely at process spawn. No fallback. All synchronous, so
5268
- // the reserve gate stays atomic. (The connector itself was resolved up top, before the capacity gate.)
5269
- const harness = this.launchHarness(connector);
5270
- if ("refusal" in harness)
5271
- return { ok: false, error: this.harnessUnavailableError(harness.refusal, opts.route ?? "inst") };
5272
- // Resume is a connector capability: reject an unsupported resume HERE, before the reserve/mint, so
5273
- // it can never provision creds + durables and then throw at buildLaunch (mint-then-orphan). Same
5274
- // reject-before-side-effects window as the harness preflight above; buildLaunch stays the backstop.
5275
- if (opts.resume && !connector.supportsResume)
5276
- return { ok: false, error: `${agent} connector does not support resuming an existing session (resume)` };
5277
- // A carried resume (#1499) is checked here too, before anything is minted. The claim is only
5278
- // looked at: the connector may still refuse the launch, and a refused launch leaves it unspent.
5279
- let carried;
5280
- if (opts.resumeClaim !== undefined) {
5281
- if (opts.resume === undefined)
5282
- return { ok: false, error: "resumeClaim: names carried bytes of a resume; the launch carries no resume" };
5283
- if (!connector.resumeTranscript)
5284
- return { ok: false, error: `${agent} connector does not take a carried transcript (resumeClaim)` };
5285
- if (opts.resumeAgent !== agent)
5286
- return { ok: false, error: `resumeClaim: the session was carried for agent "${opts.resumeAgent ?? "<none>"}", and this launch resolves agent "${agent}"` };
5287
- if (!this.transcripts)
5288
- return { ok: false, error: "resumeClaim: this manager does not receive carried transcripts" };
5289
- try {
5290
- carried = this.transcripts.peek(opts.resumeClaim, opts.resume);
5291
- }
5292
- catch (e) {
5293
- return { ok: false, error: rejectionText(e) };
5294
- }
5295
- }
5296
- // A restart policy this host cannot honour is refused at accept, never accepted and ignored.
5297
- // External runtimes (tmux/cmux/orca/herdr) attach to a process they do not own and stream no
5298
- // exit, so a name cannot be respawned in place. User-mode seats have no static slot that
5299
- // keeps the incarnation owned across a process death, so the same refusal applies there.
5300
- if (opts.supervise !== undefined) {
5301
- if (runtime.kind !== "pty")
5302
- return { ok: false, error: `supervise is a restart policy this host cannot enforce: runtime "${runtime.kind}" cannot respawn a name in place` };
5303
- if (this.userMode)
5304
- 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" };
5305
- if (runtime.supportsWorkClosure !== true)
5306
- return { ok: false, error: `supervise is a restart policy this host cannot enforce: runtime "${runtime.kind}" cannot prove prior local work ended` };
5307
- }
5308
- // One read of the cotal config per spawn: the delegated refusal, the model policy and the launch
5309
- // fields below all take this value, so the awaits between the policy check and the launch cannot
5310
- // admit the seat under one file and launch it with another's servers and env allowlist. Read per
5311
- // spawn, so a policy edit reaches the next spawn without a restart. The launch fields are resolved
5312
- // here too, before the spawn is accepted, so a sharing selection that names an undeclared server
5313
- // is refused while there is nothing to roll back.
5314
- let cotalConfig;
5315
- let hostFields;
5316
- try {
5317
- cotalConfig = loadCotalConfig(this.workspaceRoot);
5318
- hostFields = this.hostLaunchFields(cotalConfig, agent, opts.shareTools, harness);
5319
- }
5320
- catch (e) {
5321
- const error = rejectionText(e);
5322
- // An input refusal here precedes allocation and onAccepted, like a connector refusal above:
5323
- // a hosted run proves it not-executed instead of binding a goal to a spawn that never starts.
5324
- if (hooks?.onAccepted)
5325
- throw new EpEnvelopeError("failed-precondition", error, undefined, "not-executed");
5326
- return { ok: false, error };
5327
- }
5328
- // A delegated seat starts outside this host from values alone, so a choice only this host can
5329
- // honour is refused here, before enrollment, and named rather than dropped.
5330
- if (runtime.spawnDelegated) {
5331
- const delegatedBy = `runtime "${runtime.kind}" starts seats outside this host`;
5332
- if (!this.remoteAuthority?.enrollManagedAgent)
5333
- return { ok: false, error: `${delegatedBy}, which needs a host that enrolls managed agents (remoteAuthority.enrollManagedAgent); a delegated seat has no local grant path` };
5334
- try {
5335
- this.delegatedMeshRecord();
5336
- }
5337
- catch (e) {
5338
- return { ok: false, error: rejectionText(e) };
5339
- }
5340
- if (opts.resume)
5341
- return { ok: false, error: `${delegatedBy}, so it cannot resume a session held on this host (resume)` };
5342
- if (opts.resolved?.continuity === "exact")
5343
- return { ok: false, error: `${delegatedBy}, so it cannot reopen a session held on this host (continuity: exact)` };
5344
- if (typeof opts.cwd === "string" && opts.cwd !== "")
5345
- 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` };
5346
- const shared = Object.keys(hostFields.mcpServers);
5347
- if (shared.length)
5348
- return { ok: false, error: `${delegatedBy}, so it cannot share MCP servers that run on this host (${shared.join(", ")}); pass --share-tools none` };
5349
- }
5350
- // A placed spawn's cwd is checked on this host BEFORE anything is minted or reserved: an absolute
5351
- // path this manager cannot realpath, or one that is not a directory, is refused here with the
5352
- // asked path, the reason and this host, so a misplaced spawn in a multi-manager space is
5353
- // diagnosable at the moment it happens (#385 item 2) instead of failing inside the pty launch.
5354
- // The resolved realpath is threaded to the launch cwd below (`resolvedCwd`) so it is computed once.
5355
- let resolvedCwd;
5356
- if (typeof opts.cwd === "string" && opts.cwd !== "") {
5357
- const asked = opts.cwd;
5358
- const target = resolve(this.workspaceRoot, asked);
5359
- const checked = this.checkSpawnCwd(target);
5360
- if ("refusal" in checked)
5361
- return { ok: false, error: `spawn: cwd does not resolve on this host (${hostname()}): ${JSON.stringify(asked)} (${checked.refusal}); the seat was not launched` };
5362
- resolvedCwd = checked.cwd;
5363
- }
5364
- // Resolve the launch profile: IDENTITY (free-form `name:`) + role + read/post ACL + capabilities
5365
- // + model/variant. Either from a fully-resolved manifest launch object (`opts.resolved`, whose `config`
5366
- // is a materialized transient persona — the file is NOT the access authority), or from the
5367
- // persona file. The number rides the IDENTITY (socrates → socrates_2), not the file ref — a
5368
- // redelivered identical spawn yields a fresh numbered agent (MAX_AGENTS bounds the blast radius).
5369
- let identityName;
5370
- let role;
5371
- let subscribe;
5372
- let allowSubscribe;
5373
- let allowPublish;
5374
- let capabilities;
5375
- // The endpoint commands the persona hands on (SPEC 13.15), as the persona names them and as the
5376
- // mint grants them. A manifest launch carries none: its schema has no slot for them.
5377
- let personaEndpoints;
5378
- let endpoints = [];
5379
- let model = opts.model;
5380
- let variant = opts.variant;
5381
- let launchOptions = opts.launchOptions;
5382
- let prompt = opts.prompt;
5383
- // The read set the persona and the overrides name, before `join` adds to it: what a saved copy keeps.
5384
- let ownSubscribe;
5385
- if (opts.resolved) {
5386
- // A manifest launch is the access + identity authority: imperative overrides arriving
5387
- // alongside `resolved` are a caller contract error, not something to merge (no fallbacks).
5388
- if (opts.subscribe || opts.allowSubscribe || opts.allowPublish || opts.join || opts.callerAcl || opts.prompt || opts.shareTools || opts.identity)
5389
- return { ok: false, error: "a manifest launch (resolved) rejects imperative overrides (identity/subscribe/allow*/join/callerAcl/prompt/shareTools)" };
5390
- const r = opts.resolved;
5391
- identityName = r.name;
5392
- role = opts.role ?? r.role;
5393
- subscribe = r.subscribe;
5394
- allowSubscribe = r.allowSubscribe;
5395
- allowPublish = r.allowPublish;
5396
- capabilities = r.capabilities;
5397
- model = opts.model ?? r.model;
5398
- variant = opts.variant ?? r.variant;
5399
- launchOptions = mergeLaunchOptions(r.launchOptions, opts.launchOptions);
5400
- prompt = r.prompt; // the guard above rejected an imperative prompt — one source
5401
- }
5402
- else {
5403
- // `def` was loaded once above the connector resolution (#869 ordering); consume it here.
5404
- // `resolved` is the only path that skips the load, and this is its opposite branch.
5405
- if (!def)
5406
- return { ok: false, error: "internal: persona definition missing at launch profile" };
5407
- // Identity: the `--name` override wins over the file's `name:` — foreground parity (there,
5408
- // `requested = values.name ?? def.name`). The override is minted into the creds and rides
5409
- // COTAL_NAME below, so the presence identity and its credential can't diverge.
5410
- identityName = opts.identity ?? def.name;
5411
- role = opts.role ?? def.role;
5412
- // Flags > persona file — the same precedence as foreground `cotal spawn`, so the two launch
5413
- // paths of the merged grammar can't diverge. One source feeds BOTH the minted creds and the
5414
- // connector env below.
5415
- // A persona that names no channel field at all is scoped to its spawner's ACL (`callerAcl`,
5416
- // when the door sent one). The spawner's own event channel is dropped from it: that plane is
5417
- // foreign to the child, and the guard below refuses any spawn that asks for one. The joined
5418
- // set is never copied from the spawner: a helper starts on what its persona lists plus what
5419
- // the caller passes in `join`, and nothing else. The ACL is the caller's own report, so on a
5420
- // static mesh it is clamped to what the caller's evidence shows it holds, and a caller with
5421
- // no evidence gets no default at all.
5422
- const personaNamesChannels = def.subscribe !== undefined || def.allowSubscribe !== undefined || def.allowPublish !== undefined;
5423
- const heldChannels = (field, channels) => {
5424
- const own = channels.filter((ch) => eventChannelPrincipal(ch) === null);
5425
- return bound.kind === "bounded" ? own.filter((ch) => grantOverreach(this.space, bound.caller, bound.ceiling, { [field]: [ch] }).length === 0) : own;
5426
- };
5427
- let scoped;
5428
- try {
5429
- scoped = !personaNamesChannels && opts.callerAcl && bound.kind !== "none" ? {
5430
- allowSubscribe: heldChannels("allowSubscribe", opts.callerAcl.allowSubscribe),
5431
- allowPublish: heldChannels("allowPublish", opts.callerAcl.allowPublish),
5432
- } : undefined;
5433
- }
5434
- catch (e) {
5435
- return { ok: false, error: `callerAcl: ${rejectionText(e)}` };
5436
- }
5437
- const base = opts.subscribe ?? def.subscribe;
5438
- ownSubscribe = base;
5439
- subscribe = opts.join?.length ? [...new Set([...(base ?? []), ...opts.join])] : base;
5440
- allowSubscribe = opts.allowSubscribe ?? def.allowSubscribe ?? scoped?.allowSubscribe ?? [];
5441
- allowPublish = opts.allowPublish ?? def.allowPublish ?? scoped?.allowPublish;
5442
- capabilities = def.capabilities;
5443
- personaEndpoints = copyPersonaEndpoints(def.endpoints);
5444
- // A user-auth mesh grants endpoint access through the service owner's records, which a spawn
5445
- // cannot write (SPEC 13.15), so a persona that names the field is refused there, `[]` included,
5446
- // before any bound or exemption reads it.
5447
- if (personaEndpoints !== undefined && this.meshMode === "user")
5448
- return { ok: false, error: userMeshEndpointsRefusal("spawn") };
5449
- endpoints = lowerPersonaEndpoints(personaEndpoints);
5450
- // #651: fold the persona's model into the launch record, mirroring the variant line below
5451
- // and the manifest branch above. Without this, a persona-file model (the common pin source)
5452
- // never reaches `launch.model`, so the connector runs the seat on it while `ps --wide`/`--json`
5453
- // reports the model ABSENT - a false "no model pinned" for a seat that has one.
5454
- model = opts.model ?? def.model;
5455
- variant = opts.variant ?? def.variant;
5456
- launchOptions = mergeLaunchOptions(def.launchOptions, opts.launchOptions);
5457
- }
5458
- // Resolved once for both branches, because this one list is granted, minted, recorded on the
5459
- // launch and forwarded to the session, and each of those must read the list the provisioner does.
5460
- try {
5461
- allowSubscribe = resolveReadAcl(subscribe ?? [], allowSubscribe);
5462
- }
5463
- catch (e) {
5464
- return { ok: false, error: opts.resolved ? `launch agent: ${rejectionText(e)}` : `persona ${where}: ${rejectionText(e)}` };
5465
- }
5466
- // Default events on where the connector supports them, unless the launch explicitly opts out.
5467
- const events = this.eventsRequired || opts.events === true || (opts.events !== false && !!connector.eventChannel);
5468
- if (this.eventPayloadsWithheld && opts.eventPayloads === true)
5469
- return { ok: false, error: "space policy withholds event payloads" };
5470
- const eventPayloads = !this.eventPayloadsWithheld && (opts.eventPayloads ?? def?.eventPayloads) !== false;
5471
- if (run === undefined) {
5472
- const reads = this.managedStaticInstanceReads(capabilities);
5473
- if (bound.kind === "exempt" || (bound.kind === "bounded" && !grantOverreach(this.space, bound.caller, bound.ceiling, { endpoints: reads }).length))
5474
- endpoints.push(...reads);
5475
- }
5476
- // THE DELEGATION BOUND, on the grant as it will be minted: every channel and capability the
5477
- // helper gets, from the persona, the raw overrides and the `callerAcl` default alike, and its own
5478
- // event plane, so no door reaches the mint around it. Before any reserve or mint, so a refusal
5479
- // leaves nothing.
5480
- const boundRefusal = this.spawnBoundRefusal(bound, {
5481
- allowSubscribe,
5482
- ...(allowPublish !== undefined ? { allowPublish } : {}),
5483
- ...(role !== undefined ? { role } : {}),
5484
- ...(capabilities !== undefined ? { capabilities } : {}),
5485
- ...(endpoints.length ? { endpoints } : {}),
5486
- }, events);
5487
- if (boundRefusal)
5488
- return { ok: false, error: boundRefusal };
5489
- // A run saves for the caller it was admitted for, whose catalog reads then find the copy.
5490
- const savedBy = authenticatedCaller === undefined ? undefined : this.runHosting?.admittedCaller(authenticatedCaller);
5491
- // What a saved copy keeps: the grant just checked, without the helper's own event row, which each
5492
- // later spawn derives for its own helper. The file names every channel field, so no later caller's
5493
- // default fills one, and each later spawn of it is still bounded against that caller.
5494
- const catalogCopy = inline?.save
5495
- ? {
5496
- name: ref,
5497
- owner: savedBy !== undefined ? this.personaOwner(principalKey(savedBy.owner, savedBy.actor).key) : spawner === undefined ? undefined : this.personaOwner(spawner),
5498
- role,
5499
- model,
5500
- variant,
5501
- description: def?.description,
5502
- persona: def?.persona,
5503
- subscribe: [...(ownSubscribe ?? [])],
5504
- allowSubscribe: [...allowSubscribe],
5505
- allowPublish: [...(allowPublish ?? [])],
5506
- capabilities: capabilities?.length ? [...capabilities] : undefined,
5507
- endpoints: copyPersonaEndpoints(personaEndpoints?.length ? personaEndpoints : undefined),
5508
- }
5509
- : undefined;
5510
- // Checked after every path has resolved its selectors: a direct `startAgent` call skips the
5511
- // `start` op's checks, and no connector may receive a blank one (#2862).
5512
- if (model !== undefined && !model.trim())
5513
- return { ok: false, error: "model: must not be empty" };
5514
- if (variant !== undefined && !variant.trim())
5515
- return { ok: false, error: "variant: must not be empty" };
5516
- const idErr = this.nameError(identityName);
5517
- if (idErr)
5518
- return { ok: false, error: opts.resolved ? `launch agent: ${idErr}` : `persona ${where}: ${idErr}` };
5519
- // #966: a seat labelled `manager` that cannot spawn is a worker wearing a label, and the label
5520
- // is what other agents ROUTE on (role is the anycast address). The gap is silent today because
5521
- // the mismatch is only discovered minutes in, when the seat first reaches for a worker. Refuse
5522
- // at accept, before any reserve/mint, naming the remediation for each author: an operator edits
5523
- // the file to add the grant, and the persona's owner may redefine it with the grant only if the
5524
- // owner holds spawn, because define-persona bounds capabilities against the definer. The
5525
- // check keys on the EFFECTIVE role (a spawn-time role: override wins
5526
- // over the file, mirroring the resolution above), not the file's, so the label other agents
5527
- // will actually see is the label that is held to account. `manager` is the label that MEANS
5528
- // spawn-holding: naming it literally keeps this the narrow guard for the observed harm, not a
5529
- // vocabulary any caller can trigger with a synonym (roles are free-form and mostly
5530
- // non-manager: this workspace's own catalog carries worker/reviewer/orchestrator seats with no
5531
- // spawn grant, all legitimate).
5532
- if (role === "manager" && !capabilities?.includes("spawn") && inline)
5533
- return {
5534
- ok: false,
5535
- error: `inline persona "${ref}" would join with role "manager" but no spawn capability: it presents as a manager ` +
5536
- `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.`,
5537
- };
5538
- if (role === "manager" && !capabilities?.includes("spawn"))
5539
- return {
5540
- ok: false,
5541
- error: `persona "${ref}" would join with role "manager" but no spawn capability: it presents as a manager ` +
5542
- `while being unable to seat workers, and it would discover that only on first use. ` +
5543
- `An operator adds \`capabilities: [spawn]\` to ${configPath}, or the persona's owner redefines it ` +
5544
- `with \`capabilities: [spawn]\` (cotal_persona) if the owner holds spawn.`,
5545
- };
5546
- // #581: the operator's per-role model allowlist, judged on the EFFECTIVE role and model resolved
5547
- // above, before any reserve or mint. This is where the launch is performed, so no caller can
5548
- // skip it, and a definition pinned to a stale model (or to none) is refused here instead of
5549
- // serving on it.
5550
- const policyRefusal = modelPolicyRefusal(cotalConfig, {
5551
- persona: opts.resolved ? `manifest agent "${ref}"` : configPath ? `persona "${ref}" (${configPath})` : where,
5552
- role, model, variant,
5553
- // A manifest launch carries its own declared model/variant in these options
5554
- // (launchAgentToStartOpts), so there they are the definition's field, never a flag.
5555
- modelFlag: !opts.resolved && opts.model !== undefined,
5556
- variantFlag: !opts.resolved && opts.variant !== undefined,
5557
- launchOptions,
5558
- });
5559
- if (policyRefusal)
5560
- return { ok: false, error: policyRefusal };
5561
- // The alias-reuse gate: a name whose previous agent is still retiring REFUSES
5562
- // legibly (never a silent suffix), and the refusal re-drives the FULL durable teardown so
5563
- // "retry the spawn" is also the nudge. It routes through `deprovision` (not `requestRetirement`
5564
- // alone) so a retry re-drives the standing-authority revoke (INT-2) AND the broker cleanup before
5565
- // any hold-clear (C): the alias must not free while the durable teardown or the revoke is still
5566
- // outstanding. All the teardown ops are idempotent, and the rail request is single-flighted.
5567
- if (this.staticLifecycle.isReconciling(identityName))
5568
- return { ok: false, error: `the name "${identityName}" is still reconciling at manager startup; its prior lifecycle terminal owns this alias until it completes. Retry shortly.` };
5569
- const held = this.retirement.held(identityName);
5570
- if (held !== undefined) {
5571
- hooks?.onEffect?.();
5572
- void this.deprovision(held.target).catch(() => { });
5573
- 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" });
5574
- return { ok: false, error: renderLifecycleBlocked(err.message, err), details: err.details };
5575
- }
5576
- // A manifest `continuity: exact` agent reopens the session this manager last bound to its
5577
- // declared name. Refused before any reserve or mint when the connector cannot reopen an exact
5578
- // session or the recorded assignment does not match this declaration.
5579
- const exact = opts.resolved?.continuity === "exact";
5580
- const unsupported = this.capabilityRefusal(connector, { variant, prompt, exact });
5581
- if (unsupported)
5582
- return { ok: false, error: unsupported };
5583
- const onceRefused = opts.once && this.onceRefusal(connector, runtime, { ...opts, launchOptions, prompt }, spawner, hooks);
5584
- if (onceRefused)
5585
- return { ok: false, error: onceRefused };
5586
- let reopenSession;
5587
- if (exact) {
5588
- try {
5589
- reopenSession = readContinuityAssignment(this.workspaceRoot, { space: this.space, name: identityName, connector: agent, cwd: resolvedCwd ?? this.workspaceRoot });
5590
- }
5591
- catch (e) {
5592
- return { ok: false, error: rejectionText(e) };
5593
- }
5594
- }
5595
- // The child takes launch options as `--opt k=v`, so only string values can cross to it.
5596
- const unportable = runtime.spawnDelegated ? Object.keys(launchOptions ?? {}).filter((k) => typeof launchOptions[k] !== "string") : [];
5597
- if (unportable.length)
5598
- return { ok: false, error: `runtime "${runtime.kind}" starts seats outside this host, so it cannot pass non-string launch options (${unportable.join(", ")})` };
5599
- // An event plane the connector cannot emit is refused HERE, before anything is minted: a
5600
- // connector that cannot emit must fail before provisioning rather than after, as an
5601
- // unsupported `resume` does.
5602
- // The GRANT itself cannot be derived yet. It is keyed on the agent's PRINCIPAL, and in user mode
5603
- // the principal's owner is resolved further down, so deriving it from anything in scope here
5604
- // would mean guessing at the identity the child will actually connect as. It is added at the
5605
- // accept seam below, where the allocated triple exists.
5606
- const eventsRefused = this.eventsRefusal(connector, opts.events);
5607
- if (eventsRefused)
5608
- return { ok: false, error: eventsRefused };
5609
- // The roster the allocation consults must reflect the initial presence snapshot,
5610
- // or a spawn immediately after manager boot races an already-live unmanaged peer and re-opens the
5611
- // very collision black-hole this closes. Await the snapshot (bounded internally, fail-safe on an
5612
- // empty mesh) before allocating; the broker/auth remain the authority downstream. Deliberately
5613
- // unconditional: a half-wired endpoint without the seam must fail loud here, not silently
5614
- // allocate off a pre-snapshot roster.
5615
- await this.ep.waitForPresenceSnapshot();
5616
- // Spawn-as-action: a HARD-PINNED name — an imperative `--name`/identity override
5617
- // or a manifest-declared name (opts.resolved) — that collides with a LIVE/provisioning/reserved
5618
- // incarnation REFUSES loud at accept, BEFORE any reserve/mint/bind, never a silent `_2`
5619
- // suffix (so an address-by-triple caller's pinned name can't be re-pointed). A PERSONA-DERIVED
5620
- // base name (no pin) keeps uniqueName's collision numbering, so multi-peer `spawn reviewer` twice
5621
- // still yields reviewer + reviewer_2. The alias-reuse gate above is orthogonal and already fired.
5622
- const hardPinned = opts.identity !== undefined || opts.resolved !== undefined;
5623
- const owner = this.launchOwner(opts, spawner);
5624
- const unavailable = new Set();
5625
- let name;
5626
- for (;;) {
5627
- if (hardPinned) {
5628
- if (this.nameInUse(identityName))
5629
- 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` };
5630
- name = identityName;
5631
- }
5632
- else {
5633
- try {
5634
- name = this.uniqueName(identityName, unavailable);
5635
- }
5636
- catch (e) {
5637
- return { ok: false, error: rejectionText(e) };
5638
- }
5639
- }
5640
- // In user mode the name is the principal's actor. A fresh nkey in static/open mode
5641
- // cannot collide with an earlier transcript. Use the connector's own startup proof.
5642
- const eventOwner = opts.owner ?? (spawner === undefined ? undefined : parsePrincipalKey(spawner)?.owner);
5643
- if (events && this.userMode && !runtime.spawnDelegated && eventOwner?.startsWith("u_")) {
5644
- try {
5645
- await checkEventStartup({
5646
- workspaceRoot: this.workspaceRoot,
5647
- space: this.space,
5648
- principal: { owner: eventOwner, actor: name },
5649
- retainedMessages: async () => {
5650
- try {
5651
- return (await this.ep.chatRetention()).senders;
5652
- }
5653
- catch (e) {
5654
- // Older hosts do not issue this metadata grant. Do not infer that the name is
5655
- // free or renumber it: preserve the requested candidate and let the launched
5656
- // agent's existing startup check decide. Every other read failure stays loud.
5657
- if (!isPermissionDenied(e))
5658
- throw e;
5659
- 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`);
5660
- throw new LegacyEventCountPermissionError();
5661
- }
5662
- },
5663
- });
5664
- }
5665
- catch (e) {
5666
- if (e instanceof EventStateConflictError && !hardPinned) {
5667
- unavailable.add(name);
5668
- continue;
5669
- }
5670
- if (!(e instanceof LegacyEventCountPermissionError))
5671
- return { ok: false, code: "failed-precondition", error: `cannot check event startup for ${eventOwner}.${name}: ${rejectionText(e)}` };
5672
- }
5673
- // Another spawn may have reserved the candidate while the disk/broker proof awaited.
5674
- // Recheck in the same synchronous window as the cap and reservation below.
5675
- if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
5676
- if (!hardPinned)
5677
- continue;
5678
- return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
5679
- }
5680
- }
5681
- break;
5682
- }
5683
- // The `chat_` prefix belongs to static chat sessions, whose aliases only `chat-session-open`
5684
- // draws. Checked once the name is fixed by either branch above, so a persona name, a numbered
5685
- // collision, a manifest name and a `--name` override all meet it, and before the reservation.
5686
- if (name.startsWith(CHAT_ALIAS_PREFIX))
5687
- return { ok: false, error: `the name "${name}" starts with "${CHAT_ALIAS_PREFIX}", which is reserved for chat sessions; pick another name` };
5688
- // THE PER-OWNER CEILING, read in the same synchronous window as the reserve below rather than
5689
- // beside the host capacity gate higher up: the count it takes must be the one the reservation
5690
- // lands against, or a burst of concurrent launches for one owner each reads a count taken
5691
- // before any of the others reserved, and they all pass. Nothing between here and the reserve
5692
- // awaits. It refuses BEFORE `onEffect`, so the launch states `not-executed` and leaves no
5693
- // name, no mint and no footprint behind.
5694
- const overCap = this.seatCapRefusal(owner);
5695
- if (overCap)
5696
- return { ok: false, code: overCap.code, error: overCap.message, ...(overCap.details ? { details: overCap.details } : {}) };
5697
- // Set once the agent's footprint (durables + creds, or the user-mode grant + secret files)
5698
- // exists; cleared when a live slot takes ownership. If it survives to `finally`, the spawn threw
5699
- // AFTER provisioning (buildLaunch / runtime.spawn) — the orphan-rollback tears it down. Carries
5700
- // `userOwner` for a user-mode spawn so that rollback runs the revoke+shred branch, not just the
5701
- // static durable teardown, which would leak the managed grant + files.
5702
- // The RESERVED custody reference rides the rollback object: a spawn that launched the seat and
5703
- // then threw (the activation CAS refuses a slot that is not this spawn's intent) reaches the
5704
- // `finally` with the handle only in a local, so without this the terminal has nothing to reap
5705
- // and retires over a live process. The slot row holds the same reference; this is the copy the
5706
- // in-process rollback can actually read.
5707
- let provisioned;
5708
- // A carried resume's seat-private home, removed by the finally unless a live seat took it.
5709
- let seatHome;
5710
- // The lifecycle whose inline snapshot this spawn wrote: removed by the finally unless a live seat
5711
- // took it. A write that failed sets nothing, so the finally never removes a file it did not make.
5712
- let snapshotUid;
5713
- // Taken right before the try so its finally is the only release; a refusal belongs above the
5714
- // allocation, where there is no name to give back.
5715
- hooks?.onEffect?.();
5716
- if (!hardPinned && name !== identityName)
5717
- this.namesCapacity.rememberNumbered(name);
5718
- this.namesCapacity.reserve(name, owner);
5719
- try {
5720
- // A stable nkey identity assigned at spawn: the public key is the agent's card.id (threaded via
5721
- // COTAL_ID); the seed is retained to mint matching creds later.
5722
- const identity = newIdentity();
5723
- // The incarnation's lifecycle UID (SPEC 13.1), minted ONCE per spawn: every lifecycle-keyed
5724
- // broker resource (dm_/dlv_/chathist_ durables, ACL row, memberships) and the teardown
5725
- // credential carry it, so a same-name successor's footprint is name-disjoint by construction.
5726
- //
5727
- // On the HOSTED enrollment arm (#1972) this value is PROVISIONAL. The host selects the
5728
- // authoritative uid, because it alone reads the retirement tombstones that make a uid
5729
- // permanently unusable, and the enrollment below rebinds this binding to what the host
5730
- // returned before anything durable is keyed by it.
5731
- let lifecycleUid = mintLifecycleUid();
5732
- // Reserve the seat's custody reference NOW, before any durable row and long before the
5733
- // launch. Minting it inside `runtime.spawn` (as it used to be) put the processes on disk
5734
- // before anything recorded how to address them, so a crash in that window left a live seat
5735
- // outside every manager and the successor retired the slot over it.
5736
- const custody = this.reserveCustody(runtime);
5737
- // ACCEPT SEAM (spawn-as-action): the incarnation identity is minted and NOTHING has
5738
- // been provisioned yet — the action serve path binds the goal + replies the acceptance HERE. A
5739
- // throw (bind conflict / duplicate goalId) aborts the spawn before provisioning: the catch below
5740
- // returns the failure and the finally releases the reserve, so a refused accept leaves zero
5741
- // footprint. The hosted enrollment arm is the exception, below. Blocking callers
5742
- // (roster boot) pass no hooks and this is a no-op.
5743
- // The ALLOCATED agent's addressing triple (the acceptance floor names what was actually
5744
- // allocated, never the requested-but-unallocated name). Static/open key on DEV_OWNER + the
5745
- // freshly-minted nkey; user mode keys on the derived owner (opts.owner, else a u_-owner spawner)
5746
- // + the alias — derived HERE where the mode and owner source are in scope.
5747
- const agentTriple = this.userMode
5748
- ? { owner, actor: name, uid: lifecycleUid }
5749
- : { owner, actor: identity.id, uid: lifecycleUid };
5750
- // THE EVENT GRANT, derived from the principal that was actually ALLOCATED and never from the
5751
- // display name. A display name is UI convenience: this mesh permits two live agents to carry
5752
- // one, so a name-keyed channel fuses two principals onto one subject and, in auth mode,
5753
- // authorizes both onto it from the same name-only value. `agentTriple` is the triple the child
5754
- // will connect as in both modes, so the grant and the subject the session derives from its own
5755
- // endpoint are the same derivation. Placed here rather than beside the refusal above
5756
- // because this is the first point at which that triple exists, and still before every
5757
- // provisioning call that consumes `allowPublish`.
5758
- // THE OWN-CHANNEL RULE FOR THE EVENT PLANE, and it is the first thing this seam does.
5759
- //
5760
- // An event channel carries a session's tool inputs and outputs, which makes it the most
5761
- // valuable read on the mesh, and `subscribe` / `allowSubscribe` / `allowPublish` are
5762
- // caller-supplied on every spawn door. On a per-user-auth mesh the ledger's spawner envelope
5763
- // already refuses a delegation wider than the spawner's own grant. On a STATIC mesh there is
5764
- // no ledger, so nothing attenuates a caller-supplied ACL at all, and a caller that may spawn
5765
- // may mint its child a read on any subject.
5766
- //
5767
- // What this rule asks is NOT who the caller is. That question has no answer on a static mesh:
5768
- // an untargeted spawn carries no authorization mode, and the admin reach a static caller
5769
- // holds is true by construction for everyone who can reach the handler. It asks whether the
5770
- // event channel being minted BELONGS TO THE AGENT BEING CREATED, which the manager knows
5771
- // because it has just allocated the principal.
5772
- //
5773
- // STATED LIMIT, because a fence whose gap is discovered later is worse than one whose gap is
5774
- // written down. `eventChannelPrincipal` decodes a principal and refuses anything that is not exactly
5775
- // two principal tokens, so a WILDCARD is not an event channel to it: `events.<owner>.>` and
5776
- // `events.>` pass this rule untouched and are governed by ordinary ACL authority, which on a
5777
- // user mesh is the envelope and on a static mesh is the spawn credential itself. So this
5778
- // closes the concrete form and not the wildcard form. It is worth having anyway: it is the
5779
- // form a caller writes when it knows which agent it wants to read, and the wildcard form is
5780
- // the one an operator writes deliberately for an observer.
5781
- const foreign = foreignEventChannels([...allowSubscribe, ...(allowPublish ?? [])], agentTriple.owner, agentTriple.actor);
5782
- if (foreign.length) {
5783
- // Throws rather than returning, because this seam is inside the accept body: the throw
5784
- // unwinds before `onAccepted`, so no goal is bound and no identity is minted, and the
5785
- // enclosing `finally` releases the reserved name. Returning here would be a value nobody
5786
- // reads.
5787
- throw new Error(`this spawn asks for another agent's event channel: ${foreign.join(", ")}. An ` +
5788
- `agent may be granted its OWN event plane and no other, because that plane carries the ` +
5789
- `session's tool inputs and outputs. Grant a reader out of band rather than through a ` +
5790
- `spawn: ${this.readerRemedy(agentTriple.owner, foreign[0])}`);
5791
- }
5792
- if (events)
5793
- allowPublish = [...(allowPublish ?? []), connector.eventChannel({ owner: agentTriple.owner, actor: agentTriple.actor })];
5794
- await hooks?.onReadinessWindow?.(readinessTimeoutMs);
5795
- // The hosted enrollment arm accepts only once the host has answered: the floor names the uid
5796
- // the agent runs at, and before the host picks it there is no such uid to name.
5797
- const hostedEnrollment = this.userMode && (opts.delegatedIntent !== undefined || this.remoteAuthority?.enrollManagedAgent !== undefined);
5798
- // A once spawn's task is accepted with the spawn, before anything launches.
5799
- let onceTask;
5800
- const acceptOnce = async (seat) => {
5801
- if (opts.once === undefined)
5802
- return;
5803
- onceTask = await hooks.onOnce({
5804
- seat: { name, ...seat }, prompt: prompt, spawner: this.spawnerName(spawner), deadlineMs: opts.once.deadlineMs, readinessDeadlineMs: readinessTimeoutMs,
5805
- ...(connector.retireAfterExit ? { retire: connector.name } : {}),
5806
- });
5807
- };
5808
- if (!hostedEnrollment) {
5809
- await hooks?.onAccepted?.({ name, identity, lifecycleUid, agentTriple });
5810
- await acceptOnce(agentTriple);
5811
- }
5812
- // In auth mode, mint the agent's creds from the space signing key and write them where the
5813
- // spawned session reads them (COTAL_CREDS path). Open mesh → no creds. Scope = the resolved
5814
- // subscribe/allowSubscribe (read) + allowPublish (post, default-deny).
5815
- let credsPath;
5816
- let issued;
5817
- let userLaunch;
5818
- let userOwner;
5819
- let enrolled;
5820
- if (this.userMode) {
5821
- const prep = await this.provisionUserAgent(name, {
5822
- eventPayloads,
5823
- spawner,
5824
- specOwner: opts.owner,
5825
- subscribe,
5826
- allowSubscribe,
5827
- allowPublish,
5828
- role,
5829
- capabilities,
5830
- label: ref,
5831
- lifecycleUid,
5832
- enrollmentCaller: authenticatedCaller ? { owner: authenticatedCaller.owner, actor: authenticatedCaller.actor } : undefined,
5833
- delegatedIntent: opts.delegatedIntent,
5834
- ...(opts.served !== undefined ? { spawnRequest: this.servedSpawnRequest(opts.served, authenticatedCaller) } : {}),
5835
- // Hold the name at the UID the host enrolled for the intent's user before any later local
5836
- // step runs, so no later failure, its refusal included, releases a lifecycle that only that
5837
- // user's retirement intent retires.
5838
- onEnrolled: opts.delegatedIntent
5839
- ? (enrolled) => {
5840
- provisioned = { id: principalKey(enrolled.owner, name).key, name, lifecycleUid: enrolled.lifecycleUid, userOwner: enrolled.owner, delegated: true, secretPaths: enrolled.files };
5841
- }
5842
- : undefined,
5843
- });
5844
- if ("error" in prep) {
5845
- if (prep.refused !== undefined)
5846
- hooks?.onUndone?.(prep.refused);
5847
- return { ok: false, error: prep.error, ...(prep.refused !== undefined ? { code: prep.refused } : {}), ...(prep.details ? { details: prep.details } : {}) };
5848
- }
5849
- // THE HOST'S UID WINS (#1972). On the local arm this is the value passed in, unchanged. On
5850
- // the hosted enrollment arm the host selected it, and from here every lifecycle-keyed thing
5851
- // this spawn records — the slot, the launch, the managed row, the teardown credential — must
5852
- // carry that value and not the provisional one, or the manager would address a footprint the
5853
- // host never created.
5854
- lifecycleUid = prep.lifecycleUid;
5855
- userLaunch = prep.launch;
5856
- userOwner = prep.owner;
5857
- enrolled = prep.enrolled;
5858
- provisioned = { id: principalKey(prep.owner, name).key, name, lifecycleUid, userOwner: prep.owner, ...(opts.delegatedIntent ? { delegated: true } : {}), secretPaths: prep.files, ...(custody ? { runtime: custody } : {}) };
5859
- if (hostedEnrollment) {
5860
- try {
5861
- await hooks?.onAccepted?.({ name, identity, lifecycleUid, agentTriple: { owner: prep.owner, actor: name, uid: lifecycleUid } });
5862
- await acceptOnce({ owner: prep.owner, actor: name, uid: lifecycleUid });
5863
- }
5864
- catch (e) {
5865
- // A refused accept rolls the enrollment back: the host's grant through `provisioned`, and
5866
- // this participant's secret family here, before the refusal returns. The hosted retirement
5867
- // removes it too, but only once the host's release completes.
5868
- const unshredded = [];
5869
- await this.shredUserSecrets(unshredded, prep.files);
5870
- if (unshredded.length)
5871
- throw new Error(`${rejectionText(e)}; cleanup failed: ${describeCleanupFailures(unshredded)}`, { cause: e });
5872
- throw e;
5873
- }
5874
- }
5875
- }
5876
- else if (this.auth) {
5877
- // §13.1: reserve + activate this incarnation's DURABLE identity BEFORE any
5878
- // broker footprint — the outer spawn intent first (slot row, phase `provisioning`),
5879
- // then the SHARED core activation saga (reserve uid -> gate frozen -> head CAS -> reopen
5880
- // LAST) over the key-pinned executor. The wire AUTHORITY principal is the incarnation-
5881
- // unique nkey; the alias is protected by the name-keyed slot + freeSlot hold.
5882
- 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 }));
5883
- // From here the DURABLE registration exists: arm the rollback BEFORE minting, so a throw
5884
- // between activation and provisioning still drives the exact-op static terminal (the
5885
- // finally's deprovision tolerates absent files; the broker teardown is idempotent).
5886
- provisioned = { id: identity.id, name, lifecycleUid, ...(custody ? { runtime: custody } : {}) };
5887
- // Pre-create the agent's bind-only chat (+ DM + role TASK) durables and mint its scoped creds
5888
- // — the shared onboarding step (provisionAgent). It runs on a short-lived PROVISIONER connection
5889
- // (NOT the supervisor's long-lived endpoint), so the DM/DLV consumer-create surface exists only
5890
- // for the provisioning window, never as a standing grant on the always-on daemon (residual 2).
5891
- // The credential is BOUNDED (`expiresAt`) — the manager push-renews it ahead of expiry.
5892
- const now = Math.floor(Date.now() / 1000);
5893
- const exp = now + MANAGED_STATIC_TTL_SEC;
5894
- // The credential is an ISSUANCE (SPEC 13.15): its caller rails carry a fresh generation
5895
- // and its ceiling is recorded as evidence bound to this incarnation's ledger family. The
5896
- // §13.1 ledger append (ledger BEFORE materialization) is the release's finalizer, so the
5897
- // evidence activates only once the row exists, and the row exists only after the evidence
5898
- // was staged. The agent learns the generation by reading the accepted row under its token.
5899
- // The generation's horizon bounds every renewal of this incarnation's credential.
5900
- issued = { generation: mintGeneration(now + STATIC_GENERATION_HORIZON_SEC), acceptedToken: mintAcceptedToken(), listing: true };
5901
- const issuedAgent = { name, id: identity.id, lifecycleUid };
5902
- const creds = await this.withIssuer((i) => this.withProvisioner((prov) => provisionAgent(prov, this.auth, identity, {
5903
- eventPayloads,
5904
- subscribe,
5905
- allowSubscribe,
5906
- allowPublish,
5907
- role,
5908
- capabilities,
5909
- ...(endpoints.length ? { endpointCapabilities: endpoints } : {}),
5910
- lifecycleUid,
5911
- expiresAt: exp,
5912
- issued,
5913
- issuance: this.issuanceSeam(i, "issue", issuedAgent, exp),
5914
- })));
5915
- // Store first (the source of truth), then materialize: `buildLaunch` hands the CHILD this
5916
- // file path, so the cred must exist as a file regardless of the store behind the seam. The
5917
- // manager's ONE store (injected for hosted, workstation FS locally).
5918
- const secrets = this.secrets;
5919
- // LIFECYCLE-KEYED (SPEC 13.1 on the FS): the incarnation's cred file embeds its uid, so a
5920
- // replayed/stale teardown can never address a same-name successor's credential.
5921
- credsPath = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, lifecycleUid).creds;
5922
- await secrets.put(agentSecretKeyForFile(credsPath, this.space), creds);
5923
- await materializeSecretToFile(secrets, agentSecretKeyForFile(credsPath, this.space), credsPath);
5924
- provisioned = { id: identity.id, name, lifecycleUid, secretPaths: { creds: credsPath }, ...(custody ? { runtime: custody } : {}) }; // footprint now exists — the finally rolls it back if the spawn throws
5925
- }
5926
- // Per-agent cwd overrides the manager's shared workspace root, so agents can be rooted at
5927
- // arbitrary folders/repos. A relative path resolves against the workspace root; omitted → the
5928
- // agent shares the workspace root (the prior, unchanged behavior).
5929
- // The realpath the admission check above already resolved (#385 item 2) — never re-resolved here,
5930
- // so the admission refusal and the launch cwd can never disagree on the same request.
5931
- const cwd = resolvedCwd ?? this.workspaceRoot;
5932
- // An inline persona's snapshot, and its catalog copy when saved, are written here: after the
5933
- // grant (the static issuance, the user-auth ledger, a hosted enrollment that may replace the
5934
- // uid) and before launch, so a refused grant leaves neither file and the snapshot carries the
5935
- // final uid. A copy that loses a create race throws, and the finally rolls the grant back.
5936
- if (inline) {
5937
- configPath = writeInlineSnapshot(this.workspaceRoot, lifecycleUid, { name, role, model, variant, description: def.description, body: def.persona });
5938
- snapshotUid = lifecycleUid;
5939
- if (catalogCopy)
5940
- saveAgentFile(agentFilePath(this.workspaceRoot, ref), catalogCopy, { createOnly: true });
5941
- }
5942
- if (configPath === undefined)
5943
- throw new Error("internal: the persona file is missing at launch");
5944
- const configSha256 = this.fileDigest(configPath);
5945
- const manifestPath = opts.launchRef
5946
- ? join(this.workspaceRoot, ".cotal", "run", `${opts.launchRef.runId}.json`)
5947
- : undefined;
5948
- const manifestSha256 = manifestPath ? this.fileDigest(manifestPath) : undefined;
5949
- const launchOpts = {
5950
- ...hostFields,
5951
- name,
5952
- role,
5953
- // User mode: the principal IS the identity (the endpoint derives card.id from owner+actor);
5954
- // no nkey id, no static creds.
5955
- id: userLaunch ? undefined : identity.id,
5956
- creds: credsPath,
5957
- userAuth: userLaunch,
5958
- // The incarnation's lifecycle UID: the agent endpoint binds its lifecycle-keyed dm/dlv/
5959
- // chathist durables by this exact value (its creds pin the same names, so a mismatch fails
5960
- // at the broker, never silently).
5961
- lifecycleUid,
5962
- acceptedToken: issued?.acceptedToken,
5963
- configPath,
5964
- model,
5965
- variant,
5966
- launchOptions,
5967
- // Fork an existing session into the mesh. Taken straight from `opts.resume` (the imperative
5968
- // control arg), never from `opts.resolved` — so the manifest launch path carries no resume by
5969
- // construction. An unsupported connector throws here before any process is spawned.
5970
- resume: opts.resume,
5971
- reopenSession,
5972
- // Initial prompt: the `--prompt` flag, or the manifest entry's `prompt:` on a resolved launch.
5973
- // A reopened session already had its kickoff turn, so it is not submitted again. A once
5974
- // seat gets its prompt as its one relayed task instead.
5975
- prompt: reopenSession === undefined && opts.once === undefined ? prompt : undefined,
5976
- ...(opts.once !== undefined ? { once: true } : {}),
5977
- // The SAME access set the creds were minted from (above) — forwarded so the session's
5978
- // runtime read/post set matches its credentials. Without this a manifest-spawned agent
5979
- // (materialized persona has no access frontmatter) has no channel set to read and joins
5980
- // nothing, even though its creds authorize the manifest's channels.
5981
- subscribe,
5982
- allowSubscribe,
5983
- allowPublish,
5984
- capabilities,
5985
- // Always the list the launch resolved, `[]` included, so the session never reads a persona
5986
- // file that may have changed since.
5987
- endpoints: copyPersonaEndpoints(personaEndpoints) ?? [],
5988
- events,
5989
- eventPayloads,
5990
- cwd,
5991
- };
5992
- // A delegated seat gets no local launch at all: no launch-material file, control token or
5993
- // manager path is produced for it, only the handoff its runtime writes into the child.
5994
- let spec;
5995
- let handle;
5996
- if (runtime.spawnDelegated) {
5997
- const handoff = this.composeManagedHandoff(enrolled.material, enrolled.actorToken);
5998
- if (this.delegatedLaunched.has(lifecycleUid))
5999
- throw new Error(`lifecycle ${lifecycleUid} was already handed to runtime "${runtime.kind}"; a lifecycle is handed off at most once`);
6000
- this.delegatedLaunched.add(lifecycleUid);
6001
- const holder = retainConnectorSeat(this.managerInstanceId, name);
6002
- handle = runtime.spawnDelegated({ agent, persona: readFileSync(configPath, "utf8"), managerInstanceId: this.managerInstanceId, role, model, variant, prompt, launchOptions: launchOptions, events, eventPayloads }, handoff);
6003
- this.watchConnectorHolder(handle, holder);
6004
- }
6005
- else {
6006
- if (carried) {
6007
- seatHome = join(this.workspaceRoot, ".cotal", "seat-homes", lifecycleUid);
6008
- mkdirSync(seatHome, { recursive: true, mode: 0o700 });
6009
- launchOpts.carried = { home: seatHome, transcript: carried.path, cwd };
6010
- }
6011
- spec = connector.buildLaunch(launchOpts);
6012
- if (carried)
6013
- this.transcripts.consume(opts.resumeClaim, opts.resume);
6014
- spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
6015
- handle = await this.spawnCustodied(runtime, name, spec, cwd, custody);
6016
- }
6017
- if (onceTask && !handle.waitForExit)
6018
- throw new Error(`once: runtime "${handle.kind}" cannot prove the seat's exit, which is what ends its task when the seat goes first`);
6019
- const launchedAt = Date.now();
6020
- hooks?.onLaunched?.(); // The "launched" progress edge (process spawned, pre-presence)
6021
- const managed = {
6022
- name,
6023
- role,
6024
- agent,
6025
- ...(seatHome ? { seatHome } : {}),
6026
- id: userLaunch ? principalKey(userLaunch.owner, name).key : identity.id,
6027
- lifecycleUid,
6028
- // The lifecycle-keyed family this spawn just materialized (absent on an open mesh) — the
6029
- // recorded truth teardown/preservation/health consume, never re-derived by name.
6030
- secretPaths: provisioned?.secretPaths,
6031
- ...(userLaunch ? { userOwner } : { seed: identity.seed }),
6032
- ...(opts.delegatedIntent ? { delegated: true } : {}),
6033
- ...(issued ? { issued } : {}),
6034
- spawner: spawner ?? this.ep.ref().id,
6035
- authorityParent: userLaunch && spawner && parsePrincipalKey(spawner) ? spawner : undefined,
6036
- startedAt: Date.now(),
6037
- handle,
6038
- control: spec?.control,
6039
- ...(spec ? {} : { handedOff: true }),
6040
- launch: {
6041
- runtime: runtime.kind,
6042
- source: opts.resolved
6043
- ? {
6044
- kind: "manifest",
6045
- runId: opts.launchRef?.runId,
6046
- requested: opts.launchRef?.requested ?? opts.resolved.name,
6047
- hash: opts.launchRef?.hash ?? opts.resolved.hash,
6048
- configPath,
6049
- configSha256,
6050
- manifestSha256,
6051
- }
6052
- : inline
6053
- ? { kind: "inline", ref, configPath, configSha256 }
6054
- : { kind: "persona", ref: opts.config ? identityName : ref, configPath, configSha256 },
6055
- cwd,
6056
- model,
6057
- variant,
6058
- // The kickoff prompt is part of the launch form: a stale-restart re-submits it, so the
6059
- // recorded launch must carry it for the restart gate (and preserve) to see it. A once
6060
- // seat's prompt is its task, which no relaunch may submit again.
6061
- prompt: onceTask ? undefined : prompt,
6062
- subscribe,
6063
- allowSubscribe,
6064
- allowPublish,
6065
- capabilities,
6066
- ...(personaEndpoints?.length ? { endpoints: copyPersonaEndpoints(personaEndpoints) } : {}),
6067
- events,
6068
- eventPayloads,
6069
- shareTools: opts.shareTools,
6070
- forkSource: opts.resume,
6071
- ...(opts.resume !== undefined && spec?.resumeRecordPath ? { resumeRecordPath: spec.resumeRecordPath } : {}),
6072
- ...(carried ? { carried: { transcriptSha256: carried.sha256, host: carried.sourceHost, transferredAt: carried.stagedAt } } : {}),
6073
- // Opaque values may contain secrets. Preserve only their keys and require the referenced
6074
- // persona/manifest to resolve the values again; imperative overrides have no safe payload.
6075
- unresolvedLaunchOptionKeys: opts.launchOptions && Object.keys(opts.launchOptions).length
6076
- ? Object.keys(opts.launchOptions).sort()
6077
- : undefined,
6078
- },
6079
- // A delegated agent is never restarted (SPEC 13.16), and a once seat never runs its task
6080
- // twice, so neither slot arms recovery.
6081
- ...(onceTask ? { once: { ref: onceTask.ref, ...(connector.retireAfterExit ? { retire: connector.name } : {}) } } : {}),
6082
- ...(spec && (connector.supportsSessionContinuation || opts.supervise !== undefined) && !opts.delegatedIntent && !onceTask
6083
- ? {
6084
- restart: {
6085
- opts: launchOpts,
6086
- sessionStatePath: spec.sessionStatePath,
6087
- crashes: [],
6088
- recovering: false,
6089
- armed: false,
6090
- ...(opts.supervise !== undefined ? { policy: opts.supervise } : {}),
6091
- },
6092
- }
6093
- : {}),
6094
- };
6095
- // The DURABLE slot takes the `active` phase before the in-memory row takes the
6096
- // name — a crash between the two leaves an active-but-unadopted slot the boot sweep
6097
- // terminalizes (never an untracked orphan). Static auth only; a failed CAS fails the spawn
6098
- // (the finally's rollback then drives the exact-op terminal).
6099
- if (this.auth && !this.userMode) {
6100
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: managed.id, lifecycleUid, alias: name }, async (t) => {
6101
- const slot = await readStaticSlot(t, DEV_OWNER, name);
6102
- if (slot === undefined || slot.row.lifecycleUid !== lifecycleUid || slot.row.phase !== "provisioning")
6103
- 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`);
6104
- // The custody reference rides the SAME CAS as activation: a crash after this write leaves
6105
- // an active slot a successor can reap by reference, never a live seat nobody addresses.
6106
- await casStaticSlot(t, { ...slot.row, phase: "active", ...(handle.reference ? { runtime: handle.reference } : {}) }, slot.revision);
6107
- });
6108
- }
6109
- this.agents.set(name, managed);
6110
- this.namesCapacity.placed(name);
6111
- if (managed.once)
6112
- this.watchOnceExit(managed);
6113
- // The live slot now owns teardown — freeSlot deprovisions this identity on exit — so the
6114
- // orphan-rollback in `finally` no longer applies to it.
6115
- provisioned = undefined;
6116
- seatHome = undefined;
6117
- snapshotUid = undefined;
6118
- // #159 B1: reply on a REAL outcome, not a timer. Wait for the agent to actually join the mesh
6119
- // (presence) → started, the child to exit → failed (with its last output; already reaped), or
6120
- // neither in time → uncertain. `✓ started` therefore means "it joined", never just "a process
6121
- // launched", except for a launch whose options make the harness wait for the operator first: that
6122
- // one is ready once its process runs, and its reply names the screen it waits at.
6123
- const operator = connector.waitsForOperator?.(launchOptions);
6124
- const readiness = await this.awaitReadiness(managed, readinessTimeoutMs, operator === undefined ? {} : { operator });
6125
- // Deliberately stopped mid-launch: reaped by onExit, and the despawn/stop path owns the
6126
- // goal terminal. Return BEFORE the failed/uncertain arms so this emits no competing
6127
- // outcome and does not re-arm an exit watcher on an agent already gone.
6128
- if (!readiness.ok && readiness.deliberate) {
6129
- hooks?.onTerminalDeferred?.();
6130
- return { ok: false, error: readiness.detail };
6131
- }
6132
- if (!readiness.ok && !readiness.uncertain) { // failed → already reaped
6133
- // A reopen fails before readiness when the host no longer has the recorded session, which
6134
- // is refused rather than replaced by an empty one; name the record that pins it.
6135
- const error = reopenSession === undefined ? readiness.detail
6136
- : `${readiness.detail} (continuity: exact was reopening recorded session ${reopenSession}; if the harness no longer has it, ` +
6137
- `remove ${join(this.workspaceRoot, ".cotal", "continuity", `${name}.json`)} to start a new session)`;
6138
- if (managed.once)
6139
- managed.once.stopReason ??= "launch-failed";
6140
- await hooks?.onOutcome?.({ kind: "failed", data: { error } });
6141
- return { ok: false, error };
6142
- }
6143
- // Started OR uncertain: the agent stays managed, so wire the ongoing exit reaper (it reaps a later
6144
- // death — including one that follows an `uncertain` verdict, which deliberately does NOT deprovision).
6145
- if (!readiness.ok) {
6146
- this.watchExit(managed);
6147
- if (managed.launch.carried)
6148
- void this.refuseLateCarriedFork(managed, readinessTimeoutMs);
6149
- // A once seat is never left running with nothing to do, and its stop does not wait on the
6150
- // spawn's terminal, whose write can stall. The spawn keeps that terminal: the stop lets go
6151
- // of the spawn goal first. Its task was never served and is cancelled with the verdict.
6152
- if (managed.once) {
6153
- this.agentGoals.delete(managed.name);
6154
- this.stopOnceSeat(managed, "readiness-timeout");
6155
- }
6156
- await hooks?.onOutcome?.({ kind: "uncertain", data: { reason: readiness.detail, ...(readiness.running ? { running: true } : {}) } });
6157
- return { ok: false, error: readiness.detail };
6158
- }
6159
- // A once seat whose connector needs a confirmed startup is served only on that outcome. Any
6160
- // other ends it like a seat that never joined: stopped before the failed terminal, and its
6161
- // task, never served, cancelled with the verdict.
6162
- if (onceTask && connector.onceNeedsConfirmed !== undefined) {
6163
- const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
6164
- if (managed.terminalizing || this.leaseStopping) {
6165
- hooks?.onTerminalDeferred?.();
6166
- return { ok: false, error: `${name} was stopped before its startup ended` };
6167
- }
6168
- if (startup !== "confirmed") {
6169
- const watch = { ready: "opened its input screen without the prompt", failed: "failed", exited: "saw the seat exit", pending: "had not ended" }[startup];
6170
- const error = `${name} joined, but ${connector.onceNeedsConfirmed}: its startup watch ${watch}, so it cannot take a once task`;
6171
- this.watchExit(managed);
6172
- this.agentGoals.delete(managed.name);
6173
- managed.once.stopReason ??= "launch-failed";
6174
- this.stopOnceSeat(managed, "launch-failed");
6175
- await hooks?.onOutcome?.({ kind: "failed", data: { error } });
6176
- return { ok: false, error };
6177
- }
6178
- }
6179
- // A plain seat on such a connector starts whatever its startup showed. One whose watch opened the
6180
- // input screen without the prompt is not woken by mesh traffic, and the spawn says so instead of
6181
- // starting it silently without push (#5737).
6182
- if (!onceTask && connector.idleWakeNeedsConfirmed !== undefined && runtime.reportsStartupOutcome) {
6183
- const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
6184
- if (managed.terminalizing || this.leaseStopping) {
6185
- hooks?.onTerminalDeferred?.();
6186
- return { ok: false, error: `${name} was stopped before its startup ended` };
6187
- }
6188
- if (startup === "ready") {
6189
- managed.startupNotice = connector.idleWakeNeedsConfirmed;
6190
- console.error(`! ${name}: ${connector.idleWakeNeedsConfirmed}`);
6191
- }
6192
- }
6193
- if (managed.launch.carried) {
6194
- const refused = await this.refuseCarriedFork(managed, readinessTimeoutMs);
6195
- if (refused !== undefined && managed.terminalizing) {
6196
- hooks?.onTerminalDeferred?.();
6197
- return { ok: false, error: refused };
6198
- }
6199
- if (refused !== undefined) {
6200
- this.stopHandle(managed, false, "carried-fork-refused");
6201
- this.trackStoppedHandle(managed, true, "carried-fork-refused");
6202
- await hooks?.onOutcome?.({ kind: "failed", data: { error: refused } });
6203
- return { ok: false, error: refused };
6204
- }
6205
- }
6206
- if (managed.restart) {
6207
- if (connector.supportsSessionContinuation) {
6208
- try {
6209
- await this.armSessionRecovery(managed);
6210
- // The capability flags are only a claim. An exact seat is recorded once the connector
6211
- // has proved its session over its authenticated control endpoint, never before.
6212
- if (exact && !managed.restart.armed)
6213
- throw new Error("continuity: exact needs the connector to prove its session over an authenticated control endpoint, and it supplied none");
6214
- managed.launch.sessionId = this.readManagedSession(managed);
6215
- if (reopenSession !== undefined && managed.launch.sessionId !== reopenSession)
6216
- throw new Error(`continuity: exact asked for session ${reopenSession}, the connector bound ${managed.launch.sessionId}`);
6217
- if (exact) {
6218
- managed.continuity = { space: this.space, name, connector: agent, cwd };
6219
- this.recordContinuity(managed, managed.launch.sessionId);
6220
- }
6221
- }
6222
- catch (error) {
6223
- const detail = `${managed.name} joined, but its exact host session could not be bound for supervised recovery: ${rejectionText(error)}`;
6224
- this.stopHandle(managed, false, "session-bind-failed");
6225
- this.trackStoppedHandle(managed, true, "session-bind-failed");
6226
- await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
6227
- return { ok: false, error: detail };
6228
- }
6229
- }
6230
- else {
6231
- managed.restart.armed = true;
6232
- }
6233
- if (managed.restart.policy) {
6234
- try {
6235
- this.recordSeat(managed);
6236
- }
6237
- catch (error) {
6238
- const detail = `${managed.name} joined, but supervise cannot cover a manager restart for it: ${rejectionText(error)}`;
6239
- this.stopHandle(managed, false, "supervise-record-failed");
6240
- this.trackStoppedHandle(managed, true, "supervise-record-failed");
6241
- await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
6242
- return { ok: false, error: detail };
6243
- }
6244
- }
6245
- }
6246
- // An unsupervised seat a successor could adopt keeps a record too; one that cannot be written
6247
- // costs only that adoption, so the spawn stands and the line says so.
6248
- if (!managed.restart?.policy)
6249
- this.refreshSeatRecord(managed);
6250
- this.watchExit(managed);
6251
- // Reply with the id the slot actually carries (user-mode: the owner.actor principal —
6252
- // presence, ps, and the manifest ownership ledger all key on it; the throwaway static nkey
6253
- // would never match and down -f would treat the agent as foreign).
6254
- // `lifecycleUid` rides the reply so callers that record this spawn (the manifest ledger) can
6255
- // later address the incarnation's lifecycle-keyed artifacts without re-deriving by name.
6256
- // OMIT an absent role: the goal terminal commits this data through the strict
6257
- // canonicalJson (undefined never coerces to null, SPEC 13.6), so a role-less spawn would
6258
- // otherwise fail its succeeded terminal. The CLI/connector already render an absent role as
6259
- // "no role", so dropping the key preserves the reply (surfaced by readiness:live).
6260
- // A host that granted other channels than this spawn asked for: the receipt carries both.
6261
- const acl = enrolled ? enrolledAcl({ allowSubscribe, allowPublish }, enrolled.material) : undefined;
6262
- 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 } : {}) } } : {}) };
6263
- // The task is served once the succeeded terminal is written, so a served task always has it
6264
- // and a successor reads it as the readiness verdict. Every failure arm above ran before it. A
6265
- // terminal this call did not commit never served the task: the seat is stopped, which cancels it.
6266
- const committed = await hooks?.onOutcome?.({ kind: "succeeded", data: okData });
6267
- if (onceTask && committed === true)
6268
- this.openOnceDelivery(onceTask.ref);
6269
- else if (onceTask) {
6270
- this.agentGoals.delete(managed.name);
6271
- managed.once.stopReason ??= "launch-failed";
6272
- this.stopOnceSeat(managed, "launch-failed");
6273
- }
6274
- return { ok: true, data: okData };
6275
- }
6276
- catch (e) {
6277
- // Failure after reserve (provision / launch threw): the slot was never live, so no cold-start
6278
- // was paid — the reserved rollback (finally) is enough, no cooling stamp.
6279
- // Keep the envelope's code and lifecycle details on the ControlReply so the serve boundary
6280
- // can carry the refusal's classification and barrier to the caller. An extension can throw
6281
- // any value, and an envelope's `message` is only typed as a string, so the refusal text always
6282
- // comes from rejectionText; telling an envelope apart is guarded because a thrown Proxy can
6283
- // throw from `instanceof` or from its own fields.
6284
- const error = rejectionText(e);
6285
- try {
6286
- if (e instanceof EpEnvelopeError)
6287
- return controlReplyFromThrown(e, error);
6288
- }
6289
- catch { /* not a readable envelope */ }
6290
- return { ok: false, error };
6291
- }
6292
- finally {
6293
- this.namesCapacity.release(name);
6294
- if (seatHome)
6295
- rmSync(seatHome, { recursive: true, force: true });
6296
- // A failed removal is logged, never thrown, so the grant's teardown below is still scheduled.
6297
- const snapshotGone = snapshotUid === undefined || this.dropInlineSnapshot(name, snapshotUid);
6298
- // Minted but never handed to a live slot (buildLaunch / runtime.spawn threw after mint) → tear the
6299
- // orphan down (detached, fail-loud) so a failed spawn leaves no creds/durables behind (#159 B).
6300
- if (provisioned) {
6301
- // Settled when this spawn wrote no snapshot or removed the one it wrote. A file its write
6302
- // refused is not this lifecycle's, so the terminal leaves the uid's path alone; a removal
6303
- // that failed is the terminal's to retry and report.
6304
- const orphan = { ...provisioned, ...(snapshotGone ? { snapshotSettled: true } : {}) };
6305
- // The host enrolled this UID for the intent's user, so only that user's retirement intent
6306
- // retires it, and its name stays held for retireDelegatedAgent.
6307
- const p = orphan.delegated ? parsePrincipalKey(orphan.id) : null;
6308
- if (p)
6309
- this.retirement.hold(orphan.name, { opId: managedRetirementOpId(orphan.lifecycleUid), owner: p.owner, actor: p.actor, target: orphan, startedAt: Date.now() });
6310
- this.trackDeprovision(orphan, "(orphaned spawn)");
6311
- }
6312
- }
6313
- }
4219
+ /** {@link SeatLaunch.spawnPersona}. */
4220
+ spawnPersona(...args) { return this.seatLaunch.spawnPersona(...args); }
4221
+ /** {@link SeatLaunch.spawnRun}. */
4222
+ spawnRun(caller, runId) { return this.seatLaunch.spawnRun(caller, runId); }
4223
+ /** {@link SeatLaunch.staticSpawnBound}. */
4224
+ staticSpawnBound(caller, run) { return this.seatLaunch.staticSpawnBound(caller, run); }
4225
+ /** {@link SeatLaunch.spawnBoundRefusal}. */
4226
+ spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") { return this.seatLaunch.spawnBoundRefusal(bound, grant, armsEvents, door); }
4227
+ /** {@link SeatLaunch.managedStaticInstanceReads}. */
4228
+ managedStaticInstanceReads(capabilities) { return this.seatLaunch.managedStaticInstanceReads(capabilities); }
6314
4229
  /** Preflight the whole inventory before launching its first process, then adopt each exact retained
6315
4230
  * principal without provisioning. A later runtime launch failure is reported per-agent, but malformed
6316
4231
  * or missing inventory material can never produce a partially resumed set. */
@@ -6708,6 +4623,7 @@ export class Manager {
6708
4623
  catch (e) {
6709
4624
  return { ok: false, error: rejectionText(e) };
6710
4625
  }
4626
+ await this.refreshUnavailableConnectors(connector.name, true);
6711
4627
  const harness = this.launchHarness(connector);
6712
4628
  if ("refusal" in harness)
6713
4629
  return { ok: false, error: harness.refusal };
@@ -7262,57 +5178,13 @@ export class Manager {
7262
5178
  occupancy() { return this.namesCapacity.occupancy(); }
7263
5179
  occupancyText(o) { return this.namesCapacity.occupancyText(o); }
7264
5180
  capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
7265
- /**
7266
- * The owner a launch belongs to, read ONCE so the per-owner ceiling, the agent's addressing
7267
- * triple and the user-mode provisioner cannot charge three different owners for one seat. A
7268
- * static or open mesh has one owner by construction; a user-auth mesh takes the spec's owner,
7269
- * else the owner of the principal that asked, which is what {@link provisionUserAgent} resolves
7270
- * from the same two values (it refuses outright where this falls back, so the two never disagree
7271
- * on an admitted launch).
7272
- */
7273
- launchOwner(opts, spawner) {
7274
- if (!this.userMode)
7275
- return DEV_OWNER;
7276
- const asked = spawner === undefined ? undefined : parsePrincipalKey(spawner)?.owner;
7277
- return opts.owner ?? (asked?.startsWith("u_") ? asked : DEV_OWNER);
7278
- }
7279
- /** The owner of a seat this manager supervises, by the same rule {@link launchOwner} admitted it
7280
- * under: a user-mode seat records its derived owner, and every other seat is the mesh's one owner. */
7281
- seatOwner(a) {
7282
- return a.userOwner ?? DEV_OWNER;
7283
- }
7284
- /**
7285
- * Live seats this manager holds for one owner: the seats it supervises, plus the launches it has
7286
- * reserved for that owner and not yet placed. It deliberately does NOT count cooling stamps — a
7287
- * cooling slot is a seat that already freed, and the recycle floor it holds is a global
7288
- * fork-bomb bound (P4c), not one tenant's occupancy. Mirrors {@link occupancy}'s reserved rule,
7289
- * so a reservation stops being counted twice the moment its seat reaches `agents`.
7290
- */
7291
- ownerSeats(owner) {
7292
- let seats = 0;
7293
- for (const a of this.agents.values())
7294
- if (this.seatOwner(a) === owner)
7295
- seats++;
7296
- seats += this.namesCapacity.ownerReservations(owner);
7297
- return seats;
7298
- }
7299
- /**
7300
- * The per-owner ceiling, consulted at accept: `undefined` admits the launch, and a refusal
7301
- * carries the owner's count and the cap so a caller can render a remedy and a script can decide
7302
- * without re-reading prose. Distinct from {@link capacityRefusal}, which bounds the HOST: that
7303
- * one frees when anyone stops a seat or a cooling slot expires, this one frees only when THIS
7304
- * owner stops one of its own, or the operator raises the cap, so they cannot share a sentence.
7305
- */
7306
- seatCapRefusal(owner) {
7307
- const cap = this.seatCap;
7308
- if (cap === SEAT_CAP_UNLIMITED)
7309
- return undefined;
7310
- const seats = this.ownerSeats(owner);
7311
- if (seats < cap)
7312
- return undefined;
7313
- return seatCapRefused(`owner ${owner} holds ${seats} of the ${cap} seat${cap === 1 ? "" : "s"} manager ${this.managerInstanceId} admits per owner; ` +
7314
- `stop one of that owner's seats, or ask the operator who runs this manager for a higher seat cap`, { owner, seats, cap });
7315
- }
5181
+ /** The owner a launch belongs to: {@link NamesCapacity.launchOwner}. */
5182
+ launchOwner(opts, spawner) { return this.namesCapacity.launchOwner(opts, spawner); }
5183
+ /** Live seats this manager holds for one owner: {@link NamesCapacity.ownerSeats}. */
5184
+ // @ts-expect-error TS6133: the seat-cap smoke reads this private count through a structural view.
5185
+ ownerSeats(owner) { return this.namesCapacity.ownerSeats(owner); }
5186
+ /** The per-owner ceiling at accept: {@link NamesCapacity.seatCapRefusal}. */
5187
+ seatCapRefusal(owner) { return this.namesCapacity.seatCapRefusal(owner); }
7316
5188
  // @ts-expect-error TS6133: retained fixtures call this private adapter through structural views.
7317
5189
  async opStop(args, caller, admin) {
7318
5190
  const name = String(args.name ?? "").trim();
@@ -7563,8 +5435,8 @@ export class Manager {
7563
5435
  /** The served manager-level health summary. Given an owner, `agentCount` counts only that owner's
7564
5436
  * seats, as `ps` lists them ({@link psOwnerFilter}), so a person reading a shared Manager does not
7565
5437
  * learn how many seats other owners hold on it. */
7566
- managerStatusData(ownerFilter) {
7567
- this.refreshUnavailableConnectors();
5438
+ managerStatusData(ownerFilter, setupClaude = false) {
5439
+ this.refreshUnavailableConnectors(undefined, setupClaude);
7568
5440
  return {
7569
5441
  instanceId: this.managerInstanceId,
7570
5442
  lifecycleUid: this.managerLifecycleUid,
@@ -7661,311 +5533,21 @@ export class Manager {
7661
5533
  }
7662
5534
  dialServeConnection(state, readCreds = () => state.creds, deadline) { return this.servePlane.dialServeConnection(state, readCreds, deadline); }
7663
5535
  registerManagerService() { return this.servePlane.registerManagerService(); }
7664
- /** Mint the standing `goal-writer` credential and STAGE it into this
7665
- * instance's §13.1 revocation family (`epcred.<e>.<iid>`), over the passed executor's `authKv`
7666
- * (the scoped `endpoint-serve-executor`, which holds the epcred write grant). The GRANT profile
7667
- * stays goal-writer-only (Q2, disjoint from the serve credential); only the FAMILY membership
7668
- * is shared, so the registration barrier's existing enumerate+revoke+evict catches the
7669
- * goal-writer on takeover/retire with NO barrier code change. Used both at registration (the run
7670
- * block's `authKv`) and at renewal (a fresh executor's), re-minting the SAME stable nkey with a
7671
- * fresh bounded exp: `mintCreds` stamps a random `issuance:` tag on `goal-writer` (`userTags`),
7672
- * so each issuance signs distinct bytes and stages a distinct ledger row (per-JWT `credentialId`
7673
- * digest) even within one second. */
7674
- async mintAndStageGoalWriter(authKv) {
7675
- const auth = this.auth;
7676
- const identity = this.goalWriterIdentity;
7677
- // The issuance gate + §13.1 revocation family are keyed by the REGISTRATION instanceId
7678
- // (the persisted logical id), NOT the per-process lifecycleUid — the barrier
7679
- // enumerates `epcred.<e>.<managerInstanceId>`, so the goal-writer must stage into that family.
7680
- const iid = this.managerInstanceId;
7681
- const creds = await mintCreds(auth, identity, "goal-writer", { goalWriter: { endpoint: MANAGER_ENDPOINT } });
7682
- const exp = inspectCredHealth(creds).exp;
7683
- if (exp === undefined)
7684
- throw new Error(`the goal-writer credential for ${MANAGER_ENDPOINT}/${iid} is unbounded; the §13.1 ledger row requires an expiry`);
7685
- const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
7686
- const observed = await fence.observe();
7687
- if (observed === null)
7688
- throw new Error(`the issuance gate for ${MANAGER_ENDPOINT}/${iid} vanished; the goal-writer cannot join its §13.1 revocation family`);
7689
- // The §13.1 open-and-commit fence, the SAME one the serve credential's own mint runs: a frozen
7690
- // gate refuses, and a gate that moved under us loses the CAS and revokes the staged row. Without
7691
- // it a barrier mid-takeover (already past its enumeration) would let this credential land
7692
- // ACTIVE in a family nothing revokes again.
7693
- await commitSiblingIssuance(fence, observed, {
7694
- credentialId: credentialIdOf(creds),
7695
- credentialKey: identity.id,
7696
- holderPrincipal: principalKey(DEV_OWNER, identity.id).key,
7697
- endpoint: MANAGER_ENDPOINT, lifecycleUid: iid, sourceChain: ["root"], state: "active", exp,
7698
- generation: observed.generation, processEpoch: observed.processEpoch,
7699
- registrationRevision: observed.registrationRevision, nameAuthorityRevision: observed.nameAuthorityRevision,
7700
- });
7701
- return creds;
7702
- }
7703
- /** #2073: dial the goal-writer's ONE standing connection and rebuild everything derived from it
7704
- * (the fence-resolving action context, the issuance-gate reader) — shared by the initial start
7705
- * and the closed-connection recovery ({@link onGoalWriterConnectionClosed}), so a redial never
7706
- * leaves the context bound to a dead socket. */
7707
- async dialGoalWriter(gw) {
7708
- const nc = await this.dial({
7709
- ...((this.auth || this.remoteAuthority) ? standaloneConnectOpts({ creds: () => gw.creds, tls: false }) : {}),
7710
- inboxPrefix: `_INBOX_${gw.identity.id}`,
7711
- maxReconnectAttempts: -1,
7712
- });
7713
- nc.closed().then((err) => { void this.onGoalWriterConnectionClosed(err ?? undefined); });
7714
- this.trackTransport(nc);
7715
- gw.nc = nc;
7716
- // The (i) fence resolver (SPEC 13.6): resolve an executing instance's CURRENT gate
7717
- // epoch. This manager reconciles only ITS OWN goals, so it resolves its own
7718
- // registration instanceId to this incarnation's serve-grant epoch; a foreign/retired instance
7719
- // is `null` (no current terminal to surface). A successor incarnation carries an ADVANCED epoch
7720
- // here, so its reads pick the current-epoch subject and the predecessor's terminal is fenced out.
7721
- gw.ctx = await actionContext(nc, this.space);
7722
- // The own-issuance-gate READER for the currency belt, on BOTH mesh modes. Reads
7723
- // `epgate.<e>.<iid>` over this connection; observe-only (stage/commit/revoke are never called
7724
- // through it — the goal-writer holds no gate/epcred WRITE grant, so a mis-call would
7725
- // broker-deny anyway).
7726
- //
7727
- // OPEN MESH IS NOT EXEMPT, and this is load-bearing. An open-mesh registration mints no
7728
- // credentials, so the §13.1 takeover barrier's revoke-and-evict loop enumerates an EMPTY family
7729
- // and is VACUOUS — yet it still advances processEpoch. The gate row itself DOES exist there
7730
- // (`provisionEndpointGateOpen`, over the authority stores the open serve path ensures), and a
7731
- // bare connection CAN read it (executed probe). So this belt is the ONLY thing standing between
7732
- // a deposed open-mesh incarnation and a wrong terminal on the one create-only result subject.
7733
- //
7734
- // NAME IT HONESTLY: on an open mesh this is a COOPERATIVE fence. The broker enforces nothing, so
7735
- // a hostile or non-conformant process can simply not run the check — the same guarantee class as
7736
- // every other open-mesh property. It is also a read-then-CAS, so it NARROWS the commit window
7737
- // rather than closing it. An AUTH mesh gets durable closure from the §13.1 barrier (revoke +
7738
- // cluster-verified eviction BEFORE the epoch advance); an open mesh gets none.
7739
- gw.gate = serveIssuanceGateKv(await new Kvm(nc).open(epAuthBucket(this.space)), this.space, { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId });
7740
- }
7741
- /** #2073: the goal-writer rail's closed-connection fault, the same bounded shape the serve rail
7742
- * uses ({@link onServeConnectionClosed}) through the same {@link boundedReconnect} helper:
7743
- * re-dial with the current credential (a transport blip needs nothing new), re-mint through the
7744
- * existing goal-writer renewal branch when the credential itself has expired, then re-attach.
7745
- * Unlike the serve rail this never exits the process on exhaustion (brief step 4: only the serve
7746
- * rail is the control plane the report lost) — it logs and leaves the credential to the next
7747
- * scheduled renewal pass. */
7748
- async onGoalWriterConnectionClosed(err) {
7749
- if (this.leaseStopping)
7750
- return;
7751
- console.error(`! manager goal-writer connection closed: ${err?.message ?? "unknown reason"}`);
7752
- const gw = this.goalWriter;
7753
- const recovered = await this.boundedReconnect("goal-writer", async () => {
7754
- if (!gw)
7755
- return false;
7756
- if (this.remoteAuthority)
7757
- await this.renewRemoteBeforeRedial("goal-writer", () => gw.creds);
7758
- else if (gw.creds !== undefined && inspectCredHealth(gw.creds).state !== "healthy") {
7759
- gw.creds = await this.withEndpointServeExecutor(({ authKv }) => this.mintAndStageGoalWriter(authKv));
7760
- this.goalWriterCreds = gw.creds;
7761
- }
7762
- await this.dialGoalWriter(gw);
7763
- console.error("manager goal-writer re-dialed");
7764
- return true;
7765
- }, inspectCredHealth(gw?.creds ?? "").state === "expired");
7766
- if (this.leaseStopping || recovered)
7767
- return;
7768
- console.error("! manager goal-writer could not be re-dialed; leaving the credential to the next renewal pass");
7769
- }
7770
- /** Spawn-as-action: stand up the standing self-mediated goal-writer connection +
7771
- * ActionContext. Mode-dual, mirroring {@link registerManagerService}: an AUTH mesh uses the
7772
- * scoped `goal-writer` credential already minted + family-STAGED inside registration's run block
7773
- * ({@link mintAndStageGoalWriter} — DISJOINT grant from the serve cred, SHARED §13.1 revocation
7774
- * family); an OPEN mesh uses a bare connection (no credential system to mint from - the broker
7775
- * enforces nothing). The connection presents the CURRENT credential on every (re)connect (a
7776
- * renewal is adopted without reconnecting the whole endpoint); the ActionContext bonds its
7777
- * KV + JS + JSM to this one connection and space (SPEC 13.4), so a composition mixup cannot splice
7778
- * goal state across brokers. */
7779
- async startGoalWriter() {
7780
- const identity = (this.auth || this.remoteAuthority) ? this.goalWriterIdentity : newIdentity();
7781
- // The mutable holder captured by the authenticator (mirrors the serve connection): a half-TTL
7782
- // renewal updates `gw.creds` and the next (re)connect presents the refreshed credential.
7783
- const gw = { nc: undefined, ctx: undefined, creds: (this.auth || this.remoteAuthority) ? this.goalWriterCreds : undefined, identity };
7784
- await this.dialGoalWriter(gw);
7785
- this.goalWriter = gw;
7786
- console.error(`manager goal-writer standing (endpoint ${MANAGER_ENDPOINT}, ${(this.auth || this.remoteAuthority) ? "scoped cred, §13.1 family-staged" : "open/bare"})`);
7787
- }
7788
- /** Retire the goal-writer connection (best-effort, both exit paths). */
7789
- async stopGoalWriter() {
7790
- const gw = this.goalWriter;
7791
- if (!gw)
7792
- return;
7793
- this.goalWriter = undefined;
7794
- await this.retireConnection(gw.nc);
7795
- }
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); }
7796
5542
  mintAndStageSessionLedger(authKv) { return this.servePlane.mintAndStageSessionLedger(authKv); }
7797
5543
  startSessionPlane() { return this.servePlane.startSessionPlane(); }
7798
5544
  stopSessionPlane() { return this.servePlane.stopSessionPlane(); }
7799
- /** The boot reconcile: a fresh incarnation (a manager restart takes a NEW
7800
- * instanceId, so the in-memory acceptance map starts empty) inherits the endpoint's accepted-but-
7801
- * unterminal goals from any predecessor. The local signer enumerates with an ephemeral PROVISIONER.
7802
- * A remote manager calls the authenticated host-owned scan, which keeps the sealed consumer and its
7803
- * lifecycle authority on the host; the instance executor, goal-writer, and supervisor hold NO records
7804
- * consumer grant. Settle each orphan so an accepted goal is NEVER dropped across a restart. Open mesh:
7805
- * a bare connection (the broker enforces nothing). Runs ONCE at start, BEFORE spawn-as-action begins
7806
- * accepting (the `goalReconcileDone` gate), so it never races a live goal's acceptance. Never
7807
- * fatal — a reconcile failure is logged and the gate opens either way. */
7808
- async reconcileGoalIndex() {
7809
- const gw = this.goalWriter;
7810
- if (!gw) {
7811
- this.goalReconcileDone = true;
7812
- return;
7813
- }
7814
- try {
7815
- let entries = [];
7816
- if (this.remoteAuthority) {
7817
- entries = (await this.remoteAuthority.scanGoalIndex()).map((entry) => ({
7818
- ref: { endpoint: entry.endpoint, caller: { owner: entry.owner, actor: entry.actor, uid: entry.uid }, goalId: entry.goalId },
7819
- iid: entry.iid,
7820
- ...(entry.allocated !== undefined ? { allocated: entry.allocated } : {}),
7821
- ...(entry.note !== undefined ? { note: entry.note } : {}),
7822
- }));
7823
- }
7824
- else {
7825
- const nc = this.auth
7826
- ? await this.dial({ ...standaloneConnectOpts({ creds: await mintCreds(this.auth, newIdentity(), "provisioner"), /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 })
7827
- : await this.dial({ maxReconnectAttempts: 0 });
7828
- try {
7829
- const kvm = new Kvm(nc);
7830
- await ensureAuthorityStores(await jetstreamManager(nc), kvm, this.space);
7831
- entries = await listGoalIndex(await kvm.open(recordsBucket(this.space)), MANAGER_ENDPOINT);
7832
- }
7833
- finally {
7834
- await drainAndClose(nc);
7835
- }
7836
- }
7837
- // Single-manager: EVERY inherited entry belongs to a DEAD predecessor (only one manager
7838
- // at a time), so all are reconciled. The `iid` field is the hook the multi-instance sweep
7839
- // filters on (skip a goal whose accepting `iid` is a still-LIVE sibling — never settle its goal).
7840
- for (const entry of entries) {
7841
- const key = goalKey(entry.ref);
7842
- if (this.goalAcceptances.has(key) || this.turnRelay.hasAcceptance(key))
7843
- continue; // never settle a goal THIS incarnation drives
7844
- try {
7845
- // A note marks a TURN entry: its relay is rebuilt (the hold is its bounded ending), never
7846
- // settled uncertain — the spawn arm's readiness window is the wrong ending for a relay.
7847
- if (entry.note !== undefined)
7848
- await this.adoptTurnGoal(entry);
7849
- else
7850
- await this.reconcileOneGoal(entry.ref, entry.iid);
7851
- }
7852
- catch (e) {
7853
- console.error(`! goal reconcile for ${entry.ref.goalId}: ${rejectionText(e)}`);
7854
- }
7855
- }
7856
- if (entries.length)
7857
- console.error(`goal-index boot reconcile: swept ${entries.length} inherited goal(s)`);
7858
- }
7859
- catch (e) {
7860
- console.error(`! goal-index boot reconcile failed: ${rejectionText(e)} - accepted goals from a predecessor may stay unsettled until the next restart`);
7861
- }
7862
- finally {
7863
- this.goalReconcileDone = true;
7864
- this.turnRelay.markReconciled(Date.now());
7865
- // A seat that pulled during the window was refused, and a predecessor may have died before
7866
- // its notice went out, so every seat holding a rebuilt turn is told once.
7867
- const seats = this.turnRelay.pendingSeats();
7868
- for (const seat of seats)
7869
- this.noticeSeatTurns(seat);
7870
- }
7871
- }
7872
- /** Settle ONE inherited goal by evidence: no goal record (a crash between the index write and the
7873
- * goal-record create) leaves the pointer untouched (never settle a goal that was never accepted,
7874
- * and clearing it would race a live goal mid-creation); a TERMINAL goal clears the index
7875
- * (converged — the predecessor committed but died before clearing); a NON-TERMINAL goal settles
7876
- * `uncertain` (the accepting incarnation is gone, so the success signal will never reach us — the
7877
- * bounded readiness outcome the plan maps the window to). Within the readiness window it arms a
7878
- * bounded, unref'd timer to settle at the deadline (an early uncertain would steal a still-possible
7879
- * success the substrate guards against). */
7880
- async reconcileOneGoal(ref, acceptedByIid) {
7881
- const gw = this.goalWriter;
7882
- if (!gw)
7883
- return;
7884
- const status = await readGoalStatus(gw.ctx, ref);
7885
- if (status === undefined)
7886
- return; // index points at no goal record: a dead pointer, left for honesty
7887
- if (GOAL_TERMINAL_STATES.includes(status.value.state)) {
7888
- await clearGoalIndex(gw.ctx, ref);
7889
- return;
7890
- }
7891
- const spec = await readGoalSpec(gw.ctx, ref);
7892
- if (spec === undefined)
7893
- return; // a status without its spec is garbled — leave for the next boot
7894
- // NEVER A CROSS-INSTANCE SETTLE. The accepting incarnation is recorded on the INDEX ENTRY
7895
- // itself (`iid`, written at accept), which is the honest coordinate: a same-instanceId restart
7896
- // inherits its predecessor's orphans, and a goal accepted by a DIFFERENT (possibly still-live)
7897
- // sibling is left for its owner. This replaces the goal spec's `executor` pin, which existed
7898
- // only to epoch-scope the terminal subject and is gone with it (§13.2 reserved subjects).
7899
- if (acceptedByIid !== this.managerInstanceId) {
7900
- console.error(`goal reconcile ${ref.goalId}: accepted by instance "${acceptedByIid}", not this incarnation "${this.managerInstanceId}"; left for its owner (never a cross-instance settle)`);
7901
- return;
7902
- }
7903
- const settle = async () => {
7904
- // A SUCCESSOR settling work it inherited: the committer is THIS incarnation at its CURRENT
7905
- // serve epoch, which is strictly greater than the goal's acceptedEpoch — the `committed >
7906
- // accepted` arm of the attribution rule, and the reason that arm has to exist.
7907
- 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
7908
- await clearGoalIndex(gw.ctx, ref);
7909
- };
7910
- const remaining = spec.value.acceptedAt + (spec.value.readinessDeadlineMs ?? this.readinessTimeoutMs) - Date.now();
7911
- if (remaining <= 0) {
7912
- await settle();
7913
- return;
7914
- }
7915
- console.error(`goal reconcile ${ref.goalId}: within the readiness window (${remaining}ms) - arming a bounded settle`);
7916
- const t = setTimeout(() => { settle().catch((e) => console.error(`! goal reconcile settle ${ref.goalId}: ${rejectionText(e)}`)); }, remaining + 100);
7917
- t.unref?.();
7918
- }
7919
- /** Publish a goal PROGRESS event on the caller-scoped epe subtree, over the SERVE
7920
- * connection (which holds the `epe.<e>.<iid>.<epoch>.>` egress grant; the goal-writer deliberately
7921
- * does not). The terminal rides a final event `phase:"terminal"` (the caller follows epe to
7922
- * the terminal; the durable result fact + inspect/ps are the reconcile authority). A dropped event
7923
- * is non-fatal (the terminal is authoritative in the journal). */
7924
- emitGoalProgress(ref, epoch, event) {
7925
- const nc = this.serviceServe?.nc;
7926
- if (!nc)
7927
- return;
7928
- try {
7929
- nc.publish(epeSubject(this.space, MANAGER_ENDPOINT, this.managerInstanceId, epoch, goalProgressTopic(ref)), new TextEncoder().encode(JSON.stringify({ v: 1, goalId: ref.goalId, ...event })));
7930
- }
7931
- catch (e) {
7932
- console.error(`! goal progress emit for ${ref.goalId} failed: ${rejectionText(e)}`);
7933
- }
7934
- }
7935
- /** The own-gate currency belt: before the goal-writer commits a terminal fact, the manager reads
7936
- * its OWN issuance gate epoch and REFUSES the commit if superseded. This NARROWS the window; it
7937
- * is not the fence. Layer 1 below is closed by the sibling-mint fence; layers 2 and 3 are not
7938
- * closed by any planned slice and must not be described as temporary.
7939
- *
7940
- * THE RESIDUAL, STACKED:
7941
- * 1. SIBLING-MINT INJECTION. A §13.1 barrier's revoke/evict loop closes only over the family
7942
- * SNAPSHOT IT ENUMERATED, so a sibling mint that observes the gate and stages a ledger row
7943
- * WITHOUT the observe/open/commit fence can be staged and released AFTER that enumerate and
7944
- * never be revoked. This layer is closed exactly where BOTH sibling mint sites
7945
- * ({@link mintAndStageGoalWriter}, {@link mintAndStageSessionLedger}) route their stage
7946
- * through `commitSiblingIssuance` (the revision-pinned CAS that makes a losing mint release
7947
- * nothing), and open exactly where they do not — state the mechanism, never the branch.
7948
- * 2. THE BARRIER WINDOW. A gate FREEZE neither kills this connection nor advances the epoch,
7949
- * and this belt compares `processEpoch` alone, so it still PASSES from barrier start until
7950
- * the reopen. A ledger revoke marks a row; it does not re-check a live JWT mid-publish. The
7951
- * durable kill is the CLUSTER-VERIFIED EVICTION, so a deposed manager can INITIATE new
7952
- * terminal publishes from barrier start until eviction is verified — not merely finish bytes
7953
- * already on the wire. Successor EXISTENCE and corpse DEATH are different phases, so the
7954
- * barrier's ordering licenses no conclusion about when the corpse stops being able to write.
7955
- * 3. OPEN MESH. No credential family exists, so the revoke/evict loop is vacuous and this belt
7956
- * is COOPERATIVE only: a non-conformant process simply does not run it.
7957
- * The named follow-up that would close 2 and 3 is the gate-linearized commit (routing the
7958
- * terminal through the issuance gate's own CAS), deliberately deferred as substrate territory. */
7959
- async assertGoalWriterEpochCurrent(epoch) {
7960
- const gate = this.goalWriter?.gate;
7961
- if (!gate)
7962
- return; // no goal-writer standing yet
7963
- const observed = await gate.observe();
7964
- if (observed === null)
7965
- 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)`);
7966
- if (observed.processEpoch !== epoch)
7967
- 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)`);
7968
- }
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); }
7969
5551
  /** A spawn's refusal reaches only its caller's terminal, so the manager also writes one line for it
7970
5552
  * to its own log, naming the request ID the caller printed, the persona and the reason. */
7971
5553
  async loggedSpawnRefusal(ctx, serve) {
@@ -8362,17 +5944,9 @@ export class Manager {
8362
5944
  * no hold; its goal still records the spawn's readiness budget, which a successor needs to settle
8363
5945
  * it. */
8364
5946
  acceptOnceTurn(o) { return this.turnRelay.acceptOnceTurn(o); }
8365
- /** How a once seat's startup watch ended, waited for until {@link STARTUP_OUTCOME_MS} after its
8366
- * launch or the readiness window, whichever is longer. A watch that has not ended by then, or a
8367
- * seat being stopped, answers what the handle reports at that moment. */
8368
- async awaitStartupOutcome(a, launchedAt, readinessTimeoutMs) {
8369
- const until = launchedAt + Math.max(readinessTimeoutMs, STARTUP_OUTCOME_MS);
8370
- for (;;) {
8371
- const outcome = a.handle.startupOutcome?.() ?? "pending";
8372
- if (outcome !== "pending" || a.terminalizing || this.leaseStopping || Date.now() >= until)
8373
- return outcome;
8374
- await new Promise((resolve) => setTimeout(resolve, 250));
8375
- }
5947
+ /** How a once seat's startup watch ended: {@link awaitStartupOutcome}. */
5948
+ awaitStartupOutcome(a, launchedAt, readinessTimeoutMs) {
5949
+ return awaitStartupOutcome(a, launchedAt, readinessTimeoutMs, () => this.leaseStopping);
8376
5950
  }
8377
5951
  /** Serve a once task from now on: its spawn's succeeded terminal is written. */
8378
5952
  openOnceDelivery(ref) { return this.turnRelay.openOnceDelivery(ref); }
@@ -8397,6 +5971,25 @@ export class Manager {
8397
5971
  this.trackStoppedHandle(a, false, cause);
8398
5972
  void this.cancelAgentGoal(a.name, "graceful");
8399
5973
  }
5974
+ /** Stop a seat this spawn just placed and track its exit: the stop first, so the terminalizing
5975
+ * latch is set before anything awaits, then the exit tracking. Both are synchronous. */
5976
+ stopAndTrack(a, cause) {
5977
+ this.stopHandle(a, false, cause);
5978
+ this.trackStoppedHandle(a, true, cause);
5979
+ }
5980
+ /** End a once seat before its task is served: let go of the spawn goal, record why it stopped if
5981
+ * `stopReason` is given and none is recorded yet, then stop the seat. Synchronous, in that order. */
5982
+ endOnceBeforeServe(a, reason, stopReason) {
5983
+ this.agentGoals.delete(a.name);
5984
+ if (stopReason !== undefined)
5985
+ a.once.stopReason ??= stopReason;
5986
+ this.stopOnceSeat(a, reason);
5987
+ }
5988
+ /** Put a launched seat in the agent table, then mark its reserved name placed. */
5989
+ place(name, a) {
5990
+ this.agents.set(name, a);
5991
+ this.namesCapacity.placed(name);
5992
+ }
8400
5993
  /** The once task's exit hook, on the handle the seat was launched with: whichever path ends the
8401
5994
  * seat, its proved exit cancels a task that has no terminal yet and discharges the seat's debt. An
8402
5995
  * exit that cannot be proved leaves both. */
@@ -8462,18 +6055,8 @@ export class Manager {
8462
6055
  spawnCustodied(runtime, name, spec, cwd, reserved) {
8463
6056
  return this.seatCustody.spawnCustodied(runtime, name, spec, cwd, reserved);
8464
6057
  }
8465
- /** Keep launch provenance independent of status and runtime wire contracts. */
8466
- watchConnectorHolder(handle, holder) {
8467
- if (!holder.active)
8468
- return;
8469
- holder.launched(handle.pid);
8470
- // A released handle may outlive its Manager. Only an authoritative exit removes
8471
- // identity-less holders, never a release or a failed stop request.
8472
- watchProvedExit(handle, () => holder.ended(), () => true);
8473
- }
8474
- recordSeat(a) {
8475
- return this.seatCustody.recordSeat(a);
8476
- }
6058
+ /** Keep launch provenance independent of status and runtime wire contracts: {@link watchConnectorHolder}. */
6059
+ watchConnectorHolder(handle, holder) { watchConnectorHolder(handle, holder); }
8477
6060
  refreshSeatRecord(a) {
8478
6061
  return this.seatCustody.refreshSeatRecord(a);
8479
6062
  }