@cotal-ai/manager 0.168.0 → 0.170.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/commands.js +1 -0
  2. package/dist/commands.js.map +1 -1
  3. package/dist/control-session.d.ts +5 -5
  4. package/dist/control-session.d.ts.map +1 -1
  5. package/dist/control-session.js +17 -65
  6. package/dist/control-session.js.map +1 -1
  7. package/dist/control-shutdown.d.ts +6 -7
  8. package/dist/control-shutdown.d.ts.map +1 -1
  9. package/dist/control-shutdown.js +9 -38
  10. package/dist/control-shutdown.js.map +1 -1
  11. package/dist/manager.d.ts +53 -603
  12. package/dist/manager.d.ts.map +1 -1
  13. package/dist/manager.js +329 -1950
  14. package/dist/manager.js.map +1 -1
  15. package/dist/names-capacity.d.ts +34 -2
  16. package/dist/names-capacity.d.ts.map +1 -1
  17. package/dist/names-capacity.js +53 -1
  18. package/dist/names-capacity.js.map +1 -1
  19. package/dist/run-hosting.d.ts +1 -0
  20. package/dist/run-hosting.d.ts.map +1 -1
  21. package/dist/run-hosting.js +26 -8
  22. package/dist/run-hosting.js.map +1 -1
  23. package/dist/seat-custody.d.ts +2 -0
  24. package/dist/seat-custody.d.ts.map +1 -1
  25. package/dist/seat-custody.js +10 -1
  26. package/dist/seat-custody.js.map +1 -1
  27. package/dist/seat-launch.d.ts +185 -0
  28. package/dist/seat-launch.d.ts.map +1 -0
  29. package/dist/seat-launch.js +522 -0
  30. package/dist/seat-launch.js.map +1 -0
  31. package/dist/seat-types.d.ts +362 -0
  32. package/dist/seat-types.d.ts.map +1 -0
  33. package/dist/seat-types.js +2 -0
  34. package/dist/seat-types.js.map +1 -0
  35. package/dist/serve-plane.d.ts +3 -0
  36. package/dist/serve-plane.d.ts.map +1 -1
  37. package/dist/serve-plane.js +18 -8
  38. package/dist/serve-plane.js.map +1 -1
  39. package/dist/service-child.js +2 -2
  40. package/dist/service-child.js.map +1 -1
  41. package/dist/session-recovery.d.ts +2 -4
  42. package/dist/session-recovery.d.ts.map +1 -1
  43. package/dist/session-recovery.js.map +1 -1
  44. package/dist/turn-relay.d.ts +397 -0
  45. package/dist/turn-relay.d.ts.map +1 -0
  46. package/dist/turn-relay.js +1068 -0
  47. package/dist/turn-relay.js.map +1 -0
  48. package/dist/user-provision.d.ts +152 -0
  49. package/dist/user-provision.d.ts.map +1 -0
  50. package/dist/user-provision.js +328 -0
  51. package/dist/user-provision.js.map +1 -0
  52. package/package.json +12 -12
package/dist/manager.js CHANGED
@@ -1,15 +1,17 @@
1
+ import { UserProvision } from "./user-provision.js";
2
+ import { TurnRelay, goalKey, caughtEnvelope, TURN_ANSWER_RETENTION_MS } from "./turn-relay.js";
1
3
  import { createHash, randomBytes } from "node:crypto";
2
4
  import { checkEventStartup, EventStateConflictError, isPermissionDenied, chatStream, drainAndClose, requestSafeReconnect } from "@cotal-ai/core";
3
- import { hostname, homedir } from "node:os";
4
- import { listDirectory } from "./list-dir.js";
5
+ import { hostname } from "node:os";
5
6
  import { credsAuthenticator, RequestError } from "@nats-io/transport-node";
6
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
7
- import { isAbsolute, join, resolve, sep } from "node:path";
7
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
8
+ import { join, resolve } from "node:path";
8
9
  import { parse as parseYaml } from "yaml";
9
10
  import Headless from "@xterm/headless";
10
- import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, MANAGED_HANDOFF_KIND, 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, provisionAgentDurables, registry, resolveAuthProvider, resolveReadAcl, runAgentBearer, runDriverCaller, saveAgentFile, eventChannel, eventChannelPrincipal, digestIdToken, capabilityWithin, grantOverreach, grantParts, isIssuedCaller, issuedSpawnerStanding, withIssuerSession, renderOnceTask, shownSpawner, } from "@cotal-ai/core";
11
- import { loadLaunchPersonaFile, PersonaSourceError, retainConnectorSeat } from "@cotal-ai/workspace";
12
- 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";
11
+ import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, registry, resolveAuthProvider, resolveReadAcl, saveAgentFile, eventChannelPrincipal, capabilityWithin, grantOverreach, } from "@cotal-ai/core";
12
+ import { retainConnectorSeat } from "@cotal-ai/workspace";
13
+ import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
14
+ import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, remintDaemonCreds, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
13
15
  import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
14
16
  import { Retirement } from "./retirement.js";
15
17
  import { ServePlane } from "./serve-plane.js";
@@ -22,21 +24,21 @@ export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js"
22
24
  import { LeaseKeeper } from "./lease-keeper.js";
23
25
  export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
24
26
  import { SessionRecovery } from "./session-recovery.js";
25
- import { SeatCustody } from "./seat-custody.js";
27
+ import { SeatCustody, watchConnectorHolder } from "./seat-custody.js";
28
+ import { SeatLaunch, ownLists, ownPersona, userMeshEndpointsRefusal } from "./seat-launch.js";
26
29
  import { withTimeout } from "./manager-timeout.js";
27
30
  import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
28
- import { inlinePersonaDir, inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, writeInlineSnapshot, parseLaunchSpec, persistLaunchSpec, readContinuityAssignment } from "./launch.js";
31
+ import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, writeInlineSnapshot, parseLaunchSpec, persistLaunchSpec, readContinuityAssignment } from "./launch.js";
29
32
  import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
30
33
  import { controlShutdown } from "./control-shutdown.js";
31
34
  import { RunHosting, servedRequestSubject } from "./run-hosting.js";
32
35
  import { enrolledAcl } from "./remote-authority.js";
33
- import { pendingEnrollment } from "./pending-enrollment.js";
34
36
  import { rejectionText, attemptCleanup, describeCleanupFailures } from "@cotal-ai/core";
35
37
  import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, supervisePolicy, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
36
38
  import { TranscriptReceiver } from "./transcript-receive.js";
37
39
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
38
40
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
39
- import { jetstream, jetstreamManager } from "@nats-io/jetstream";
41
+ import { jetstreamManager } from "@nats-io/jetstream";
40
42
  import { Kvm } from "@nats-io/kv";
41
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";
42
44
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
@@ -46,29 +48,18 @@ import { ManagerSessionPlane } from "./session/index.js";
46
48
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
47
49
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
48
50
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
49
- import { serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, requestGoalCancel, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, mintCheckpoint, MAX_SCHEDULE_MS, resumeCheckpoint, readCheckpointSettle, readCheckpointSpec, expireCheckpoint, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, seatCapRefused, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
51
+ import { serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, MAX_SCHEDULE_MS, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
50
52
  import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
51
53
  import { measureManagerVitals } from "./vitals.js";
52
54
  import { staticLifecycleTransport, activateStaticLifecycle, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, observeStaticSlot, listStaticSlotObservations, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
53
55
  import { CHAT_ALIAS_PREFIX, } from "./chat-session.js";
54
56
  // Capture the loaded package version before an installation can replace its files.
55
57
  const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
56
- /** Cadence of the turn-deadline sweep while turns are pending: the poll that turns an elapsed
57
- * hold's fire into its expired settle and commits the deadline terminal. Deadlines are
58
- * minutes-scale; a few seconds of lateness on the commit is invisible to the run. */
59
- const TURN_SWEEP_MS = 5_000;
60
- /** How long a settled turn's answer is kept so a RETRIED yield hears it instead of `not-found`.
61
- * The window a lost reply is retried in is seconds; five minutes is generous for that and short
62
- * enough that the map drains between bursts rather than growing for the process lifetime. */
63
- const TURN_ANSWER_RETENTION_MS = 5 * 60_000;
64
58
  /** A `once` spawn's task deadline when the caller names none: one hour from the spawn's accept. */
65
59
  const ONCE_DEFAULT_DEADLINE_MS = 60 * 60_000;
66
60
  /** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
67
61
  * stays and the turn sweep asks again. */
68
62
  const ONCE_RETIRE_MS = 60_000;
69
- /** The goal index's bound on a relay note (core `GOAL_INDEX_NOTE_MAX`). A once task's note must
70
- * fit it, and is refused at admission when it cannot. */
71
- const TURN_NOTE_MAX = 65536;
72
63
  /** Backstop for the detached-launch readiness race (#159 B1). `startAgent` waits on two REAL outcomes —
73
64
  * the assigned id joining the mesh (presence) = started, the child process exiting = failed — NOT a
74
65
  * liveness-inferring timer. This is only the last-resort bound for "neither happened in time": the launch
@@ -82,10 +73,6 @@ export const READINESS_TIMEOUT_MS = 30_000;
82
73
  * from its launch: the watch's 15s for the confirm prompt and 15s for its notice, plus 5s for the
83
74
  * last read. The readiness window applies when it is longer. */
84
75
  const STARTUP_OUTCOME_MS = 35_000;
85
- /** The cancel reason of an inherited once task whose spawn has no succeeded terminal. */
86
- const NEVER_SERVED = "never served: the manager restarted before the spawn's readiness verdict";
87
- /** Said by every settle of an inherited once task whose seat this manager does not hold. */
88
- const UNHELD_SEAT = "the manager does not hold the seat; it may still be running";
89
76
  /** How often the readiness race asks a runtime that streams no exit whether its child has exited, and
90
77
  * how long it waits past the window for the proof of its last read. An operator waits on this reply,
91
78
  * so it asks more often than the exit watch that outlives readiness. */
@@ -175,16 +162,6 @@ function resumeOwner(entry) {
175
162
  * dash) — what {@link Manager.psOwnerFilter} returns for an unparseable caller so a malformed
176
163
  * principal fail-closes to an empty `ps` instead of an unbounded one. */
177
164
  const NO_OWNER_MATCHES = "-no-owner-";
178
- /** A caught value as a lifecycle envelope, or undefined when it is not one. A thrown Proxy can throw
179
- * from `instanceof` itself, so the test runs inside the guard. */
180
- function caughtEnvelope(e) {
181
- try {
182
- return e instanceof EpEnvelopeError ? e : undefined;
183
- }
184
- catch {
185
- return undefined;
186
- }
187
- }
188
165
  /** Why a frozen manager gate stays frozen on an open mesh. Reconciliation must prove the holder
189
166
  * gone, and an open mesh runs no delivery daemon to prove it, so neither boot self-heal nor
190
167
  * `cotal manager reconcile` can reopen the gate there. */
@@ -240,37 +217,6 @@ function sameStrings(a, b) {
240
217
  function bearerEntryArgv() {
241
218
  return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
242
219
  }
243
- /** The caller keeps the arrays it passed, so a launch form is admitted with its own copies: a later
244
- * write to the caller's array cannot change what the manager grants, shares or preserves. */
245
- function ownLists(form) {
246
- return {
247
- ...form,
248
- ...(form.subscribe && { subscribe: [...form.subscribe] }),
249
- ...(form.allowSubscribe && { allowSubscribe: [...form.allowSubscribe] }),
250
- ...(form.allowPublish && { allowPublish: [...form.allowPublish] }),
251
- ...(form.capabilities && { capabilities: [...form.capabilities] }),
252
- ...(form.shareTools && { shareTools: [...form.shareTools] }),
253
- };
254
- }
255
- /** The inline record is admitted the same way, one level deeper: the record itself, its lists, and
256
- * each `endpoints` entry with its commands. It is still untrusted here, so a shape the validator
257
- * will refuse is copied as far as it goes and refused where it is read. */
258
- function ownPersona(record) {
259
- if (record === null || typeof record !== "object" || Array.isArray(record))
260
- return record;
261
- const owned = ownLists({ ...record });
262
- const endpoints = owned.endpoints;
263
- if (Array.isArray(endpoints))
264
- owned.endpoints = endpoints.map((e) => {
265
- if (e === null || typeof e !== "object" || Array.isArray(e))
266
- return e;
267
- const entry = { ...e };
268
- if (Array.isArray(entry.commands))
269
- entry.commands = [...entry.commands];
270
- return entry;
271
- });
272
- return owned;
273
- }
274
220
  /** Operator-facing phrasing per cause. Kept beside the union so adding a member without a sentence
275
221
  * is a type error rather than a blank in the log. The stop family's sentences carry the principal
276
222
  * from the cause, so they render through {@link STOP_CAUSE_TEXT} under the same exhaustive-Record
@@ -315,141 +261,12 @@ function onceStopReason(cause) {
315
261
  default: return cause;
316
262
  }
317
263
  }
318
- /** Why a revoked run starts no helper, the same words wherever the marker is read. */
319
- function revokedRunRefusal(runId, revoked) {
320
- return `run ${runId} was revoked by ${revoked.by} (${revoked.reason}); a revoked run starts no helper (SPEC 14.8)`;
321
- }
322
- const INLINE_PERSONA_KEYS = ["prompt", "role", "model", "variant", "description", "subscribe", "allowSubscribe", "allowPublish", "capabilities", "endpoints", "save"];
323
- /** Read an inline persona into the definition a catalog file would load as, refusing what a file
324
- * load refuses plus any shape the closed record does not take. The body is literal text: nothing in
325
- * it becomes a field, so a body that starts with `---` stays body. */
326
- function inlinePersonaDef(name, raw) {
327
- if (raw === null || typeof raw !== "object" || Array.isArray(raw))
328
- throw new Error("persona: expected an object");
329
- const rec = raw;
330
- const extra = Object.keys(rec).filter((k) => !INLINE_PERSONA_KEYS.includes(k));
331
- if (extra.length)
332
- throw new Error(`persona: unknown key ${extra[0]}; it takes ${INLINE_PERSONA_KEYS.join(", ")}`);
333
- const text = (k) => {
334
- const v = rec[k];
335
- if (v === undefined)
336
- return undefined;
337
- if (typeof v !== "string" || !v.trim())
338
- throw new Error(`persona.${k}: expected a non-blank string`);
339
- return v;
340
- };
341
- const list = (k) => {
342
- const v = rec[k];
343
- if (v === undefined)
344
- return undefined;
345
- if (!Array.isArray(v) || v.some((x) => typeof x !== "string"))
346
- throw new Error(`persona.${k}: expected an array of strings`);
347
- return [...v];
348
- };
349
- const prompt = text("prompt");
350
- if (prompt === undefined)
351
- throw new Error("persona.prompt: required; it is the persona body");
352
- if (rec.save !== undefined && typeof rec.save !== "boolean")
353
- throw new Error("persona.save: expected a boolean");
354
- const def = {
355
- name,
356
- persona: prompt.trim(),
357
- role: text("role"),
358
- model: text("model"),
359
- variant: text("variant"),
360
- description: text("description"),
361
- subscribe: list("subscribe"),
362
- allowSubscribe: list("allowSubscribe"),
363
- allowPublish: list("allowPublish"),
364
- capabilities: list("capabilities"),
365
- endpoints: parsePersonaEndpoints(rec.endpoints, "persona"),
366
- };
367
- // The checks a file load makes on these fields: channel names, and the read set within the read ACL.
368
- try {
369
- for (const ch of [...(def.subscribe ?? []), ...(def.allowSubscribe ?? []), ...(def.allowPublish ?? [])])
370
- assertValidChannel(ch);
371
- resolveReadAcl(def.subscribe ?? [], def.allowSubscribe);
372
- }
373
- catch (e) {
374
- throw new Error(`persona: ${rejectionText(e)}`);
375
- }
376
- return { def, save: rec.save === true };
377
- }
378
- /** The refusal a user-auth mesh gives a persona that names `endpoints`. */
379
- function userMeshEndpointsRefusal(door) {
380
- 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). ` +
381
- "Drop `endpoints` from the persona, and ask the operator to grant the helper with `cotal service-endpoint grant` once it runs.";
382
- }
383
264
  class LegacyEventCountPermissionError extends Error {
384
265
  }
385
266
  const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
386
267
  function participantKey(owner, actor, uid) {
387
268
  return `${owner}.${actor}.${uid}`;
388
269
  }
389
- function parseTurnNote(raw) {
390
- let o;
391
- try {
392
- o = JSON.parse(raw);
393
- }
394
- catch {
395
- return undefined;
396
- }
397
- if (o === null || typeof o !== "object")
398
- return undefined;
399
- const n = o;
400
- if (n.once !== undefined && n.once !== true)
401
- return undefined;
402
- if (typeof n.payload !== "string" || typeof n.holdEpoch !== "number")
403
- return undefined;
404
- if (typeof n.deadlineAt !== "number" && !(n.once === true && n.deadlineAt === undefined))
405
- return undefined;
406
- if (n.holdToken !== undefined && typeof n.holdToken !== "string")
407
- return undefined;
408
- if (n.handoffFrom !== undefined && typeof n.handoffFrom !== "string")
409
- return undefined;
410
- if (n.retire !== undefined && (n.once !== true || typeof n.retire !== "string"))
411
- return undefined;
412
- if (n.spawn !== undefined && (n.once !== true || typeof n.spawn !== "string"))
413
- return undefined;
414
- return {
415
- payload: n.payload, holdEpoch: n.holdEpoch,
416
- ...(typeof n.deadlineAt === "number" ? { deadlineAt: n.deadlineAt } : {}),
417
- ...(typeof n.holdToken === "string" ? { holdToken: n.holdToken } : {}),
418
- ...(typeof n.handoffFrom === "string" ? { handoffFrom: n.handoffFrom } : {}),
419
- ...(n.once === true ? { once: true } : {}),
420
- ...(typeof n.retire === "string" ? { retire: n.retire } : {}),
421
- ...(typeof n.spawn === "string" ? { spawn: n.spawn } : {}),
422
- };
423
- }
424
- function retireOf(d) {
425
- return d.retire === undefined ? undefined : { connector: d.retire, name: d.seat.name, uid: d.seat.uid };
426
- }
427
- /** The relay record of a `once` task. The prompt is only ever the string value of `context`, so a
428
- * prompt shaped like a run payload stays text and cannot add an `ask` or a `checkpoint`; the
429
- * `once` block is the manager's, rendered by the seat beside the prompt. */
430
- function onceTurnNote(o) {
431
- const payload = JSON.stringify({ context: o.prompt, once: { spawner: o.spawner, ...(o.deadlineAt !== undefined ? { deadlineAt: o.deadlineAt } : {}) } });
432
- const note = JSON.stringify({
433
- payload, holdEpoch: o.holdEpoch,
434
- ...(o.deadlineAt !== undefined ? { deadlineAt: o.deadlineAt } : {}),
435
- ...(o.holdToken !== undefined ? { holdToken: o.holdToken } : {}),
436
- once: true,
437
- ...(o.retire !== undefined ? { retire: o.retire } : {}),
438
- spawn: o.spawn,
439
- });
440
- return { payload, note };
441
- }
442
- /** A goal's key in the manager's maps: the caller triple and goal id the goal plane stores the
443
- * goal under, because a goal id is the caller's own (SPEC 13.6 item 1) and two callers may pick
444
- * the same one. Every part is a subject token, so the dotted join is unambiguous. */
445
- function goalKey(ref) {
446
- return `${ref.caller.owner}.${ref.caller.actor}.${ref.caller.uid}.${ref.goalId}`;
447
- }
448
- /** A turn hold's token, DERIVED from the relay key, so two callers' turns under one goal id never
449
- * share a hold. */
450
- function turnHoldToken(key) {
451
- return digestIdToken(`${key}:turn-deadline`);
452
- }
453
270
  /**
454
271
  * Event channels in `channels` that do NOT belong to `{owner, actor}`.
455
272
  *
@@ -502,6 +319,31 @@ class DeliveryAdminUnanswered extends Error {
502
319
  }
503
320
  /** How long one store challenge waits for the delivery daemon's answer. */
504
321
  const STORE_CHALLENGE_TIMEOUT_MS = 5_000;
322
+ /** The refusal a control instance with `execution: none` gives every launch, hosting, model and write door. */
323
+ const EXECUTION_NONE_REFUSAL = "execution: none forbids seat launch, workflow hosting, model inspection and caller-driven writes on this control instance; select the participant Manager with an instance-pinned manager-caller view";
324
+ /** The sha256 hex digest of a file's bytes. */
325
+ function fileDigest(path) {
326
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
327
+ }
328
+ /** The wire PRINCIPAL dot-form a managed agent's presence/control identity carries: user-mode
329
+ * entries already store it in `id`; static mints store the raw nkey there (the durable/teardown
330
+ * key), so the wire form derives under DEV_OWNER. Every comparison against an AUTHENTICATED wire
331
+ * id (presence card.id, control from.id) must go through this, never raw `a.id`. */
332
+ function managedPrincipal(a) {
333
+ return a.userOwner ? a.id : principalKey(DEV_OWNER, a.id).key;
334
+ }
335
+ /** How a once seat's startup watch ended, waited for until {@link STARTUP_OUTCOME_MS} after its
336
+ * launch or the readiness window, whichever is longer. A watch that has not ended by then, or a
337
+ * seat being stopped, answers what the handle reports at that moment. */
338
+ async function awaitStartupOutcome(a, launchedAt, readinessTimeoutMs, stopping) {
339
+ const until = launchedAt + Math.max(readinessTimeoutMs, STARTUP_OUTCOME_MS);
340
+ for (;;) {
341
+ const outcome = a.handle.startupOutcome?.() ?? "pending";
342
+ if (outcome !== "pending" || a.terminalizing || stopping() || Date.now() >= until)
343
+ return outcome;
344
+ await new Promise((resolve) => setTimeout(resolve, 250));
345
+ }
346
+ }
505
347
  /**
506
348
  * The agent supervisor: a long-lived mesh node that owns agent process lifecycle.
507
349
  * It serves control requests on the "manager" service and spawns/kills agents
@@ -531,6 +373,7 @@ export class Manager {
531
373
  /** See {@link ManagerOptions.installedExtensions}. */
532
374
  installedExtensions;
533
375
  expectedConnectorGeneration;
376
+ machineSetupCommand;
534
377
  executionState;
535
378
  /** One backend per kind a seat has asked for, beside {@link runtime}. The manager's own runtime
536
379
  * stays the default and is never replaced by a later seat's choice. */
@@ -632,59 +475,41 @@ export class Manager {
632
475
  /** The live spawn goal ref for each managed agent name, so a despawn MID-GOAL
633
476
  * drives the cancel path (transition -> cancel terminal). Cleared when the goal terminalizes. */
634
477
  agentGoals = new Map();
635
- /**
636
- * The turn relay's same-incarnation idempotency map ({@link goalAcceptances}'s twin), by
637
- * {@link goalKey}: a same-goal retry serves the identical acceptance; cross-incarnation retries
638
- * rebuild from the goal-index entry (its acceptance floor + note).
639
- *
640
- * One entry per turn this incarnation accepted: the acceptance a duplicate submission is served
641
- * from, and — once the turn settles — the answer a RETRIED yield is served from.
642
- *
643
- * A yield's reply can be lost, and the retry used to find the pending turn already deleted and
644
- * hear `not-found`, which a seat reads as "drop it": failure reported for work that committed.
645
- * The settled answer lives here for a bounded window instead, and the sweep drops it after,
646
- * which is also what keeps this map from being one entry per turn for the process lifetime.
647
- *
648
- * `ref` is the goal coordinates the durable terminal is published under. A late yield that
649
- * arrives after pendingTurns is gone and before `settled` is remembered (or after a concurrent
650
- * sweep dropped the settled field) still has to name that terminal, never `not-found`. The
651
- * index entry is not that answer: it is cleared at commit, and the yield path never consults it.
652
- *
653
- * `leftoverSince` is when the pending latch dropped. An unsettled leftover ages off that stamp,
654
- * never off `acceptance.deadlineAt`: a turn that expired after a long outage would otherwise be
655
- * pruned on the first sweep tick, taking the GoalRef with it, and a late yield in the retry
656
- * window would hear `not-found` again.
657
- */
658
- turnAcceptances = new Map();
478
+ turnRelayInstance;
479
+ get turnRelay() {
480
+ return this.turnRelayInstance ??= new TurnRelay({
481
+ goalWriter: () => this.goalWriter,
482
+ serviceServe: () => this.serviceServe,
483
+ space: this.space,
484
+ managerInstanceId: () => this.managerInstanceId,
485
+ execution: this.execution,
486
+ executionRefusal: this.executionRefusal(),
487
+ goalReconcileDone: () => this.goalReconcileDone,
488
+ readinessTimeoutMs: () => this.readinessTimeoutMs,
489
+ adoptsSeats: () => this.auth !== undefined && !this.userMode,
490
+ onceSeatReconciling: (uid) => this.staticLifecycle.pendingLifecycle(uid),
491
+ assertGoalWriterEpochCurrent: (epoch) => this.assertGoalWriterEpochCurrent(epoch),
492
+ emitGoalProgress: (ref, epoch, event) => this.emitGoalProgress(ref, epoch, event),
493
+ noticeSeatTurns: (seat) => this.noticeSeatTurns(seat),
494
+ turnExecutorEpoch: (name, owner, actor, uid) => this.turnExecutorEpoch(name, owner, actor, uid),
495
+ endOnceSeat: (pending, reason) => this.endOnceSeat(pending, reason),
496
+ findManagedByTarget: (target) => this.findManagedByTarget(target),
497
+ stopOnceSeat: (agent, reason) => this.stopOnceSeat(agent, reason),
498
+ watchOnceExit: (agent) => this.watchOnceExit(agent),
499
+ retireOnceSeat: (seat) => this.retireOnceSeat(seat),
500
+ forgetOnceWatch: (key) => { this.onceWatched.delete(key); },
501
+ });
502
+ }
659
503
  participants = new Map();
660
- /** Every relayed turn awaiting its seat's yield, by {@link goalKey}. The seat's `turn-pending` pull
661
- * scans it; the deadline sweep drives expiry; a seat reap stamps its entries `seatDiedAt`, which
662
- * the deadline terminal carries as `agentDownAt` so the run reads that death as L4002.
663
- * Rebuilt at boot from goal-index entries carrying a turn note. */
664
- pendingTurns = new Map();
665
- /** The deadline sweep behind {@link pendingTurns}: takes the hold's fire into an expired
666
- * settle and commits the deadline terminal. Unref'd; idle when no turn is pending. */
667
- turnSweepTimer;
668
- /** Once tasks whose ending is owed, by {@link goalKey}: the task can no longer run (its seat's
669
- * exit is proved, or it was never served), so it is cancelled if it has no terminal and its index
670
- * entry is dropped. A settle that fails stays here and the turn sweep retries it. */
671
- onceSettles = new Map();
672
504
  /** Once tasks whose seat's exit is watched: that exit, not the spawn's outcome, settles the debt. */
673
505
  onceWatched = new Set();
674
- /** Once tasks a predecessor accepted, by seat uid, until this incarnation binds the seat or
675
- * proves it gone. `readinessMs` bounds how long a seat no reconcile here can account for is
676
- * waited for. */
677
- onceInherited = new Map();
678
- /** Inherited once seats this manager does not hold whose task has a terminal, by lifecycle uid.
679
- * Every pull from one is answered `stop`, and its notice repeats until a pull has carried it. */
680
- onceStops = new Map();
681
- /** When the goal reconcile finished: the start of an inherited once task's wait for its seat. */
682
- goalReconcileDoneAt = 0;
683
506
  /** Process start, for the served `status` uptime. */
684
507
  startedAtMs = Date.now();
685
- /** Connector harness paths resolved ONCE at boot. Missing binaries do not stop unrelated manager
686
- * work, but they are named before the manager reports ready and remain visible in manager status. */
508
+ /** Connector harness inventory. Available paths stay pinned; unavailable rows are retried when
509
+ * launch, model lookup or status asks, without stopping unrelated Manager work. */
687
510
  connectorStatuses = [];
511
+ connectorRequirements = new Map();
512
+ claudeWakeRecheck;
688
513
  /** The boot inventory's warnings, printed once start completes, so a refused start prints none. */
689
514
  bootNotes = [];
690
515
  /** The complete boot task. stop() joins it after fencing static reconciliation, so a registration
@@ -717,6 +542,9 @@ export class Manager {
717
542
  userMode = false;
718
543
  namesCapacity = new NamesCapacity({
719
544
  userMode: () => this.userMode,
545
+ seatCap: () => this.seatCap,
546
+ managerInstanceId: () => this.managerInstanceId,
547
+ agents: () => this.agents.values(),
720
548
  authEnabled: () => this.auth !== undefined,
721
549
  maintenanceActive: () => this.maintenanceState === "active",
722
550
  roster: () => this.ep.getRoster(),
@@ -760,7 +588,7 @@ export class Manager {
760
588
  setSessionPlane: (value) => { this.sessionPlane = value; },
761
589
  sessionKeyRenewTimer: () => this.sessionKeyRenewTimer,
762
590
  setSessionKeyRenewTimer: (value) => { this.sessionKeyRenewTimer = value; },
763
- connectorStatuses: () => this.connectorStatuses,
591
+ connectorStatuses: () => { this.refreshUnavailableConnectors(); return this.connectorStatuses; },
764
592
  setGoalWriterIdentity: (value) => { this.goalWriterIdentity = value; },
765
593
  setGoalWriterCreds: (value) => { this.goalWriterCreds = value; },
766
594
  remoteStandingBudgetMs: REMOTE_STANDING_BUDGET_MS,
@@ -849,6 +677,7 @@ export class Manager {
849
677
  * does not re-acquire: a manager that is stopping never puts its own key back. It also closes the
850
678
  * lifecycle fence ({@link beginLifecycle}), so no spawn can launch a seat the stop never sees. */
851
679
  leaseStopping = false;
680
+ shutdownReadiness = new AbortController();
852
681
  /** The class-2 renewal owner's half-TTL schedule; armed only on auth meshes. */
853
682
  credRenewTimer;
854
683
  resumeCredRenewal;
@@ -1015,6 +844,41 @@ export class Manager {
1015
844
  adoptSeat: (row, record) => this.adoptSeat(row, record),
1016
845
  dropSeatRecord: (a) => this.dropSeatRecord(a),
1017
846
  });
847
+ /** User-mode provisioning owns no manager state: each dependency reads through at its use. */
848
+ userProvision = new UserProvision({
849
+ space: () => this.space,
850
+ workspaceRoot: () => this.workspaceRoot,
851
+ secrets: () => this.secrets,
852
+ managerInstanceId: () => this.managerInstanceId,
853
+ runHosting: () => this.runHosting,
854
+ remoteAuthority: () => this.remoteAuthority,
855
+ deprovision: (target) => this.deprovision(target),
856
+ withProvisioner: (fn) => this.withProvisioner(fn),
857
+ shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
858
+ bearerEntryArgv,
859
+ });
860
+ /** The launch pipeline's leaf steps. Every dependency reads through at its use. */
861
+ seatLaunch = new SeatLaunch({
862
+ space: () => this.space,
863
+ servers: () => this.servers,
864
+ workspaceRoot: () => this.workspaceRoot,
865
+ installedExtensions: () => this.installedExtensions,
866
+ ep: () => this.ep,
867
+ auth: () => this.auth,
868
+ userMode: () => this.userMode,
869
+ managerInstanceId: () => this.managerInstanceId,
870
+ serviceServe: () => this.serviceServe,
871
+ runHosting: () => this.runHosting,
872
+ connectorStatuses: () => this.connectorStatuses,
873
+ execution: () => this.execution,
874
+ requiredRuntime: () => this.requiredRuntime,
875
+ meshMode: () => this.meshMode,
876
+ executionRefusal: () => this.executionRefusal(),
877
+ nameError: (name) => this.nameError(name),
878
+ canReadPersona: (owner, caller, admin) => this.canReadPersona(owner, caller, admin),
879
+ epAdminReach: (caller) => this.epAdminReach(caller),
880
+ startAgent: (opts) => this.startAgent(opts),
881
+ });
1018
882
  constructor(opts) {
1019
883
  if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
1020
884
  throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
@@ -1055,6 +919,7 @@ export class Manager {
1055
919
  this.secretStoreIdentity = injectedSecretStoreIdentity(opts.secretStore);
1056
920
  this.installedExtensions = opts.installedExtensions ?? false;
1057
921
  this.expectedConnectorGeneration = MANAGER_VERSION;
922
+ this.machineSetupCommand = opts.machineSetupCommand;
1058
923
  this.pooled = opts.pooled === true;
1059
924
  this.executionState = opts.execution === "none" ? { kind: "none" } : { kind: "runtime" };
1060
925
  if (!this.remoteAuthority) {
@@ -1114,7 +979,7 @@ export class Manager {
1114
979
  return this.executionState.kind;
1115
980
  }
1116
981
  executionRefusal() {
1117
- 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";
982
+ return EXECUTION_NONE_REFUSAL;
1118
983
  }
1119
984
  /** A defensive last barrier, not a substitute Runtime. Entry admission runs before effects. */
1120
985
  get requiredRuntime() {
@@ -2678,9 +2543,7 @@ export class Manager {
2678
2543
  }
2679
2544
  return undefined;
2680
2545
  }
2681
- fileDigest(path) {
2682
- return createHash("sha256").update(readFileSync(path)).digest("hex");
2683
- }
2546
+ fileDigest(path) { return fileDigest(path); }
2684
2547
  fileDigestOrEmpty(path) {
2685
2548
  try {
2686
2549
  return this.fileDigest(path);
@@ -3026,6 +2889,7 @@ export class Manager {
3026
2889
  }
3027
2890
  async stopOnce(withAgents) {
3028
2891
  this.leaseStopping = true;
2892
+ this.shutdownReadiness.abort();
3029
2893
  clearTimeout(this.credentialPushRetry);
3030
2894
  this.credentialPushRetry = undefined;
3031
2895
  this.transcripts?.stop();
@@ -3419,7 +3283,7 @@ export class Manager {
3419
3283
  * readiness reads the same status; the maintenance fence refuses every other command in both
3420
3284
  * states. The read is counted in `lifecycleInFlight` like any admitted operation and released in
3421
3285
  * `finally`, so a drain waits at most for one status snapshot; the membership gate still
3422
- * applies. `preserving` and a stopping manager stay fenced. Status writes nothing. */
3286
+ * applies. `preserving` and a stopping manager stay fenced. */
3423
3287
  async serveObservation(ctx, fn) {
3424
3288
  const preserved = this.maintenanceState === "preserved" && !this.resumeRequired;
3425
3289
  const resumePending = this.maintenanceState === "active" && this.resumeRequired;
@@ -3523,9 +3387,7 @@ export class Manager {
3523
3387
  const agent = [...this.agents.values()].find((a) => this.managedPrincipal(a) === caller && a.lifecycleUid === ctx.subject.caller.uid);
3524
3388
  if (agent === undefined || agent.launch.capabilities?.includes("run"))
3525
3389
  return;
3526
- const pending = [...this.pendingTurns.values()].find((p) => p.seat.owner === ctx.subject.caller.owner
3527
- && p.seat.actor === ctx.subject.caller.actor
3528
- && p.seat.uid === ctx.subject.caller.uid);
3390
+ const pending = this.turnRelay.pendingForSeat(ctx.subject.caller);
3529
3391
  if (pending === undefined)
3530
3392
  throw new EpEnvelopeError("permission-denied", `run-answer is allowed to this baseline seat only for a pending ask or escalation addressed to its own incarnation; none is pending for ${agent.name}`);
3531
3393
  let payload;
@@ -3692,7 +3554,12 @@ export class Manager {
3692
3554
  vitals: (ctx) => this.serveGated(ctx, () => measureManagerVitals()),
3693
3555
  // A remote Manager files every seat under its own owner, so only a user mesh's shared local
3694
3556
  // Manager narrows the count, and status never waits on a remote admin check.
3695
- status: (ctx) => this.serveObservation(ctx, async () => this.managerStatusData(this.remoteAuthority ? undefined : await this.psOwnerFilter(ctx.subject.caller, false))),
3557
+ status: (ctx) => this.serveObservation(ctx, async () => {
3558
+ const ownerFilter = this.remoteAuthority ? undefined : await this.psOwnerFilter(ctx.subject.caller, false);
3559
+ // The daemon's status deadline is shorter than an install. Report the current inventory
3560
+ // without waiting for the install, which has its own lifecycle admission below.
3561
+ return this.managerStatusData(ownerFilter, !this.resumeRequired);
3562
+ }),
3696
3563
  ps: (ctx) => this.serveGated(ctx, async () => this.list(await this.psOwnerFilter(ctx.subject.caller, false))),
3697
3564
  inspect: (ctx) => this.serveGated(ctx, async () => {
3698
3565
  const name = String(args(ctx).name ?? "").trim();
@@ -3730,7 +3597,7 @@ export class Manager {
3730
3597
  if (observed !== undefined && observed.slotPhase !== "retired")
3731
3598
  throw new EpEnvelopeError("failed-precondition", `no live agent "${name}"; durable state contradicts absence ${renderStaticSlotObservation(observed)}`, [observed]);
3732
3599
  }
3733
- throw new EpEnvelopeError("not-found", `no agent "${name}"`);
3600
+ throw new EpEnvelopeError("not-found", `no agent "${name}"`, undefined, "not-executed");
3734
3601
  }
3735
3602
  return row;
3736
3603
  }),
@@ -3998,13 +3865,8 @@ export class Manager {
3998
3865
  scopeOf: (owner, actor) => resolveAuthProvider().actorScope({ dir: userAuthStateDir(this.workspaceRoot, this.space), owner, actor }),
3999
3866
  });
4000
3867
  }
4001
- /** The wire PRINCIPAL dot-form a managed agent's presence/control identity carries: user-mode
4002
- * entries already store it in `id`; static mints store the raw nkey there (the durable/teardown
4003
- * key), so the wire form derives under DEV_OWNER. Every comparison against an AUTHENTICATED wire
4004
- * id (presence card.id, control from.id) must go through this, never raw `a.id`. */
4005
- managedPrincipal(a) {
4006
- return a.userOwner ? a.id : principalKey(DEV_OWNER, a.id).key;
4007
- }
3868
+ /** The wire principal of a managed agent: {@link managedPrincipal}. */
3869
+ managedPrincipal(a) { return managedPrincipal(a); }
4008
3870
  resumeLivenessErrors(inventory, roster) {
4009
3871
  const inactive = [];
4010
3872
  const expectedNames = new Set(inventory.agents.map((entry) => entry.name));
@@ -4191,277 +4053,7 @@ export class Manager {
4191
4053
  })
4192
4054
  .finally(() => this.releaseLifecycle());
4193
4055
  }
4194
- /** The served spawn a hosted enrollment forwards. A run's spawn also names its run, so the host
4195
- * bounds the helper by what the run's starter held when the run was admitted (SPEC 14.8). */
4196
- servedSpawnRequest(served, caller) {
4197
- const run = caller !== undefined ? this.runHosting?.runAdmission(caller) : undefined;
4198
- return { served, ...(run !== undefined ? { runId: run.runId } : {}) };
4199
- }
4200
- /** USER-MODE spawn provisioning (the gate-1 counterpart to the static mint block): resolve the
4201
- * OWNER (ctl caller's principal, or the manifest's stamped owner — never a payload field),
4202
- * pre-create the principal-keyed durables + ACL row on the ephemeral provisioner, author the
4203
- * ledger grant (the upsert ROTATES the per-agent secret on every start — a non-running agent
4204
- * never holds a standing mint secret), materialize the 0600 secret/sentinel files, and
4205
- * PREFLIGHT the bearer chain once — the spawned agent must never be the first to discover a
4206
- * dead auth plane. Every failure is returned as the refusal sentence, with the grant + files
4207
- * rolled back. */
4208
- async provisionUserAgent(name, opts) {
4209
- if (opts.delegatedIntent) {
4210
- // startAgentActive refused a delegated launch on a manager without this callback.
4211
- const execute = this.remoteAuthority.executeDelegatedUserIntent;
4212
- const { intentId, owner } = opts.delegatedIntent;
4213
- // The hosted arm with the intent's execution in place of the holder's own enrollment: the
4214
- // spawning owner is the intent's, so its existing owner check refuses any other.
4215
- return this.enrollUserAgent(name, { ...opts, specOwner: owner }, async ({ target }) => {
4216
- const result = await execute({ intentId, operation: "launch", target: { actor: target.actor, tokenHash: target.tokenHash } });
4217
- if (result.operation !== "launch" || result.intentId !== intentId)
4218
- throw new Error(`the host answered delegated intent ${intentId} with another execution`);
4219
- return result.material;
4220
- });
4221
- }
4222
- if (this.remoteAuthority?.enrollManagedAgent)
4223
- return this.enrollUserAgent(name, opts, this.remoteAuthority.enrollManagedAgent);
4224
- const spawnerPr = opts.spawner ? parsePrincipalKey(opts.spawner) : null;
4225
- const owner = opts.specOwner ?? (spawnerPr && spawnerPr.owner.startsWith("u_") ? spawnerPr.owner : undefined);
4226
- if (!owner)
4227
- return {
4228
- error: `user-auth space "${this.space}": no owner for this spawn - call it from a user-mode session (\`cotal login\` then \`cotal spawn\`), or apply a manifest as a logged-in operator`,
4229
- };
4230
- let provider;
4231
- try {
4232
- provider = resolveAuthProvider();
4233
- }
4234
- catch (e) {
4235
- return { error: rejectionText(e) };
4236
- }
4237
- const dir = userAuthStateDir(this.workspaceRoot, this.space);
4238
- // The agent's capability scope rides its ledger row (act.scope in every bearer) — same
4239
- // vocabulary as static capabilities; the broker maps them to the ctl tiers. `role:<r>` tokens
4240
- // pass through too (a persona may hold delegable roles) — the ledger's envelope walk still
4241
- // attenuates every one of these against the spawner chain.
4242
- const scope = (opts.capabilities ?? []).filter((c) => c === "spawn" || c === "run" || c === "admin" || /^role:[A-Za-z0-9_-]+$/.test(c));
4243
- // The manager's ONE store (injected for a hosted composition, workstation FS locally). A hosted
4244
- // user-mode spawn reads the callout material from it — the same store the auth-store kinds
4245
- // (callout/issuer/…) were migrated onto — so this is no longer a local-only path.
4246
- const secrets = this.secrets;
4247
- // LIFECYCLE-KEYED family (SPEC 13.1 name-disjointness on the FS): this incarnation's files
4248
- // embed its uid, so no teardown addressed to another incarnation can ever reach them.
4249
- const files = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, opts.lifecycleUid);
4250
- const { actorToken: tokenPath, sentinelCreds: sentinelPath, health: healthPath } = files;
4251
- try {
4252
- // The GRANT first — it is the envelope-rule enforcement point (a delegation must sit within
4253
- // the spawner's own grant), so a refused delegation exits here having touched nothing beyond
4254
- // the ledger: no durables, no broker footprint, nothing for a corrected respawn to race.
4255
- const grant = await provider.grantAgent({
4256
- store: secrets,
4257
- dir,
4258
- space: this.space,
4259
- owner,
4260
- actor: name,
4261
- scope,
4262
- allowSubscribe: opts.allowSubscribe,
4263
- allowPublish: opts.allowPublish ?? [],
4264
- ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
4265
- role: opts.role,
4266
- parent: spawnerPr ? opts.spawner : undefined,
4267
- label: opts.label,
4268
- lifecycleUid: opts.lifecycleUid,
4269
- // This manager attests its own persisted logical instance id: the same id a static slot
4270
- // records as its owner. Recovery binds a managed row to a manager only through this.
4271
- custody: { kind: "local-manager", instanceId: this.managerInstanceId },
4272
- });
4273
- // Durables + ACL row, LIFECYCLE-keyed (SPEC 13.1) — the same onboarding as static agents minus
4274
- // the mint (a user agent's credential is its bearer, minted by the callout per connect from the
4275
- // ledger row's recorded lifecycleUid — the same value provisioned here).
4276
- await this.withProvisioner((prov) => provisionAgentDurables(prov, { owner, actor: name, lifecycleUid: opts.lifecycleUid }, {
4277
- subscribe: opts.subscribe,
4278
- allowSubscribe: opts.allowSubscribe,
4279
- role: opts.role,
4280
- }));
4281
- // The store holds the source of truth; the bearer re-exec (`--token-file`) and the launch's
4282
- // sentinel handoff read FILES, so materialize both at the canonical paths (under the local
4283
- // FS composition, a byte-identical rewrite of the keys' own locations).
4284
- await secrets.put(agentSecretKeyForFile(tokenPath, this.space), grant.actorToken);
4285
- await secrets.put(agentSecretKeyForFile(sentinelPath, this.space), grant.sentinelCreds);
4286
- await materializeSecretToFile(secrets, agentSecretKeyForFile(tokenPath, this.space), tokenPath);
4287
- await materializeSecretToFile(secrets, agentSecretKeyForFile(sentinelPath, this.space), sentinelPath);
4288
- rmSync(healthPath, { force: true }); // a fresh start opens a fresh health window
4289
- const bearerCmd = [
4290
- // The manager's own invocation prefix (node + loader flags + the cotal entry) — the agent
4291
- // process execs this argv for every bearer, so it must resolve from ANY cwd. Correct
4292
- // whenever the manager runs under a real `cotal` entry (supervise/up); a test constructing
4293
- // Manager directly never reaches this branch (user meshes boot through the CLI).
4294
- ...bearerEntryArgv(),
4295
- provider.agentBearerCommand,
4296
- "--dir", dir,
4297
- "--space", this.space,
4298
- "--owner", owner,
4299
- "--actor", name,
4300
- "--token-file", tokenPath,
4301
- "--health-file", healthPath,
4302
- ];
4303
- // One bearer run before the launch is the end-to-end auth preflight (state dir, daemon, ledger
4304
- // row, secret); its failure sentence is the spawn refusal.
4305
- await runAgentBearer(bearerCmd);
4306
- return { owner, lifecycleUid: opts.lifecycleUid, files, launch: { owner, actor: name, sentinelCredsPath: sentinelPath, bearerCmd } };
4307
- }
4308
- catch (e) {
4309
- // Roll back everything this attempt materialized — a refused spawn must leave no standing
4310
- // secret, no ledger row, no durable footprint — and AWAIT the broker teardown: the caller
4311
- // may respawn the moment it reads the refusal, and a detached teardown would race (and
4312
- // delete) that fresh spawn's just-provisioned durables. deprovision shreds the secret family
4313
- // and revokes the grant, but only logs a failed revoke, so the revoke is attempted here first.
4314
- // Each failure joins the refusal, so the caller learns what this spawn left behind.
4315
- const failed = [];
4316
- await attemptCleanup(failed, "revoke agent grant", () => provider.revokeAgent({ dir, owner, actor: name }));
4317
- await attemptCleanup(failed, "deprovision", () => this.deprovision({ id: principalKey(owner, name).key, name, lifecycleUid: opts.lifecycleUid, userOwner: owner, secretPaths: files }));
4318
- const leftover = failed.length ? `; cleanup failed: ${describeCleanupFailures(failed)}` : "";
4319
- return { error: `agent auth preflight failed for "${name}": ${rejectionText(e)}${leftover}` };
4320
- }
4321
- }
4322
- /**
4323
- * HOSTED user-mode spawn provisioning (#1972): the participant arm of host-owned enrollment.
4324
- *
4325
- * A registered participant holds no ledger writer, no JetStream provisioner, and no signing seed,
4326
- * so every step the local arm above performs itself is the HOST's here. What stays local is the
4327
- * one thing that must: the standing `actorToken`. This method generates it, writes it at 0600
4328
- * BEFORE the request, and sends only its SHA-256 digest — so the plaintext never crosses the
4329
- * network and a host compromise cannot replay an agent's exchange secret.
4330
- *
4331
- * The HOST picks the lifecycle UID. It alone can see the retirement tombstones that make a UID
4332
- * permanently unusable (a retired uid is refused forever by the retirement frontier), so a
4333
- * participant-chosen uid could aim a fresh grant at a dead incarnation. The uid the host returns
4334
- * is the one the spawn records and the one the child's durables are keyed by.
4335
- *
4336
- * The bearer argv selects `--exchange-url`: the local `--dir` arm reads a state directory this
4337
- * machine does not have, and a signerless participant must never appear to hold one.
4338
- */
4339
- async enrollUserAgent(name, opts, enroll) {
4340
- let provider;
4341
- try {
4342
- provider = resolveAuthProvider();
4343
- }
4344
- catch (e) {
4345
- return { error: rejectionText(e) };
4346
- }
4347
- const secrets = this.secrets;
4348
- const input = {
4349
- target: {
4350
- actor: name,
4351
- ...(opts.role !== undefined ? { role: opts.role } : {}),
4352
- label: opts.label,
4353
- ...(opts.capabilities !== undefined ? { capabilities: opts.capabilities } : {}),
4354
- ...(opts.subscribe !== undefined ? { subscribe: opts.subscribe } : {}),
4355
- allowSubscribe: opts.allowSubscribe,
4356
- ...(opts.allowPublish !== undefined ? { allowPublish: opts.allowPublish } : {}),
4357
- ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
4358
- },
4359
- ...(opts.spawnRequest !== undefined ? { spawn: opts.spawnRequest } : {}),
4360
- };
4361
- // An unanswered enrollment may already hold the host's alias. Keep its request and standing
4362
- // token together until preflight succeeds, rather than minting a conflicting successor.
4363
- let pending;
4364
- if (!opts.delegatedIntent) {
4365
- try {
4366
- pending = await pendingEnrollment({ store: secrets, space: this.space,
4367
- instanceId: this.managerInstanceId, actor: name, input,
4368
- authority: { target: input.target, owner: this.remoteAuthority.owner,
4369
- managerLifecycleUid: this.remoteAuthority.lifecycleUid, specOwner: opts.specOwner, spawner: opts.spawner,
4370
- caller: opts.enrollmentCaller, runId: opts.spawnRequest?.runId } });
4371
- }
4372
- catch (e) {
4373
- return { error: `agent auth preflight failed for "${name}": ${rejectionText(e)}` };
4374
- }
4375
- }
4376
- const actorToken = pending?.record.actorToken ?? randomBytes(32).toString("base64url");
4377
- const tokenHash = createHash("sha256").update(actorToken, "utf8").digest("hex");
4378
- // Provisional paths under the participant's OWN uid: the token has to be on disk before the
4379
- // request (a host that granted against a digest whose plaintext was lost would leave an agent
4380
- // that can never exchange), and the host's uid is not known until the request answers. The
4381
- // family is re-keyed to the host's uid below.
4382
- const staged = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, pending?.record.lifecycleUid ?? opts.lifecycleUid);
4383
- let files = staged;
4384
- let material;
4385
- let sent = false;
4386
- try {
4387
- await secrets.put(agentSecretKeyForFile(staged.actorToken, this.space), actorToken);
4388
- await materializeSecretToFile(secrets, agentSecretKeyForFile(staged.actorToken, this.space), staged.actorToken);
4389
- const saved = pending?.record.input ?? input;
4390
- if (canonicalJson(saved.target) !== canonicalJson(input.target))
4391
- throw new Error(`pending enrollment for "${name}" names different target authority`);
4392
- sent = true;
4393
- // The original observation may have expired, or vanished on a host restart before commit.
4394
- // Same-authority retries keep the enrollment identity but carry this freshly served spawn.
4395
- material = await enroll({ ...input, target: { ...saved.target, tokenHash },
4396
- ...(pending ? { requestId: pending.record.requestId } : {}) });
4397
- if (material.actor !== name)
4398
- throw new Error(`the host enrolled actor "${material.actor}", not the requested "${name}"`);
4399
- const specOwner = opts.specOwner ?? (opts.spawner ? parsePrincipalKey(opts.spawner)?.owner : undefined);
4400
- if (specOwner !== undefined && specOwner.startsWith("u_") && material.owner !== specOwner)
4401
- throw new Error(`the host enrolled the agent under owner ${material.owner}, not the spawning owner ${specOwner}`);
4402
- assertLifecycleToken(material.lifecycleUid, "host-enrolled managed agent lifecycleUid");
4403
- // Re-key the family onto the HOST's uid (SPEC 13.1 name-disjointness on the FS): the child's
4404
- // credential paths must embed the uid its broker footprint carries, never the provisional one.
4405
- files = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, material.lifecycleUid);
4406
- // From here the host holds a grant at that uid.
4407
- opts.onEnrolled?.({ owner: material.owner, lifecycleUid: material.lifecycleUid, files });
4408
- if (files.actorToken !== staged.actorToken) {
4409
- await secrets.put(agentSecretKeyForFile(files.actorToken, this.space), actorToken);
4410
- await materializeSecretToFile(secrets, agentSecretKeyForFile(files.actorToken, this.space), files.actorToken);
4411
- await secrets.delete(agentSecretKeyForFile(staged.actorToken, this.space));
4412
- rmSync(staged.actorToken, { force: true });
4413
- }
4414
- await secrets.put(agentSecretKeyForFile(files.sentinelCreds, this.space), material.sentinelCreds);
4415
- await materializeSecretToFile(secrets, agentSecretKeyForFile(files.sentinelCreds, this.space), files.sentinelCreds);
4416
- rmSync(files.health, { force: true }); // a fresh start opens a fresh health window
4417
- const bearerCmd = [
4418
- ...bearerEntryArgv(),
4419
- provider.agentBearerCommand,
4420
- // The signerless arm: the pinned public exchange, never a local state dir.
4421
- "--exchange-url", material.agentBearerExchangeUrl,
4422
- "--space", this.space,
4423
- "--owner", material.owner,
4424
- "--actor", name,
4425
- "--token-file", files.actorToken,
4426
- "--health-file", files.health,
4427
- ];
4428
- await runAgentBearer(bearerCmd);
4429
- if (pending)
4430
- await secrets.delete(pending.key);
4431
- return {
4432
- owner: material.owner,
4433
- lifecycleUid: material.lifecycleUid,
4434
- files,
4435
- launch: { owner: material.owner, actor: name, sentinelCredsPath: files.sentinelCreds, bearerCmd },
4436
- enrolled: { material, actorToken },
4437
- };
4438
- }
4439
- catch (e) {
4440
- // Remove launch-file materializations, but retain the pending token and request when the
4441
- // host may have committed. The next same-authority spawn replays that enrollment.
4442
- // A failed removal joins the refusal instead of throwing, so every removal is attempted and
4443
- // the refusal still reaches the caller.
4444
- const unshredded = [];
4445
- for (const family of files.actorToken === staged.actorToken ? [staged] : [staged, files])
4446
- await this.shredUserSecrets(unshredded, family);
4447
- const rejected = material === undefined ? caughtEnvelope(e) : undefined;
4448
- // Only a first, definitively refused request proves there was no earlier commit. A refusal
4449
- // during replay cannot prove that an earlier unanswered attempt enrolled nothing.
4450
- const discard = pending?.created && (!sent || rejected?.outcome === "not-executed");
4451
- if (discard && pending) {
4452
- const key = pending.key;
4453
- await attemptCleanup(unshredded, "pending enrollment", () => secrets.delete(key));
4454
- }
4455
- const retained = pending && !discard;
4456
- const leftover = unshredded.length ? `; cleanup failed: ${describeCleanupFailures(unshredded)}` : "";
4457
- const remedy = retained ? `; the name "${name}" is held by this manager's earlier enrollment. Retry this persona with the same caller to replay it. Once it launches, stop it before changing its authority` : "";
4458
- const refusal = !retained && material === undefined && !unshredded.length ? rejected : undefined;
4459
- return {
4460
- error: `agent auth preflight failed for "${name}": ${rejectionText(e)}${leftover}${remedy}`,
4461
- ...(refusal?.outcome === "not-executed" ? { refused: refusal.code, ...(refusal.details ? { details: refusal.details } : {}) } : {}),
4462
- };
4463
- }
4464
- }
4056
+ provisionUserAgent(name, opts) { return this.userProvision.provisionUserAgent(name, opts); }
4465
4057
  /** Shred a user agent's secret family from the store and from disk. Every removal is attempted,
4466
4058
  * and each failure joins `unshredded`, so one fault cannot leave the rest of the family behind. */
4467
4059
  async shredUserSecrets(unshredded, family) {
@@ -4472,43 +4064,6 @@ export class Manager {
4472
4064
  if (path)
4473
4065
  await attemptCleanup(unshredded, `file ${path}`, () => rmSync(path, { force: true }));
4474
4066
  }
4475
- /** This manager's registry record for its space, which pins the broker and IdP a delegated seat's
4476
- * handoff carries. It must pin the exchange the host enrolls against, or the child would register
4477
- * a mesh whose bearers come from somewhere else. */
4478
- delegatedMeshRecord() {
4479
- const record = loadMeshes().find((m) => m.space === this.space);
4480
- if (!record?.userAuth)
4481
- throw new Error(`a delegated seat needs this manager's user-mode registry record for space "${this.space}", and there is none`);
4482
- if (record.userAuth.endpoints?.url !== this.remoteAuthority?.agentBearerExchangeUrl)
4483
- throw new Error(`the registry record for space "${this.space}" pins a different exchange than the host's agentBearerExchangeUrl`);
4484
- return record;
4485
- }
4486
- /** The one handoff a delegated seat receives, built from values this manager holds: the
4487
- * enrollment result, the token it generated, and its own registry record. No path crosses. */
4488
- composeManagedHandoff(enrolled, actorToken) {
4489
- const record = this.delegatedMeshRecord();
4490
- if (enrolled.agentBearerExchangeUrl !== record.userAuth.endpoints?.url)
4491
- throw new Error(`the host enrolled "${enrolled.actor}" against a different exchange than this manager's registry record pins`);
4492
- const { url, issuer, audience } = record.userAuth.idp;
4493
- return {
4494
- kind: MANAGED_HANDOFF_KIND,
4495
- space: this.space,
4496
- owner: enrolled.owner,
4497
- actor: enrolled.actor,
4498
- lifecycleUid: enrolled.lifecycleUid,
4499
- server: record.server,
4500
- tlsRequired: record.tlsRequired === true,
4501
- authProvider: record.userAuth.provider,
4502
- idp: { url, issuer, audience },
4503
- exchangeUrl: enrolled.agentBearerExchangeUrl,
4504
- sentinelCreds: enrolled.sentinelCreds,
4505
- actorToken,
4506
- subscribe: enrolled.subscribe,
4507
- allowSubscribe: enrolled.allowSubscribe,
4508
- allowPublish: enrolled.allowPublish,
4509
- ...(record.policy ? { policy: record.policy } : {}),
4510
- };
4511
- }
4512
4067
  /**
4513
4068
  * WHY A SEAT LEFT — one line, at the one place every free path passes through.
4514
4069
  *
@@ -4672,12 +4227,6 @@ export class Manager {
4672
4227
  forkProvenance(a) {
4673
4228
  return this.sessionRecovery.forkProvenance(a);
4674
4229
  }
4675
- refuseCarriedFork(a, timeoutMs) {
4676
- return this.sessionRecovery.refuseCarriedFork(a, timeoutMs);
4677
- }
4678
- refuseLateCarriedFork(a, timeoutMs) {
4679
- return this.sessionRecovery.refuseLateCarriedFork(a, timeoutMs);
4680
- }
4681
4230
  readManagedSession(a) {
4682
4231
  return this.sessionRecovery.readManagedSession(a);
4683
4232
  }
@@ -4757,13 +4306,11 @@ export class Manager {
4757
4306
  this.reapChildrenOf(this.managedPrincipal(a));
4758
4307
  }
4759
4308
  nameError(name) { return this.namesCapacity.nameError(name); }
4760
- nameInUse(name, live) { return this.namesCapacity.nameInUse(name, live); }
4761
- uniqueName(base, unavailable = new Set()) { return this.namesCapacity.uniqueName(base, unavailable); }
4762
4309
  /** Spawn a teammate by persona ref (`name` loads `.cotal/agents/<name>.md`; the peer presents
4763
4310
  * under that file's own `name:`), as if a peer asked via the control plane. Used to pre-spawn the
4764
4311
  * demo's experts at startup so the manager owns them. */
4765
4312
  async startByName(name) {
4766
- return this.startAgent({ name });
4313
+ return this.seatLaunch.startByName(name);
4767
4314
  }
4768
4315
  /** Resolve once `name` shows up on the mesh roster (presence registered), or after `timeoutMs`.
4769
4316
  * Lets the pre-spawn loop stagger heavy agent cold-starts so they don't all boot at once.
@@ -4771,13 +4318,7 @@ export class Manager {
4771
4318
  * resolution: a same-named *unmanaged* peer already present could satisfy this early. That's
4772
4319
  * acceptable for cold-start staggering; it never routes anything. */
4773
4320
  async waitForPresence(name, timeoutMs = 30_000) {
4774
- const deadline = Date.now() + timeoutMs;
4775
- while (Date.now() < deadline) {
4776
- if (this.ep.getRoster().some((p) => p.card.name === name))
4777
- return true;
4778
- await new Promise((r) => setTimeout(r, 1_000));
4779
- }
4780
- return false;
4321
+ return this.seatLaunch.waitForPresence(name, timeoutMs);
4781
4322
  }
4782
4323
  /** Parse a served `spawn` request into {@link StartAgentOpts}. The compiled spawn input contract
4783
4324
  * is the shape check: it already refused a non-mapping `launchOptions`, a `supervise` that is not
@@ -4868,57 +4409,11 @@ export class Manager {
4868
4409
  ...(served !== undefined ? { served } : {}),
4869
4410
  }, caller, hooks, authenticatedCaller);
4870
4411
  }
4871
- /** The realpath + directory checks a placed spawn directory must pass on this manager's host,
4872
- * shared by the served `resolve-cwd` command and the `spawn` admission check (#385 item 2): one
4873
- * function, so the two doors never drift. Creates nothing and never substitutes the workspace root. */
4874
- checkSpawnCwd(resolved) {
4875
- let cwd = resolved;
4876
- try {
4877
- cwd = realpathSync(resolved);
4878
- }
4879
- catch (error) {
4880
- return { refusal: `path cannot be resolved: ${rejectionText(error)}` };
4881
- }
4882
- try {
4883
- if (!statSync(cwd).isDirectory())
4884
- return { refusal: "path is not a directory" };
4885
- }
4886
- catch (error) {
4887
- return { refusal: rejectionText(error) };
4888
- }
4889
- return { cwd, host: hostname() };
4890
- }
4891
- /** Refuse host directory reads before lookup when seats cannot use this host. */
4892
- assertHostDirectoryExecution() {
4893
- if (this.execution === "none")
4894
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
4895
- if (this.execution === "runtime" && this.requiredRuntime.spawnDelegated)
4896
- 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`);
4897
- }
4898
- async listSpawnDirectory(args) {
4899
- this.assertHostDirectoryExecution();
4900
- const { cwd } = this.resolveSpawnCwd(args.path ?? homedir());
4901
- try {
4902
- return await listDirectory(cwd, args.includeHidden === true, typeof args.limit === "number" ? args.limit : 200);
4903
- }
4904
- catch (error) {
4905
- throw new EpEnvelopeError("failed-precondition", `directory cannot be listed on this host: ${JSON.stringify(cwd)} (${rejectionText(error)})`);
4906
- }
4907
- }
4908
- /** Resolve a placed spawn directory without creating or substituting a workspace. */
4909
- resolveSpawnCwd(value) {
4910
- this.assertHostDirectoryExecution();
4911
- const asked = typeof value === "string" ? value : String(value ?? "");
4912
- const refuse = (reason) => {
4913
- throw new EpEnvelopeError("failed-precondition", `cwd does not resolve on this host: ${JSON.stringify(asked)} (${reason})`);
4914
- };
4915
- if (!isAbsolute(asked))
4916
- refuse("expected an absolute path");
4917
- const result = this.checkSpawnCwd(asked);
4918
- if ("refusal" in result)
4919
- return refuse(result.refusal);
4920
- return result;
4921
- }
4412
+ /** {@link SeatLaunch.checkSpawnCwd}. */
4413
+ checkSpawnCwd(resolved) { return this.seatLaunch.checkSpawnCwd(resolved); }
4414
+ listSpawnDirectory(args) { return this.seatLaunch.listSpawnDirectory(args); }
4415
+ /** {@link SeatLaunch.resolveSpawnCwd}. */
4416
+ resolveSpawnCwd(value) { return this.seatLaunch.resolveSpawnCwd(value); }
4922
4417
  /** Resolve a connector by agent type. Library composition (installedExtensions off) → a registry
4923
4418
  * hit, exactly as before (the composition root imported what it wants). The published binary gates
4924
4419
  * on MANIFEST membership FIRST — so a live `cotal ext remove` is honored even though the registry
@@ -4934,11 +4429,8 @@ export class Manager {
4934
4429
  throw new Error(connectorInstallHint(name));
4935
4430
  return materializeFromManifest({ kind: "connector", name }, { hint: (ref) => connectorInstallHint(ref.name), expectedGeneration: this.expectedConnectorGeneration });
4936
4431
  }
4937
- /** Connector names the manager can spawn WITHOUT importing: the manifest on the published binary,
4938
- * else whatever a composition root registered. Drives the `models` catalog enumeration. */
4939
- connectorNames() {
4940
- return this.installedExtensions ? manifestExtensionNames("connector") : registry.all("connector").map((c) => c.name);
4941
- }
4432
+ /** {@link SeatLaunch.connectorNames}. */
4433
+ connectorNames() { return this.seatLaunch.connectorNames(); }
4942
4434
  /** Resolve every installed/registered connector's declared harness binaries before the manager
4943
4435
  * reports ready. A missing harness degrades only that connector, never unrelated lifecycle work:
4944
4436
  * boot continues, names it once start completes and records it on both manager status surfaces. */
@@ -4952,7 +4444,7 @@ export class Manager {
4952
4444
  let declared;
4953
4445
  if (this.installedExtensions) {
4954
4446
  try {
4955
- declared = loadExtensionsManifest().extensions.flatMap((ext) => extensionConnectors(ext));
4447
+ declared = loadExtensionsManifest().extensions.flatMap((ext) => extensionConnectors(ext).map((connector) => ({ ...connector, pkg: ext.pkg })));
4956
4448
  }
4957
4449
  catch (error) {
4958
4450
  const reason = rejectionText(error);
@@ -4969,8 +4461,12 @@ export class Manager {
4969
4461
  eventPlane: connector.eventChannel !== undefined,
4970
4462
  }));
4971
4463
  }
4464
+ this.connectorRequirements = new Map(declared.map(({ name, requires, pkg }) => [name, {
4465
+ requires, needsClaudeWake: !!this.machineSetupCommand && name === "claude" && pkg === OFFICIAL_CONNECTORS.claude,
4466
+ }]));
4972
4467
  for (const { name, requires, eventPlane } of declared) {
4973
- const { binaries, reason } = resolveHarness(name, requires);
4468
+ const { binaries, reason: missing } = resolveHarness(name, requires);
4469
+ const reason = missing ?? (this.connectorRequirements.get(name)?.needsClaudeWake ? await this.prepareClaudeWake() : undefined);
4974
4470
  if (reason) {
4975
4471
  rows.push({ agent: name, state: "unavailable", binaries, eventPlane, reason });
4976
4472
  this.bootNotes.push(`! manager boot: connector ${name} unavailable - ${reason}`);
@@ -4983,31 +4479,82 @@ export class Manager {
4983
4479
  if (!this.classSpawnEnabled())
4984
4480
  this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
4985
4481
  }
4986
- /** True when at least one declared connector is available. Empty inventory (or a failed
4987
- * inventory load) skips the class `one` subscribe for spawn/launch so this member cannot
4988
- * consume an unpinned request a sibling could serve. */
4989
- classSpawnEnabled() {
4990
- if (this.execution === "none")
4991
- return false;
4992
- return this.connectorStatuses.some((row) => row.state === "available");
4993
- }
4994
- omitClassCommands() {
4995
- return this.classSpawnEnabled() ? undefined : ["spawn", "launch"];
4482
+ /** Install and verify the hosted Claude wake channel, or report the cause and remedy. */
4483
+ async prepareClaudeWake() {
4484
+ try {
4485
+ const connector = await this.resolveConnector("claude");
4486
+ if (!connector.setup)
4487
+ throw new Error("Claude connector has no setup provider");
4488
+ const provider = await materializeFromManifest(connector.setup, { expectedGeneration: this.expectedConnectorGeneration });
4489
+ if (!provider.connector)
4490
+ throw new Error("Claude connector has no install action");
4491
+ const cotal = bearerEntryArgv();
4492
+ cotal[cotal.length - 1] = logicalExecutionEntry() ?? cotal.at(-1);
4493
+ await provider.connector.run({ cotal, machineHost: true });
4494
+ }
4495
+ catch (error) {
4496
+ const detail = oneLine(rejectionText(error).replace(/eyJ[A-Za-z0-9_.-]*/g, "<redacted>").slice(0, 800));
4497
+ return `Claude wake channel setup failed: ${detail}. Correct the cause and run \`${this.machineSetupCommand}\` on this computer.`;
4498
+ }
4996
4499
  }
4997
- /** Named harness-unavailable refusal. On the class rail a partial inventory must not look
4998
- * like the space cannot launch: name `--on` so the caller can pin a sibling. The standing
4999
- * serve credential cannot enumerate sibling `svc.*.status` inventories, so the residual
5000
- * is the flag, not a list of capable instance ids. Instance-pinned calls keep the local
5001
- * reason only. */
5002
- harnessUnavailableError(reason, route) {
5003
- if (route !== "one")
5004
- return reason;
5005
- 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)`;
4500
+ /** Retry unavailable applications without changing resolved available rows. Claude launches
4501
+ * join the status or launch that started wake setup, before any name or capacity is reserved. */
4502
+ refreshUnavailableConnectors(name, setupClaude = false) {
4503
+ const wasEnabled = this.classSpawnEnabled();
4504
+ let pending;
4505
+ for (const row of this.connectorStatuses) {
4506
+ if (row.state !== "unavailable" || (name !== undefined && row.agent !== name))
4507
+ continue;
4508
+ const requirements = this.connectorRequirements.get(row.agent);
4509
+ if (!requirements)
4510
+ continue;
4511
+ if (requirements.needsClaudeWake && this.claudeWakeRecheck) {
4512
+ pending = this.claudeWakeRecheck;
4513
+ continue;
4514
+ }
4515
+ const { binaries, reason } = resolveHarness(row.agent, requirements.requires);
4516
+ if (reason) {
4517
+ row.binaries = binaries;
4518
+ row.reason = reason;
4519
+ }
4520
+ else if (requirements.needsClaudeWake) {
4521
+ const release = setupClaude ? this.beginLifecycle(true) : undefined;
4522
+ if (!release)
4523
+ continue;
4524
+ pending = this.claudeWakeRecheck = this.prepareClaudeWake().then((failure) => {
4525
+ row.binaries = binaries;
4526
+ if (failure) {
4527
+ row.reason = failure;
4528
+ return;
4529
+ }
4530
+ const alreadyEnabled = this.classSpawnEnabled();
4531
+ row.state = "available";
4532
+ delete row.reason;
4533
+ if (!alreadyEnabled)
4534
+ this.servePlane.enableClassSpawn();
4535
+ }).finally(() => { this.claudeWakeRecheck = undefined; release(); });
4536
+ void pending.catch((error) => console.error(`! manager: Claude recheck failed: ${rejectionText(error)}`));
4537
+ }
4538
+ else {
4539
+ row.binaries = binaries;
4540
+ row.state = "available";
4541
+ delete row.reason;
4542
+ }
4543
+ }
4544
+ if (!wasEnabled && this.classSpawnEnabled())
4545
+ this.servePlane.enableClassSpawn();
4546
+ return pending;
5006
4547
  }
4548
+ /** {@link SeatLaunch.classSpawnEnabled}. */
4549
+ classSpawnEnabled() { return this.seatLaunch.classSpawnEnabled(); }
4550
+ omitClassCommands() { return this.seatLaunch.omitClassCommands(); }
4551
+ /** {@link SeatLaunch.harnessUnavailableError}. */
4552
+ harnessUnavailableError(reason, route) { return this.seatLaunch.harnessUnavailableError(reason, route); }
5007
4553
  /** The harness binaries a managed launch runs, as boot resolved them, or the refusal naming what is
5008
4554
  * missing. Spawn, resume and the model catalog all take it, so a seat launches from the same files
5009
4555
  * whichever path starts it and the catalog never disagrees with a launch about whether the harness
5010
- * is there. A connector registered after boot has no inventory row and is checked on PATH now. */
4556
+ * is there. Callers recheck unavailable rows first; available rows retain their resolved files.
4557
+ * A connector registered after boot has no inventory row and is checked on PATH now. */
5011
4558
  launchHarness(connector) {
5012
4559
  const row = this.connectorStatuses.find((status) => status.agent === connector.name);
5013
4560
  if (row?.state === "unavailable")
@@ -5052,59 +4599,20 @@ export class Manager {
5052
4599
  return `${connector.name} connector does not support exact session continuity (continuity: exact)`;
5053
4600
  return undefined;
5054
4601
  }
5055
- /** The refusal for a `once` spawn this manager cannot run as one task: every check is made before
5056
- * anything is allocated, so a refused spawn leaves nothing behind. */
5057
- onceRefusal(connector, runtime, launch, spawner, hooks) {
5058
- if (!hooks?.onOnce)
5059
- return "once: a once task rides the spawn action, which this launch door is not";
5060
- if (launch.prompt === undefined || launch.prompt.trim() === "")
5061
- return "once: needs a prompt, which is the task";
5062
- if (launch.supervise !== undefined)
5063
- return "once: a once seat is never restarted, so it cannot carry supervise";
5064
- if (!connector.supportsTurnRelay)
5065
- return `once: the ${connector.name} connector cannot take a once task${connector.turnRelayRefusal ? `: ${connector.turnRelayRefusal}` : ""}`;
5066
- if (connector.onceNeedsConfirmed !== undefined && !runtime.reportsStartupOutcome)
5067
- return `once: runtime "${runtime.kind}" does not report how a seat's startup ended, which a once seat on the ${connector.name} connector needs`;
5068
- if (runtime.spawnDelegated)
5069
- return `once: runtime "${runtime.kind}" starts seats outside this host, where this manager cannot prove the seat's exit`;
5070
- const operator = connector.waitsForOperator?.(launch.launchOptions);
5071
- if (operator !== undefined)
5072
- return `once: these launch options make the seat wait at ${operator} before it starts, so nothing could take its task`;
5073
- // The task's relay record, measured with the widest deadline it could carry.
5074
- const { note, payload } = onceTurnNote({
5075
- prompt: launch.prompt, spawner: this.spawnerName(spawner),
5076
- ...(launch.once.deadlineMs !== undefined ? { deadlineAt: MAX_SCHEDULE_MS, holdToken: turnHoldToken("") } : {}),
5077
- holdEpoch: this.serviceServe?.grant.epoch ?? 0,
5078
- ...(connector.retireAfterExit ? { retire: connector.name } : {}),
5079
- // The longest id token core accepts (endpoint-subjects `assertIdToken`).
5080
- spawn: "x".repeat(64),
5081
- });
5082
- if (note.length > TURN_NOTE_MAX)
5083
- return `once: the prompt is too long for one task (its relay record is ${note.length} characters, over ${TURN_NOTE_MAX})`;
5084
- if (connector.turnFrameLimit !== undefined) {
5085
- // The text the seat shows, rendered by the seat's own function with the widest values it could
5086
- // carry: the task's goal id is a digest token, and a deadline renders as one ISO instant.
5087
- const text = renderOnceTask({ goalId: digestIdToken("once"), payload, spawner: this.spawnerName(spawner), ...(launch.once.deadlineMs !== undefined ? { deadlineAt: MAX_SCHEDULE_MS } : {}) });
5088
- if (text.length > connector.turnFrameLimit)
5089
- return `once: the prompt is too long for one ${connector.name} turn (the task renders to ${text.length} characters, over ${connector.turnFrameLimit})`;
5090
- }
5091
- return undefined;
5092
- }
5093
- /** How a once task names who sent it: the spawner's roster name, or its principal when that name is missing or only whitespace. */
5094
- spawnerName(spawner) {
5095
- const id = spawner ?? this.ep.ref().id;
5096
- return shownSpawner(this.ep.getRoster().find((p) => p.card.id === id)?.card.name, id);
5097
- }
4602
+ /** {@link SeatLaunch.onceRefusal}. */
4603
+ onceRefusal(connector, runtime, launch, spawner, hooks) { return this.seatLaunch.onceRefusal(connector, runtime, launch, spawner, hooks); }
4604
+ /** {@link SeatLaunch.spawnerName}. */
4605
+ spawnerName(spawner) { return this.seatLaunch.spawnerName(spawner); }
5098
4606
  /** The refusal for an event-plane choice the registration policy or the connector cannot meet.
5099
4607
  * Spawn and resume both ask before a seat's launch is built, so a seat retained without the
5100
- * plane cannot come back on a space that now requires it. An absent choice arms the plane. */
4608
+ * plane cannot come back on a space that now requires it. An absent choice arms supported planes. */
5101
4609
  eventsRefusal(connector, events) {
5102
4610
  if (this.eventsRequired && events === false)
5103
4611
  return `space "${this.space}" requires the event plane by registration policy; --no-events (events: false on the start op) is not allowed`;
5104
- if (events !== false && !connector.eventChannel)
4612
+ if ((this.eventsRequired || events === true) && !connector.eventChannel)
5105
4613
  return this.eventsRequired
5106
4614
  ? `space "${this.space}" requires the event plane by registration policy, but connector "${connector.name}" does not publish one`
5107
- : `connector "${connector.name}" does not publish an AG-UI event plane; pass --no-events (events: false on the start op) to launch it without one`;
4615
+ : `connector "${connector.name}" does not publish an AG-UI event plane; omit --events to launch it without one`;
5108
4616
  return undefined;
5109
4617
  }
5110
4618
  /** Return connector-provided model catalogs for selector UIs. Optional by connector: a host with no
@@ -5116,9 +4624,10 @@ export class Manager {
5116
4624
  const requested = String(args.agent ?? "").trim();
5117
4625
  const refresh = args.refresh === true;
5118
4626
  const one = async (connector) => {
4627
+ await this.refreshUnavailableConnectors(connector.name, true);
4628
+ const harness = this.launchHarness(connector);
5119
4629
  if (!connector.listModels)
5120
4630
  return { agent: connector.name, supported: false, models: [] };
5121
- const harness = this.launchHarness(connector);
5122
4631
  if ("refusal" in harness)
5123
4632
  return { agent: connector.name, supported: true, models: [], error: harness.refusal };
5124
4633
  try {
@@ -5274,271 +4783,16 @@ export class Manager {
5274
4783
  release();
5275
4784
  }
5276
4785
  }
5277
- /** The persona file a spawn loads and the harness it resolves, shared by `spawn` and the served
5278
- * `resolve-agent` read: a detached resume locates the session it carries with the connector this
5279
- * names, so the two doors must not drift (#2899). */
5280
- async spawnPersona(opts, spawner, authenticatedCaller) {
5281
- // Both config-taking wire commands and direct/roster starts enter here before interpreting
5282
- // a path. A resolved manifest is host-built authority over its own materialized resource,
5283
- // never a wire-supplied config override (the public schemas accept no `resolved` field).
5284
- if (this.execution === "runtime" && this.requiredRuntime.spawnDelegated && opts.config !== undefined && !opts.resolved)
5285
- return { error: "delegated execution cannot use a manager-host persona config path; select a named persona" };
5286
- // The spawn argument is a persona REF — a filename in `.cotal/agents` (the unique spawn KEY), or
5287
- // a path via `--config`. It is NOT the mesh identity: the identity comes from inside the file
5288
- // (`name:`), so a persona can be filed descriptively (review-critic.md) yet present under a
5289
- // free-form name (socrates) — the same model `cotal spawn` already uses. You always spawn by
5290
- // filename (unique on disk); two files can't collide on the key.
5291
- const ref = opts.name.trim();
5292
- if (!ref)
5293
- return { error: "name required" };
5294
- // An inline persona is its own definition, read here like a file so every later check sees a
5295
- // def. It has no file until its snapshot is written, once the seat's lifecycle uid is final.
5296
- if (opts.persona !== undefined) {
5297
- if (opts.resolved || opts.config !== undefined || opts.identity !== undefined)
5298
- return { error: "persona: an inline persona names the helper itself, so it takes no config, identity or manifest launch", code: "bad-request" };
5299
- const refErr = this.nameError(ref);
5300
- if (refErr)
5301
- return { error: refErr };
5302
- let inline;
5303
- try {
5304
- inline = inlinePersonaDef(ref, opts.persona);
5305
- }
5306
- catch (e) {
5307
- return { error: rejectionText(e), code: "bad-request" };
5308
- }
5309
- // A save under a name the catalog already holds is refused here, before anything is allocated,
5310
- // so the refusal starts nothing. The create-only write after the grant settles a race.
5311
- if (inline.save) {
5312
- const target = agentFilePath(this.workspaceRoot, ref);
5313
- let taken = true;
5314
- try {
5315
- lstatSync(target);
5316
- }
5317
- catch (e) {
5318
- if (e.code !== "ENOENT")
5319
- return { error: `persona.save: ${rejectionText(e)}` };
5320
- taken = false;
5321
- }
5322
- if (taken)
5323
- 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` };
5324
- }
5325
- return { ref, def: inline.def, agent: resolveAgentType({ flag: opts.agent, pin: undefined, callerDefault: opts.defaultAgent }), inline: { save: inline.save } };
5326
- }
5327
- // A bare ref maps to `.cotal/agents/<ref>.md`, so it must be a safe token (no path traversal); a
5328
- // `--config` path is validated by existsSync below instead.
5329
- if (!opts.config) {
5330
- const refErr = this.nameError(ref);
5331
- if (refErr)
5332
- return { error: refErr };
5333
- }
5334
- // Resolve the persona file (fail loud — NO silent default-ACL fallback). A missing persona used
5335
- // to mint DEFAULT creds (read `general` only, default-deny publish, no capabilities), so a
5336
- // typo'd / renamed / spawned-by-display-name agent became live with silently-wrong ACLs — a
5337
- // behavioral/security bug. Fail loud instead, matching `cotal spawn` (loadAgentFile throws).
5338
- // This runs BEFORE the spawn path resolves its connector: the file's `agent:` pin participates in
5339
- // the harness choice (flag > file > COTAL_DEFAULT_AGENT > default, #869), which is impossible if
5340
- // the connector is materialized first.
5341
- let configPath;
5342
- if (opts.config) {
5343
- configPath = agentFilePath(this.workspaceRoot, opts.config);
5344
- if (!existsSync(configPath))
5345
- return { error: `agent file not found: ${configPath}` };
5346
- }
5347
- else {
5348
- configPath = agentFilePath(this.workspaceRoot, ref);
5349
- if (!existsSync(configPath))
5350
- return { error: `no persona "${ref}" in the catalog of manager ${this.managerInstanceId} on host ${hostname()}: ${configPath} not found; create it there` };
5351
- }
5352
- // An inline snapshot belongs to its own seat's lifecycle, which removes it at retirement and
5353
- // refuses a restart once it changed, so no other launch may read it. Compared after symlinks
5354
- // resolve, for a config path and a catalog entry alike.
5355
- if (!opts.resolved && this.insideInlineDir(configPath))
5356
- 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` };
5357
- // Load the persona ONCE, here, ahead of the connector choice. The file's `agent:` pin feeds the
5358
- // harness resolution below; the spawn path's identity/ACL profile block consumes the SAME def (no
5359
- // second load). A manifest launch (`resolved`) materializes its own transient persona and the
5360
- // file is NOT its authority, so its def (and its agent pin) is deliberately not consulted here —
5361
- // the manifest's own `agent:` field drove the launch object already.
5362
- let def;
5363
- if (!opts.resolved) {
5364
- try {
5365
- def = loadLaunchPersonaFile(configPath);
5366
- }
5367
- catch (e) {
5368
- return { error: rejectionText(e), ...(e instanceof PersonaSourceError ? { code: "bad-request" } : {}) };
5369
- }
5370
- // Shared operator files remain launchable. Owned content follows the catalog's visibility
5371
- // decision before connector loading or any allocation. A hosted run acts for its admission;
5372
- // only a complete authenticated caller can request the current ledger's admin decision.
5373
- if (this.userMode && def.owner !== undefined) {
5374
- const acting = authenticatedCaller === undefined ? undefined
5375
- : this.runHosting?.admittedCaller(authenticatedCaller) ?? authenticatedCaller;
5376
- const personaCaller = acting === undefined ? spawner ?? "" : principalKey(acting.owner, acting.actor).key;
5377
- const admin = authenticatedCaller !== undefined && await this.epAdminReach(authenticatedCaller);
5378
- if (!this.canReadPersona(def.owner, personaCaller, admin))
5379
- return { error: `no persona "${ref}"` };
5380
- }
5381
- }
5382
- return { ref, configPath, def, agent: resolveAgentType({ flag: opts.agent, pin: def?.agent, callerDefault: opts.defaultAgent }) };
5383
- }
5384
- /** Whether a persona path resolves into the inline snapshot directory, the directory itself
5385
- * included. A directory that does not exist holds nothing. */
5386
- insideInlineDir(path) {
5387
- const dir = inlinePersonaDir(this.workspaceRoot);
5388
- if (!existsSync(dir))
5389
- return false;
5390
- const real = realpathSync(path);
5391
- const realDir = realpathSync(dir);
5392
- return real === realDir || real.startsWith(realDir + sep);
5393
- }
5394
- /** The run a spawn acts for (SPEC 14.8). The run this manager drives under `caller` answers from
5395
- * memory. On a static mesh, a spawn from a run hosted elsewhere names its run, whether the program
5396
- * placed it here or the class queue delivered it, and its caller must be that run's driver, whose
5397
- * triple derives from the run id; the run's admission and revocation marker are then read
5398
- * leader-served, so the helper is bounded as the hosting manager bounds it. Elsewhere the run id
5399
- * is not read: a user-auth run's issuing host bounds the helper, and an open mesh bounds none.
5400
- * `undefined` for a spawn that acts for no run. */
5401
- async spawnRun(caller, runId) {
5402
- const hosted = caller !== undefined ? this.runHosting?.runAdmission(caller) : undefined;
5403
- if (hosted !== undefined) {
5404
- if (runId !== undefined && runId !== hosted.runId)
5405
- return { refused: `it names run ${runId}, but its caller drives run ${hosted.runId}` };
5406
- return { admission: hosted, hosted: true };
5407
- }
5408
- if (runId === undefined || this.meshMode !== "static")
5409
- return undefined;
5410
- let driver;
5411
- try {
5412
- driver = caller !== undefined ? runDriverCaller(runId, caller.owner) : undefined;
5413
- }
5414
- catch (e) {
5415
- return { refused: `runId ${JSON.stringify(runId)} is not a run id (${rejectionText(e)})` };
5416
- }
5417
- if (driver === undefined || driver.actor !== caller.actor || driver.uid !== caller.uid)
5418
- return { refused: `it names run ${runId}, but its caller is not that run's driver` };
5419
- if (this.runHosting === undefined)
5420
- return { refused: `run ${runId} asked this manager for a helper, but this manager hosts no runs, so it cannot read the run's admission` };
5421
- let view;
5422
- try {
5423
- view = await this.runHosting.admission(runId);
5424
- }
5425
- catch (e) {
5426
- return { refused: `run ${runId}'s admission and revocation marker could not be read (${rejectionText(e)}), so it starts no helper (SPEC 14.8)` };
5427
- }
5428
- if (view.revoked !== undefined)
5429
- return { refused: revokedRunRefusal(runId, view.revoked) };
5430
- return { admission: view.admission, hosted: false };
5431
- }
5432
- /**
5433
- * Resolve what bounds a spawn's grant on a STATIC mesh: the caller's issued evidence, read the way
5434
- * keyed runs read it. A user-auth mesh bounds the mint on its ledger instead, and an open mesh
5435
- * mints no grant, so both return `exempt`. So does a call with no authenticated caller, which is
5436
- * the manager's own composition root (roster boot, a manifest `launch`, which a static mesh mints
5437
- * only into operator instruments). A workflow run's spawn, whether this manager hosts the run or
5438
- * its spawn reached this manager from another host ({@link spawnRun}), is bounded by the run's admission (SPEC 14.8):
5439
- * the ceiling it recorded, at the starter's coordinate, unless the starter was exempt then. That
5440
- * ceiling is the starter's evidence as resolved at admission, or for a local run the channels the
5441
- * operator named. Any other caller with no issued generation, or whose evidence does not resolve,
5442
- * hands on no grant. The evidence's own standing decides the rest.
5443
- */
5444
- async staticSpawnBound(caller, run) {
5445
- if (this.meshMode !== "static" || caller === undefined)
5446
- return { kind: "exempt" };
5447
- // The driver's own credential is not the run's authority, and the starter's evidence may have
5448
- // expired or changed since: the admission recorded both the ceiling and the verdict.
5449
- if (run !== undefined) {
5450
- const admission = run.admission;
5451
- // Read leader-served before each of the run's spawns, so a run revoked mid-step starts no
5452
- // helper, and a marker this manager cannot read refuses the spawn too. The marker of a run
5453
- // hosted elsewhere was read with its admission.
5454
- let refusal;
5455
- if (run.hosted)
5456
- try {
5457
- const revoked = (await this.runHosting.admission(admission.runId)).revoked;
5458
- if (revoked !== undefined)
5459
- refusal = revokedRunRefusal(admission.runId, revoked);
5460
- }
5461
- catch (e) {
5462
- refusal = `run ${admission.runId}'s revocation marker could not be read (${rejectionText(e)}), so it starts no helper (SPEC 14.8)`;
5463
- }
5464
- if (refusal !== undefined)
5465
- return { kind: "refused", reason: refusal };
5466
- if (admission.spawnExempt)
5467
- return { kind: "exempt" };
5468
- // The helper is projected at the admitted coordinate, which needs a lifecycle token. A local
5469
- // admission written before its uid was one records the CLI's own holder id, and bounds nothing.
5470
- try {
5471
- assertLifecycleToken(admission.caller.uid);
5472
- }
5473
- catch {
5474
- 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)` };
5475
- }
5476
- return { kind: "bounded", caller: admission.caller, ceiling: admission.ceiling, run: admission.runId };
5477
- }
5478
- if (!isIssuedCaller(caller))
5479
- return { kind: "none", reason: "its credential carries no issued generation (an unissued mint or a legacy rail)" };
5480
- const ref = { space: this.space, owner: caller.owner, actor: caller.actor, uid: caller.uid, generation: caller.generation };
5481
- try {
5482
- const { evidence } = await withIssuerSession({ servers: this.servers ?? DEFAULT_SERVER, space: this.space, auth: this.auth, tls: false }, (s) => s.store.resolve(ref, s.sourceIsLive));
5483
- return issuedSpawnerStanding(evidence) === "bounded" ? { kind: "bounded", caller, ceiling: evidence.permissions } : { kind: "exempt" };
5484
- }
5485
- catch (e) {
5486
- return { kind: "none", reason: `its issued evidence does not resolve: ${rejectionText(e)}` };
5487
- }
5488
- }
5489
- /** The refusal for a grant its static spawner does not hold, or `undefined` when it holds all of
5490
- * it. Each part is named, so the caller can drop exactly what overreached. `armsEvents` is whether
5491
- * the helper's own event plane will be minted: that row is keyed on a principal allocated later,
5492
- * so it is measured as the spawner's own, the rule the ledger applies. `door` names the command
5493
- * being bounded: a persona definition is bounded against its definer as a spawn is. */
5494
- spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") {
5495
- if (bound.kind === "exempt")
5496
- return undefined;
5497
- if (bound.kind === "refused")
5498
- return `${door}: ${bound.reason}`;
5499
- let over;
5500
- let eventsOver;
5501
- try {
5502
- over = bound.kind === "none" ? grantParts(grant) : grantOverreach(this.space, bound.caller, bound.ceiling, grant);
5503
- eventsOver = armsEvents && (bound.kind === "none"
5504
- || grantOverreach(this.space, bound.caller, bound.ceiling, { allowPublish: [eventChannel({ owner: bound.caller.owner, actor: bound.caller.actor })] }).length > 0);
5505
- }
5506
- catch (e) {
5507
- return `${door}: ${rejectionText(e)}`;
5508
- }
5509
- if (!over.length && !eventsOver)
5510
- return undefined;
5511
- const named = [
5512
- // A role is handed on by a spawner whose credential binds that role's task queue: its own
5513
- // role, or a `role:<r>` token in its capabilities.
5514
- ...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}`),
5515
- ...(eventsOver ? ["events (the helper's own event plane; pass events: false to spawn without it)"] : []),
5516
- ].join(", ");
5517
- if (door === "define-persona")
5518
- return bound.kind === "none"
5519
- ? `define-persona: the definer holds no issued evidence (SPEC 13.15), so its persona can grant nothing: ${bound.reason}. This persona asks for ${named}. ` +
5520
- `Define it without these, or start the definer under a manager (\`cotal spawn --detach\`), whose seats carry issued evidence.`
5521
- : `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). ` +
5522
- `Drop these from the persona, or have the operator widen the definer's own persona.`;
5523
- if (bound.kind === "bounded" && bound.run !== undefined)
5524
- return `spawn: this spawn hands its helper more than run ${bound.run}'s starter held when the run was admitted: ${named}. ` +
5525
- `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). ` +
5526
- `Drop these from the persona or the spawn, or start the run from a caller that holds them.`;
5527
- return bound.kind === "none"
5528
- ? `spawn: the spawner holds no issued evidence (SPEC 13.15), so it hands on no grant: ${bound.reason}. This spawn asks for ${named}. ` +
5529
- `Spawn a persona that names none of these, or start the spawner under a manager (\`cotal spawn --detach\`), whose seats carry issued evidence.`
5530
- : `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). ` +
5531
- `Drop these from the persona or the spawn, or have the operator widen the spawner's own persona.`;
5532
- }
5533
- /** Ordinary static control seats can read their holding instance. A run's recorded ceiling is
5534
- * authoritative, so its helpers receive no additional instance reads. */
5535
- managedStaticInstanceReads(capabilities) {
5536
- if (this.meshMode !== "static" || !this.managerInstanceId || !capabilities?.some(c => c === "spawn" || c === "run" || c === "admin"))
5537
- return [];
5538
- return ["describe", "inspect"].map(command => ({
5539
- endpoint: MANAGER_ENDPOINT, command, instanceId: this.managerInstanceId, instanceOnly: true,
5540
- }));
5541
- }
4786
+ /** {@link SeatLaunch.spawnPersona}. */
4787
+ spawnPersona(...args) { return this.seatLaunch.spawnPersona(...args); }
4788
+ /** {@link SeatLaunch.spawnRun}. */
4789
+ spawnRun(caller, runId) { return this.seatLaunch.spawnRun(caller, runId); }
4790
+ /** {@link SeatLaunch.staticSpawnBound}. */
4791
+ staticSpawnBound(caller, run) { return this.seatLaunch.staticSpawnBound(caller, run); }
4792
+ /** {@link SeatLaunch.spawnBoundRefusal}. */
4793
+ spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") { return this.seatLaunch.spawnBoundRefusal(bound, grant, armsEvents, door); }
4794
+ /** {@link SeatLaunch.managedStaticInstanceReads}. */
4795
+ managedStaticInstanceReads(capabilities) { return this.seatLaunch.managedStaticInstanceReads(capabilities); }
5542
4796
  async startAgentActive(opts, spawner, hooks, authenticatedCaller) {
5543
4797
  // Before the first await, so the grant, the launch, the retained form and the restart slot all read
5544
4798
  // the lists and the restart policy as admitted.
@@ -5606,13 +4860,19 @@ export class Manager {
5606
4860
  const readinessTimeoutMs = connector.readinessTimeoutMs ?? this.readinessTimeoutMs;
5607
4861
  if (!Number.isSafeInteger(readinessTimeoutMs) || readinessTimeoutMs <= 0)
5608
4862
  return { ok: false, error: `connector ${connector.name} declares invalid readinessTimeoutMs ${JSON.stringify(connector.readinessTimeoutMs)}; expected a positive safe integer` };
5609
- // Capacity check first (cheap, fail-fast). Everything from here to the reserve below is
5610
- // SYNCHRONOUS (existsSync / registry / accessSync / readFileSync — no await), so the gate stays
5611
- // atomic: the capacity snapshot and the reserve land in one tick (P4a/P4c), and two concurrent
5612
- // spawns can't overshoot the ceiling or pick the same name.
5613
- const occupancy = this.occupancy(); // prunes expired cooling stamps; counts each name once
4863
+ // Fail fast when full. If hosted Claude has to await wake setup, resample capacity after it.
4864
+ // The final capacity check and the reserve below stay in the same tick or two concurrent
4865
+ // spawns could overshoot the ceiling or pick the same name.
4866
+ let occupancy = this.namesCapacity.occupancy(); // prunes expired cooling stamps; counts each name once
5614
4867
  if (occupancy.used >= MAX_AGENTS)
5615
- return { ok: false, error: this.capacityRefusal(occupancy) };
4868
+ return { ok: false, error: this.namesCapacity.capacityRefusal(occupancy) };
4869
+ const recheck = this.refreshUnavailableConnectors(connector.name, true);
4870
+ if (recheck) {
4871
+ await recheck;
4872
+ occupancy = this.namesCapacity.occupancy();
4873
+ if (occupancy.used >= MAX_AGENTS)
4874
+ return { ok: false, error: this.namesCapacity.capacityRefusal(occupancy) };
4875
+ }
5616
4876
  // Harness preflight before reserving a slot or minting — a missing `claude`/`opencode` binary
5617
4877
  // fails here with a clear name, not obscurely at process spawn. No fallback. All synchronous, so
5618
4878
  // the reserve gate stays atomic. (The connector itself was resolved up top, before the capacity gate.)
@@ -5682,7 +4942,7 @@ export class Manager {
5682
4942
  if (!this.remoteAuthority?.enrollManagedAgent)
5683
4943
  return { ok: false, error: `${delegatedBy}, which needs a host that enrolls managed agents (remoteAuthority.enrollManagedAgent); a delegated seat has no local grant path` };
5684
4944
  try {
5685
- this.delegatedMeshRecord();
4945
+ this.userProvision.delegatedMeshRecord();
5686
4946
  }
5687
4947
  catch (e) {
5688
4948
  return { ok: false, error: rejectionText(e) };
@@ -5813,9 +5073,8 @@ export class Manager {
5813
5073
  catch (e) {
5814
5074
  return { ok: false, error: opts.resolved ? `launch agent: ${rejectionText(e)}` : `persona ${where}: ${rejectionText(e)}` };
5815
5075
  }
5816
- // The AG-UI event plane is on unless the launch explicitly opted out. A connector that cannot
5817
- // emit one is refused further down, before anything is minted.
5818
- const events = this.eventsRequired || opts.events !== false;
5076
+ // Default events on where the connector supports them, unless the launch explicitly opts out.
5077
+ const events = this.eventsRequired || opts.events === true || (opts.events !== false && !!connector.eventChannel);
5819
5078
  if (this.eventPayloadsWithheld && opts.eventPayloads === true)
5820
5079
  return { ok: false, error: "space policy withholds event payloads" };
5821
5080
  const eventPayloads = !this.eventPayloadsWithheld && (opts.eventPayloads ?? def?.eventPayloads) !== false;
@@ -5864,7 +5123,7 @@ export class Manager {
5864
5123
  return { ok: false, error: "model: must not be empty" };
5865
5124
  if (variant !== undefined && !variant.trim())
5866
5125
  return { ok: false, error: "variant: must not be empty" };
5867
- const idErr = this.nameError(identityName);
5126
+ const idErr = this.namesCapacity.nameError(identityName);
5868
5127
  if (idErr)
5869
5128
  return { ok: false, error: opts.resolved ? `launch agent: ${idErr}` : `persona ${where}: ${idErr}` };
5870
5129
  // #966: a seat labelled `manager` that cannot spawn is a worker wearing a label, and the label
@@ -5920,7 +5179,7 @@ export class Manager {
5920
5179
  const held = this.retirement.held(identityName);
5921
5180
  if (held !== undefined) {
5922
5181
  hooks?.onEffect?.();
5923
- void this.deprovision(held.target).catch(() => { });
5182
+ void this.retirement.deprovision(held.target).catch(() => { });
5924
5183
  const err = lifecycleBlocked("failed-precondition", `the name "${identityName}" is reserved pending retirement: its previous agent's despawn started that lifecycle's teardown (footprint + standing-authority revoke + auth-side retirement), and the name frees only when all of it completes${held.lastError !== undefined ? ` (last attempt: ${held.lastError})` : ""}. NEXT: wait a moment and retry this spawn (retrying re-drives the whole teardown), or pick another name.`, { blockedOp: "retirement", opId: held.opId, remedy: "retry" });
5925
5184
  return { ok: false, error: renderLifecycleBlocked(err.message, err), details: err.details };
5926
5185
  }
@@ -5976,13 +5235,13 @@ export class Manager {
5976
5235
  let name;
5977
5236
  for (;;) {
5978
5237
  if (hardPinned) {
5979
- if (this.nameInUse(identityName))
5238
+ if (this.namesCapacity.nameInUse(identityName))
5980
5239
  return { ok: false, code: "already-exists", error: `the name "${identityName}" is hard-pinned (${opts.resolved ? "manifest-declared" : "--name/identity override"}) but is already held by a live incarnation (managed here, an unmanaged foreground/connector session, or another manager's agent); a pinned same-name collision refuses at accept - pick another name or despawn the existing one` };
5981
5240
  name = identityName;
5982
5241
  }
5983
5242
  else {
5984
5243
  try {
5985
- name = this.uniqueName(identityName, unavailable);
5244
+ name = this.namesCapacity.uniqueName(identityName, unavailable);
5986
5245
  }
5987
5246
  catch (e) {
5988
5247
  return { ok: false, error: rejectionText(e) };
@@ -6023,7 +5282,7 @@ export class Manager {
6023
5282
  }
6024
5283
  // Another spawn may have reserved the candidate while the disk/broker proof awaited.
6025
5284
  // Recheck in the same synchronous window as the cap and reservation below.
6026
- if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
5285
+ if (this.namesCapacity.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
6027
5286
  if (!hardPinned)
6028
5287
  continue;
6029
5288
  return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
@@ -6084,7 +5343,7 @@ export class Manager {
6084
5343
  // launch. Minting it inside `runtime.spawn` (as it used to be) put the processes on disk
6085
5344
  // before anything recorded how to address them, so a crash in that window left a live seat
6086
5345
  // outside every manager and the successor retired the slot over it.
6087
- const custody = this.reserveCustody(runtime);
5346
+ const custody = this.seatCustody.reserveCustody(runtime);
6088
5347
  // ACCEPT SEAM (spawn-as-action): the incarnation identity is minted and NOTHING has
6089
5348
  // been provisioned yet — the action serve path binds the goal + replies the acceptance HERE. A
6090
5349
  // throw (bind conflict / duplicate goalId) aborts the spawn before provisioning: the catch below
@@ -6182,7 +5441,7 @@ export class Manager {
6182
5441
  lifecycleUid,
6183
5442
  enrollmentCaller: authenticatedCaller ? { owner: authenticatedCaller.owner, actor: authenticatedCaller.actor } : undefined,
6184
5443
  delegatedIntent: opts.delegatedIntent,
6185
- ...(opts.served !== undefined ? { spawnRequest: this.servedSpawnRequest(opts.served, authenticatedCaller) } : {}),
5444
+ ...(opts.served !== undefined ? { spawnRequest: this.userProvision.servedSpawnRequest(opts.served, authenticatedCaller) } : {}),
6186
5445
  // Hold the name at the UID the host enrolled for the intent's user before any later local
6187
5446
  // step runs, so no later failure, its refusal included, releases a lifecycle that only that
6188
5447
  // user's retirement intent retires.
@@ -6345,13 +5604,13 @@ export class Manager {
6345
5604
  let spec;
6346
5605
  let handle;
6347
5606
  if (runtime.spawnDelegated) {
6348
- const handoff = this.composeManagedHandoff(enrolled.material, enrolled.actorToken);
5607
+ const handoff = this.userProvision.composeManagedHandoff(enrolled.material, enrolled.actorToken);
6349
5608
  if (this.delegatedLaunched.has(lifecycleUid))
6350
5609
  throw new Error(`lifecycle ${lifecycleUid} was already handed to runtime "${runtime.kind}"; a lifecycle is handed off at most once`);
6351
5610
  this.delegatedLaunched.add(lifecycleUid);
6352
5611
  const holder = retainConnectorSeat(this.managerInstanceId, name);
6353
5612
  handle = runtime.spawnDelegated({ agent, persona: readFileSync(configPath, "utf8"), managerInstanceId: this.managerInstanceId, role, model, variant, prompt, launchOptions: launchOptions, events, eventPayloads }, handoff);
6354
- this.watchConnectorHolder(handle, holder);
5613
+ watchConnectorHolder(handle, holder);
6355
5614
  }
6356
5615
  else {
6357
5616
  if (carried) {
@@ -6363,7 +5622,7 @@ export class Manager {
6363
5622
  if (carried)
6364
5623
  this.transcripts.consume(opts.resumeClaim, opts.resume);
6365
5624
  spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
6366
- handle = await this.spawnCustodied(runtime, name, spec, cwd, custody);
5625
+ handle = await this.seatCustody.spawnCustodied(runtime, name, spec, cwd, custody);
6367
5626
  }
6368
5627
  if (onceTask && !handle.waitForExit)
6369
5628
  throw new Error(`once: runtime "${handle.kind}" cannot prove the seat's exit, which is what ends its task when the seat goes first`);
@@ -6457,8 +5716,7 @@ export class Manager {
6457
5716
  await casStaticSlot(t, { ...slot.row, phase: "active", ...(handle.reference ? { runtime: handle.reference } : {}) }, slot.revision);
6458
5717
  });
6459
5718
  }
6460
- this.agents.set(name, managed);
6461
- this.namesCapacity.placed(name);
5719
+ this.place(name, managed);
6462
5720
  if (managed.once)
6463
5721
  this.watchOnceExit(managed);
6464
5722
  // The live slot now owns teardown — freeSlot deprovisions this identity on exit — so the
@@ -6496,13 +5754,12 @@ export class Manager {
6496
5754
  if (!readiness.ok) {
6497
5755
  this.watchExit(managed);
6498
5756
  if (managed.launch.carried)
6499
- void this.refuseLateCarriedFork(managed, readinessTimeoutMs);
5757
+ void this.sessionRecovery.refuseLateCarriedFork(managed, readinessTimeoutMs);
6500
5758
  // A once seat is never left running with nothing to do, and its stop does not wait on the
6501
5759
  // spawn's terminal, whose write can stall. The spawn keeps that terminal: the stop lets go
6502
5760
  // of the spawn goal first. Its task was never served and is cancelled with the verdict.
6503
5761
  if (managed.once) {
6504
- this.agentGoals.delete(managed.name);
6505
- this.stopOnceSeat(managed, "readiness-timeout");
5762
+ this.endOnceBeforeServe(managed, "readiness-timeout");
6506
5763
  }
6507
5764
  await hooks?.onOutcome?.({ kind: "uncertain", data: { reason: readiness.detail, ...(readiness.running ? { running: true } : {}) } });
6508
5765
  return { ok: false, error: readiness.detail };
@@ -6512,7 +5769,7 @@ export class Manager {
6512
5769
  // task, never served, cancelled with the verdict.
6513
5770
  if (onceTask && connector.onceNeedsConfirmed !== undefined) {
6514
5771
  const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
6515
- if (managed.terminalizing) {
5772
+ if (managed.terminalizing || this.leaseStopping) {
6516
5773
  hooks?.onTerminalDeferred?.();
6517
5774
  return { ok: false, error: `${name} was stopped before its startup ended` };
6518
5775
  }
@@ -6520,9 +5777,7 @@ export class Manager {
6520
5777
  const watch = { ready: "opened its input screen without the prompt", failed: "failed", exited: "saw the seat exit", pending: "had not ended" }[startup];
6521
5778
  const error = `${name} joined, but ${connector.onceNeedsConfirmed}: its startup watch ${watch}, so it cannot take a once task`;
6522
5779
  this.watchExit(managed);
6523
- this.agentGoals.delete(managed.name);
6524
- managed.once.stopReason ??= "launch-failed";
6525
- this.stopOnceSeat(managed, "launch-failed");
5780
+ this.endOnceBeforeServe(managed, "launch-failed", "launch-failed");
6526
5781
  await hooks?.onOutcome?.({ kind: "failed", data: { error } });
6527
5782
  return { ok: false, error };
6528
5783
  }
@@ -6532,7 +5787,7 @@ export class Manager {
6532
5787
  // starting it silently without push (#5737).
6533
5788
  if (!onceTask && connector.idleWakeNeedsConfirmed !== undefined && runtime.reportsStartupOutcome) {
6534
5789
  const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
6535
- if (managed.terminalizing) {
5790
+ if (managed.terminalizing || this.leaseStopping) {
6536
5791
  hooks?.onTerminalDeferred?.();
6537
5792
  return { ok: false, error: `${name} was stopped before its startup ended` };
6538
5793
  }
@@ -6542,14 +5797,13 @@ export class Manager {
6542
5797
  }
6543
5798
  }
6544
5799
  if (managed.launch.carried) {
6545
- const refused = await this.refuseCarriedFork(managed, readinessTimeoutMs);
5800
+ const refused = await this.sessionRecovery.refuseCarriedFork(managed, readinessTimeoutMs);
6546
5801
  if (refused !== undefined && managed.terminalizing) {
6547
5802
  hooks?.onTerminalDeferred?.();
6548
5803
  return { ok: false, error: refused };
6549
5804
  }
6550
5805
  if (refused !== undefined) {
6551
- this.stopHandle(managed, false, "carried-fork-refused");
6552
- this.trackStoppedHandle(managed, true, "carried-fork-refused");
5806
+ this.stopAndTrack(managed, "carried-fork-refused");
6553
5807
  await hooks?.onOutcome?.({ kind: "failed", data: { error: refused } });
6554
5808
  return { ok: false, error: refused };
6555
5809
  }
@@ -6557,23 +5811,22 @@ export class Manager {
6557
5811
  if (managed.restart) {
6558
5812
  if (connector.supportsSessionContinuation) {
6559
5813
  try {
6560
- await this.armSessionRecovery(managed);
5814
+ await this.sessionRecovery.armSessionRecovery(managed);
6561
5815
  // The capability flags are only a claim. An exact seat is recorded once the connector
6562
5816
  // has proved its session over its authenticated control endpoint, never before.
6563
5817
  if (exact && !managed.restart.armed)
6564
5818
  throw new Error("continuity: exact needs the connector to prove its session over an authenticated control endpoint, and it supplied none");
6565
- managed.launch.sessionId = this.readManagedSession(managed);
5819
+ managed.launch.sessionId = this.sessionRecovery.readManagedSession(managed);
6566
5820
  if (reopenSession !== undefined && managed.launch.sessionId !== reopenSession)
6567
5821
  throw new Error(`continuity: exact asked for session ${reopenSession}, the connector bound ${managed.launch.sessionId}`);
6568
5822
  if (exact) {
6569
5823
  managed.continuity = { space: this.space, name, connector: agent, cwd };
6570
- this.recordContinuity(managed, managed.launch.sessionId);
5824
+ this.sessionRecovery.recordContinuity(managed, managed.launch.sessionId);
6571
5825
  }
6572
5826
  }
6573
5827
  catch (error) {
6574
5828
  const detail = `${managed.name} joined, but its exact host session could not be bound for supervised recovery: ${rejectionText(error)}`;
6575
- this.stopHandle(managed, false, "session-bind-failed");
6576
- this.trackStoppedHandle(managed, true, "session-bind-failed");
5829
+ this.stopAndTrack(managed, "session-bind-failed");
6577
5830
  await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
6578
5831
  return { ok: false, error: detail };
6579
5832
  }
@@ -6583,12 +5836,11 @@ export class Manager {
6583
5836
  }
6584
5837
  if (managed.restart.policy) {
6585
5838
  try {
6586
- this.recordSeat(managed);
5839
+ this.seatCustody.recordSeat(managed);
6587
5840
  }
6588
5841
  catch (error) {
6589
5842
  const detail = `${managed.name} joined, but supervise cannot cover a manager restart for it: ${rejectionText(error)}`;
6590
- this.stopHandle(managed, false, "supervise-record-failed");
6591
- this.trackStoppedHandle(managed, true, "supervise-record-failed");
5843
+ this.stopAndTrack(managed, "supervise-record-failed");
6592
5844
  await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
6593
5845
  return { ok: false, error: detail };
6594
5846
  }
@@ -6597,7 +5849,7 @@ export class Manager {
6597
5849
  // An unsupervised seat a successor could adopt keeps a record too; one that cannot be written
6598
5850
  // costs only that adoption, so the spawn stands and the line says so.
6599
5851
  if (!managed.restart?.policy)
6600
- this.refreshSeatRecord(managed);
5852
+ this.seatCustody.refreshSeatRecord(managed);
6601
5853
  this.watchExit(managed);
6602
5854
  // Reply with the id the slot actually carries (user-mode: the owner.actor principal —
6603
5855
  // presence, ps, and the manifest ownership ledger all key on it; the throwaway static nkey
@@ -6618,9 +5870,7 @@ export class Manager {
6618
5870
  if (onceTask && committed === true)
6619
5871
  this.openOnceDelivery(onceTask.ref);
6620
5872
  else if (onceTask) {
6621
- this.agentGoals.delete(managed.name);
6622
- managed.once.stopReason ??= "launch-failed";
6623
- this.stopOnceSeat(managed, "launch-failed");
5873
+ this.endOnceBeforeServe(managed, "launch-failed", "launch-failed");
6624
5874
  }
6625
5875
  return { ok: true, data: okData };
6626
5876
  }
@@ -7059,6 +6309,7 @@ export class Manager {
7059
6309
  catch (e) {
7060
6310
  return { ok: false, error: rejectionText(e) };
7061
6311
  }
6312
+ await this.refreshUnavailableConnectors(connector.name, true);
7062
6313
  const harness = this.launchHarness(connector);
7063
6314
  if ("refusal" in harness)
7064
6315
  return { ok: false, error: harness.refusal };
@@ -7462,6 +6713,7 @@ export class Manager {
7462
6713
  if (joinedPoll !== undefined)
7463
6714
  clearInterval(joinedPoll);
7464
6715
  this.ep.off("presence", onPresence);
6716
+ this.shutdownReadiness.signal.removeEventListener("abort", onShutdown);
7465
6717
  unsubExit();
7466
6718
  resolve(r);
7467
6719
  };
@@ -7469,6 +6721,9 @@ export class Manager {
7469
6721
  if (joined())
7470
6722
  finish({ ok: true });
7471
6723
  };
6724
+ // Shutdown owns the seat's stop and retirement after the lifecycle ticket drains. Do not
6725
+ // keep that ticket waiting on a connector's readiness window while shutdown waits on it.
6726
+ const onShutdown = () => finish({ ok: false, deliberate: true, detail: `${a.name} was stopped before it reported ready` });
7472
6727
  if (opts.joinedAfter !== undefined) {
7473
6728
  // Heartbeats bump roster.ts without emitting "presence" (same status/uid/activity).
7474
6729
  // A supervised restart needs that bump, so poll joined() rather than waiting on the event.
@@ -7557,8 +6812,11 @@ export class Manager {
7557
6812
  else
7558
6813
  pollProvedExit(a.handle, onExit, () => !done, READINESS_EXIT_POLL_MS);
7559
6814
  this.ep.on("presence", onPresence);
6815
+ this.shutdownReadiness.signal.addEventListener("abort", onShutdown, { once: true });
7560
6816
  // Subscribe-then-check (TOCTOU): a join or an exit that already landed before we subscribed.
7561
- if (s && a.handle.status() === "exited")
6817
+ if (this.shutdownReadiness.signal.aborted)
6818
+ onShutdown();
6819
+ else if (s && a.handle.status() === "exited")
7562
6820
  onExit();
7563
6821
  else
7564
6822
  onPresence();
@@ -7606,57 +6864,13 @@ export class Manager {
7606
6864
  occupancy() { return this.namesCapacity.occupancy(); }
7607
6865
  occupancyText(o) { return this.namesCapacity.occupancyText(o); }
7608
6866
  capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
7609
- /**
7610
- * The owner a launch belongs to, read ONCE so the per-owner ceiling, the agent's addressing
7611
- * triple and the user-mode provisioner cannot charge three different owners for one seat. A
7612
- * static or open mesh has one owner by construction; a user-auth mesh takes the spec's owner,
7613
- * else the owner of the principal that asked, which is what {@link provisionUserAgent} resolves
7614
- * from the same two values (it refuses outright where this falls back, so the two never disagree
7615
- * on an admitted launch).
7616
- */
7617
- launchOwner(opts, spawner) {
7618
- if (!this.userMode)
7619
- return DEV_OWNER;
7620
- const asked = spawner === undefined ? undefined : parsePrincipalKey(spawner)?.owner;
7621
- return opts.owner ?? (asked?.startsWith("u_") ? asked : DEV_OWNER);
7622
- }
7623
- /** The owner of a seat this manager supervises, by the same rule {@link launchOwner} admitted it
7624
- * under: a user-mode seat records its derived owner, and every other seat is the mesh's one owner. */
7625
- seatOwner(a) {
7626
- return a.userOwner ?? DEV_OWNER;
7627
- }
7628
- /**
7629
- * Live seats this manager holds for one owner: the seats it supervises, plus the launches it has
7630
- * reserved for that owner and not yet placed. It deliberately does NOT count cooling stamps — a
7631
- * cooling slot is a seat that already freed, and the recycle floor it holds is a global
7632
- * fork-bomb bound (P4c), not one tenant's occupancy. Mirrors {@link occupancy}'s reserved rule,
7633
- * so a reservation stops being counted twice the moment its seat reaches `agents`.
7634
- */
7635
- ownerSeats(owner) {
7636
- let seats = 0;
7637
- for (const a of this.agents.values())
7638
- if (this.seatOwner(a) === owner)
7639
- seats++;
7640
- seats += this.namesCapacity.ownerReservations(owner);
7641
- return seats;
7642
- }
7643
- /**
7644
- * The per-owner ceiling, consulted at accept: `undefined` admits the launch, and a refusal
7645
- * carries the owner's count and the cap so a caller can render a remedy and a script can decide
7646
- * without re-reading prose. Distinct from {@link capacityRefusal}, which bounds the HOST: that
7647
- * one frees when anyone stops a seat or a cooling slot expires, this one frees only when THIS
7648
- * owner stops one of its own, or the operator raises the cap, so they cannot share a sentence.
7649
- */
7650
- seatCapRefusal(owner) {
7651
- const cap = this.seatCap;
7652
- if (cap === SEAT_CAP_UNLIMITED)
7653
- return undefined;
7654
- const seats = this.ownerSeats(owner);
7655
- if (seats < cap)
7656
- return undefined;
7657
- return seatCapRefused(`owner ${owner} holds ${seats} of the ${cap} seat${cap === 1 ? "" : "s"} manager ${this.managerInstanceId} admits per owner; ` +
7658
- `stop one of that owner's seats, or ask the operator who runs this manager for a higher seat cap`, { owner, seats, cap });
7659
- }
6867
+ /** The owner a launch belongs to: {@link NamesCapacity.launchOwner}. */
6868
+ launchOwner(opts, spawner) { return this.namesCapacity.launchOwner(opts, spawner); }
6869
+ /** Live seats this manager holds for one owner: {@link NamesCapacity.ownerSeats}. */
6870
+ // @ts-expect-error TS6133: the seat-cap smoke reads this private count through a structural view.
6871
+ ownerSeats(owner) { return this.namesCapacity.ownerSeats(owner); }
6872
+ /** The per-owner ceiling at accept: {@link NamesCapacity.seatCapRefusal}. */
6873
+ seatCapRefusal(owner) { return this.namesCapacity.seatCapRefusal(owner); }
7660
6874
  // @ts-expect-error TS6133: retained fixtures call this private adapter through structural views.
7661
6875
  async opStop(args, caller, admin) {
7662
6876
  const name = String(args.name ?? "").trim();
@@ -7907,7 +7121,8 @@ export class Manager {
7907
7121
  /** The served manager-level health summary. Given an owner, `agentCount` counts only that owner's
7908
7122
  * seats, as `ps` lists them ({@link psOwnerFilter}), so a person reading a shared Manager does not
7909
7123
  * learn how many seats other owners hold on it. */
7910
- managerStatusData(ownerFilter) {
7124
+ managerStatusData(ownerFilter, setupClaude = false) {
7125
+ this.refreshUnavailableConnectors(undefined, setupClaude);
7911
7126
  return {
7912
7127
  instanceId: this.managerInstanceId,
7913
7128
  lifecycleUid: this.managerLifecycleUid,
@@ -8182,7 +7397,7 @@ export class Manager {
8182
7397
  // filters on (skip a goal whose accepting `iid` is a still-LIVE sibling — never settle its goal).
8183
7398
  for (const entry of entries) {
8184
7399
  const key = goalKey(entry.ref);
8185
- if (this.goalAcceptances.has(key) || this.turnAcceptances.has(key))
7400
+ if (this.goalAcceptances.has(key) || this.turnRelay.hasAcceptance(key))
8186
7401
  continue; // never settle a goal THIS incarnation drives
8187
7402
  try {
8188
7403
  // A note marks a TURN entry: its relay is rebuilt (the hold is its bounded ending), never
@@ -8204,11 +7419,11 @@ export class Manager {
8204
7419
  }
8205
7420
  finally {
8206
7421
  this.goalReconcileDone = true;
8207
- this.goalReconcileDoneAt = Date.now();
7422
+ this.turnRelay.markReconciled(Date.now());
8208
7423
  // A seat that pulled during the window was refused, and a predecessor may have died before
8209
7424
  // its notice went out, so every seat holding a rebuilt turn is told once.
8210
- const seats = new Map([...this.pendingTurns.values()].map((p) => [`${p.seat.owner}.${p.seat.actor}.${p.seat.uid}`, p.seat]));
8211
- for (const seat of seats.values())
7425
+ const seats = this.turnRelay.pendingSeats();
7426
+ for (const seat of seats)
8212
7427
  this.noticeSeatTurns(seat);
8213
7428
  }
8214
7429
  }
@@ -8633,178 +7848,10 @@ export class Manager {
8633
7848
  * path (idempotent retry map, index-CAS-before-bind, create-only bindGoal) but runs it INLINE:
8634
7849
  * there is no launch to hand off, so the accept either completes durably or unwinds its own
8635
7850
  * bound goal with a `failed` terminal before refusing. */
8636
- async serveTurnGoal(ctx, target) {
8637
- const gw = this.goalWriter;
8638
- if (!gw)
8639
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; turn-as-action cannot accept (SPEC 13.6)");
8640
- const serve = this.serviceServe;
8641
- if (!serve)
8642
- throw new EpEnvelopeError("unavailable", "the manager service endpoint is not serving; a turn's deadline hold is armed over its connection (SPEC 13.9)");
8643
- if (!this.goalReconcileDone)
8644
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; retry shortly (SPEC 13.6)");
8645
- const t = ctx.request.target; // targeted command: the serve boundary enforced presence + currency
8646
- const name = target.name;
8647
- const goalId = ctx.request.id;
8648
- const { fingerprint } = submissionFingerprint(ctx.request, ctx.subject);
8649
- const ref = goalRefOf(ctx.subject, goalId);
8650
- const key = goalKey(ref);
8651
- const executor = { lifecycleUid: this.managerInstanceId, epoch: this.serviceServe?.grant.epoch ?? 0 };
8652
- const acceptedAt = Date.now();
8653
- const prior = this.turnAcceptances.get(key)?.acceptance;
8654
- if (prior !== undefined) {
8655
- if (prior.fingerprint !== fingerprint)
8656
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted under a different submission; one goalId never carries two specs (SPEC 13.6)`);
8657
- return prior;
8658
- }
8659
- // Refused here, before anything durable, so the caller's goal id stays free for another seat.
8660
- this.assertSeatTurnFree(name, t, goalId);
8661
- if (target.kind === "managed" && target.agent.once)
8662
- throw new EpEnvelopeError("failed-precondition", `seat "${name}" is a once seat; it takes only the task it was spawned with`, undefined, "not-executed");
8663
- const raw = (ctx.request.args ?? {});
8664
- const payload = String(raw.payload);
8665
- const deadlineAt = raw.deadlineAt === undefined ? acceptedAt + Number(raw.deadlineMs) : Number(raw.deadlineAt);
8666
- if (deadlineAt <= acceptedAt)
8667
- throw new EpEnvelopeError("deadline-exceeded", `goal "${goalId}" names a deadline already past (${new Date(deadlineAt).toISOString()}); a turn with no time left to serve it is never accepted (SPEC 13.6)`);
8668
- const deadlineMs = deadlineAt - acceptedAt;
8669
- const handoffFrom = raw.handoffFrom === undefined ? undefined : String(raw.handoffFrom);
8670
- const holdToken = turnHoldToken(key);
8671
- const note = JSON.stringify({ payload, deadlineAt, holdEpoch: executor.epoch, holdToken, ...(handoffFrom !== undefined ? { handoffFrom } : {}) });
8672
- // A goal that already ENDED is never accepted again, whatever the retry carries: the bind is
8673
- // create-only and outlives an unwind (the failed terminal, the cleared index), so a retry of an
8674
- // unwound accept would otherwise re-record an index entry over a tombstone and, before that
8675
- // check existed, be served an acceptance rebuilt from it — a live deadline on a turn no seat
8676
- // would ever be shown. The terminal is the durable answer, and it is read before anything is
8677
- // written.
8678
- const ended = await readGoalResult(gw.ctx, ref);
8679
- if (ended !== undefined)
8680
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" already ended ${ended.state}; a bound goal is never accepted again (SPEC 13.6)`);
8681
- // Index-CAS-before-bind, exactly as spawn: the entry (floor + note) is the durable relay
8682
- // record a successor rebuilds from, so it must exist before the acceptance is servable.
8683
- const idx = await recordGoalIndex(gw.ctx, ref, executor.lifecycleUid, { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid, readinessDeadlineMs: deadlineMs }, note);
8684
- if (!idx.recorded && idx.existing.iid !== executor.lifecycleUid)
8685
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted by instance "${idx.existing.iid}"; that instance owns its relay and this attempt provisions nothing (SPEC 13.6)`);
8686
- const b = await bindGoal(gw.ctx, ref, fingerprint);
8687
- if (!b.bound) {
8688
- if (b.existing.fingerprint !== fingerprint)
8689
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" is already bound to a different submission; one goalId never carries two specs (SPEC 13.6)`);
8690
- // Same submission, bound, not ended, and not in the acceptance map. Every relay this
8691
- // incarnation holds is in that map (the accept path and the boot sweep both write it), so
8692
- // this is a goal nobody is relaying: an earlier attempt bound it and could not finish its
8693
- // unwind, or a predecessor's relay was left unadopted. Nothing here can rebuild a relay a
8694
- // seat will be shown, so the caller is refused rather than served an acceptance no pending
8695
- // entry backs; the index entry this attempt recorded is withdrawn with it.
8696
- if (idx.recorded)
8697
- await clearGoalIndex(gw.ctx, ref);
8698
- throw new EpEnvelopeError("unavailable", `goal "${goalId}" is bound but no relay of it is pending on this instance; retry (SPEC 13.6)`);
8699
- }
8700
- try {
8701
- await createGoal(gw.ctx, ref, {
8702
- fingerprint,
8703
- command: ctx.subject.command,
8704
- caller: { id: `${ctx.subject.caller.owner}.${ctx.subject.caller.actor}`, lifecycleUid: ctx.subject.caller.uid },
8705
- acceptedEpoch: executor.epoch,
8706
- requestId: goalId,
8707
- sourceSeq: 0,
8708
- acceptedAt,
8709
- readinessDeadlineMs: deadlineMs,
8710
- // The §13.6 target pin: the seat INCARNATION this payload is addressed to. A successor
8711
- // under the same name is a different addressee; its uid differs and the pin holds that.
8712
- target: { owner: t.owner, actor: t.actor, lifecycleUid: t.lifecycleUid, mappingRevision: 0 },
8713
- });
8714
- // The deadline, as a goal-bound hold on the plane: its EXPIRED settle is the one predicate
8715
- // `commitGoalResult` accepts for the deny. The record rides the goal-writer's KV; the
8716
- // `.schedule` request rides the SERVE connection, because the timer row is the serving
8717
- // instance's own (`ept.<e>.<iid>.<epoch>.*.schedule`, SPEC 13.9) and the goal-writer holds
8718
- // none. Measured on an auth mesh: minted over the goal-writer, the schedule publish was
8719
- // broker-denied and every accept unwound.
8720
- await mintCheckpoint(gw.ctx.kv, jetstream(serve.nc), this.space, {
8721
- ref: { endpoint: ref.endpoint, token: holdToken },
8722
- instanceId: this.managerInstanceId,
8723
- epoch: executor.epoch,
8724
- goal: { caller: { owner: ctx.subject.caller.owner, actor: ctx.subject.caller.actor, uid: ctx.subject.caller.uid }, goalId },
8725
- holder: { id: MANAGER_ENDPOINT, lifecycleUid: this.managerInstanceId },
8726
- deadline: deadlineAt,
8727
- now: acceptedAt,
8728
- });
8729
- // Again after the awaits, with no await before the maps are written: another caller's
8730
- // accept of this id to this seat may have finished meanwhile, and this unwinds the loser.
8731
- this.assertSeatTurnFree(name, t, goalId);
8732
- }
8733
- catch (e) {
8734
- // The accept is inline (no launch closure to fail later), so a post-bind throw unwinds HERE:
8735
- // commit the failed terminal this attempt owns, clear the index, and refuse the accept — an
8736
- // accepted-but-unanswered goal must never be left for the boot sweep to find (H1's rule).
8737
- const msg = rejectionText(e);
8738
- try {
8739
- await this.assertGoalWriterEpochCurrent(executor.epoch);
8740
- // The goal is TARGET-PINNED, so its completion proves the seat's currency exactly as the
8741
- // yield's does (managed-seat epochs are 0 within an incarnation; the resolver answers from
8742
- // the live agents map). Committed without it, core refused the terminal and the unwind
8743
- // left a bound goal with no ending for every retry to find.
8744
- await commitGoalResult(gw.ctx, {
8745
- ref, now: Date.now(), cause: "complete", state: "failed", data: { error: msg },
8746
- committer: { instanceId: this.managerInstanceId, epoch: executor.epoch },
8747
- executor: { lifecycleUid: t.lifecycleUid, epoch: 0 },
8748
- resolveCurrentEpoch: (current) => this.turnExecutorEpoch(name, t.owner, t.actor, current.lifecycleUid),
8749
- });
8750
- await clearGoalIndex(gw.ctx, ref);
8751
- }
8752
- catch (e2) {
8753
- console.error(`! turn accept unwind for ${goalId}: ${rejectionText(e2)}`);
8754
- }
8755
- throw caughtEnvelope(e) ?? new EpEnvelopeError("internal", `turn accept for ${goalId} failed: ${msg}`);
8756
- }
8757
- const pending = {
8758
- ref, goalId,
8759
- seat: { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid },
8760
- payload, acceptedAt, deadlineAt,
8761
- holdToken, holdEpoch: executor.epoch,
8762
- ...(handoffFrom !== undefined ? { handoffFrom } : {}),
8763
- };
8764
- this.pendingTurns.set(key, pending);
8765
- this.ensureTurnSweep();
8766
- this.noticeSeatTurns(pending.seat);
8767
- const acceptance = { name, owner: t.owner, actor: t.actor, uid: t.lifecycleUid, goalId, fingerprint, deadlineAt, executor };
8768
- this.turnAcceptances.set(key, { acceptance, ref });
8769
- this.emitGoalProgress(ref, executor.epoch, { phase: "relayed" });
8770
- return acceptance;
8771
- }
7851
+ serveTurnGoal(ctx, target) { return this.turnRelay.serveTurnGoal(ctx, target); }
8772
7852
  /** The seat's pull: every pending turn addressed to the CALLER's incarnation, oldest first.
8773
7853
  * The uid is part of the address — a successor seat never receives a predecessor's turn. */
8774
- turnPendingFor(c) {
8775
- // AN EMPTY LIST IS AN ANSWER, so it must not be given before the index is rebuilt. Between
8776
- // registration and `reconcileGoalIndex`, `pendingTurns` holds nothing a predecessor accepted,
8777
- // and a seat that pulls in that window is told authoritatively that it has no turn. The seat
8778
- // treats a refusal as "keep what you hold" and an empty list as "you hold nothing", so the
8779
- // window has to refuse, the same way `serveTurnGoal` does.
8780
- if (!this.goalReconcileDone)
8781
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; the pending-turn index is not rebuilt yet, retry (SPEC 13.6)");
8782
- // A once seat this manager does not hold, whose task has ended, is told to end itself. Nothing
8783
- // else rides that answer, and the settled task is never served again.
8784
- const stop = this.onceStops.get(c.uid);
8785
- if (stop !== undefined && stop.owner === c.owner && stop.actor === c.actor) {
8786
- stop.told = true;
8787
- return { turns: [], notices: true, stop: true };
8788
- }
8789
- // Two turns on one seat are serialized at the dispatch (cotal-lang 6.5): only the oldest
8790
- // unsettled one is served, and the next surfaces once it yields or its deadline denies, so a
8791
- // seat is never shown two turns at once.
8792
- // An ELAPSED turn is not servable: its hold is expirable and its run has already thrown from
8793
- // its own pause, so handing it to the seat buys work whose yield is refused. It also cannot be
8794
- // allowed to stay the head, or one expired turn dams every later turn for that seat. A once
8795
- // task is not served before its spawn's readiness verdict, and one with no deadline never
8796
- // elapses.
8797
- const now = Date.now();
8798
- const head = [...this.pendingTurns.values()]
8799
- .filter((p) => p.seat.owner === c.owner && p.seat.actor === c.actor && p.seat.uid === c.uid)
8800
- .filter((p) => (p.deadlineAt === undefined || now < p.deadlineAt) && p.once?.deliverable !== false)
8801
- .sort((x, y) => x.acceptedAt - y.acceptedAt)
8802
- .slice(0, 1);
8803
- for (const p of head)
8804
- p.pulledAt ??= now;
8805
- const turns = head.map((p) => ({ goalId: p.goalId, payload: p.payload, acceptedAt: p.acceptedAt, ...(p.deadlineAt !== undefined ? { deadlineAt: p.deadlineAt } : {}), ...(p.once ? { once: true } : {}) }));
8806
- return { turns, notices: true };
8807
- }
7854
+ turnPendingFor(c) { return this.turnRelay.turnPendingFor(c); }
8808
7855
  /** Tell a seat that its `turn-pending` answer changed (SPEC 14.3 turn notice), over the serve
8809
7856
  * connection that holds this instance's reply rows. The notice carries no turn and the seat
8810
7857
  * pulls on it, so a lost notice delays that seat until its next pull, and nothing else. */
@@ -8824,163 +7871,17 @@ export class Manager {
8824
7871
  console.error(`! turn notice for ${seat.actor} failed: ${rejectionText(e)}`);
8825
7872
  }
8826
7873
  }
8827
- /** A seat names a turn by goal id alone when it yields, so one incarnation holding two callers'
8828
- * turns under one id could not say which of the two it answered. */
8829
- assertSeatTurnFree(name, t, goalId) {
8830
- if (this.seatTurnKey({ owner: t.owner, actor: t.actor, uid: t.lifecycleUid }, goalId) !== undefined)
8831
- throw new EpEnvelopeError("failed-precondition", `seat "${name}" already holds another caller's turn "${goalId}"; a seat yields by goal id, so it is never handed two turns under one (SPEC 13.6)`);
8832
- }
8833
- /** The relay key of the turn addressed to seat incarnation `c` under `goalId`, pending or kept
8834
- * for a retried yield. The accept path never hands one incarnation two turns under one goal
8835
- * id, so at most one matches. */
8836
- seatTurnKey(c, goalId) {
8837
- for (const [key, { acceptance: a }] of this.turnAcceptances)
8838
- if (a.goalId === goalId && a.owner === c.owner && a.actor === c.actor && a.uid === c.uid)
8839
- return key;
8840
- return undefined;
8841
- }
8842
7874
  /** The seat's yield: claim the hold (one-use; expiry fails closed), then commit the goal
8843
7875
  * `succeeded` carrying the TurnResult. A yield AFTER the deadline drives the deadline terminal
8844
7876
  * instead and refuses — the expiry outcome stands, never a late success over it. */
8845
- async serveTurnYield(c, raw) {
8846
- if (this.execution === "none")
8847
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
8848
- // Same boot window as the pull, and checked first because it is the earlier boot phase: before
8849
- // the index is rebuilt a predecessor's accepted turn is not in `pendingTurns`, and `not-found`
8850
- // would tell the seat to drop work it is holding.
8851
- if (!this.goalReconcileDone)
8852
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; this yield's turn may not be indexed yet, retry (SPEC 13.6)");
8853
- const gw = this.goalWriter;
8854
- if (!gw)
8855
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
8856
- const goalId = String(raw.goalId);
8857
- const status = String(raw.status);
8858
- const to = raw.to === undefined ? undefined : String(raw.to);
8859
- const yieldNote = raw.note === undefined ? undefined : String(raw.note);
8860
- if (status === "handoff" && (to === undefined || to.length === 0))
8861
- throw new EpEnvelopeError("failed-precondition", `a handoff yield names its addressee ("to"); a handoff to nobody relays nothing`);
8862
- const key = this.seatTurnKey(c, goalId);
8863
- if (key === undefined)
8864
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
8865
- const p = this.pendingTurns.get(key);
8866
- if (!p)
8867
- return this.settledTurnAnswer(key, goalId);
8868
- await this.claimTurnHold(p);
8869
- const epoch = this.serviceServe?.grant.epoch ?? 0;
8870
- await this.assertGoalWriterEpochCurrent(epoch);
8871
- const at = Date.now();
8872
- const data = { status, ...(to !== undefined ? { to } : {}), ...(yieldNote !== undefined ? { note: yieldNote } : {}), ...(p.handoffFrom !== undefined ? { handoffFrom: p.handoffFrom } : {}), at };
8873
- // The goal is TARGET-PINNED, so this completion proves the EXECUTOR's (the seat's) fresh
8874
- // currency, not the manager's: managed-seat epochs are 0 within an incarnation (the same
8875
- // convention resolveTarget serves), and the resolver answers from the live agents map — a
8876
- // seat that died between its yield call and this commit refuses `expired` here.
8877
- const { fact } = await commitGoalResult(gw.ctx, {
8878
- ref: p.ref, now: at, cause: "complete", state: "succeeded", data,
8879
- committer: { instanceId: this.managerInstanceId, epoch },
8880
- executor: { lifecycleUid: p.seat.uid, epoch: 0 },
8881
- resolveCurrentEpoch: (target) => this.turnExecutorEpoch(p.seat.name, p.seat.owner, p.seat.actor, target.lifecycleUid),
8882
- });
8883
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
8884
- // A once task's index entry is its seat's debt, dropped at the seat's proved exit.
8885
- if (!p.once)
8886
- await clearGoalIndex(gw.ctx, p.ref);
8887
- this.pendingTurns.delete(key);
8888
- this.noticeSeatTurns(p.seat);
8889
- this.markTurnLatchDropped(key, at);
8890
- this.rememberSettledTurn(key, fact.state, at);
8891
- if (p.once)
8892
- this.endOnceSeat(p, `yielded ${status}`);
8893
- this.maybeStopTurnSweep();
8894
- return { goalId, state: fact.state };
8895
- }
8896
- /** A seat's answer for a turn no longer pending. A REPLY THAT WAS LOST IS NOT AN ANSWER THAT
8897
- * FAILED: the commit deleted the pending turn, so a retry found nothing and heard `not-found`,
8898
- * which a seat reads as "drop it", reporting failure for work the run already has. The answer
8899
- * the first reply carried is served again instead, to the addressee it was addressed to and
8900
- * nobody else. */
8901
- async settledTurnAnswer(key, goalId) {
8902
- const settled = this.turnAcceptances.get(key);
8903
- if (settled !== undefined) {
8904
- if (settled.settled !== undefined)
8905
- return { goalId, state: settled.settled.state };
8906
- // The in-memory answer is not yet remembered (pending deleted before the terminal CAS,
8907
- // or a concurrent sweep dropped `settled` while the commit was still in flight). The
8908
- // durable terminal is the one the run already has; name it, never `not-found`.
8909
- if (settled.ref !== undefined && this.goalWriter) {
8910
- const ended = await readGoalResult(this.goalWriter.ctx, settled.ref);
8911
- if (ended !== undefined) {
8912
- this.rememberSettledTurn(key, ended.state, ended.ts);
8913
- return { goalId, state: ended.state };
8914
- }
8915
- }
8916
- }
8917
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
8918
- }
8919
- /** Claim a pending turn's deadline hold before the seat's answer commits: one use, and a hold
8920
- * that already expired drives the deadline terminal instead and refuses the answer. A once task
8921
- * with no deadline has no hold. */
8922
- async claimTurnHold(p) {
8923
- if (p.holdToken === undefined)
8924
- return;
8925
- const gw = this.goalWriter;
8926
- const cpRef = { endpoint: p.ref.endpoint, token: p.holdToken };
8927
- try {
8928
- await resumeCheckpoint(gw.ctx.kv, gw.ctx.js, gw.ctx.jsm, this.space, { ref: cpRef, presenter: { id: MANAGER_ENDPOINT, lifecycleUid: this.managerInstanceId }, now: Date.now() });
8929
- }
8930
- catch (e) {
8931
- const settle = await readCheckpointSettle(gw.ctx.jsm, this.space, cpRef).catch(() => undefined);
8932
- if (settle?.settle === "expired") {
8933
- await this.commitTurnDeadline(p);
8934
- throw new EpEnvelopeError("failed-precondition", `turn "${p.goalId}" elapsed its deadline before the seat answered; the deadline terminal stands (SPEC 13.6)`);
8935
- }
8936
- // Already resumed BY THIS MANAGER (the hold is holder-bound): a prior attempt claimed it
8937
- // and then failed to commit. Fall through and commit; the claim is ours to finish.
8938
- if (settle?.settle !== "resumed")
8939
- throw e;
8940
- }
8941
- }
7877
+ serveTurnYield(c, raw) { return this.turnRelay.serveTurnYield(c, raw); }
8942
7878
  /** A once seat's report that its task's handoff to its harness was not confirmed. The seat sealed
8943
7879
  * the task before it reported, so nothing hands it over again; the task fails
8944
7880
  * `delivery-unconfirmed` and the seat is stopped. The commit proves the seat's live currency, as
8945
7881
  * a yield's does: a seat already gone commits nothing here, and its exit cancels the task. Only
8946
7882
  * the addressed seat may report, only for its once task; a repeat after the terminal is answered
8947
7883
  * with it. */
8948
- async serveTurnUnconfirmed(c, raw) {
8949
- if (this.execution === "none")
8950
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
8951
- if (!this.goalReconcileDone)
8952
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; this report's turn may not be indexed yet, retry (SPEC 13.6)");
8953
- const gw = this.goalWriter;
8954
- if (!gw)
8955
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
8956
- const goalId = String(raw.goalId);
8957
- const key = this.seatTurnKey(c, goalId);
8958
- if (key === undefined)
8959
- throw new EpEnvelopeError("not-found", `no pending turn "${goalId}" on this manager`);
8960
- const p = this.pendingTurns.get(key);
8961
- if (!p)
8962
- return this.settledTurnAnswer(key, goalId);
8963
- if (!p.once)
8964
- throw new EpEnvelopeError("failed-precondition", `turn "${goalId}" is a run's turn; turn-unconfirmed reports only a once task, and a run's turn is offered again`);
8965
- await this.claimTurnHold(p);
8966
- const epoch = this.serviceServe?.grant.epoch ?? 0;
8967
- await this.assertGoalWriterEpochCurrent(epoch);
8968
- const at = Date.now();
8969
- const { fact } = await commitGoalResult(gw.ctx, {
8970
- ref: p.ref, now: at, cause: "complete", state: "failed", data: { reason: "delivery-unconfirmed", at },
8971
- committer: { instanceId: this.managerInstanceId, epoch },
8972
- executor: { lifecycleUid: p.seat.uid, epoch: 0 },
8973
- resolveCurrentEpoch: (target) => this.turnExecutorEpoch(p.seat.name, p.seat.owner, p.seat.actor, target.lifecycleUid),
8974
- });
8975
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
8976
- this.pendingTurns.delete(key);
8977
- this.noticeSeatTurns(p.seat);
8978
- this.markTurnLatchDropped(key, at);
8979
- this.rememberSettledTurn(key, fact.state, at);
8980
- this.endOnceSeat(p, "delivery-unconfirmed");
8981
- this.maybeStopTurnSweep();
8982
- return { goalId, state: fact.state };
8983
- }
7884
+ serveTurnUnconfirmed(c, raw) { return this.turnRelay.serveTurnUnconfirmed(c, raw); }
8984
7885
  /** The caller withdraws a turn it submitted (the reserved `cancel`, SPEC 13.6 item 4), so the
8985
7886
  * seat is not shown it again and a late yield is answered from the cancelled terminal. Only a
8986
7887
  * relay this incarnation holds is moved to `cancelling`, because only its holder can commit the
@@ -8991,317 +7892,20 @@ export class Manager {
8991
7892
  * held: a yield that read the entry first, or this commit with only its reply lost. An entry
8992
7893
  * whose outcome cannot be read back stays out and converges through the goal index at the
8993
7894
  * next boot, as a failed deadline commit does. */
8994
- async serveTurnCancel(ctx) {
8995
- if (this.execution === "none")
8996
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
8997
- if (!this.goalReconcileDone)
8998
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; the pending-turn index is not rebuilt yet, retry (SPEC 13.6)");
8999
- const gw = this.goalWriter;
9000
- if (!gw)
9001
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing (SPEC 13.6)");
9002
- const raw = (ctx.request.args ?? {});
9003
- const goalId = String(raw.goalId);
9004
- const ref = goalRefOf(ctx.subject, goalId);
9005
- const key = goalKey(ref);
9006
- const p = this.pendingTurns.get(key);
9007
- if (p === undefined) {
9008
- const ended = await readGoalResult(gw.ctx, ref);
9009
- if (ended !== undefined)
9010
- throw goalAlreadyTerminal(goalId, ended);
9011
- throw new EpEnvelopeError("failed-precondition", `no turn "${goalId}" of this caller is pending on this manager; cancel withdraws a relayed turn (SPEC 13.6)`);
9012
- }
9013
- this.pendingTurns.delete(key);
9014
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9015
- let fact;
9016
- try {
9017
- await requestGoalCancel(gw.ctx, { request: ctx.subject, goalId, mode: (raw.mode ?? "graceful") });
9018
- await this.assertGoalWriterEpochCurrent(epoch);
9019
- ({ fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "caller" }, committer: { instanceId: this.managerInstanceId, epoch } }));
9020
- }
9021
- catch (e) {
9022
- // The remembered answer is read after the durable one, with no await before the put back:
9023
- // a yield that has dropped the entry remembered its answer, and one still committing drops
9024
- // the entry it finds. An ended relay is stamped so its acceptance still ages off.
9025
- if ((await readGoalResult(gw.ctx, ref)) !== undefined)
9026
- this.markTurnLatchDropped(key);
9027
- else if (this.turnAcceptances.get(key)?.settled === undefined)
9028
- this.pendingTurns.set(key, p);
9029
- throw e;
9030
- }
9031
- this.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9032
- this.noticeSeatTurns(p.seat);
9033
- this.markTurnLatchDropped(key);
9034
- this.rememberSettledTurn(key, fact.state, Date.now());
9035
- if (p.once)
9036
- this.endOnceSeat(p, "cancelled");
9037
- else
9038
- await clearGoalIndex(gw.ctx, ref);
9039
- this.maybeStopTurnSweep();
9040
- return { goalId, state: fact.state };
9041
- }
9042
- /** Commit the deadline terminal for one pending turn whose hold settled EXPIRED: the deny's
9043
- * predicate is that recorded settle, verified by core against the spec's goal binding. The map
9044
- * delete is the idempotency latch (yield-loss and sweep race here); a commit failure after it
9045
- * converges through the goal index at the next boot, the same narrow leg spawn leaves open. */
9046
- async commitTurnDeadline(p) {
9047
- const gw = this.goalWriter;
9048
- if (!gw)
9049
- return;
9050
- const key = goalKey(p.ref);
9051
- if (!this.pendingTurns.delete(key))
9052
- return;
9053
- this.noticeSeatTurns(p.seat);
9054
- this.markTurnLatchDropped(key);
9055
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9056
- try {
9057
- await this.assertGoalWriterEpochCurrent(epoch);
9058
- const { fact } = await commitGoalResult(gw.ctx, { ref: p.ref, now: Date.now(), cause: "deny", denial: { kind: "hold-expired", token: p.holdToken }, data: { reason: "turn-deadline", ...(p.seatDiedAt !== undefined ? { agentDownAt: p.seatDiedAt } : {}), ...(p.handoffFrom !== undefined ? { handoffFrom: p.handoffFrom } : {}), ...(this.onceSeatUnheld(p) ? { seat: UNHELD_SEAT } : {}) }, committer: { instanceId: this.managerInstanceId, epoch } });
9059
- this.emitGoalProgress(p.ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9060
- // Remember BEFORE the index clear: a late yield that arrives after the pending latch
9061
- // (the delete at the top of this function) and after this CAS has to name this terminal.
9062
- // Clearing first, then remembering, left a window where maybeStopTurnSweep saw no pending
9063
- // turn and no settled answer, wiped the acceptance, and rememberSettledTurn no-op'd.
9064
- this.rememberSettledTurn(key, fact.state, Date.now());
9065
- if (p.once)
9066
- this.endOnceSeat(p, "turn-deadline");
9067
- else
9068
- await clearGoalIndex(gw.ctx, p.ref);
9069
- }
9070
- catch (e) {
9071
- console.error(`! turn deadline terminal for ${p.goalId}: ${rejectionText(e)}`);
9072
- // A once seat stops at its deadline whether or not the terminal landed, and the task stays
9073
- // pending so the turn sweep writes the terminal again while this manager runs.
9074
- if (p.once) {
9075
- this.pendingTurns.set(key, p);
9076
- this.endOnceSeat(p, "turn-deadline");
9077
- this.ensureTurnSweep();
9078
- }
9079
- }
9080
- this.maybeStopTurnSweep();
9081
- }
7895
+ serveTurnCancel(ctx) { return this.turnRelay.serveTurnCancel(ctx); }
9082
7896
  /** The reap hook: a pending turn addressed to the reaped INCARNATION is MARKED dead, never
9083
7897
  * settled early — no honest terminal exists for it (a completion must prove the executor's
9084
7898
  * live currency, and the hold is only expirable once due), so the entry rides to its deadline
9085
7899
  * and the deny then records both facts. The addressee's own client observes the death from
9086
7900
  * presence long before that, which is the run's L4002. */
9087
- failSeatTurns(name, uid) {
9088
- for (const p of this.pendingTurns.values()) {
9089
- if (p.seat.name !== name || p.seat.uid !== uid || p.seatDiedAt !== undefined)
9090
- continue;
9091
- p.seatDiedAt = Date.now();
9092
- console.error(`turn ${p.goalId}: addressed seat ${name}/${uid} died before yielding; the deadline terminal will record it`);
9093
- }
9094
- }
9095
- /** Settle one DUE hold as its owner: the manager minted it, so once the deadline has passed it
9096
- * expires the pause itself ({@link expireCheckpoint}, the guard-hold precedent) rather than
9097
- * waiting on the broker's fire — which it holds no grant to read, and which a hold minted under
9098
- * a predecessor's epoch would carry on a subject this incarnation never subscribes. Idempotent
9099
- * by the plane: a yield that claimed the hold first is observed as `resumed` and left to its
9100
- * own commit, and an already-expired hold returns its recorded settle. */
9101
- async expireTurnHold(p) {
9102
- const gw = this.goalWriter;
9103
- if (!gw)
9104
- return undefined;
9105
- return expireCheckpoint(gw.ctx.kv, gw.ctx.js, gw.ctx.jsm, this.space, { ref: { endpoint: p.ref.endpoint, token: p.holdToken }, now: Date.now() });
9106
- }
9107
- ensureTurnSweep() {
9108
- if (this.turnSweepTimer !== undefined)
9109
- return;
9110
- const t = setInterval(() => { void this.sweepTurnDeadlines().catch((e) => console.error(`! turn deadline sweep: ${rejectionText(e)}`)); }, TURN_SWEEP_MS);
9111
- t.unref?.();
9112
- this.turnSweepTimer = t;
9113
- }
9114
- /** The answer a retried yield is served, held for {@link TURN_ANSWER_RETENTION_MS}. Only for a
9115
- * turn this incarnation accepted: an entry it has no acceptance for is one it cannot vouch for. */
9116
- rememberSettledTurn(key, state, at) {
9117
- const entry = this.turnAcceptances.get(key);
9118
- if (entry === undefined)
9119
- return;
9120
- entry.settled = { state, at };
9121
- }
9122
- /** Stamp when the pending latch dropped, so an unsettled leftover ages off that instant rather
9123
- * than the original deadline. Idempotent: the first drop is the one the retry window starts at. */
9124
- markTurnLatchDropped(key, at = Date.now()) {
9125
- const entry = this.turnAcceptances.get(key);
9126
- if (entry === undefined || entry.leftoverSince !== undefined)
9127
- return;
9128
- entry.leftoverSince = at;
9129
- }
9130
- /** Stop the sweep only when it has nothing left to do. It drives elapsed turns to their deadline
9131
- * terminals AND drops settled answers once their retry window has passed, so a stop while the
9132
- * second is still owed would leave one entry per turn for the process lifetime. */
9133
- maybeStopTurnSweep() {
9134
- if (this.pendingTurns.size > 0 || this.onceSettles.size > 0 || this.onceInherited.size > 0 || [...this.onceStops.values()].some((s) => !s.told))
9135
- return;
9136
- // An acceptance with no `settled` yet is the in-flight deadline commit: pending was the
9137
- // latch and is already gone, the terminal CAS has not returned, and a concurrent sweep
9138
- // tick used to clear the map here, so rememberSettledTurn no-op'd and a late yield heard
9139
- // `not-found` for a deny the run already has. Prune is the only deleter; stop only when
9140
- // it has left nothing.
9141
- if (this.turnAcceptances.size > 0)
9142
- return;
9143
- this.stopTurnSweep();
9144
- }
9145
- stopTurnSweep() {
9146
- if (this.turnSweepTimer === undefined)
9147
- return;
9148
- clearInterval(this.turnSweepTimer);
9149
- this.turnSweepTimer = undefined;
9150
- }
9151
- /** Drive every elapsed pending turn to its deadline terminal. Only entries at/past their own
9152
- * `deadlineAt` are read at all; a `resumed` settle is a yield mid-commit and is left alone. */
9153
- async sweepTurnDeadlines() {
9154
- const now = Date.now();
9155
- // A settled answer is kept only as long as a lost reply could still be retried under it.
9156
- // An UNSETTLED acceptance whose pending latch is already gone is the in-flight (or failed)
9157
- // deadline commit: keep it for the same window so a late yield can still read the durable
9158
- // terminal, then drop it so a commit that never remembered cannot pin the sweep forever.
9159
- for (const [key, e] of [...this.turnAcceptances.entries()]) {
9160
- if (this.pendingTurns.has(key))
9161
- continue;
9162
- // Unsettled leftovers age off the latch-drop stamp, never `deadlineAt`.
9163
- const at = e.settled?.at ?? e.leftoverSince;
9164
- if (at !== undefined && now - at >= TURN_ANSWER_RETENTION_MS)
9165
- this.turnAcceptances.delete(key);
9166
- }
9167
- // The prune above is the one event after which the sweep may have nothing left to do, and
9168
- // the settle-time callers cannot see it: they run when an answer has just been remembered.
9169
- this.maybeStopTurnSweep();
9170
- // A notice is at-most-once, so a seat offline when it went out has not pulled its head turn.
9171
- // Repeat the notice until it does; a seat that pulled is not told again for that turn.
9172
- const heads = new Map();
9173
- for (const p of this.pendingTurns.values()) {
9174
- if ((p.deadlineAt !== undefined && now >= p.deadlineAt) || p.once?.deliverable === false)
9175
- continue;
9176
- const k = `${p.seat.owner}.${p.seat.actor}.${p.seat.uid}`;
9177
- const h = heads.get(k);
9178
- if (h === undefined || p.acceptedAt < h.acceptedAt)
9179
- heads.set(k, p);
9180
- }
9181
- for (const p of heads.values())
9182
- if (p.pulledAt === undefined)
9183
- this.noticeSeatTurns(p.seat);
9184
- for (const stop of this.onceStops.values())
9185
- if (!stop.told)
9186
- this.noticeSeatTurns(stop);
9187
- for (const owed of [...this.onceSettles.values()])
9188
- if (!owed.flight)
9189
- void this.settleOnceTurn(owed.ref, owed.reason);
9190
- if (this.onceInherited.size > 0)
9191
- await this.settleInheritedOnce().catch((e) => console.error(`! inherited once tasks: ${rejectionText(e)}`));
9192
- for (const p of [...this.pendingTurns.values()]) {
9193
- if (p.deadlineAt === undefined || now < p.deadlineAt)
9194
- continue;
9195
- try {
9196
- const settle = await this.expireTurnHold(p);
9197
- if (settle?.settle === "expired")
9198
- await this.commitTurnDeadline(p);
9199
- }
9200
- catch (e) {
9201
- console.error(`! turn deadline sweep for ${p.goalId}: ${rejectionText(e)}`);
9202
- }
9203
- }
9204
- }
7901
+ failSeatTurns(name, uid) { return this.turnRelay.failSeatTurns(name, uid); }
9205
7902
  /** Adopt one inherited TURN goal at boot (the reconcile sweep's turn branch): a non-terminal
9206
7903
  * entry carrying a parseable note rebuilds its pending relay — never an `uncertain` settle,
9207
7904
  * because the deadline hold IS this goal's bounded ending and it survived the restart. No
9208
7905
  * liveness verdict is made here (the agents map is empty during reconcile, so absence means
9209
7906
  * "not yet re-registered", never "dead"); a garbled note or a floor that does not name the
9210
7907
  * seat's owner is logged and left, the dead-pointer honesty rule. */
9211
- async adoptTurnGoal(entry) {
9212
- const gw = this.goalWriter;
9213
- if (!gw)
9214
- return;
9215
- const status = await readGoalStatus(gw.ctx, entry.ref);
9216
- if (status === undefined)
9217
- return; // index points at no goal record: a dead pointer, left for honesty
9218
- const parsed = entry.note !== undefined ? parseTurnNote(entry.note) : undefined;
9219
- const ownOnce = parsed?.once === true && entry.iid === this.managerInstanceId && entry.allocated?.owner !== undefined;
9220
- if (GOAL_TERMINAL_STATES.includes(status.value.state)) {
9221
- // A once task's entry is its seat's debt until that seat's exit is proved, so it outlives
9222
- // the terminal: the stop the predecessor owed may never have landed.
9223
- if (ownOnce)
9224
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9225
- else
9226
- await clearGoalIndex(gw.ctx, entry.ref);
9227
- return;
9228
- }
9229
- if (entry.iid !== this.managerInstanceId) {
9230
- console.error(`turn reconcile ${entry.ref.goalId}: accepted by instance "${entry.iid}", not this incarnation "${this.managerInstanceId}"; left for its owner (never a cross-instance settle)`);
9231
- return;
9232
- }
9233
- if (entry.allocated?.owner === undefined || parsed === undefined) {
9234
- console.error(`turn reconcile ${entry.ref.goalId}: the relay record is garbled (no floor naming the seat's owner, or an unparseable note); left unsettled`);
9235
- return;
9236
- }
9237
- const spec = await readGoalSpec(gw.ctx, entry.ref);
9238
- if (spec === undefined) {
9239
- // NOW IS NOT WHEN THIS WAS ACCEPTED. `acceptedAt` is what orders a seat's queue, and a turn
9240
- // stamped with the boot instant sorts BEHIND every turn accepted since — a predecessor's
9241
- // oldest turn served last, which is the one thing the ordering exists to prevent. A goal
9242
- // with an index entry and no spec is a relay record that is not readable, and this is the
9243
- // same verdict the garbled-note branch above reaches: left unsettled, said out loud.
9244
- console.error(`turn reconcile ${entry.ref.goalId}: the goal spec is unreadable, so its acceptance time is unknown; left unsettled rather than re-stamped with the boot instant`);
9245
- return;
9246
- }
9247
- const p = {
9248
- ref: entry.ref, goalId: entry.ref.goalId,
9249
- seat: { name: entry.allocated.name, owner: entry.allocated.owner, actor: entry.allocated.actor, uid: entry.allocated.uid },
9250
- payload: parsed.payload,
9251
- acceptedAt: spec.value.acceptedAt,
9252
- holdEpoch: parsed.holdEpoch,
9253
- ...(parsed.deadlineAt !== undefined ? { deadlineAt: parsed.deadlineAt, holdToken: parsed.holdToken ?? turnHoldToken(entry.ref.goalId) } : {}),
9254
- ...(parsed.handoffFrom !== undefined ? { handoffFrom: parsed.handoffFrom } : {}),
9255
- // An inherited once task is served again only once its seat is bound to this incarnation.
9256
- ...(parsed.once ? { once: { deliverable: false } } : {}),
9257
- };
9258
- // The hold is the relay's bounded ending, minted AFTER the index entry and the goal record,
9259
- // so a crash between them leaves a goal with no hold: nothing could ever settle it, and the
9260
- // sweep would report the same missing pause every tick. Left unsettled, said once.
9261
- if (p.holdToken !== undefined && (await readCheckpointSpec(gw.ctx.kv, { endpoint: p.ref.endpoint, token: p.holdToken })) === undefined) {
9262
- // A once task's hold is minted before its seat launches, so without one no seat ever ran it:
9263
- // the task is cancelled and its entry dropped, with nothing launched to prove gone.
9264
- if (parsed.once) {
9265
- await this.settleOnceTurn(p.ref, "launch-failed");
9266
- return;
9267
- }
9268
- console.error(`turn reconcile ${p.goalId}: its deadline hold was never minted (the accept crashed before it); left unsettled`);
9269
- return;
9270
- }
9271
- // A once task whose spawn has no succeeded terminal was never served, whatever seat exists:
9272
- // it is cancelled, its row is not rebuilt so a later pull finds nothing, and its seat is
9273
- // settled as an inherited debt.
9274
- if (parsed.once && !(await this.onceServed(entry.ref, parsed))) {
9275
- await this.commitOnceCancel(entry.ref, NEVER_SERVED);
9276
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9277
- return;
9278
- }
9279
- const key = goalKey(p.ref);
9280
- this.pendingTurns.set(key, p);
9281
- // THE ACCEPTANCE TOO, or the adopted turn's answer is never remembered: `rememberSettledTurn`
9282
- // writes only against an acceptance this incarnation holds, and adoption rebuilt the pending
9283
- // relay without one, so a yield whose reply was lost after a restart still heard `not-found`
9284
- // on the very path adoption exists for. The acceptance is rebuilt from the same records the
9285
- // relay was: the spec holds the fingerprint, the index holds the seat, the note the deadline.
9286
- this.turnAcceptances.set(key, {
9287
- acceptance: {
9288
- name: p.seat.name, owner: p.seat.owner, actor: p.seat.actor, uid: p.seat.uid, goalId: p.goalId,
9289
- fingerprint: spec.value.fingerprint, deadlineAt: p.deadlineAt,
9290
- executor: { lifecycleUid: this.managerInstanceId, epoch: p.holdEpoch },
9291
- },
9292
- ref: p.ref,
9293
- });
9294
- // NO LIVENESS VERDICT AT BOOT. The agents map is empty here: seats are re-registered later,
9295
- // by the resume path, so `not in the map` at this moment means "not yet re-registered", never
9296
- // "dead". Stamping death from it marked EVERY adopted turn as a dead seat, and its deadline
9297
- // terminal then carried `agentDownAt`, so the run raised L4002 for a seat that was alive the
9298
- // whole time where the reference says L4003. The reap hook is the only honest writer of that
9299
- // fact: it fires when a managed seat actually dies.
9300
- console.error(`turn reconcile ${p.goalId}: pending relay to ${p.seat.name}/${p.seat.uid} adopted (deadline ${p.deadlineAt ?? "none"})`);
9301
- if (parsed.once)
9302
- await this.inheritOnce(entry.ref, entry.allocated, parsed);
9303
- this.ensureTurnSweep();
9304
- }
7908
+ adoptTurnGoal(entry) { return this.turnRelay.adoptTurnGoal(entry); }
9305
7909
  // ---- once (a spawn whose prompt is its one relayed task) ----------------------------------------
9306
7910
  //
9307
7911
  // A once spawn's prompt is not a kickoff: the manager accepts it as one turn addressed to the
@@ -9315,97 +7919,13 @@ export class Manager {
9315
7919
  * the goal ref and the seat given rather than read off a request. A task with no deadline mints
9316
7920
  * no hold; its goal still records the spawn's readiness budget, which a successor needs to settle
9317
7921
  * it. */
9318
- async acceptOnceTurn(o) {
9319
- const gw = this.goalWriter;
9320
- if (!gw)
9321
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; a once task cannot be accepted (SPEC 13.6)");
9322
- const serve = this.serviceServe;
9323
- if (o.deadlineMs !== undefined && !serve)
9324
- throw new EpEnvelopeError("unavailable", "the manager service endpoint is not serving; a once task's deadline hold is armed over its connection (SPEC 13.9)");
9325
- const ref = { endpoint: o.spawnRef.endpoint, caller: { ...o.spawnRef.caller }, goalId: digestIdToken(`${o.spawnRef.goalId}:once`) };
9326
- const key = goalKey(ref);
9327
- const deadlineAt = o.deadlineMs === undefined ? undefined : o.acceptedAt + o.deadlineMs;
9328
- if (deadlineAt !== undefined && deadlineAt > MAX_SCHEDULE_MS)
9329
- throw new EpEnvelopeError("failed-precondition", `once: the deadline ends after the deadline scheduler's last instant (the end of year 9999)`);
9330
- const holdToken = deadlineAt === undefined ? undefined : turnHoldToken(key);
9331
- const { payload, note } = onceTurnNote({ prompt: o.prompt, spawner: o.spawner, holdEpoch: o.executor.epoch, ...(deadlineAt !== undefined ? { deadlineAt, holdToken } : {}), ...(o.retire !== undefined ? { retire: o.retire } : {}), spawn: o.spawnRef.goalId });
9332
- const { seat } = o;
9333
- const idx = await recordGoalIndex(gw.ctx, ref, o.executor.lifecycleUid, { name: seat.name, owner: seat.owner, actor: seat.actor, uid: seat.uid, readinessDeadlineMs: o.readinessDeadlineMs }, note);
9334
- if (!idx.recorded)
9335
- throw new EpEnvelopeError("failed-precondition", `once: the task goal "${ref.goalId}" is already recorded; a spawn accepts its task once (SPEC 13.6)`);
9336
- const b = await bindGoal(gw.ctx, ref, o.fingerprint);
9337
- if (!b.bound) {
9338
- await clearGoalIndex(gw.ctx, ref);
9339
- throw new EpEnvelopeError("failed-precondition", `once: the task goal "${ref.goalId}" is already bound; a spawn accepts its task once (SPEC 13.6)`);
9340
- }
9341
- try {
9342
- await createGoal(gw.ctx, ref, {
9343
- fingerprint: o.fingerprint,
9344
- command: o.command,
9345
- caller: { id: `${ref.caller.owner}.${ref.caller.actor}`, lifecycleUid: ref.caller.uid },
9346
- acceptedEpoch: o.executor.epoch,
9347
- requestId: ref.goalId,
9348
- sourceSeq: 0,
9349
- acceptedAt: o.acceptedAt,
9350
- readinessDeadlineMs: o.readinessDeadlineMs,
9351
- target: { owner: seat.owner, actor: seat.actor, lifecycleUid: seat.uid, mappingRevision: 0 },
9352
- });
9353
- if (deadlineAt !== undefined)
9354
- await mintCheckpoint(gw.ctx.kv, jetstream(serve.nc), this.space, {
9355
- ref: { endpoint: ref.endpoint, token: holdToken },
9356
- instanceId: this.managerInstanceId,
9357
- epoch: o.executor.epoch,
9358
- goal: { caller: { ...ref.caller }, goalId: ref.goalId },
9359
- holder: { id: MANAGER_ENDPOINT, lifecycleUid: this.managerInstanceId },
9360
- deadline: deadlineAt,
9361
- now: o.acceptedAt,
9362
- });
9363
- }
9364
- catch (e) {
9365
- // Nothing launched and nothing was served, so the task is withdrawn with `cancel`.
9366
- try {
9367
- await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: "terminate" } });
9368
- await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "manager", reason: "accept-failed" }, committer: { instanceId: this.managerInstanceId, epoch: o.executor.epoch } });
9369
- await clearGoalIndex(gw.ctx, ref);
9370
- }
9371
- catch (e2) {
9372
- console.error(`! once task accept unwind for ${ref.goalId}: ${rejectionText(e2)}`);
9373
- }
9374
- throw e;
9375
- }
9376
- this.pendingTurns.set(key, {
9377
- ref, goalId: ref.goalId, seat: { ...seat }, payload, acceptedAt: o.acceptedAt, holdEpoch: o.executor.epoch,
9378
- ...(deadlineAt !== undefined ? { deadlineAt, holdToken } : {}),
9379
- once: { deliverable: false },
9380
- });
9381
- this.turnAcceptances.set(key, {
9382
- acceptance: { name: seat.name, owner: seat.owner, actor: seat.actor, uid: seat.uid, goalId: ref.goalId, fingerprint: o.fingerprint, ...(deadlineAt !== undefined ? { deadlineAt } : {}), executor: o.executor },
9383
- ref,
9384
- });
9385
- this.ensureTurnSweep();
9386
- this.emitGoalProgress(ref, o.executor.epoch, { phase: "relayed" });
9387
- return { ref, ...(deadlineAt !== undefined ? { deadlineAt } : {}) };
9388
- }
9389
- /** How a once seat's startup watch ended, waited for until {@link STARTUP_OUTCOME_MS} after its
9390
- * launch or the readiness window, whichever is longer. A watch that has not ended by then, or a
9391
- * seat being stopped, answers what the handle reports at that moment. */
9392
- async awaitStartupOutcome(a, launchedAt, readinessTimeoutMs) {
9393
- const until = launchedAt + Math.max(readinessTimeoutMs, STARTUP_OUTCOME_MS);
9394
- for (;;) {
9395
- const outcome = a.handle.startupOutcome?.() ?? "pending";
9396
- if (outcome !== "pending" || a.terminalizing || Date.now() >= until)
9397
- return outcome;
9398
- await new Promise((resolve) => setTimeout(resolve, 250));
9399
- }
7922
+ acceptOnceTurn(o) { return this.turnRelay.acceptOnceTurn(o); }
7923
+ /** How a once seat's startup watch ended: {@link awaitStartupOutcome}. */
7924
+ awaitStartupOutcome(a, launchedAt, readinessTimeoutMs) {
7925
+ return awaitStartupOutcome(a, launchedAt, readinessTimeoutMs, () => this.leaseStopping);
9400
7926
  }
9401
7927
  /** Serve a once task from now on: its spawn's succeeded terminal is written. */
9402
- openOnceDelivery(ref) {
9403
- const p = this.pendingTurns.get(goalKey(ref));
9404
- if (p?.once === undefined || p.once.deliverable)
9405
- return;
9406
- p.once.deliverable = true;
9407
- this.noticeSeatTurns(p.seat);
9408
- }
7928
+ openOnceDelivery(ref) { return this.turnRelay.openOnceDelivery(ref); }
9409
7929
  /** Stop the seat of a once task that just ended, found by its incarnation and never by its name.
9410
7930
  * After the readiness verdict the spawn goal's outcome belongs to that verdict, so the stop lets
9411
7931
  * go of the spawn goal first and never cancels it. Before the verdict it is a deliberate stop,
@@ -9427,6 +7947,25 @@ export class Manager {
9427
7947
  this.trackStoppedHandle(a, false, cause);
9428
7948
  void this.cancelAgentGoal(a.name, "graceful");
9429
7949
  }
7950
+ /** Stop a seat this spawn just placed and track its exit: the stop first, so the terminalizing
7951
+ * latch is set before anything awaits, then the exit tracking. Both are synchronous. */
7952
+ stopAndTrack(a, cause) {
7953
+ this.stopHandle(a, false, cause);
7954
+ this.trackStoppedHandle(a, true, cause);
7955
+ }
7956
+ /** End a once seat before its task is served: let go of the spawn goal, record why it stopped if
7957
+ * `stopReason` is given and none is recorded yet, then stop the seat. Synchronous, in that order. */
7958
+ endOnceBeforeServe(a, reason, stopReason) {
7959
+ this.agentGoals.delete(a.name);
7960
+ if (stopReason !== undefined)
7961
+ a.once.stopReason ??= stopReason;
7962
+ this.stopOnceSeat(a, reason);
7963
+ }
7964
+ /** Put a launched seat in the agent table, then mark its reserved name placed. */
7965
+ place(name, a) {
7966
+ this.agents.set(name, a);
7967
+ this.namesCapacity.placed(name);
7968
+ }
9430
7969
  /** The once task's exit hook, on the handle the seat was launched with: whichever path ends the
9431
7970
  * seat, its proved exit cancels a task that has no terminal yet and discharges the seat's debt. An
9432
7971
  * exit that cannot be proved leaves both. */
@@ -9441,62 +7980,9 @@ export class Manager {
9441
7980
  * the seat's launched processes gone, cancel the task with `reason` if it has no terminal yet,
9442
7981
  * then drop its index entry. One flight per task; a failure keeps it in {@link onceSettles} and
9443
7982
  * the turn sweep retries it. */
9444
- settleOnceTurn(ref, reason, retire) {
9445
- const key = goalKey(ref);
9446
- const owed = this.onceSettles.get(key) ?? { ref, reason, ...(retire !== undefined ? { retire } : {}) };
9447
- if (owed.flight)
9448
- return owed.flight;
9449
- this.onceSettles.set(key, owed);
9450
- const flight = this.runOnceSettle(key, owed).finally(() => { owed.flight = undefined; });
9451
- owed.flight = flight;
9452
- return flight;
9453
- }
9454
- async runOnceSettle(key, owed) {
9455
- const gw = this.goalWriter;
9456
- if (!gw)
9457
- return;
9458
- // The pending entry is the latch the yield and the deadline race on; a task settled here is
9459
- // served to no one again.
9460
- const p = this.pendingTurns.get(key);
9461
- // A task past its deadline owes the deadline terminal, which the turn sweep writes again until
9462
- // it lands; the settle waits for it rather than record a cancel in its place.
9463
- const denyOwed = p?.deadlineAt !== undefined && p.deadlineAt <= Date.now();
9464
- if (p && !denyOwed) {
9465
- this.pendingTurns.delete(key);
9466
- this.markTurnLatchDropped(key);
9467
- this.noticeSeatTurns(p.seat);
9468
- }
9469
- try {
9470
- if (denyOwed)
9471
- throw new Error("its deadline terminal is not written yet");
9472
- // A seat whose exit is proved may have left processes of its own running the task: the task
9473
- // is not recorded as ended, nor its debt cleared, before they are proved gone.
9474
- const retired = owed.retire === undefined ? undefined : await this.retireOnceSeat(owed.retire);
9475
- await this.commitOnceCancel(owed.ref, owed.reason);
9476
- await clearGoalIndex(gw.ctx, owed.ref);
9477
- this.onceSettles.delete(key);
9478
- this.onceWatched.delete(key);
9479
- await retired?.discard().catch((e) => console.error(`! once task ${owed.ref.goalId}: its retirement receipt was not discarded (${rejectionText(e)})`));
9480
- }
9481
- catch (e) {
9482
- console.error(`! once task ${owed.ref.goalId} (${owed.reason}): ${rejectionText(e)}; retried by the turn sweep`);
9483
- this.ensureTurnSweep();
9484
- }
9485
- this.maybeStopTurnSweep();
9486
- }
7983
+ settleOnceTurn(ref, reason, retire) { return this.turnRelay.settleOnceTurn(ref, reason, retire); }
9487
7984
  /** Cancel a once task with `reason` unless it already has a terminal. */
9488
- async commitOnceCancel(ref, reason) {
9489
- const gw = this.goalWriter;
9490
- if ((await readGoalResult(gw.ctx, ref)) !== undefined)
9491
- return;
9492
- const epoch = this.serviceServe?.grant.epoch ?? 0;
9493
- await this.assertGoalWriterEpochCurrent(epoch);
9494
- if ((await readGoalStatus(gw.ctx, ref))?.value.state !== "cancelling")
9495
- await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: "terminate" } });
9496
- const { fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "manager", reason }, committer: { instanceId: this.managerInstanceId, epoch } });
9497
- this.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
9498
- this.rememberSettledTurn(goalKey(ref), fact.state, Date.now());
9499
- }
7985
+ commitOnceCancel(ref, reason) { return this.turnRelay.commitOnceCancel(ref, reason); }
9500
7986
  /** Ask the seat's connector to prove its launched processes gone, within {@link ONCE_RETIRE_MS}.
9501
7987
  * Throws without that proof. */
9502
7988
  async retireOnceSeat(r) {
@@ -9505,106 +7991,9 @@ export class Manager {
9505
7991
  throw new Error(`the ${r.connector} connector cannot prove seat ${r.name}'s launched processes gone`);
9506
7992
  return withTimeout(connector.retireAfterExit({ space: this.space, name: r.name, lifecycleUid: r.uid, workspaceRoot: this.workspaceRoot }), ONCE_RETIRE_MS, `seat ${r.name}'s launched processes were not proved gone within ${ONCE_RETIRE_MS}ms`);
9507
7993
  }
9508
- /** Record a once task a predecessor accepted, and bind its seat if this incarnation already
9509
- * adopted it. The static adoption and the goal reconcile run in either order, so each side
9510
- * binds what the other has already found. */
9511
- async inheritOnce(ref, allocated, note) {
9512
- this.onceInherited.set(allocated.uid, {
9513
- ref, seat: { name: allocated.name, owner: allocated.owner, actor: allocated.actor, uid: allocated.uid },
9514
- ...(note.deadlineAt !== undefined ? { deadlineAt: note.deadlineAt } : {}),
9515
- readinessMs: allocated.readinessDeadlineMs ?? this.readinessTimeoutMs,
9516
- ...(note.retire !== undefined ? { retire: note.retire } : {}),
9517
- });
9518
- const a = this.findManagedByTarget({ owner: allocated.owner, actor: allocated.actor, lifecycleUid: allocated.uid });
9519
- if (a !== undefined)
9520
- await this.bindOnceSeat(a);
9521
- this.ensureTurnSweep();
9522
- }
9523
- /** An inherited once task whose seat this manager cannot hold: it adopts no seats (an open or
9524
- * user-mode mesh) and the seat is not bound here. */
9525
- onceSeatUnheld(p) {
9526
- return p.once !== undefined && this.onceInherited.has(p.seat.uid) && !(this.auth !== undefined && !this.userMode);
9527
- }
9528
- /** Whether a once task was served: its spawn's succeeded terminal is written. */
9529
- async onceServed(ref, note) {
9530
- if (note.spawn === undefined)
9531
- return false;
9532
- const spawn = await readGoalResult(this.goalWriter.ctx, { endpoint: ref.endpoint, caller: ref.caller, goalId: note.spawn });
9533
- return spawn?.state === "succeeded";
9534
- }
9535
7994
  /** Make an adopted seat a once seat again: its exit settles its task, and the task is served to
9536
7995
  * it. A task that ended before the restart owes the stop the predecessor may not have made. */
9537
- async bindOnceSeat(a) {
9538
- const inherited = this.onceInherited.get(a.lifecycleUid);
9539
- if (inherited === undefined || a.once !== undefined)
9540
- return;
9541
- this.onceInherited.delete(a.lifecycleUid);
9542
- a.once = { ref: inherited.ref, ...(inherited.retire !== undefined ? { retire: inherited.retire } : {}) };
9543
- this.watchOnceExit(a);
9544
- const p = this.pendingTurns.get(goalKey(inherited.ref));
9545
- if (p?.once) {
9546
- p.once.deliverable = true;
9547
- this.noticeSeatTurns(p.seat);
9548
- return;
9549
- }
9550
- const ended = this.goalWriter ? await readGoalResult(this.goalWriter.ctx, inherited.ref) : undefined;
9551
- if (ended !== undefined)
9552
- this.stopOnceSeat(a, "turn-ended");
9553
- }
9554
- /** Inherited once tasks whose seat is not bound here. On a static mesh the boot reconcile adopts
9555
- * every seat it can and reaps the rest by their custody reference, so once it has finished with
9556
- * a seat's slot, an unbound seat is proved gone. A manager that adopts no seats cannot reach the
9557
- * old seat or prove its exit: it does not serve the task to it, a task with a deadline ends at
9558
- * that deadline, and one without is settled `uncertain` after one readiness window. Its debt is
9559
- * never cleared here, since nothing proves that seat gone. */
9560
- async settleInheritedOnce() {
9561
- const gw = this.goalWriter;
9562
- if (!gw || !this.goalReconcileDone)
9563
- return;
9564
- const adopts = this.auth !== undefined && !this.userMode;
9565
- for (const [uid, d] of [...this.onceInherited]) {
9566
- const live = this.findManagedByTarget({ owner: d.seat.owner, actor: d.seat.actor, lifecycleUid: uid });
9567
- if (live !== undefined) {
9568
- await this.bindOnceSeat(live);
9569
- continue;
9570
- }
9571
- if (adopts) {
9572
- const reconciling = this.staticLifecycle.pendingLifecycle(uid);
9573
- if (reconciling)
9574
- continue;
9575
- this.onceInherited.delete(uid);
9576
- void this.settleOnceTurn(d.ref, "seat-exited", retireOf(d));
9577
- continue;
9578
- }
9579
- if ((await readGoalResult(gw.ctx, d.ref)) !== undefined) {
9580
- this.onceInherited.delete(uid);
9581
- this.keepUnprovedOnceDebt(d);
9582
- continue;
9583
- }
9584
- if (d.deadlineAt !== undefined || Date.now() - this.goalReconcileDoneAt < d.readinessMs)
9585
- continue;
9586
- this.onceInherited.delete(uid);
9587
- const key = goalKey(d.ref);
9588
- this.pendingTurns.delete(key);
9589
- this.markTurnLatchDropped(key);
9590
- try {
9591
- await settleGoalUncertain(gw.ctx, { ref: d.ref, now: Date.now(), committer: { instanceId: this.managerInstanceId, epoch: this.serviceServe?.grant.epoch ?? 0 }, reason: `the manager restarted and could not reach the seat; ${UNHELD_SEAT}, and the task may have run in part or in full` });
9592
- this.keepUnprovedOnceDebt(d);
9593
- }
9594
- catch (e) {
9595
- console.error(`! inherited once task ${d.ref.goalId}: ${rejectionText(e)}`);
9596
- }
9597
- }
9598
- }
9599
- /** An inherited task's seat this manager cannot reach: its terminal stands, and its index entry,
9600
- * the seat's debt, stays recorded, because nothing here can prove that seat gone. The seat is
9601
- * told to end itself on its next pull, and its notice repeats until a pull carries that. */
9602
- keepUnprovedOnceDebt(d) {
9603
- console.error(`! once task ${d.ref.goalId}: this manager cannot reach seat ${d.seat.name}/${d.seat.uid} to prove it gone; its debt stays in the goal index, and the seat is told to end itself`);
9604
- this.onceStops.set(d.seat.uid, { ...d.seat });
9605
- this.noticeSeatTurns(d.seat);
9606
- this.ensureTurnSweep();
9607
- }
7996
+ bindOnceSeat(a) { return this.turnRelay.bindOnceSeat(a); }
9608
7997
  /** Settle race: a despawn MID-GOAL drives the goal's cancel terminal - transition to
9609
7998
  * `cancelling`, then commit the `cancel` cause on the goal-writer connection. First-terminal-fact
9610
7999
  * wins: if the readiness outcome already committed (succeeded/failed/uncertain) the transition or
@@ -9642,18 +8031,8 @@ export class Manager {
9642
8031
  spawnCustodied(runtime, name, spec, cwd, reserved) {
9643
8032
  return this.seatCustody.spawnCustodied(runtime, name, spec, cwd, reserved);
9644
8033
  }
9645
- /** Keep launch provenance independent of status and runtime wire contracts. */
9646
- watchConnectorHolder(handle, holder) {
9647
- if (!holder.active)
9648
- return;
9649
- holder.launched(handle.pid);
9650
- // A released handle may outlive its Manager. Only an authoritative exit removes
9651
- // identity-less holders, never a release or a failed stop request.
9652
- watchProvedExit(handle, () => holder.ended(), () => true);
9653
- }
9654
- recordSeat(a) {
9655
- return this.seatCustody.recordSeat(a);
9656
- }
8034
+ /** Keep launch provenance independent of status and runtime wire contracts: {@link watchConnectorHolder}. */
8035
+ watchConnectorHolder(handle, holder) { watchConnectorHolder(handle, holder); }
9657
8036
  refreshSeatRecord(a) {
9658
8037
  return this.seatCustody.refreshSeatRecord(a);
9659
8038
  }