@cotal-ai/manager 0.171.2 → 0.171.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/broker-transport.d.ts +126 -0
  2. package/dist/broker-transport.d.ts.map +1 -0
  3. package/dist/broker-transport.js +263 -0
  4. package/dist/broker-transport.js.map +1 -0
  5. package/dist/command-dispatch.d.ts +206 -0
  6. package/dist/command-dispatch.d.ts.map +1 -0
  7. package/dist/command-dispatch.js +471 -0
  8. package/dist/command-dispatch.js.map +1 -0
  9. package/dist/connector-inventory.d.ts +37 -0
  10. package/dist/connector-inventory.d.ts.map +1 -0
  11. package/dist/connector-inventory.js +73 -0
  12. package/dist/connector-inventory.js.map +1 -0
  13. package/dist/harness-resolution.d.ts +71 -0
  14. package/dist/harness-resolution.d.ts.map +1 -0
  15. package/dist/harness-resolution.js +111 -0
  16. package/dist/harness-resolution.js.map +1 -0
  17. package/dist/manager.d.ts +91 -375
  18. package/dist/manager.d.ts.map +1 -1
  19. package/dist/manager.js +400 -2811
  20. package/dist/manager.js.map +1 -1
  21. package/dist/persona-catalog.d.ts +86 -0
  22. package/dist/persona-catalog.d.ts.map +1 -0
  23. package/dist/persona-catalog.js +325 -0
  24. package/dist/persona-catalog.js.map +1 -0
  25. package/dist/preservation.d.ts +157 -0
  26. package/dist/preservation.d.ts.map +1 -0
  27. package/dist/preservation.js +583 -0
  28. package/dist/preservation.js.map +1 -0
  29. package/dist/readiness-wait.d.ts +64 -0
  30. package/dist/readiness-wait.d.ts.map +1 -0
  31. package/dist/readiness-wait.js +244 -0
  32. package/dist/readiness-wait.js.map +1 -0
  33. package/dist/runtime/index.d.ts +2 -0
  34. package/dist/runtime/index.d.ts.map +1 -1
  35. package/dist/runtime/index.js +22 -0
  36. package/dist/runtime/index.js.map +1 -1
  37. package/dist/service-adapter.d.ts.map +1 -1
  38. package/dist/service-adapter.js +6 -0
  39. package/dist/service-adapter.js.map +1 -1
  40. package/dist/spawn-goal.d.ts +77 -0
  41. package/dist/spawn-goal.d.ts.map +1 -0
  42. package/dist/spawn-goal.js +357 -0
  43. package/dist/spawn-goal.js.map +1 -0
  44. package/dist/start-doors.d.ts +51 -0
  45. package/dist/start-doors.d.ts.map +1 -0
  46. package/dist/start-doors.js +187 -0
  47. package/dist/start-doors.js.map +1 -0
  48. package/dist/status-and-models.d.ts +155 -0
  49. package/dist/status-and-models.d.ts.map +1 -0
  50. package/dist/status-and-models.js +290 -0
  51. package/dist/status-and-models.js.map +1 -0
  52. package/dist/terminal-input.d.ts +82 -0
  53. package/dist/terminal-input.d.ts.map +1 -0
  54. package/dist/terminal-input.js +266 -0
  55. package/dist/terminal-input.js.map +1 -0
  56. package/package.json +12 -12
package/dist/manager.js CHANGED
@@ -5,18 +5,16 @@ import { drainAndClose } from "@cotal-ai/core";
5
5
  import { hostname } from "node:os";
6
6
  import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
7
7
  import { join, resolve } from "node:path";
8
- import { parse as parseYaml } from "yaml";
9
- import Headless from "@xterm/headless";
10
- import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, injectedSecretStoreIdentity, agentFilePath, dialerFor, connectorServers, spawnEnvAllow, idFromCreds, identityFromCreds, inspectCredHealth, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, mintCreds, bindIssuedStores, mintLifecycleUid, newIdentity, oneLine, parsePrincipalKey, principalKey, probeConnect, registry, resolveAuthProvider, saveAgentFile, capabilityWithin, } from "@cotal-ai/core";
8
+ import { CotalEndpoint, copyPersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, injectedSecretStoreIdentity, idFromCreds, identityFromCreds, loadAgentFile, loadCotalConfig, mintCreds, mintLifecycleUid, newIdentity, oneLine, parsePrincipalKey, principalKey, probeConnect, resolveAuthProvider, } from "@cotal-ai/core";
11
9
  import { retainConnectorSeat } from "@cotal-ai/workspace";
12
- import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
13
- import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
14
- import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
10
+ import { logicalExecutionEntry } from "@cotal-ai/workspace";
11
+ import { agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, DEFAULT_SEAT_CAP, findCotalRoot, getSpaceAuth, hasUserAuthState, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
12
+ import { createRuntime, isCustodialRuntime, requireRuntimeAdopt, requireRuntimeReap, } from "./runtime/index.js";
15
13
  import { Retirement } from "./retirement.js";
16
14
  import { ServePlane } from "./serve-plane.js";
17
15
  import { NamesCapacity } from "./names-capacity.js";
18
16
  import { AttachEndpoint } from "./attach-endpoint.js";
19
- import { DELIVERY_ADMIN_BOOT_WAIT_MS, makeManagerEndpointHolderEvictor, withScopedEndpoint } from "./endpoint-evict.js";
17
+ import { DELIVERY_ADMIN_BOOT_WAIT_MS, makeManagerEndpointHolderEvictor } from "./endpoint-evict.js";
20
18
  import { makeManagerHolderLivenessProbe } from "./holder-liveness.js";
21
19
  import { ManagedStaticLifecycle, STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
22
20
  export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js";
@@ -27,21 +25,33 @@ import { SessionRecovery } from "./session-recovery.js";
27
25
  import { SeatCustody, watchConnectorHolder } from "./seat-custody.js";
28
26
  import { GoalWriter } from "./goal-writer.js";
29
27
  import { DEPROVISION_TIMEOUT_MS, SeatStop } from "./seat-stop.js";
28
+ import { CommandDispatch, participantKey } from "./command-dispatch.js";
29
+ import { SpawnGoal } from "./spawn-goal.js";
30
+ import { PersonaCatalog } from "./persona-catalog.js";
31
+ import { TerminalInput } from "./terminal-input.js";
32
+ import { StatusAndModels, MANAGER_VERSION } from "./status-and-models.js";
33
+ import { ReadinessWait } from "./readiness-wait.js";
34
+ import { BrokerTransport } from "./broker-transport.js";
35
+ import { StartDoors } from "./start-doors.js";
36
+ import { HarnessResolution, resolveHarness } from "./harness-resolution.js";
37
+ import { ConnectorInventory } from "./connector-inventory.js";
38
+ import { Preservation } from "./preservation.js";
39
+ export { PASTE_END, PASTE_START, RUNTIME_NO_TERMINAL_DETAIL } from "./terminal-input.js";
30
40
  import { CredentialRenewal, credRenewIntervalMs, REMOTE_STANDING_BUDGET_MS, remoteStandingTimeLeft, sameStrings } from "./credential-renewal.js";
31
- import { SeatLaunch, foreignEventChannels, userMeshEndpointsRefusal } from "./seat-launch.js";
41
+ import { SeatLaunch, foreignEventChannels } from "./seat-launch.js";
32
42
  import { withTimeout } from "./manager-timeout.js";
33
43
  import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
34
- import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, parseLaunchSpec, persistLaunchSpec } from "./launch.js";
35
- import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
36
- import { RunHosting, servedRequestSubject } from "./run-hosting.js";
44
+ import { inlineSnapshotPath, launchSpecForRun } from "./launch.js";
45
+ import { authorizeNamedControl } from "./authorize.js";
46
+ import { RunHosting } from "./run-hosting.js";
37
47
  import { rejectionText, attemptCleanup } from "@cotal-ai/core";
38
- import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
48
+ import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference } from "./resume.js";
39
49
  import { TranscriptReceiver } from "./transcript-receive.js";
40
50
  // The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
41
51
  // manager-side adapter (transport + slot orchestration + the terminal) — see static-lifecycle.ts.
42
52
  import { jetstreamManager } from "@nats-io/jetstream";
43
53
  import { Kvm } from "@nats-io/kv";
44
- import { recordsBucket, epAuthBucket, ensureAuthorityStores, standaloneConnectOpts } from "@cotal-ai/core";
54
+ import { recordsBucket, ensureAuthorityStores, standaloneConnectOpts } from "@cotal-ai/core";
45
55
  // The manager's ONE §13.6 session plane — offer mint + one-use redeem + PTY-bridge
46
56
  // standup for `attach`, over a dedicated standing session-LEDGER connection (the byte rails ride
47
57
  // per-session credentials on their own short-lived connections).
@@ -49,14 +59,9 @@ import { ManagerSessionPlane } from "./session/index.js";
49
59
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
50
60
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
51
61
  // the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
52
- import { epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, commitGoalResult, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, MAX_SCHEDULE_MS, goalRefOf, turnNoticeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom } from "@cotal-ai/core";
53
- import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
54
- import { measureManagerVitals } from "./vitals.js";
55
- import { staticLifecycleTransport, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, observeStaticSlot, listStaticSlotObservations, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
56
- // Capture the loaded package version before an installation can replace its files.
57
- const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
58
- /** A `once` spawn's task deadline when the caller names none: one hour from the spawn's accept. */
59
- const ONCE_DEFAULT_DEADLINE_MS = 60 * 60_000;
62
+ import { epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, listGoalIndex, turnNoticeSubject, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom } from "@cotal-ai/core";
63
+ import { MANAGER_ENDPOINT } from "./manager-service-contract.js";
64
+ import { ownedBySibling, } from "./static-lifecycle.js";
60
65
  /** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
61
66
  * stays and the turn sweep asks again. */
62
67
  const ONCE_RETIRE_MS = 60_000;
@@ -73,18 +78,10 @@ export const READINESS_TIMEOUT_MS = 30_000;
73
78
  * from its launch: the watch's 15s for the confirm prompt and 15s for its notice, plus 5s for the
74
79
  * last read. The readiness window applies when it is longer. */
75
80
  const STARTUP_OUTCOME_MS = 35_000;
76
- /** How often the readiness race asks a runtime that streams no exit whether its child has exited, and
77
- * how long it waits past the window for the proof of its last read. An operator waits on this reply,
78
- * so it asks more often than the exit watch that outlives readiness. */
79
- const READINESS_EXIT_POLL_MS = 1_000;
80
81
  /** How often a resumed seat whose readiness was uncertain is checked for a join its predecessor's
81
82
  * presence row hides (see {@link Manager.watchResumeAdoption}). The wait has no end of its own, so
82
83
  * it asks less often than the readiness fence's 50 ms poll. */
83
84
  const LATE_JOIN_POLL_MS = 1_000;
84
- /** How long the process of a launch that waits for the operator ({@link Connector.waitsForOperator})
85
- * must run without exiting before it is ready: long enough that a harness refusing its arguments
86
- * exits first and is reported as failed. */
87
- const OPERATOR_READINESS_MS = 3_000;
88
85
  /** At most this many retirements run at once (#4965). A retirement dials up to four fresh broker
89
86
  * connections in turn and queues an eviction and an inventory on the delivery daemon's admin rail,
90
87
  * each against a fixed deadline. A stop that started all 50 seats' retirements together lost most of
@@ -100,23 +97,6 @@ const PRESERVE_STOP_TIMEOUT_MS = 10_000;
100
97
  /** How long a resume waits for a reaped orphan's principal to leave presence. Presence rows age
101
98
  * out after their 6s TTL, so three TTLs covers a killed seat that never published its leave. */
102
99
  const ORPHAN_PRESENCE_CLEAR_MS = 20_000;
103
- /** How much of an `input` text is written to a seat's pty at a time. Comfortably under the 4096-byte
104
- * kernel input buffer, so a slice is never re-split at a boundary the manager did not choose: the
105
- * tail of an oversized write stays queued and swallows the submit key that follows it (issue #1649).
106
- * Sized in CHARS against a byte buffer on purpose — a multi-byte character can only make a slice
107
- * shorter in characters than in bytes, never longer, so the margin cannot be eaten from below. */
108
- const INPUT_SLICE_CHARS = 2048;
109
- /** Bracketed-paste delimiters (DECSET 2004). `input` wraps a seat's text in these so the return it
110
- * writes afterwards is a KEYSTROKE rather than the newline trailing a pasted block: a TUI that
111
- * classifies a fast burst as a paste consumes that trailing newline and the text sits unsubmitted
112
- * in the composer until the next call's return (issue #1649). Framing, never content - these bytes
113
- * are not counted into the receipt, so `bytes` still reports what the caller asked to deliver. */
114
- export const PASTE_START = "\x1b[200~";
115
- export const PASTE_END = "\x1b[201~";
116
- /** `details[].kind` on an `attach` refusal raised because the seat's runtime opens no terminal
117
- * stream. The message carries that runtime's own guidance, which is operator copy and changes; this
118
- * marker is the contract a caller keys on so it can act without reading the wording. */
119
- export const RUNTIME_NO_TERMINAL_DETAIL = "ai.cotal.manager.runtime-no-terminal";
120
100
  /** Startup reconciliation overlaps control-service registration. A spawn or attach for one of
121
101
  * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
122
102
  * a reuse. */
@@ -127,10 +107,6 @@ const STARTUP_RECONCILING = "startup static lifecycle reconciliation";
127
107
  function resumeOwner(entry) {
128
108
  return entry.identity.mode === "user" ? entry.identity.owner : DEV_OWNER;
129
109
  }
130
- /** Sentinel owner-filter value that matches NO agent's `userOwner` (owner tokens never contain a
131
- * dash) — what {@link Manager.psOwnerFilter} returns for an unparseable caller so a malformed
132
- * principal fail-closes to an empty `ps` instead of an unbounded one. */
133
- const NO_OWNER_MATCHES = "-no-owner-";
134
110
  /** Why a frozen manager gate stays frozen on an open mesh. Reconciliation must prove the holder
135
111
  * gone, and an open mesh runs no delivery daemon to prove it, so neither boot self-heal nor
136
112
  * `cotal manager reconcile` can reopen the gate there. */
@@ -151,24 +127,6 @@ function openMeshFrozenGateRefusal(e, instanceId) {
151
127
  return e;
152
128
  return lifecycleBlocked(envelope.code, `the issuance gate for "${instanceId}" is frozen under another registration, and this manager cannot register while it is; ${OPEN_MESH_GATE_LIMIT} (SPEC 13.8)`, { blockedOp: blocked.blockedOp, gateState: blocked.gateState, ...(blocked.opId !== undefined ? { opId: blocked.opId } : {}) }, envelope.outcome);
153
129
  }
154
- /** The failed terminal a post-accept fallback commits for `error` and `source`'s optional details.
155
- * `commitGoalResult` refuses a payload that is not interchangeable JSON, and this terminal must commit
156
- * whatever failed, so a lone surrogate in the text becomes U+FFFD and details it cannot read or carry
157
- * (a Proxy's throwing getter, an accessor, a cycle) are dropped. A Proxy can answer the check and the
158
- * serializer differently, so the detached copy is checked again before it commits. */
159
- function failedTerminal(error, source) {
160
- const text = error.replace(/\p{Cs}/gu, "\uFFFD");
161
- try {
162
- const details = source?.details;
163
- if (details) {
164
- const copy = JSON.parse(canonicalJson(details));
165
- canonicalJson(copy);
166
- return { error: text, details: copy };
167
- }
168
- }
169
- catch { /* unreadable or not interchangeable */ }
170
- return { error: text };
171
- }
172
130
  /** The start of every agent's bearer command: node, its loader flags and this manager's entry,
173
131
  * resolved through every symlink. The agent runs that command for each renewal for as long as it
174
132
  * lives, and an install can replace the bin link meanwhile: get.cotal.ai writes a shell launcher
@@ -177,23 +135,6 @@ function bearerEntryArgv() {
177
135
  return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
178
136
  }
179
137
  const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
180
- function participantKey(owner, actor, uid) {
181
- return `${owner}.${actor}.${uid}`;
182
- }
183
- /** One connector's declared harness binaries resolved on PATH now. The refusal sentence is built only
184
- * here, so the boot row and the check for a connector registered after boot can never word it apart. */
185
- function resolveHarness(name, requires) {
186
- const binaries = {};
187
- const missing = [];
188
- for (const bin of requires) {
189
- const path = resolveOnPath(bin);
190
- if (path)
191
- binaries[bin] = path;
192
- else
193
- missing.push(bin);
194
- }
195
- return missing.length ? { binaries, reason: `${name} harness needs ${missing.join(", ")} on PATH - not found` } : { binaries };
196
- }
197
138
  /** The refusal a control instance with `execution: none` gives every launch, hosting, model and write door. */
198
139
  const EXECUTION_NONE_REFUSAL = "execution: none forbids seat launch, workflow hosting, model inspection and caller-driven writes on this control instance; select the participant Manager with an instance-pinned manager-caller view";
199
140
  /** The sha256 hex digest of a file's bytes. */
@@ -573,12 +514,8 @@ export class Manager {
573
514
  maintenanceState = "active";
574
515
  lifecycleInFlight = 0;
575
516
  lifecycleDrainWaiters = [];
576
- preservationTask;
577
- preparationTask;
578
517
  preservationGeneration = 0;
579
518
  preservationAttemptId;
580
- preservationStarted = false;
581
- preservationFailures = [];
582
519
  unverifiedStops = [];
583
520
  preservationInventory;
584
521
  resumeAttemptId;
@@ -602,36 +539,10 @@ export class Manager {
602
539
  /** A refused or failed standing candidate is cleanup debt, never a silent loss: the last-good
603
540
  * family stays live and this records what the host may have signed but the manager never adopted. */
604
541
  remoteRenewalDebt;
605
- /** Every broker dial this manager makes, through ONE transport decision.
606
- *
607
- * `this.servers` is whatever the mesh record held (`cotal supervise` reads it from there), so it
608
- * can be a `ws://`/`wss://` broker published through an HTTPS edge. The raw node transport
609
- * refuses such a URL instead of dialing it, so the scheme picks the dialer here rather than at
610
- * thirteen call sites. `dialerFor` also owns the websocket transport's options, which is why
611
- * callers below still pass their own auth options unchanged. */
612
- dial(opts) {
613
- const servers = this.servers ?? DEFAULT_SERVER;
614
- return dialerFor(servers)({ ...opts, servers });
615
- }
616
- /** Initial NATS timeout is per dial, not per server list. Keep the aggregate deadline too, and
617
- * close a late result rather than letting an abandoned preflight or recovery install a transport. */
618
- async dialRemoteStanding(opts, deadline) {
619
- const ms = remoteStandingTimeLeft(deadline);
620
- const pending = this.dial({ ...opts, timeout: ms });
621
- try {
622
- const nc = await withTimeout(pending, ms, "remote manager standing dial exceeded its 10000ms aggregate budget");
623
- remoteStandingTimeLeft(deadline);
624
- if (this.leaseStopping)
625
- throw new Error("manager stopped while a remote standing dial was in flight");
626
- return nc;
627
- }
628
- catch (e) {
629
- // Timing out our wait does not cancel connect(). It still owns its socket until it rejects
630
- // or returns a connection, which must close without serving or changing a current holder.
631
- void pending.then((nc) => nc.close(), () => { }).catch((error) => console.error(`! remote manager abandoned standing dial cleanup: ${rejectionText(error)}`));
632
- throw e;
633
- }
634
- }
542
+ /** {@link BrokerTransport.dial}. */
543
+ dial(...args) { return this.brokerTransportComponent.dial(...args); }
544
+ /** {@link BrokerTransport.dialRemoteStanding}. */
545
+ dialRemoteStanding(...args) { return this.brokerTransportComponent.dialRemoteStanding(...args); }
635
546
  seatCustody = new SeatCustody({
636
547
  staticAuth: () => !!this.auth && !this.userMode,
637
548
  workspaceRoot: () => this.workspaceRoot,
@@ -769,6 +680,256 @@ export class Manager {
769
680
  shredUserSecrets: (...args) => this.shredUserSecrets(...args),
770
681
  trackDeprovision: (...args) => this.trackDeprovision(...args),
771
682
  });
683
+ /** The typed command table and its admission. Every dependency reads through at its use. */
684
+ commandDispatch = new CommandDispatch({
685
+ agents: () => this.agents,
686
+ auth: () => this.auth,
687
+ execution: () => this.execution,
688
+ goalWriter: () => this.goalWriter,
689
+ managerInstanceId: () => this.managerInstanceId,
690
+ participants: () => this.participants,
691
+ remoteAuthority: () => this.remoteAuthority,
692
+ resumeRequired: () => this.resumeRequired,
693
+ runHosting: () => this.runHosting,
694
+ space: () => this.space,
695
+ transcripts: () => this.transcripts,
696
+ userMode: () => this.userMode,
697
+ workspaceRoot: () => this.workspaceRoot,
698
+ attachAuthorized: (...args) => this.attachAuthorized(...args),
699
+ authorizeNamed: (...args) => this.authorizeNamed(...args),
700
+ authorizeRunAmend: (...args) => this.authorizeRunAmend(...args),
701
+ authorizeRunAnswer: (...args) => this.authorizeRunAnswer(...args),
702
+ beginLifecycle: (...args) => this.beginLifecycle(...args),
703
+ despawnAuthorized: (...args) => this.despawnAuthorized(...args),
704
+ executionRefusal: (...args) => this.executionRefusal(...args),
705
+ findManagedByTarget: (...args) => this.findManagedByTarget(...args),
706
+ inputAuthorized: (...args) => this.inputAuthorized(...args),
707
+ lifecycleMembershipRefusal: (...args) => this.lifecycleMembershipRefusal(...args),
708
+ list: (...args) => this.list(...args),
709
+ listSpawnDirectory: (...args) => this.listSpawnDirectory(...args),
710
+ loggedSpawnRefusal: (ctx, fn) => this.loggedSpawnRefusal(ctx, fn),
711
+ maintenanceError: (...args) => this.maintenanceError(...args),
712
+ managedPrincipal: (...args) => this.managedPrincipal(...args),
713
+ managerStatusData: (...args) => this.managerStatusData(...args),
714
+ opCommitResume: (...args) => this.opCommitResume(...args),
715
+ opDefinePersona: (...args) => this.opDefinePersona(...args),
716
+ opFinalizeResume: (...args) => this.opFinalizeResume(...args),
717
+ opLaunch: (...args) => this.opLaunch(...args),
718
+ opListPersonas: (...args) => this.opListPersonas(...args),
719
+ opModels: (...args) => this.opModels(...args),
720
+ opPreservationCtl: (...args) => this.opPreservationCtl(...args),
721
+ opPurge: (...args) => this.opPurge(...args),
722
+ opRemovePersona: (...args) => this.opRemovePersona(...args),
723
+ opResumePreserved: (...args) => this.opResumePreserved(...args),
724
+ opShowPersona: (...args) => this.opShowPersona(...args),
725
+ opStart: (...args) => this.opStart(...args),
726
+ openStaticChatSession: (...args) => this.openStaticChatSession(...args),
727
+ psOwnerFilter: (...args) => this.psOwnerFilter(...args),
728
+ resolveSpawnCwd: (...args) => this.resolveSpawnCwd(...args),
729
+ retireStaticChatSession: (...args) => this.retireStaticChatSession(...args),
730
+ runAnswerer: (...args) => this.runAnswerer(...args),
731
+ runHost: (...args) => this.runHost(...args),
732
+ serveGated: (ctx, fn) => this.serveGated(ctx, fn),
733
+ serveObservation: (ctx, fn) => this.serveObservation(ctx, fn),
734
+ serveSpawnGoal: (...args) => this.serveSpawnGoal(...args),
735
+ serveTurnCancel: (...args) => this.serveTurnCancel(...args),
736
+ serveTurnGoal: (...args) => this.serveTurnGoal(...args),
737
+ serveTurnParticipation: (...args) => this.serveTurnParticipation(...args),
738
+ serveTurnUnconfirmed: (...args) => this.serveTurnUnconfirmed(...args),
739
+ serveTurnYield: (...args) => this.serveTurnYield(...args),
740
+ spawnPersona: (...args) => this.spawnPersona(...args),
741
+ stopHandle: (...args) => this.stopHandle(...args),
742
+ stopWindowsSeat: (...args) => this.stopWindowsSeat(...args),
743
+ trackStoppedHandle: (...args) => this.trackStoppedHandle(...args),
744
+ turnPendingFor: (...args) => this.turnPendingFor(...args),
745
+ turnTarget: (...args) => this.turnTarget(...args),
746
+ });
747
+ /** The spawn and launch goal path. Every dependency reads through at its use. */
748
+ spawnGoalComponent = new SpawnGoal({
749
+ agentGoals: () => this.agentGoals,
750
+ execution: () => this.execution,
751
+ goalAcceptanceRetentionMs: () => this.goalAcceptanceRetentionMs,
752
+ goalAcceptances: () => this.goalAcceptances,
753
+ goalReconcileDone: () => this.goalReconcileDone,
754
+ goalWriter: () => this.goalWriter,
755
+ managerInstanceId: () => this.managerInstanceId,
756
+ onceWatched: () => this.onceWatched,
757
+ readinessTimeoutMs: () => this.readinessTimeoutMs,
758
+ serviceServe: () => this.serviceServe,
759
+ userMode: () => this.userMode,
760
+ acceptOnceTurn: (...args) => this.acceptOnceTurn(...args),
761
+ assertGoalWriterEpochCurrent: (...args) => this.assertGoalWriterEpochCurrent(...args),
762
+ commitOnceCancel: (...args) => this.commitOnceCancel(...args),
763
+ emitGoalProgress: (...args) => this.emitGoalProgress(...args),
764
+ executionRefusal: (...args) => this.executionRefusal(...args),
765
+ settleOnceTurn: (...args) => this.settleOnceTurn(...args),
766
+ });
767
+ /** The persona catalog doors. Every dependency reads through at its use. */
768
+ personaCatalogComponent = new PersonaCatalog({
769
+ agents: () => this.agents,
770
+ execution: () => this.execution,
771
+ meshMode: () => this.meshMode,
772
+ remoteAuthority: () => this.remoteAuthority,
773
+ space: () => this.space,
774
+ userMode: () => this.userMode,
775
+ workspaceRoot: () => this.workspaceRoot,
776
+ executionRefusal: (...args) => this.executionRefusal(...args),
777
+ managedPrincipal: (...args) => this.managedPrincipal(...args),
778
+ nameError: (...args) => this.nameError(...args),
779
+ spawnBoundRefusal: (...args) => this.spawnBoundRefusal(...args),
780
+ spawnRun: (...args) => this.spawnRun(...args),
781
+ staticSpawnBound: (...args) => this.staticSpawnBound(...args),
782
+ });
783
+ /** Seat terminal input and attach sessions. Every dependency reads through at its use. */
784
+ terminalInputComponent = new TerminalInput({
785
+ agents: () => this.agents,
786
+ auth: () => this.auth,
787
+ managerLifecycleUid: () => this.managerLifecycleUid,
788
+ sessionPlane: () => this.sessionPlane,
789
+ wsPort: () => this.wsPort,
790
+ runtimeFor: (...args) => this.runtimeFor(...args),
791
+ });
792
+ /** Status, seat list and model catalog reads. Every dependency reads through at its use. */
793
+ statusAndModelsComponent = new StatusAndModels({
794
+ agents: () => this.agents,
795
+ auth: () => this.auth,
796
+ connectorStatuses: () => this.connectorStatuses,
797
+ ep: () => this.ep,
798
+ execution: () => this.execution,
799
+ leaseStopping: () => this.leaseStopping,
800
+ lifecycleInFlight: () => this.lifecycleInFlight,
801
+ maintenanceState: () => this.maintenanceState,
802
+ managerInstanceId: () => this.managerInstanceId,
803
+ managerLifecycleUid: () => this.managerLifecycleUid,
804
+ namesCapacity: () => this.namesCapacity,
805
+ preservationAttemptId: () => this.preservationAttemptId,
806
+ preservationInventory: () => this.preservationInventory,
807
+ remoteAuthority: () => this.remoteAuthority,
808
+ requiredRuntime: () => this.requiredRuntime,
809
+ resumeRequired: () => this.resumeRequired,
810
+ retirement: () => this.retirement,
811
+ runtimeKind: () => this.runtimeKind,
812
+ space: () => this.space,
813
+ startedAtMs: () => this.startedAtMs,
814
+ staticLifecycle: () => this.staticLifecycle,
815
+ userMode: () => this.userMode,
816
+ workspaceRoot: () => this.workspaceRoot,
817
+ classSpawnEnabled: (...args) => this.classSpawnEnabled(...args),
818
+ connectorNames: (...args) => this.connectorNames(...args),
819
+ epAdminReach: (...args) => this.epAdminReach(...args),
820
+ executionRefusal: (...args) => this.executionRefusal(...args),
821
+ forkProvenance: (...args) => this.forkProvenance(...args),
822
+ isOwnPresence: (a, p) => this.isOwnPresence(a, p),
823
+ isProcessBoundSeat: (...args) => this.isProcessBoundSeat(...args),
824
+ launchHarness: (...args) => this.launchHarness(...args),
825
+ refreshUnavailableConnectors: (...args) => this.refreshUnavailableConnectors(...args),
826
+ resolveConnector: (...args) => this.resolveConnector(...args),
827
+ staticReconciliationStatus: (...args) => this.staticReconciliationStatus(...args),
828
+ });
829
+ /** The launch readiness race and exit watch. Every dependency reads through at its use. */
830
+ readinessWaitComponent = new ReadinessWait({
831
+ agents: () => this.agents,
832
+ ep: () => this.ep,
833
+ shutdownReadiness: () => this.shutdownReadiness,
834
+ managedPrincipal: (...args) => this.managedPrincipal(...args),
835
+ onAgentExit: (...args) => this.onAgentExit(...args),
836
+ });
837
+ /** Broker dials and scoped executor connections. Every dependency reads through at its use. */
838
+ brokerTransportComponent = new BrokerTransport({
839
+ auth: () => this.auth,
840
+ endpointServeExecutorExpiresInSeconds: () => this.endpointServeExecutorExpiresInSeconds,
841
+ leaseStopping: () => this.leaseStopping,
842
+ managerInstanceId: () => this.managerInstanceId,
843
+ remoteAuthority: () => this.remoteAuthority,
844
+ remoteBundleAdoption: () => this.remoteBundleAdoption,
845
+ remoteExecutorCreds: () => this.remoteExecutorCreds,
846
+ servers: () => this.servers,
847
+ space: () => this.space,
848
+ transportDown: () => this.transportDown,
849
+ renewRemoteExecutor: (...args) => this.renewRemoteExecutor(...args),
850
+ renewRemoteStandingBundle: (...args) => this.renewRemoteStandingBundle(...args),
851
+ });
852
+ /** The start and launch control doors. Every dependency reads through at its use. */
853
+ startDoorsComponent = new StartDoors({
854
+ eventsRequired: () => this.eventsRequired,
855
+ execution: () => this.execution,
856
+ remoteAuthority: () => this.remoteAuthority,
857
+ space: () => this.space,
858
+ userMode: () => this.userMode,
859
+ workspaceRoot: () => this.workspaceRoot,
860
+ executionRefusal: (...args) => this.executionRefusal(...args),
861
+ startAgent: (...args) => this.startAgent(...args),
862
+ });
863
+ /** Connector and harness resolution for a launch. Every dependency reads through at its use. */
864
+ harnessResolutionComponent = new HarnessResolution({
865
+ connectorStatuses: () => this.connectorStatuses,
866
+ eventPayloadsWithheld: () => this.eventPayloadsWithheld,
867
+ eventsRequired: () => this.eventsRequired,
868
+ expectedConnectorGeneration: () => this.expectedConnectorGeneration,
869
+ installedExtensions: () => this.installedExtensions,
870
+ servers: () => this.servers,
871
+ space: () => this.space,
872
+ workspaceRoot: () => this.workspaceRoot,
873
+ });
874
+ /** The boot connector inventory. Every dependency reads through at its use. */
875
+ connectorInventoryComponent = new ConnectorInventory({
876
+ bootNotes: () => this.bootNotes,
877
+ setBootNotes: (value) => { this.bootNotes = value; },
878
+ connectorRequirements: () => this.connectorRequirements,
879
+ setConnectorRequirements: (value) => { this.connectorRequirements = value; },
880
+ connectorStatuses: () => this.connectorStatuses,
881
+ setConnectorStatuses: (value) => { this.connectorStatuses = value; },
882
+ execution: () => this.execution,
883
+ installedExtensions: () => this.installedExtensions,
884
+ machineSetupCommand: () => this.machineSetupCommand,
885
+ classSpawnEnabled: (...args) => this.classSpawnEnabled(...args),
886
+ prepareClaudeWake: (...args) => this.prepareClaudeWake(...args),
887
+ });
888
+ /** Manager preservation and released-seat adoption. Every dependency reads through at its use. */
889
+ preservationComponent = new Preservation({
890
+ agents: () => this.agents,
891
+ auth: () => this.auth,
892
+ credRenewTimer: () => this.credRenewTimer,
893
+ setCredRenewTimer: (value) => { this.credRenewTimer = value; },
894
+ ep: () => this.ep,
895
+ execution: () => this.execution,
896
+ lifecycleInFlight: () => this.lifecycleInFlight,
897
+ maintenanceState: () => this.maintenanceState,
898
+ setMaintenanceState: (value) => { this.maintenanceState = value; },
899
+ managerInstanceId: () => this.managerInstanceId,
900
+ meshMode: () => this.meshMode,
901
+ preservationAttemptId: () => this.preservationAttemptId,
902
+ setPreservationAttemptId: (value) => { this.preservationAttemptId = value; },
903
+ preservationGeneration: () => this.preservationGeneration,
904
+ setPreservationGeneration: (value) => { this.preservationGeneration = value; },
905
+ preservationInventory: () => this.preservationInventory,
906
+ setPreservationInventory: (value) => { this.preservationInventory = value; },
907
+ preserveStopTimeoutMs: () => this.preserveStopTimeoutMs,
908
+ resumeCredRenewal: () => this.resumeCredRenewal,
909
+ space: () => this.space,
910
+ unverifiedStops: () => this.unverifiedStops,
911
+ setUnverifiedStops: (value) => { this.unverifiedStops = value; },
912
+ userMode: () => this.userMode,
913
+ workspaceRoot: () => this.workspaceRoot,
914
+ awaitLifecycleDrain: (...args) => this.awaitLifecycleDrain(...args),
915
+ deprovision: (...args) => this.deprovision(...args),
916
+ dropInlineSnapshot: (...args) => this.dropInlineSnapshot(...args),
917
+ dropSeatRecord: (...args) => this.dropSeatRecord(...args),
918
+ executionRefusal: (...args) => this.executionRefusal(...args),
919
+ fileDigest: (...args) => this.fileDigest(...args),
920
+ logSeatReaped: (...args) => this.logSeatReaped(...args),
921
+ onAgentExit: (...args) => this.onAgentExit(...args),
922
+ recordContinuityAtStop: (...args) => this.recordContinuityAtStop(...args),
923
+ renewDaemonCreds: (...args) => this.renewDaemonCreds(...args),
924
+ resumeEntry: (...args) => this.resumeEntry(...args),
925
+ resumeEntryOf: (...args) => this.resumeEntryOf(...args),
926
+ runtimeFor: (...args) => this.runtimeFor(...args),
927
+ stopHandle: (...args) => this.stopHandle(...args),
928
+ teardownTarget: (...args) => this.teardownTarget(...args),
929
+ validateRetainedAuthority: (...args) => this.validateRetainedAuthority(...args),
930
+ watchExit: (...args) => this.watchExit(...args),
931
+ withProvisioner: (fn) => this.withProvisioner(fn),
932
+ });
772
933
  /** The goal-writer connection and the goal index it reconciles. Every dependency reads through at its use. */
773
934
  goalWriterComponent = new GoalWriter({
774
935
  auth: () => this.auth,
@@ -1161,28 +1322,6 @@ export class Manager {
1161
1322
  return "static";
1162
1323
  return "open";
1163
1324
  }
1164
- /** The CHAT stream frontier at a preservation cut (issue #545), read through whichever local
1165
- * authority this mesh mode holds: open mode's own endpoint already has `$JS.API.STREAM.INFO`
1166
- * on the CHAT stream. Local and remote supervisor credentials also hold this metadata grant
1167
- * for transcript startup checks, but this preservation path retains its existing local-authority
1168
- * boundary. Static/user modes borrow the ephemeral `provisioner` profile the manager already
1169
- * mints per spawn. A remote-authority manager (`this.auth`
1170
- * undefined in static/user mode) has no local space authority to mint that provisioner with, so
1171
- * it prints one line and returns no floor — the inventory then carries none and resumed seats
1172
- * behave exactly as before this fix, not a silent partial degrade. */
1173
- async chatFrontierForPreservation() {
1174
- switch (this.meshMode) {
1175
- case "open":
1176
- return this.ep.chatFrontier();
1177
- case "static":
1178
- case "user":
1179
- if (!this.auth) {
1180
- console.error("! preservation: this manager holds no local space authority to read the chat frontier; retained seats replay their channel windows on resume");
1181
- return undefined;
1182
- }
1183
- return this.withProvisioner((prov) => prov.chatFrontier());
1184
- }
1185
- }
1186
1325
  readerRemedy(owner, channel) {
1187
1326
  switch (this.meshMode) {
1188
1327
  case "user":
@@ -1697,288 +1836,23 @@ export class Manager {
1697
1836
  return `manager is waiting for resume attempt ${this.resumeAttemptId}; ordinary lifecycle/control work is fenced`;
1698
1837
  return `manager is in ${this.maintenanceState} mode; new lifecycle/control work is fenced`;
1699
1838
  }
1700
- /** Fence and build the inventory without stopping a child. The coordinator must durably persist
1701
- * this exact plan before calling commitPreservation with the same attempt id. */
1702
- preparePreservation(attemptId) {
1703
- if (this.execution === "none")
1704
- return Promise.reject(new EpEnvelopeError("unimplemented", this.executionRefusal()));
1705
- if (!attemptId.trim())
1706
- return Promise.reject(new Error("preservation attemptId is required"));
1707
- if (this.preservationAttemptId && this.preservationAttemptId !== attemptId)
1708
- return Promise.reject(new Error(`manager is fenced for preservation attempt ${this.preservationAttemptId}; refusing different attempt ${attemptId}`));
1709
- if (this.maintenanceState === "preserved" && this.preservationInventory)
1710
- return Promise.resolve({ ok: true, attemptId, state: "preserved", inventory: this.preservationInventory, failures: [] });
1711
- if (this.preparationTask)
1712
- return this.preparationTask;
1713
- if (this.maintenanceState === "active") {
1714
- // The fence lands before any await. Accepted work has already incremented lifecycleInFlight.
1715
- this.maintenanceState = "preserving";
1716
- this.preservationAttemptId = attemptId;
1717
- this.preservationGeneration++;
1718
- if (this.credRenewTimer) {
1719
- clearInterval(this.credRenewTimer);
1720
- this.credRenewTimer = undefined;
1721
- }
1722
- }
1723
- const generation = this.preservationGeneration;
1724
- const task = this.runPreparation(attemptId, generation);
1725
- let wrapped;
1726
- wrapped = task.finally(() => {
1727
- if (this.preservationGeneration === generation && this.preparationTask === wrapped)
1728
- this.preparationTask = undefined;
1729
- });
1730
- this.preparationTask = wrapped;
1731
- return wrapped;
1732
- }
1733
- assertPreservationGeneration(attemptId, generation) {
1734
- if (this.preservationAttemptId !== attemptId || this.preservationGeneration !== generation)
1735
- throw new Error(`preservation attempt ${attemptId} was abandoned before preparation completed`);
1736
- }
1737
- async runPreparation(attemptId, generation) {
1738
- await this.awaitLifecycleDrain();
1739
- this.assertPreservationGeneration(attemptId, generation);
1740
- // Read the chat frontier BEFORE any child stops (issue #545): a message posted between this
1741
- // read and the child's stop is delivered live now and again as `historical` on resume, a
1742
- // duplicate bounded to the cut window that the seat's own id dedup on `durable` channels
1743
- // absorbs, whereas a read taken after the stops would instead skip messages the seat never
1744
- // actually saw.
1745
- const backfillFloor = await this.chatFrontierForPreservation();
1746
- const inventory = this.preservationInventory ?? {
1747
- version: "cotal-manager-resume/v2",
1748
- space: this.space,
1749
- createdAt: new Date().toISOString(),
1750
- agents: [...this.agents.values()].map((a) => this.resumeEntry(a, backfillFloor)),
1751
- };
1752
- const failures = [];
1753
- for (const entry of inventory.agents) {
1754
- const error = this.inventoryReferenceError(entry);
1755
- if (error)
1756
- failures.push({
1757
- name: entry.name,
1758
- id: entry.identity.mode === "user" ? principalKey(entry.identity.owner, entry.identity.actor).key : entry.identity.id,
1759
- error,
1760
- });
1761
- }
1762
- // A later manager does not resume a delegated seat, and its close runs only inside its
1763
- // retirement, so a cut that holds one is refused before any child stops. A carried resume seat's
1764
- // private home is removed when its slot is freed, so a later manager would find nothing to fork.
1765
- for (const a of this.agents.values()) {
1766
- if (a.handedOff)
1767
- failures.push({ name: a.name, id: a.id, error: "a delegated seat is not resumed by a later manager; stop it before preserving" });
1768
- if (a.seatHome)
1769
- failures.push({ name: a.name, id: a.id, error: "a carried resume seat's private home is not kept for a later manager; stop it before preserving" });
1770
- if (a.once)
1771
- failures.push({ name: a.name, id: a.id, error: "a once seat runs its one task in this process, and a later manager would start it again; let its task end or stop it before preserving" });
1772
- }
1773
- const unverifiedStops = this.unverifiedStops.filter((stopped) => {
1774
- try {
1775
- if (!stopped.authoritative && stopped.handle.status() === "exited")
1776
- return false;
1777
- }
1778
- catch { /* fail closed below */ }
1779
- failures.push({
1780
- name: stopped.name,
1781
- id: stopped.id,
1782
- error: stopped.error ?? `an earlier stop on runtime "${stopped.handle.kind}" cannot prove the child is gone`,
1783
- });
1784
- return true;
1785
- });
1786
- this.assertPreservationGeneration(attemptId, generation);
1787
- // The prepared inventory must round-trip through the EXACT resume control parser (schema and
1788
- // byte cap) NOW, before any child stops: a cut that cannot resume must fail at prepare time,
1789
- // never after listener exposure.
1790
- try {
1791
- parseResumeControlArgs({ attemptId, inventory });
1792
- }
1793
- catch (e) {
1794
- failures.push({ name: "<inventory>", id: attemptId, error: `prepared inventory would be rejected at resume: ${rejectionText(e)}` });
1795
- }
1796
- this.preservationInventory = inventory;
1797
- this.preservationFailures = failures;
1798
- this.unverifiedStops = unverifiedStops;
1799
- return {
1800
- ok: failures.length === 0,
1801
- attemptId,
1802
- state: "prepared",
1803
- inventory,
1804
- failures: [...failures],
1805
- };
1806
- }
1807
- /** Stop children only after the coordinator has persisted the prepared inventory. Same-attempt
1808
- * retries are idempotent; a different attempt is refused. */
1809
- commitPreservation(attemptId) {
1810
- if (this.execution === "none")
1811
- return Promise.reject(new EpEnvelopeError("unimplemented", this.executionRefusal()));
1812
- if (!this.preservationAttemptId || this.preservationAttemptId !== attemptId)
1813
- return Promise.reject(new Error(`preservation attempt ${attemptId} was not prepared by this manager`));
1814
- if (!this.preservationInventory)
1815
- return Promise.reject(new Error(`preservation attempt ${attemptId} has no prepared inventory`));
1816
- if (this.preservationFailures.length)
1817
- return Promise.resolve({
1818
- ok: false,
1819
- attemptId,
1820
- state: "preserving",
1821
- inventory: this.preservationInventory,
1822
- failures: [...this.preservationFailures],
1823
- });
1824
- if (this.maintenanceState === "preserved")
1825
- return Promise.resolve({ ok: true, attemptId, state: "preserved", inventory: this.preservationInventory, failures: [] });
1826
- if (this.preservationTask)
1827
- return this.preservationTask;
1828
- this.preservationStarted = true;
1829
- this.preservationTask = this.runPreservation(attemptId).finally(() => {
1830
- this.preservationTask = undefined;
1831
- });
1832
- return this.preservationTask;
1833
- }
1834
- /** Recover an abandoned prepare before any child stop. Once commit begins, preservation is
1835
- * irreversible and remains fenced until the coordinator records failure/recourse. */
1836
- abortPreservation(attemptId) {
1837
- if (this.execution === "none")
1838
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
1839
- if (this.preservationAttemptId !== attemptId)
1840
- throw new Error(`preservation attempt ${attemptId} is not the active manager attempt`);
1841
- if (this.preparationTask || this.lifecycleInFlight > 0)
1842
- throw new Error(`preservation attempt ${attemptId} is still preparing or draining accepted lifecycle work and cannot be aborted`);
1843
- if (this.preservationStarted || this.preservationTask || this.maintenanceState === "preserved")
1844
- throw new Error(`preservation attempt ${attemptId} has begun stopping children and cannot return to active mode`);
1845
- this.preservationGeneration++;
1846
- this.maintenanceState = "active";
1847
- this.preservationAttemptId = undefined;
1848
- this.preservationInventory = undefined;
1849
- this.preservationFailures = [];
1850
- if (this.auth && !this.credRenewTimer) {
1851
- this.credRenewTimer = setInterval(() => { void this.renewDaemonCreds(); }, credRenewIntervalMs(STANDING_RENEWABLE_TTL_SEC));
1852
- this.credRenewTimer.unref?.();
1853
- }
1854
- this.resumeCredRenewal?.();
1855
- // Exit watchers were suppressed while the fence stood: reconcile every child that died during
1856
- // preparation now, or its slot/credential footprint would linger unreaped after the abort.
1857
- for (const agent of [...this.agents.values()]) {
1858
- try {
1859
- if (agent.handle.status() === "exited")
1860
- this.onAgentExit(agent);
1861
- }
1862
- catch { /* status unavailable - the exit watcher fires again on real exit */ }
1863
- }
1864
- }
1865
- /** In-process convenience that preserves the crash barrier by awaiting durable persistence between
1866
- * prepare and commit. Wire callers use the explicit two-phase admin operations. */
1867
- async preserveState(opts) {
1868
- const plan = await this.preparePreservation(opts.attemptId);
1869
- if (!plan.ok)
1870
- return { ok: false, attemptId: opts.attemptId, state: "preserving", inventory: plan.inventory, failures: plan.failures };
1871
- await opts.persistInventory(plan.inventory);
1872
- return this.commitPreservation(opts.attemptId);
1873
- }
1874
- async runPreservation(attemptId) {
1875
- const failures = [];
1876
- for (const a of [...this.agents.values()])
1877
- a.suppressCleanup = true;
1878
- await Promise.all([...this.agents.values()].map(async (a) => {
1879
- try {
1880
- // A preservation cut must not run the connector's logical leave/cleanup hooks.
1881
- a.handle.stop({ graceful: false });
1882
- }
1883
- catch (e) {
1884
- failures.push({ name: a.name, id: a.id, error: `stop failed: ${rejectionText(e)}` });
1885
- return;
1886
- }
1887
- try {
1888
- await this.awaitHandleExit(a.handle);
1889
- if (this.agents.get(a.name) === a)
1890
- this.agents.delete(a.name);
1891
- }
1892
- catch (e) {
1893
- failures.push({ name: a.name, id: a.id, error: rejectionText(e) });
1894
- }
1895
- }));
1896
- if (failures.length === 0)
1897
- this.maintenanceState = "preserved";
1898
- return {
1899
- ok: failures.length === 0,
1900
- attemptId,
1901
- state: this.maintenanceState === "preserved" ? "preserved" : "preserving",
1902
- inventory: this.preservationInventory,
1903
- failures,
1904
- };
1905
- }
1906
- async awaitHandleExit(handle) {
1907
- if (!handle.waitForExit)
1908
- throw new Error(`runtime "${handle.kind}" cannot prove child exit (AgentHandle.waitForExit is not implemented)`);
1909
- await withTimeout(handle.waitForExit(), this.preserveStopTimeoutMs, `child did not exit within ${this.preserveStopTimeoutMs}ms`);
1910
- if (handle.status() !== "exited")
1911
- throw new Error(`runtime "${handle.kind}" reported exit completion but status is still running`);
1912
- }
1913
- inventoryReferenceError(entry) {
1914
- if (entry.launch.source.kind === "manifest" && !entry.launch.source.runId)
1915
- return "resolved manifest launch has no retained runId";
1916
- if (entry.launch.unresolvedLaunchOptionKeys?.length)
1917
- return `imperative launch options have no non-secret durable source (${entry.launch.unresolvedLaunchOptionKeys.join(", ")})`;
1918
- if (!entry.dependencies.some((path) => resolve(path) === resolve(entry.launch.source.configPath)))
1919
- return `launch config is not declared as a retained dependency: ${entry.launch.source.configPath}`;
1920
- if (entry.launch.source.kind === "inline" && resolve(entry.launch.source.configPath) !== resolve(inlineSnapshotPath(this.workspaceRoot, entry.identity.lifecycleUid)))
1921
- return `inline persona snapshot ${entry.launch.source.configPath} is not this lifecycle's snapshot path`;
1922
- if (entry.launch.source.kind === "manifest" && entry.launch.source.runId) {
1923
- const specPath = join(this.workspaceRoot, ".cotal", "run", `${entry.launch.source.runId}.json`);
1924
- if (!entry.dependencies.some((path) => resolve(path) === resolve(specPath)))
1925
- return `manifest source is not declared as a retained dependency: ${specPath}`;
1926
- }
1927
- const required = [...entry.dependencies];
1928
- if (entry.identity.mode === "static")
1929
- required.push(entry.identity.credential.path);
1930
- if (entry.identity.mode === "user") {
1931
- required.push(entry.identity.actorToken.path, entry.identity.sentinelCredential.path);
1932
- }
1933
- for (const path of required) {
1934
- try {
1935
- const st = lstatSync(path);
1936
- if (!st.isFile() || st.isSymbolicLink())
1937
- return `retained reference is not a regular non-symlink file: ${path}`;
1938
- }
1939
- catch (e) {
1940
- return `retained reference unavailable: ${path} (${rejectionText(e)})`;
1941
- }
1942
- }
1943
- if (process.platform !== "win32") {
1944
- const secrets = entry.identity.mode === "static"
1945
- ? [entry.identity.credential.path]
1946
- : entry.identity.mode === "user"
1947
- ? [entry.identity.actorToken.path, entry.identity.sentinelCredential.path]
1948
- : [];
1949
- for (const path of secrets)
1950
- if ((lstatSync(path).mode & 0o077) !== 0)
1951
- return `retained identity file is not private (expected 0600): ${path}`;
1952
- }
1953
- try {
1954
- if (this.fileDigest(entry.launch.source.configPath) !== entry.launch.source.configSha256)
1955
- return `launch config changed since it became effective: ${entry.launch.source.configPath}`;
1956
- if (entry.identity.mode === "static" && this.fileDigest(entry.identity.credential.path) !== entry.identity.credential.sha256)
1957
- return `retained credential changed after the cut: ${entry.identity.credential.path}`;
1958
- if (entry.identity.mode === "user" &&
1959
- (this.fileDigest(entry.identity.actorToken.path) !== entry.identity.actorToken.sha256 ||
1960
- this.fileDigest(entry.identity.sentinelCredential.path) !== entry.identity.sentinelCredential.sha256))
1961
- return `retained user identity files changed after the cut for ${entry.name}`;
1962
- if (entry.launch.source.kind === "manifest" && entry.launch.source.runId) {
1963
- const specPath = join(this.workspaceRoot, ".cotal", "run", `${entry.launch.source.runId}.json`);
1964
- if (!entry.launch.source.manifestSha256 || this.fileDigest(specPath) !== entry.launch.source.manifestSha256)
1965
- return `manifest source changed since it became effective: ${specPath}`;
1966
- }
1967
- }
1968
- catch (e) {
1969
- return `retained reference cannot be hashed: ${rejectionText(e)}`;
1970
- }
1971
- return undefined;
1972
- }
1839
+ /** {@link Preservation.preparePreservation}. */
1840
+ preparePreservation(...args) { return this.preservationComponent.preparePreservation(...args); }
1841
+ /** {@link Preservation.runPreparation}. */
1842
+ runPreparation(...args) { return this.preservationComponent.runPreparation(...args); }
1843
+ /** {@link Preservation.commitPreservation}. */
1844
+ commitPreservation(...args) { return this.preservationComponent.commitPreservation(...args); }
1845
+ /** {@link Preservation.abortPreservation}. */
1846
+ abortPreservation(...args) { return this.preservationComponent.abortPreservation(...args); }
1847
+ /** {@link Preservation.preserveState}. */
1848
+ preserveState(...args) { return this.preservationComponent.preserveState(...args); }
1849
+ /** {@link Preservation.awaitHandleExit}. */
1850
+ awaitHandleExit(...args) { return this.preservationComponent.awaitHandleExit(...args); }
1851
+ /** {@link Preservation.inventoryReferenceError}. */
1852
+ inventoryReferenceError(...args) { return this.preservationComponent.inventoryReferenceError(...args); }
1973
1853
  fileDigest(path) { return fileDigest(path); }
1974
- fileDigestOrEmpty(path) {
1975
- try {
1976
- return this.fileDigest(path);
1977
- }
1978
- catch {
1979
- return "";
1980
- }
1981
- }
1854
+ /** {@link Preservation.fileDigestOrEmpty}. */
1855
+ fileDigestOrEmpty(...args) { return this.preservationComponent.fileDigestOrEmpty(...args); }
1982
1856
  resumeEntry(a, backfillFloor) {
1983
1857
  // A preservation cut is a stop boundary too, so a manifest launch after it reopens what a resume would.
1984
1858
  this.recordContinuityAtStop(a, "preservation");
@@ -2057,233 +1931,26 @@ export class Manager {
2057
1931
  ...(backfillFloor !== undefined ? { backfillFloor } : {}),
2058
1932
  });
2059
1933
  }
2060
- /** Tear down every managed agent's footprint on an explicit destructive {@link stop}, or only the
2061
- * in-process seats a default stop cannot detach. A manager exit is
2062
- * a mass agent-exit, and without this its agents' footprints (creds files + `dm_`/`dlv_` durables + ACL
2063
- * rows) would orphan exactly as the per-agent exit path prevents. Stop each child gracefully, so its
2064
- * own shutdown runs before the runtime escalates, and AWAIT its deprovision — bounded per agent (`withTimeout`) and
2065
- * best-effort (`allSettled` + a loud log), so one slow/failed teardown can neither hang nor abort exit.
2066
- * The creds file is dropped even if the broker teardown fails (see {@link deprovision}). Deliberately
2067
- * touches NEITHER the lease NOR the endpoints — the caller owns those. */
2068
- async teardownManagedAgents(managed = [...this.agents.values()]) {
1934
+ /** {@link Preservation.teardownManagedAgents}. */
1935
+ teardownManagedAgents(...args) { return this.preservationComponent.teardownManagedAgents(...args); }
1936
+ /** {@link Preservation.isProcessBoundSeat}. */
1937
+ isProcessBoundSeat(...args) { return this.preservationComponent.isProcessBoundSeat(...args); }
1938
+ /** {@link Preservation.releaseManagedAgents}. */
1939
+ releaseManagedAgents(...args) { return this.preservationComponent.releaseManagedAgents(...args); }
1940
+ /** {@link Preservation.adoptReleasedSeats}. */
1941
+ adoptReleasedSeats(...args) { return this.preservationComponent.adoptReleasedSeats(...args); }
1942
+ async stopRetainedAgentsOnExit() {
1943
+ const managed = [...this.agents.values()];
1944
+ for (const a of managed)
1945
+ a.suppressCleanup = true;
2069
1946
  const failures = [];
2070
- const stopped = [];
2071
- for (const a of managed) {
2072
- // Free the slot and stop each the way an operator stop does. `stopHandle` is best-effort (never
2073
- // throws — see it), so one bad stop can't strand the rest, and every snapshot entry is
2074
- // deprovisioned below regardless. A hard kill never runs the seat's shutdown, so a helper that
2075
- // has left the process group keeps running after `cotal down`. The runtime still escalates to
2076
- // SIGKILL after its grace.
2077
- this.recordContinuityAtStop(a, "shutdown");
2078
- if (process.platform !== "win32" || a.handle.kind !== "pty") {
2079
- this.agents.delete(a.name);
2080
- this.dropSeatRecord(a);
2081
- }
2082
- const refused = this.stopHandle(a, true, { kind: "stopped-shutdown" });
2083
- if (refused === undefined)
2084
- stopped.push(a);
2085
- else
2086
- failures.push(`${a.name}: stop failed: ${refused}`);
2087
- }
2088
- // A runtime stop request is not exit proof. Do not release the manager lease or registration
2089
- // while any seat may still hold this instance's broker rails: that creates the exact orphan
2090
- // window where a successor sees a dead manager but live predecessor authority. Every shipped
2091
- // runtime now supplies waitForExit; absence or timeout is a failed shutdown, never a clean one.
2092
- // The slot delete above bypasses freeSlot, which is where the reap line lives, so say it
2093
- // here once this shutdown has proved the seat exited. A seat whose stop was refused, or
2094
- // whose exit wait did not prove it gone, is named only by the shutdown error below (#1423, #3404).
2095
- await Promise.all(stopped.map(async (a) => {
1947
+ await Promise.all(managed.map(async (a) => {
2096
1948
  try {
2097
- await this.awaitHandleExit(a.handle);
2098
- if (process.platform === "win32" && a.handle.kind === "pty") {
2099
- this.agents.delete(a.name);
2100
- this.dropSeatRecord(a);
2101
- }
2102
- this.logSeatReaped(a, { kind: "stopped-shutdown" });
2103
- }
2104
- catch (e) {
2105
- failures.push(`${a.name}: ${rejectionText(e)}`);
2106
- }
2107
- }));
2108
- // Deprovision EVERY snapshot entry regardless of whether its stop failed (allSettled + a loud log).
2109
- await Promise.allSettled(managed.filter((a) => !a.suppressCleanup).map((a) => {
2110
- // Retired here on every mesh, the open mesh included, which runs no teardown of its own.
2111
- const settled = a.launch.source.kind !== "inline" || this.dropInlineSnapshot(a.name, a.lifecycleUid);
2112
- return this.deprovision({ ...this.teardownTarget(a), ...(settled ? { snapshotSettled: true } : {}) }).catch((e) => console.error(`deprovision ${a.name} (${a.id}) on shutdown: ${rejectionText(e)}`));
2113
- }));
2114
- if (failures.length)
2115
- throw new Error(`manager shutdown could not prove every seat exited: ${failures.join("; ")}`);
2116
- }
2117
- isProcessBoundSeat(agent) {
2118
- return agent.handle.kind === "pty" && typeof agent.handle.release !== "function";
2119
- }
2120
- /** Drop local custody of every seat that can outlive this process, and leave it running. A seat
2121
- * with a runtime reference is recorded first, so the next manager on this workspace adopts it, or
2122
- * retires it once its runtime proves it gone. The stopping manager keeps no watch on a released
2123
- * seat: its endpoint is closing, and a retirement it drove afterwards would run over a dead
2124
- * connection and race the next manager's. `stop` is every seat left for the caller to stop and
2125
- * retire now: an in-process seat, a seat the runtime already reports gone, and a seat whose record
2126
- * could not be written, because a released seat nobody can find again is the leak this stop must
2127
- * not create. */
2128
- releaseManagedAgents() {
2129
- const failures = [];
2130
- const stop = [];
2131
- for (const a of [...this.agents.values()]) {
2132
- if (this.isProcessBoundSeat(a)) {
2133
- stop.push(a);
2134
- continue;
2135
- }
2136
- let exited = false;
2137
- try {
2138
- exited = a.handle.status() === "exited";
2139
- }
2140
- catch {
2141
- // Status is not proof either way; the seat is released as any running seat is.
2142
- }
2143
- if (exited) {
2144
- stop.push(a);
2145
- continue;
2146
- }
2147
- const reference = a.handle.reference;
2148
- if (reference) {
2149
- try {
2150
- // A static manager records an adoptable seat at launch and keeps that record current. A
2151
- // user-mode manager records nothing until here.
2152
- if (this.userMode)
2153
- writeSeatRecord(this.workspaceRoot, { version: "cotal-seat-record/v1", instanceId: this.managerInstanceId, crashes: a.restart?.crashes ?? [], agent: this.resumeEntryOf(a) });
2154
- writeReleasedSeatReference(this.workspaceRoot, this.space, a.name, { version: "cotal-released-seat/v1", lifecycleUid: a.lifecycleUid, kind: reference.kind, id: reference.id });
2155
- }
2156
- catch (e) {
2157
- console.error(`! ${a.name}: the released seat could not be recorded (${rejectionText(e)}); this stop retires it instead`);
2158
- stop.push(a);
2159
- continue;
2160
- }
2161
- }
2162
- try {
2163
- a.handle.release?.();
2164
- a.suppressCleanup = true;
2165
- this.agents.delete(a.name);
2166
- }
2167
- catch (e) {
2168
- failures.push(`${a.name}: ${rejectionText(e)}`);
2169
- }
2170
- }
2171
- return { failures, stop };
2172
- }
2173
- /** Take back user-mode seats a previous manager released while they were still running. A seat
2174
- * the runtime adopts is watched, and retired when that watch proves it gone. A seat the runtime
2175
- * has already reaped is retired now. Anything the runtime cannot prove is left recorded. */
2176
- async adoptReleasedSeats() {
2177
- const dir = join(this.workspaceRoot, ".cotal", "seat-records", this.space);
2178
- if (!existsSync(dir))
2179
- return;
2180
- for (const file of readdirSync(dir)) {
2181
- if (!file.endsWith(".runtime-ref"))
2182
- continue;
2183
- const name = file.slice(0, -".runtime-ref".length);
2184
- try {
2185
- await this.adoptReleasedSeat(name);
2186
- }
2187
- catch (e) {
2188
- console.error(`! ${name}: the released seat was not adopted: ${rejectionText(e)}`);
2189
- }
2190
- }
2191
- }
2192
- async adoptReleasedSeat(name) {
2193
- const reference = readReleasedSeatReference(this.workspaceRoot, this.space, name);
2194
- const record = reference ? readSeatRecord(this.workspaceRoot, this.space, name) : undefined;
2195
- const identity = record?.agent.identity;
2196
- if (!reference || !record || identity?.mode !== "user" || identity.lifecycleUid !== reference.lifecycleUid)
2197
- return;
2198
- try {
2199
- await this.validateRetainedAuthority(record.agent);
2200
- }
2201
- catch (e) {
2202
- console.error(`! ${name}: the released seat's record was not adopted: ${rejectionText(e)}`);
2203
- return;
2204
- }
2205
- const held = this.agents.get(name);
2206
- if (held?.lifecycleUid === reference.lifecycleUid)
2207
- return;
2208
- if (held)
2209
- return;
2210
- const runtime = this.runtimeFor(reference.kind);
2211
- if (typeof runtime.adopt !== "function" || reference.kind !== runtime.kind)
2212
- return;
2213
- let handle;
2214
- try {
2215
- handle = runtime.adopt(reference);
2216
- }
2217
- catch (e) {
2218
- try {
2219
- await requireRuntimeReap(runtime, reference);
2220
- }
2221
- catch {
2222
- // The runtime could not prove the seat gone. Leave the record for a later start.
2223
- return;
2224
- }
2225
- console.error(`! ${name}: the released seat is gone (${rejectionText(e)}); retiring its lifecycle`);
2226
- handle = {
2227
- name,
2228
- kind: runtime.kind,
2229
- reference: { kind: runtime.kind, id: reference.id },
2230
- status: () => "exited",
2231
- stop: () => { },
2232
- interrupt: () => { },
2233
- waitForExit: () => Promise.resolve(),
2234
- attach: () => { throw new Error(`released seat ${name} has exited`); },
2235
- };
2236
- }
2237
- const launch = record.agent.launch;
2238
- const agent = {
2239
- name,
2240
- role: record.agent.role,
2241
- agent: launch.connector,
2242
- id: principalKey(identity.owner, identity.actor).key,
2243
- lifecycleUid: identity.lifecycleUid,
2244
- userOwner: identity.owner,
2245
- secretPaths: {
2246
- actorToken: identity.actorToken.path,
2247
- sentinelCreds: identity.sentinelCredential.path,
2248
- health: identity.health.path,
2249
- },
2250
- spawner: record.agent.spawner,
2251
- authorityParent: record.agent.authorityParent,
2252
- startedAt: Date.parse(record.agent.startedAt) || Date.now(),
2253
- handle,
2254
- launch: {
2255
- source: launch.source,
2256
- runtime: launch.runtime,
2257
- cwd: launch.cwd,
2258
- model: launch.model,
2259
- variant: launch.variant,
2260
- subscribe: launch.subscribe,
2261
- allowSubscribe: launch.allowSubscribe,
2262
- allowPublish: launch.allowPublish,
2263
- capabilities: launch.capabilities,
2264
- events: launch.events,
2265
- eventPayloads: launch.eventPayloads,
2266
- shareTools: launch.shareTools,
2267
- forkSource: launch.forkSource,
2268
- sessionId: launch.sessionId,
2269
- unresolvedLaunchOptionKeys: launch.unresolvedLaunchOptionKeys,
2270
- },
2271
- };
2272
- this.agents.set(name, agent);
2273
- this.watchExit(agent);
2274
- }
2275
- async stopRetainedAgentsOnExit() {
2276
- const managed = [...this.agents.values()];
2277
- for (const a of managed)
2278
- a.suppressCleanup = true;
2279
- const failures = [];
2280
- await Promise.all(managed.map(async (a) => {
2281
- try {
2282
- // No cut holds a delegated seat (runPreparation refuses one), so stopping it is its retirement.
2283
- if (a.handedOff)
2284
- await this.deprovision(this.teardownTarget(a));
2285
- else
2286
- a.handle.stop({ graceful: false });
1949
+ // No cut holds a delegated seat (runPreparation refuses one), so stopping it is its retirement.
1950
+ if (a.handedOff)
1951
+ await this.deprovision(this.teardownTarget(a));
1952
+ else
1953
+ a.handle.stop({ graceful: false });
2287
1954
  }
2288
1955
  catch (e) {
2289
1956
  failures.push(`${a.name}: stop failed: ${rejectionText(e)}`);
@@ -2471,51 +2138,12 @@ export class Manager {
2471
2138
  this.serviceServe = undefined;
2472
2139
  await this.retireConnection(s.nc, () => s.handle.stop());
2473
2140
  }
2474
- /** Retire a dedicated connection on stop: drain it while its transport is up, close it while the
2475
- * client is reconnecting it. A drain on a reconnecting connection does not fail, it waits for the
2476
- * reconnect, so the stop would last as long as the outage; a broker this connection cannot reach
2477
- * has nothing left to flush. `flush` (the serve loop's own drain) runs only while the transport is
2478
- * up. Best-effort, so a graceful stop completes its remaining teardown even when the broker is gone. */
2479
- async retireConnection(nc, flush) {
2480
- if (this.transportDown.has(nc)) {
2481
- try {
2482
- await nc.close();
2483
- }
2484
- catch { /* best effort */ }
2485
- return;
2486
- }
2487
- if (flush)
2488
- try {
2489
- await flush();
2490
- }
2491
- catch { /* best effort */ }
2492
- try {
2493
- await drainAndClose(nc);
2494
- }
2495
- catch { /* best effort */ }
2496
- }
2497
- /** A failed candidate must not extend preparation by draining subscriptions on a stalled socket.
2498
- * Close only that candidate first. Native stop still owns any already-dispatched handlers, whose
2499
- * outcomes remain unknown to callers and must not be replayed; they do not hold family adoption. */
2500
- async discardServeCandidate(nc, handle) {
2501
- await nc.close();
2502
- if (handle)
2503
- void handle.stop().catch((e) => console.error(`! remote manager discarded serve candidate cleanup: ${rejectionText(e)}`));
2504
- }
2505
- /** Track a dedicated connection's transport into {@link transportDown} from the first moment:
2506
- * nats.js reports `disconnect` when the socket drops and `reconnect` only after it has re-sent the
2507
- * connection's subscriptions. If the status stream itself fails, the transport can no longer be
2508
- * observed, so it counts as down. */
2509
- trackTransport(nc) {
2510
- void (async () => {
2511
- for await (const st of nc.status()) {
2512
- if (st.type === "disconnect")
2513
- this.transportDown.add(nc);
2514
- else if (st.type === "reconnect")
2515
- this.transportDown.delete(nc);
2516
- }
2517
- })().catch(() => this.transportDown.add(nc));
2518
- }
2141
+ /** {@link BrokerTransport.retireConnection}. */
2142
+ retireConnection(...args) { return this.brokerTransportComponent.retireConnection(...args); }
2143
+ /** {@link BrokerTransport.discardServeCandidate}. */
2144
+ discardServeCandidate(...args) { return this.brokerTransportComponent.discardServeCandidate(...args); }
2145
+ /** {@link BrokerTransport.trackTransport}. */
2146
+ trackTransport(...args) { return this.brokerTransportComponent.trackTransport(...args); }
2519
2147
  async opFinalizeResume(rawArgs) {
2520
2148
  if (this.execution === "none")
2521
2149
  throw new EpEnvelopeError("unimplemented", this.executionRefusal());
@@ -2668,25 +2296,8 @@ export class Manager {
2668
2296
  return { ok: false, error: rejectionText(e) };
2669
2297
  }
2670
2298
  }
2671
- /** The ONE shared control-admission chokepoint BOTH dispatch doors
2672
- * run — the v0.3 `ctl` door ({@link handle}) and the v0.4 `ep` service handlers
2673
- * ({@link serveGated}): the maintenance/resume fence (`beginLifecycle`: a resume-pending or
2674
- * non-active manager accepts no ordinary control work) and then the membership gate
2675
- * ({@link lifecycleMembershipRefusal}: a retiring/terminalizing/retired managed incarnation's
2676
- * AUTHENTICATED principal holds no control authority even with a valid JWT). Refusal carries
2677
- * WHICH fence refused so the ep door can map onto the §13.3 catalog; admission returns the
2678
- * accepted-work release. Never re-implemented per door — a fence on one door is a bypass. */
2679
- admitControl(caller) {
2680
- const release = this.beginLifecycle();
2681
- if (!release)
2682
- return { refusal: this.maintenanceError(), fence: "maintenance" };
2683
- const membership = this.lifecycleMembershipRefusal(caller);
2684
- if (membership) {
2685
- release();
2686
- return { refusal: membership, fence: "membership" };
2687
- }
2688
- return { release };
2689
- }
2299
+ /** {@link CommandDispatch.admitControl}. */
2300
+ admitControl(...args) { return this.commandDispatch.admitControl(...args); }
2690
2301
  /** Run one v0.4 service-command handler through the SHARED admission chokepoint
2691
2302
  * ({@link admitControl}) on the broker-authenticated caller principal, mapping the two fences
2692
2303
  * onto the §13.3 catalog: maintenance/resume → `unavailable`, membership →
@@ -2727,54 +2338,8 @@ export class Manager {
2727
2338
  this.releaseLifecycle();
2728
2339
  }
2729
2340
  }
2730
- /** The ep door's ADMIN flag for a caller. Static mesh: `true` — the
2731
- * admin-grade rows (any-mode despawn/attach, the `manager.admin` family, `launch`) are minted
2732
- * only into operator instruments (§13.2: `any` is operator-policy-mintable; the agent/spawn
2733
- * rollups never carry them), so REACHING the handler is holding the admin tier, exactly as
2734
- * holding `ctl.<admin>` is today. User mesh: the caller's CURRENT ledger scope must carry
2735
- * `admin`. A local-host manager reads its own ledger fresh. A remote-authority manager relays the
2736
- * subject-parsed caller tuple to its host-owned authorization callback, with no participant-ledger
2737
- * fallback. The same fresh authority drives {@link psOwnerFilter}, so a revoked scope demotes the
2738
- * very next call even on a still-valid bearer. Local ledger read failures authorize nothing;
2739
- * remote host-state faults throw and fail the operation closed.
2740
- * NAMED RESIDUAL: the static `true` has no serve-time re-check — a LEAKED static admin
2741
- * instrument keeps its reach until the credential's bounded
2742
- * TTL (the one-shot 5-minute profile), the same static-revoke≠reconnect-death class ruled
2743
- * across this campaign; static revocation is the TTL, not a ledger. */
2744
- async epAdminReach(caller) {
2745
- if (!this.userMode)
2746
- return true;
2747
- if (this.remoteAuthority) {
2748
- // A hosted run's own caller is derived from its id and holds no ledger row: it acts for the
2749
- // caller its run was admitted for, so that caller's current grant decides, and a revoked
2750
- // login demotes the run's next spawn.
2751
- const asked = this.runHosting?.admittedCaller(caller) ?? caller;
2752
- return this.remoteAuthority.authorizeAdmin({ owner: asked.owner, actor: asked.actor, lifecycleUid: asked.uid });
2753
- }
2754
- try {
2755
- const scope = await resolveAuthProvider().actorScope({
2756
- dir: userAuthStateDir(this.workspaceRoot, this.space),
2757
- owner: caller.owner,
2758
- actor: caller.actor,
2759
- });
2760
- return scope?.includes("admin") === true;
2761
- }
2762
- catch {
2763
- return false;
2764
- }
2765
- }
2766
- /** A targeted request's admin flag: mode `any` (the operator instrument's cross-agent form,
2767
- * rev 3) resolves through {@link epAdminReach}; a user-mode any-mode caller whose CURRENT
2768
- * ledger row lost `admin` since its rows were minted refuses loud rather than silently
2769
- * downgrading to the owner path (the request's declared mode is honored or denied, never
2770
- * reinterpreted). Owner mode is always the privileged (own-domain) path. */
2771
- async epAnyModeAdmin(ctx) {
2772
- if (ctx.subject.target?.mode !== "any")
2773
- return false;
2774
- if (!(await this.epAdminReach(ctx.subject.caller)))
2775
- throw new EpEnvelopeError("permission-denied", `an any-mode ${ctx.subject.command} is operator reach; the caller's current ledger grant does not carry "admin" (SPEC 13.2)`);
2776
- return true;
2777
- }
2341
+ /** {@link CommandDispatch.epAdminReach}. */
2342
+ epAdminReach(...args) { return this.commandDispatch.epAdminReach(...args); }
2778
2343
  /** The run host, or one of three refusals. A remote-authority manager holds no space signer, so
2779
2344
  * it cannot mint the per-run driver credential SPEC 14.6 requires without all four closed
2780
2345
  * host callbacks. A local user-auth mesh is `unimplemented`: a hosted run's seats
@@ -2919,310 +2484,8 @@ export class Manager {
2919
2484
  if (accepted.by !== agent.name)
2920
2485
  throw new EpEnvelopeError("permission-denied", `run-answer amend is allowed to ${agent.name} only for an answer recorded under its own name; this step's accepted answer is ${JSON.stringify(accepted.by)}'s`);
2921
2486
  }
2922
- /** The v0.4 typed command table: every ordinary handler runs the SHARED
2923
- * admission chokepoint ({@link serveGated}) and then delegates to the SAME op core the ctl
2924
- * door dispatches (one core, two thin doors). The resume/preservation family
2925
- * deliberately BYPASSES serveGated — exactly as it sits before {@link admitControl} on the ctl
2926
- * door (those ops must run while `resumeRequired` fences ordinary work) — riding its own state
2927
- * fences; its ep gate is the admin-grade `manager.admin` capability grant (static
2928
- * admin-class commands are capability-gated + untargeted, never a fabricated ledger mode).
2929
- *
2930
- * TIER SEMANTICS on the ep door: the tier lives in the CALLER'S
2931
- * GRANT, refined per-op exactly as the ctl doors refine their subject tier. Owner-mode
2932
- * `despawn`/`attach` keep the privileged semantics (`admin=false`, own-domain via
2933
- * {@link authorizeNamed}) — every spawn-capable agent holds those rows. ANY-mode requests are
2934
- * the operator instrument's cross-agent reach (rev 3): the any-mode subject row is mintable
2935
- * only under operator policy (§13.2), so on a static mesh holding it IS the admin tier, and in
2936
- * user mode the caller's CURRENT ledger scope must still carry `admin`
2937
- * ({@link epAdminReach}, the same fresh-read authority `psOwnerFilter` consults). The
2938
- * `manager.admin` family (purge + the resume/preservation ops) is capability-gated at mint AND
2939
- * re-checked at serve time via {@link epAdminReach} (the `adminGated` wrapper) so a user's
2940
- * revoked scope demotes the next call. `launch` is OWNER-EQUALITY on this door for everyone:
2941
- * the deploy path is its only consumer and stamps the caller's own owner,
2942
- * so cross-owner launch was a ctl-tier incidental never exercised, and keying it on the actor's
2943
- * ledger scope broke the deployer-view attenuation - uniform owner-equality is the safe tier.
2944
- * TWO DELIBERATE NARROWINGS vs the ctl doors (NOT bit-exact parity): (1)
2945
- * `define-persona` is `admin=false` for everyone (own-persona discipline; no ep consumer needs
2946
- * cross-owner persona writes - an operator redefines via config, not the wire), where the ctl
2947
- * admin tier allowed operator cross-owner redefine; (2) launch is owner-equality-only, above.
2948
- * Both are least-privilege reductions, never widenings. */
2949
- managerServiceDefs() {
2950
- const args = (ctx) => (ctx.request.args ?? {});
2951
- const callerOf = (ctx) => principalKey(ctx.subject.caller.owner, ctx.subject.caller.actor).key;
2952
- // A ctl-core failure reply becomes the §13.3 structured error the serve boundary publishes.
2953
- // The data half of a failure reply (e.g. a degraded resume result) rides the error MESSAGE
2954
- // only — the action model gives failures a typed channel.
2955
- const unwrap = (r) => {
2956
- if (!r.ok)
2957
- throw new EpEnvelopeError((r.code ?? "failed-precondition"), r.error ?? "the operation failed", r.details, r.outcome);
2958
- return r.data;
2959
- };
2960
- // The admin-family serve gate: every `manager.admin`-class
2961
- // command re-checks operator reach AT SERVE TIME - static: true (the mint boundary already
2962
- // gates the rows to instruments); user mesh: the caller's CURRENT ledger scope must still
2963
- // carry `admin` ({@link epAdminReach}'s fresh read), so a revoked scope demotes the very next
2964
- // call instead of riding the bearer's remaining JWT-row lifetime. The resume family keeps its
2965
- // serveGated BYPASS (those ops must run while the maintenance fence holds) but not the gate.
2966
- const adminGated = async (ctx, fn) => {
2967
- if (!(await this.epAdminReach(ctx.subject.caller)))
2968
- throw new EpEnvelopeError("permission-denied", `${ctx.subject.command} is operator reach; the caller's current ledger grant does not carry "admin" (SPEC 13.2)`, undefined, "not-executed");
2969
- return fn();
2970
- };
2971
- const targetAgent = (ctx) => {
2972
- if (this.execution === "none")
2973
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
2974
- const t = ctx.request.target; // targeted commands only: the serve boundary enforced body-target presence + fresh currency
2975
- const a = this.findManagedByTarget(t);
2976
- if (!a)
2977
- throw new EpEnvelopeError("expired", `target ${t.owner}.${t.actor} (lifecycle ${t.lifecycleUid}) is not a live managed agent of this manager`, undefined, "not-executed");
2978
- return a;
2979
- };
2980
- return managerCommandDefs({
2981
- vitals: (ctx) => this.serveGated(ctx, () => measureManagerVitals()),
2982
- // A remote Manager files every seat under its own owner, so only a user mesh's shared local
2983
- // Manager narrows the count, and status never waits on a remote admin check.
2984
- status: (ctx) => this.serveObservation(ctx, async () => {
2985
- const ownerFilter = this.remoteAuthority ? undefined : await this.psOwnerFilter(ctx.subject.caller, false);
2986
- // The daemon's status deadline is shorter than an install. Report the current inventory
2987
- // without waiting for the install, which has its own lifecycle admission below.
2988
- return this.managerStatusData(ownerFilter, !this.resumeRequired);
2989
- }),
2990
- ps: (ctx) => this.serveGated(ctx, async () => this.list(await this.psOwnerFilter(ctx.subject.caller, false))),
2991
- inspect: (ctx) => this.serveGated(ctx, async () => {
2992
- const name = String(args(ctx).name ?? "").trim();
2993
- const row = this.list(await this.psOwnerFilter(ctx.subject.caller, false)).find((x) => x.name === name);
2994
- if (!row) {
2995
- // The live hit above stays entirely local. Only a miss widens into durable static state,
2996
- // where `not-found` is honest only after the slot read itself succeeds and returns absent.
2997
- // User-mode lifecycles have no manager-local mgrslot row; their per-name projection remains
2998
- // the live map until the auth service exposes an equivalent mediated reader.
2999
- if (this.auth && !this.userMode) {
3000
- const recordsKv = this.goalWriter?.ctx.kv;
3001
- if (!recordsKv)
3002
- throw new EpEnvelopeError("unavailable", `the durable static slot store is not ready while inspecting "${name}"`, [
3003
- { kind: STATIC_SLOT_READ_FAILED_DETAIL, name, record: "slot", operation: "read" },
3004
- ]);
3005
- let observed;
3006
- try {
3007
- observed = await observeStaticSlot(recordsKv, DEV_OWNER, name, this.managerInstanceId);
3008
- }
3009
- catch (error) {
3010
- throw new EpEnvelopeError("unavailable", `the durable static slot state for "${name}" could not be read: ${rejectionText(error)}`, [
3011
- { kind: STATIC_SLOT_READ_FAILED_DETAIL, name, record: error instanceof StaticSlotReadError ? error.record : "slot-or-head", operation: "read" },
3012
- ]);
3013
- }
3014
- // A retired row affirms that no agent exists now, so it keeps the old `not-found`
3015
- // result. The changed refusal is reserved for durable NONTERMINAL state that contradicts
3016
- // the live-map miss and needs operator attention.
3017
- //
3018
- // A sibling's nonterminal row is not a contradiction: the name belongs to another
3019
- // manager instance in this space. In a multi-manager space the class queue hands this
3020
- // read to either instance, so a plain `not-found` here read the same as a name that
3021
- // exists nowhere and a caller had no way to tell the two apart (#443).
3022
- if (observed?.ownerInstanceId !== undefined)
3023
- throw new EpEnvelopeError("failed-precondition", `the durable slot for "${name}" belongs to manager instance ${observed.ownerInstanceId}, not ${this.managerInstanceId} which answered; only that instance can act on it ${renderStaticSlotObservation(observed)}`, [observed]);
3024
- if (observed !== undefined && observed.slotPhase !== "retired")
3025
- throw new EpEnvelopeError("failed-precondition", `no live agent "${name}"; durable state contradicts absence ${renderStaticSlotObservation(observed)}`, [observed]);
3026
- }
3027
- throw new EpEnvelopeError("not-found", `no agent "${name}"`, undefined, "not-executed");
3028
- }
3029
- return row;
3030
- }),
3031
- slots: (ctx) => this.serveGated(ctx, async () => {
3032
- // No manager-local durable static slot store exists for a user-mode or open manager: an
3033
- // empty list here would claim nothing is stranded from a store that was never consulted,
3034
- // the very ambiguity #1274 is about.
3035
- if (!this.auth || this.userMode)
3036
- throw new EpEnvelopeError("failed-precondition", "user-mode and open managers own no durable static slot rows; the projection is static-manager local");
3037
- const recordsKv = this.goalWriter?.ctx.kv;
3038
- if (!recordsKv)
3039
- throw new EpEnvelopeError("unavailable", "the durable static slot store is not ready", [
3040
- { kind: STATIC_SLOT_READ_FAILED_DETAIL, name: "*", record: "slot", operation: "scan" },
3041
- ]);
3042
- let observed;
3043
- try {
3044
- const query = args(ctx);
3045
- observed = await listStaticSlotObservations(recordsKv, DEV_OWNER, this.managerInstanceId, {
3046
- ...(query.names === undefined ? {} : { names: query.names }),
3047
- ...(query.includeRetired === true ? { includeRetired: true } : {}),
3048
- });
3049
- }
3050
- catch (error) {
3051
- throw new EpEnvelopeError("unavailable", `the durable static slot state could not be scanned: ${rejectionText(error)}`, [
3052
- { kind: STATIC_SLOT_READ_FAILED_DETAIL, name: "*", record: error instanceof StaticSlotReadError ? error.record : "slot-or-head", operation: "scan" },
3053
- ]);
3054
- }
3055
- return observed.map(({ kind: _kind, ...detail }) => ({
3056
- ...detail,
3057
- live: this.agents.has(detail.name),
3058
- managerInstanceId: this.managerInstanceId,
3059
- }));
3060
- }),
3061
- models: (ctx) => this.serveGated(ctx, async () => {
3062
- const data = unwrap(await this.opModels(args(ctx)));
3063
- return { catalogs: Array.isArray(data) ? data : [data] };
3064
- }),
3065
- goalResult: (ctx) => this.serveGated(ctx, async () => {
3066
- const gw = this.goalWriter;
3067
- if (!gw || gw.nc.isClosed())
3068
- throw new EpEnvelopeError("unavailable", "the manager goal-reader connection is not standing; the accepted goal is unaffected");
3069
- const goalId = args(ctx).goalId;
3070
- // Only the broker-authenticated caller's full incarnation can name this read. The
3071
- // trusted goal-writer keeps the raw EPF authority; serveEndpoint derives the reply rail.
3072
- const result = await readGoalResult(gw.ctx, goalRefOf(ctx.subject, goalId));
3073
- return { goalId, ...(result === undefined ? {} : { result }) };
3074
- }),
3075
- listDir: (ctx) => this.serveGated(ctx, () => this.listSpawnDirectory(args(ctx))),
3076
- resolveCwd: (ctx) => this.serveGated(ctx, () => this.resolveSpawnCwd(args(ctx).cwd)),
3077
- resolveAgent: (ctx) => this.serveGated(ctx, async () => {
3078
- if (this.execution === "none")
3079
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
3080
- const persona = await this.spawnPersona(args(ctx), callerOf(ctx), ctx.subject.caller);
3081
- if ("error" in persona)
3082
- throw new EpEnvelopeError(persona.code ?? (persona.error.startsWith("no persona") ? "not-found" : "failed-precondition"), persona.error);
3083
- return { agent: persona.agent };
3084
- }),
3085
- // `spawn` is an ACTION - accept a goal + reply the acceptance floor payload, drive
3086
- // progress + terminal off-handler (no ~30s block). The blocking reply path is gone.
3087
- // #373: arming the event plane (events: true, or the omission that arms it by default)
3088
- // follows owner-domain reach on a user mesh. Resolve the caller's admin tier once for
3089
- // the residual cross-owner case; opStart decides before connector resolution or grant
3090
- // mutation. Static meshes resolve true and nothing changes.
3091
- spawn: (ctx) => this.loggedSpawnRefusal(ctx, () => this.serveGated(ctx, async () => this.serveSpawnGoal(ctx, async (h) => this.opStart(args(ctx), callerOf(ctx), await this.epAdminReach(ctx.subject.caller), h, ctx.subject.route, ctx.subject.caller, servedRequestSubject(this.space, ctx))))),
3092
- despawn: (ctx) => this.serveGated(ctx, async () => {
3093
- const a = targetAgent(ctx);
3094
- const denied = await this.authorizeNamed(a, callerOf(ctx), await this.epAnyModeAdmin(ctx), ctx.subject.caller);
3095
- if (denied)
3096
- throw new EpEnvelopeError("permission-denied", denied, undefined, "not-executed");
3097
- return unwrap(await this.despawnAuthorized(a, args(ctx).graceful !== false, true, callerOf(ctx)));
3098
- }),
3099
- attach: (ctx) => this.serveGated(ctx, async () => {
3100
- const a = targetAgent(ctx);
3101
- const denied = await this.authorizeNamed(a, callerOf(ctx), await this.epAnyModeAdmin(ctx), ctx.subject.caller);
3102
- if (denied)
3103
- throw new EpEnvelopeError("permission-denied", denied, undefined, "not-executed");
3104
- return unwrap(await this.attachAuthorized(a, ctx.subject.caller));
3105
- }),
3106
- // C3 `input`: the SAME authorization as `attach`, deliberately written out rather than
3107
- // factored with it - the two share a policy, not a body, and a shared wrapper would be a
3108
- // place for one of them to quietly acquire a condition the other does not have.
3109
- input: (ctx) => this.serveGated(ctx, async () => {
3110
- const a = targetAgent(ctx);
3111
- const denied = await this.authorizeNamed(a, callerOf(ctx), await this.epAnyModeAdmin(ctx), ctx.subject.caller);
3112
- if (denied)
3113
- throw new EpEnvelopeError("permission-denied", denied, undefined, "not-executed");
3114
- return this.inputAuthorized(a, args(ctx));
3115
- }),
3116
- // The turn relay (§8 durable actions): `turn` shares despawn/input's reach policy — the
3117
- // caller must hold owner-equality or admin over the TARGET seat — written out for the same
3118
- // reason `input` is (a shared policy, not a shared body).
3119
- turn: (ctx) => this.serveGated(ctx, async () => {
3120
- const target = this.turnTarget(ctx);
3121
- if (target.kind === "managed") {
3122
- const denied = await this.authorizeNamed(target.agent, callerOf(ctx), await this.epAnyModeAdmin(ctx), ctx.subject.caller);
3123
- if (denied)
3124
- throw new EpEnvelopeError("permission-denied", denied, undefined, "not-executed");
3125
- }
3126
- else {
3127
- const admitted = this.runHosting?.admittedCaller(ctx.subject.caller);
3128
- if (!admitted || admitted.owner !== target.participant.owner || admitted.actor !== target.participant.actor || admitted.uid !== target.participant.uid)
3129
- throw new EpEnvelopeError("permission-denied", "a personal participant may be turned only by the workflow run admitted for that exact owner, actor and lifecycle", undefined, "not-executed");
3130
- if (!this.remoteAuthority?.authorizeParticipation)
3131
- throw new EpEnvelopeError("unimplemented", "the issuing host supplies no closed personal participation authorization", undefined, "not-executed");
3132
- const authorized = await this.remoteAuthority.authorizeParticipation({
3133
- owner: target.participant.owner,
3134
- actor: target.participant.actor,
3135
- lifecycleUid: target.participant.uid,
3136
- });
3137
- if (!authorized) {
3138
- this.participants.delete(participantKey(target.participant.owner, target.participant.actor, target.participant.uid));
3139
- throw new EpEnvelopeError("permission-denied", "the exact personal lifecycle is no longer foreground-authorized with run scope", undefined, "not-executed");
3140
- }
3141
- }
3142
- return this.serveTurnGoal(ctx, target);
3143
- }),
3144
- // A personal native lifecycle must opt in explicitly. The command is self-targeted and returns
3145
- // only a finite relay lease. It never inserts a ManagedAgent or grants stop/attach/input custody.
3146
- turnParticipate: (ctx) => this.serveGated(ctx, () => this.serveTurnParticipation(ctx.subject.caller)),
3147
- // The seat's own half of the relay (`manager.self`, stop-self's tier): a seat pulls the
3148
- // turns addressed to ITS incarnation and yields them; no reach beyond itself exists here.
3149
- turnPending: (ctx) => this.serveGated(ctx, () => this.turnPendingFor(ctx.subject.caller)),
3150
- turnYield: (ctx) => this.serveGated(ctx, () => this.serveTurnYield(ctx.subject.caller, args(ctx))),
3151
- turnUnconfirmed: (ctx) => this.serveGated(ctx, () => this.serveTurnUnconfirmed(ctx.subject.caller, args(ctx))),
3152
- // The reserved goal cancel (SPEC 13.6 item 4), served for the relay: the goal ref is the
3153
- // authenticated caller's own, so a run withdraws only the turns it submitted.
3154
- cancel: (ctx) => this.serveGated(ctx, () => this.serveTurnCancel(ctx)),
3155
- stopSelf: (ctx) => this.serveGated(ctx, async () => unwrap(await this.opStopSelf(callerOf(ctx), args(ctx)))),
3156
- definePersona: (ctx) => this.serveGated(ctx, async () => unwrap(await this.opDefinePersona(args(ctx), callerOf(ctx), false, ctx.subject.caller))),
3157
- removePersona: (ctx) => this.serveGated(ctx, () => {
3158
- const r = this.opRemovePersona(args(ctx), callerOf(ctx), false);
3159
- if (!r.ok)
3160
- throw new EpEnvelopeError((r.code ?? "failed-precondition"), r.error ?? "the operation failed", r.details, "not-executed");
3161
- return r.data;
3162
- }),
3163
- // Reach is the broker's: only operator instruments carry these rows. The serve gate is the
3164
- // maintenance fence, so neither runs while a shutdown or resume holds control.
3165
- chatSessionOpen: (ctx) => this.serveGated(ctx, () => this.openStaticChatSession(args(ctx))),
3166
- chatSessionRetire: (ctx) => this.serveGated(ctx, () => this.retireStaticChatSession(args(ctx))),
3167
- listPersonas: (ctx) => this.serveGated(ctx, () => unwrap(this.opListPersonas(callerOf(ctx), false))),
3168
- showPersona: (ctx) => this.serveGated(ctx, () => {
3169
- const r = this.opShowPersona(args(ctx), callerOf(ctx), false);
3170
- if (!r.ok) {
3171
- const msg = r.error ?? "not found";
3172
- if (msg.startsWith("no persona"))
3173
- throw new EpEnvelopeError("not-found", msg);
3174
- throw new EpEnvelopeError("failed-precondition", msg);
3175
- }
3176
- return r.data;
3177
- }),
3178
- purge: (ctx) => this.serveGated(ctx, () => adminGated(ctx, async () => unwrap(await this.opPurge(args(ctx), callerOf(ctx))))),
3179
- // launch is OWNER-EQUALITY on the ep door for every caller: the deploy
3180
- // path is the only launch consumer and its spec stamps the CALLER's own owner, so
3181
- // owner-equality always holds for a legitimate deploy; cross-owner launch was a ctl
3182
- // admin-tier INCIDENTAL never exercised by a real flow (static is single-owner, so the flag
3183
- // is a no-op there). Keying admin on epAdminReach read the ACTOR's ledger scope, which does
3184
- // NOT reflect the deployer VIEW's privileged-tier attenuation - an admin user's stolen
3185
- // deployer bearer would then bypass owner-equality (operator launch) despite the view holding
3186
- // no admin rows. Uniform owner-equality removes that divergence in the least-privilege
3187
- // direction.
3188
- // Manifest `launch` is an ACTION through the SAME chokepoint as spawn -
3189
- // the manifest resolve + owner-equality authz run in opLaunch's accept path, then the goal
3190
- // drives progress + terminal. The acceptance floor is the allocated identity + goal coords.
3191
- launch: (ctx) => this.serveGated(ctx, () => this.serveSpawnGoal(ctx, (h) => this.opLaunch(args(ctx), callerOf(ctx), false, h, ctx.subject.route))),
3192
- resumePreserved: (ctx) => adminGated(ctx, async () => unwrap(await this.opResumePreserved(args(ctx)))),
3193
- commitResume: (ctx) => adminGated(ctx, async () => unwrap(await this.opCommitResume(args(ctx)))),
3194
- finalizeResume: (ctx) => adminGated(ctx, async () => unwrap(await this.opFinalizeResume(args(ctx)))),
3195
- // The workflow-run family (SPEC 14.3): the manager hosts the driver. Reach is the broker's
3196
- // (`run` capability / privileged instrument rows); the serve gate is the maintenance fence.
3197
- runStart: (ctx) => this.serveGated(ctx, () => this.runHost().start(ctx, args(ctx))),
3198
- runStartKeyed: (ctx) => this.serveGated(ctx, () => this.runHost().startKeyed(ctx, args(ctx))),
3199
- runSubmissionStatus: (ctx) => this.serveGated(ctx, () => this.runHost().submissionStatus(ctx, String(args(ctx).submissionId))),
3200
- runResume: (ctx) => this.serveGated(ctx, () => this.runHost().resume(args(ctx), ctx)),
3201
- runCancel: (ctx) => {
3202
- const host = this.runHost();
3203
- host.validateCancellation(ctx, args(ctx));
3204
- return this.serveGated(ctx, () => host.cancel(ctx, args(ctx)));
3205
- },
3206
- runAnswer: (ctx) => this.serveGated(ctx, () => {
3207
- const input = args(ctx);
3208
- if (input.amend === true)
3209
- return this.runHost().amend(input, this.runAnswerer(ctx), (accepted) => this.authorizeRunAmend(ctx, accepted), ctx);
3210
- return this.runHost().answer(input, this.runAnswerer(ctx), (open) => this.authorizeRunAnswer(ctx, input, open), ctx);
3211
- }),
3212
- runStatus: (ctx) => this.serveGated(ctx, () => this.runHost().status(args(ctx), ctx)),
3213
- runPs: (ctx) => this.serveGated(ctx, () => this.runHost().list(args(ctx), ctx)),
3214
- preparePreservation: (ctx) => adminGated(ctx, async () => unwrap(await this.opPreservationCtl("preparePreservation", args(ctx)))),
3215
- commitPreservation: (ctx) => adminGated(ctx, async () => unwrap(await this.opPreservationCtl("commitPreservation", args(ctx)))),
3216
- abortPreservation: (ctx) => adminGated(ctx, async () => unwrap(await this.opPreservationCtl("abortPreservation", args(ctx)))),
3217
- transcriptReceive: (ctx) => this.serveGated(ctx, () => adminGated(ctx, () => {
3218
- if (this.execution === "none")
3219
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
3220
- if (!this.transcripts)
3221
- throw new EpEnvelopeError("failed-precondition", "transcript-receive: this manager does not receive carried transcripts (its remote authority issues no transfer reader)");
3222
- return this.transcripts.receive(args(ctx));
3223
- })),
3224
- });
3225
- }
2487
+ /** {@link CommandDispatch.managerServiceDefs}. */
2488
+ managerServiceDefs(...args) { return this.commandDispatch.managerServiceDefs(...args); }
3226
2489
  async commitResumeActivation(attemptId) {
3227
2490
  if (!this.resumeAwaitingCommit || !this.resumeResult?.ok)
3228
2491
  return { ok: false, error: `resume attempt ${attemptId} has no successful activation to commit` };
@@ -3343,25 +2606,8 @@ export class Manager {
3343
2606
  }
3344
2607
  return inactive;
3345
2608
  }
3346
- /** Self-despawn (P2b): stop the managed agent whose id == the authenticated caller. The
3347
- * no-name self-op can only ever resolve to the caller's OWN managed entry (ids are unique
3348
- * per spawn + non-forgeable in auth mode), never a peer — so it's structurally incapable of
3349
- * hitting another agent. Non-managed callers (human CLI, the manager itself, observers) find
3350
- * no match and get a loud error, not a silent no-op. */
3351
- opStopSelf(callerId, args) {
3352
- if (this.execution === "none")
3353
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
3354
- const target = [...this.agents.values()].find((a) => this.managedPrincipal(a) === callerId);
3355
- if (!target)
3356
- return { ok: false, error: `self-stop: caller ${callerId} is not a managed agent` };
3357
- const graceful = args.graceful !== false;
3358
- if (process.platform === "win32" && target.handle.kind === "pty") {
3359
- return this.stopWindowsSeat(target, graceful, true, { kind: "stopped-self" }).then(() => ({ ok: true, data: { name: target.name, stopped: true, graceful } }));
3360
- }
3361
- this.stopHandle(target, graceful, { kind: "stopped-self" });
3362
- this.trackStoppedHandle(target, true, { kind: "stopped-self" });
3363
- return { ok: true, data: { name: target.name, stopped: true, graceful } };
3364
- }
2609
+ /** {@link CommandDispatch.opStopSelf}. */
2610
+ opStopSelf(...args) { return this.commandDispatch.opStopSelf(...args); }
3365
2611
  // Plane-3 durable join/leave/list ops moved OFF the manager onto the server-side delivery daemon's
3366
2612
  // `ctl.delivery` control service (endpoint.startPlane3 → handleDeliveryControl). The manager is
3367
2613
  // lifecycle-only; it records each agent's read ACL at spawn (commitAcl) so the daemon can validate
@@ -3491,163 +2737,17 @@ export class Manager {
3491
2737
  async waitForPresence(name, timeoutMs = 30_000) {
3492
2738
  return this.seatLaunch.waitForPresence(name, timeoutMs);
3493
2739
  }
3494
- /** Parse a served `spawn` request into {@link StartAgentOpts}. The compiled spawn input contract
3495
- * is the shape check: it already refused a non-mapping `launchOptions`, a `supervise` that is not
3496
- * the closed `{ restarts, windowMs }` pair, and a list on `subscribe`, `allowSubscribe`,
3497
- * `allowPublish`, `shareTools`, `join` or `callerAcl` that is not an array of strings. This reads
3498
- * those fields as admitted, the way it reads the string fields. The connector still validates the
3499
- * launch-option keys, and `startAgent` still refuses a supervise budget the seat record would not
3500
- * take. `once` is shape-checked by that same contract. Its omitted `deadlineMs` takes the default
3501
- * here, and a deadline past the scheduler's last instant is refused here, which the schema does
3502
- * not express. */
3503
- opStart(args, caller, admin, hooks, route = "inst", authenticatedCaller, served) {
3504
- const supervise = args.supervise;
3505
- let once;
3506
- if (args.once !== undefined) {
3507
- const rec = args.once;
3508
- // The default is applied here, so every caller of the wire gets the same one.
3509
- const d = rec.deadlineMs ?? ONCE_DEFAULT_DEADLINE_MS;
3510
- if (d !== -1 && (typeof d !== "number" || !Number.isSafeInteger(d) || d < 1 || Date.now() + d > MAX_SCHEDULE_MS))
3511
- return Promise.resolve({ ok: false, error: "once.deadlineMs: expected -1 (no deadline) or a positive whole number of milliseconds that ends by the deadline scheduler's last instant (the end of year 9999)" });
3512
- once = { deadlineMs: d === -1 ? undefined : d };
3513
- }
3514
- const callerAcl = args.callerAcl;
3515
- // #373: the event-plane admission gate. `startAgent` resolves `eventsRequired || opts.events
3516
- // !== false`, so omission ARMS the plane — a gate on the explicit bit alone is bypassed by
3517
- // omitting it. The gate is on the DECISION, and it runs before connector resolution and
3518
- // before `startAgent` (which mints credentials), so a refusal provisions nothing.
3519
- if (args.eventPayloads !== undefined && typeof args.eventPayloads !== "boolean")
3520
- return Promise.resolve({ ok: false, error: "eventPayloads must be a boolean" });
3521
- const requestedEvents = typeof args.events === "boolean" ? args.events : undefined;
3522
- let eventsNotice;
3523
- let events = requestedEvents;
3524
- // Imperative spawns have no payload-selected owner. Local provisioning derives it from
3525
- // the authenticated u_-owner caller; hosted enrollment fixes it to the manager's owner.
3526
- // Match the same owner-domain boundary as authorizeNamed, without treating the spawn's
3527
- // spawner relation as authority over a different owner's session.
3528
- const callerOwner = parsePrincipalKey(caller)?.owner;
3529
- const childOwner = this.remoteAuthority?.owner ?? (callerOwner?.startsWith("u_") ? callerOwner : undefined);
3530
- const ownsChild = this.userMode && callerOwner !== undefined && callerOwner === childOwner;
3531
- if (!admin && !ownsChild) {
3532
- if (requestedEvents === true)
3533
- return Promise.resolve({
3534
- ok: false,
3535
- error: `spawn is operator reach; the caller's current ledger grant does not carry "admin" (SPEC 13.2): events: arming the event plane needs the admin tier`,
3536
- });
3537
- if (this.eventsRequired)
3538
- return Promise.resolve({
3539
- ok: false,
3540
- error: `spawn is operator reach; the caller's current ledger grant does not carry "admin" (SPEC 13.2): space "${this.space}" requires the event plane by registration policy, which cannot be met without the admin tier`,
3541
- });
3542
- // Omission arms by default in startAgent; serve it DISARMED and say so (never a silent
3543
- // downgrade). An explicit `false` is already the opt-out — served as-is, no notice.
3544
- if (requestedEvents === undefined) {
3545
- events = false;
3546
- eventsNotice = `event plane not armed: arming it on spawn needs the admin tier; the spawn was served with events: false`;
3547
- }
3548
- }
3549
- return this.startAgent({
3550
- name: String(args.name ?? "").trim(),
3551
- agent: args.agent,
3552
- defaultAgent: args.defaultAgent,
3553
- role: args.role,
3554
- config: args.config,
3555
- identity: args.identity,
3556
- // Passed as sent: spawnPersona validates the record, the one place every door reads it.
3557
- persona: args.persona,
3558
- ...(typeof args.runId === "string" ? { runId: args.runId } : {}),
3559
- model: args.model,
3560
- variant: args.variant,
3561
- launchOptions: args.launchOptions,
3562
- resume: args.resume,
3563
- resumeClaim: args.resumeClaim,
3564
- resumeAgent: args.resumeAgent,
3565
- events,
3566
- eventPayloads: args.eventPayloads,
3567
- eventsNotice,
3568
- cwd: args.cwd,
3569
- prompt: args.prompt,
3570
- subscribe: args.subscribe,
3571
- allowSubscribe: args.allowSubscribe,
3572
- allowPublish: args.allowPublish,
3573
- join: args.join,
3574
- callerAcl,
3575
- shareTools: args.shareTools,
3576
- ...(supervise !== undefined ? { supervise } : {}),
3577
- ...(once !== undefined ? { once } : {}),
3578
- ...(typeof args.runtime === "string" ? { runtime: args.runtime.trim() } : {}),
3579
- route,
3580
- ...(served !== undefined ? { served } : {}),
3581
- }, caller, hooks, authenticatedCaller);
3582
- }
2740
+ /** {@link StartDoors.opStart}. */
2741
+ opStart(...args) { return this.startDoorsComponent.opStart(...args); }
3583
2742
  listSpawnDirectory(args) { return this.seatLaunch.listSpawnDirectory(args); }
3584
2743
  /** {@link SeatLaunch.resolveSpawnCwd}. */
3585
2744
  resolveSpawnCwd(value) { return this.seatLaunch.resolveSpawnCwd(value); }
3586
- /** Resolve a connector by agent type. Library composition (installedExtensions off) → a registry
3587
- * hit, exactly as before (the composition root imported what it wants). The published binary gates
3588
- * on MANIFEST membership FIRST — so a live `cotal ext remove` is honored even though the registry
3589
- * still holds a connector imported earlier this session — then returns the registry hit or lazily
3590
- * imports the providing package (transactional + single-flight, via the workspace primitive).
3591
- * The captured Manager generation is checked for first-party providers under that lock,
3592
- * including providers already present in the registry.
3593
- * Fail-loud with an install hint; no fallback. */
3594
- async resolveConnector(name) {
3595
- if (!this.installedExtensions)
3596
- return registry.resolve("connector", name);
3597
- if (!manifestExtensionNames("connector").includes(name))
3598
- throw new Error(connectorInstallHint(name));
3599
- return materializeFromManifest({ kind: "connector", name }, { hint: (ref) => connectorInstallHint(ref.name), expectedGeneration: this.expectedConnectorGeneration });
3600
- }
2745
+ /** {@link HarnessResolution.resolveConnector}. */
2746
+ resolveConnector(...args) { return this.harnessResolutionComponent.resolveConnector(...args); }
3601
2747
  /** {@link SeatLaunch.connectorNames}. */
3602
2748
  connectorNames() { return this.seatLaunch.connectorNames(); }
3603
- /** Resolve every installed/registered connector's declared harness binaries before the manager
3604
- * reports ready. A missing harness degrades only that connector, never unrelated lifecycle work:
3605
- * boot continues, names it once start completes and records it on both manager status surfaces. */
3606
- async inspectConnectorsAtBoot() {
3607
- this.bootNotes = [];
3608
- if (this.execution === "none") {
3609
- this.connectorStatuses = [];
3610
- return;
3611
- }
3612
- const rows = [];
3613
- let declared;
3614
- if (this.installedExtensions) {
3615
- try {
3616
- declared = loadExtensionsManifest().extensions.flatMap((ext) => extensionConnectors(ext).map((connector) => ({ ...connector, pkg: ext.pkg })));
3617
- }
3618
- catch (error) {
3619
- const reason = rejectionText(error);
3620
- this.bootNotes.push(`! manager boot: connector inventory unavailable - ${reason}`);
3621
- this.connectorStatuses = [{ agent: "(inventory)", state: "unavailable", binaries: {}, eventPlane: false, reason }];
3622
- this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
3623
- return;
3624
- }
3625
- }
3626
- else {
3627
- declared = registry.all("connector").map((connector) => ({
3628
- name: connector.name,
3629
- requires: connector.requires ?? [],
3630
- eventPlane: connector.eventChannel !== undefined,
3631
- }));
3632
- }
3633
- this.connectorRequirements = new Map(declared.map(({ name, requires, pkg }) => [name, {
3634
- requires, needsClaudeWake: !!this.machineSetupCommand && name === "claude" && pkg === OFFICIAL_CONNECTORS.claude,
3635
- }]));
3636
- for (const { name, requires, eventPlane } of declared) {
3637
- const { binaries, reason: missing } = resolveHarness(name, requires);
3638
- const reason = missing ?? (this.connectorRequirements.get(name)?.needsClaudeWake ? await this.prepareClaudeWake() : undefined);
3639
- if (reason) {
3640
- rows.push({ agent: name, state: "unavailable", binaries, eventPlane, reason });
3641
- this.bootNotes.push(`! manager boot: connector ${name} unavailable - ${reason}`);
3642
- }
3643
- else {
3644
- rows.push({ agent: name, state: "available", binaries, eventPlane });
3645
- }
3646
- }
3647
- this.connectorStatuses = rows.sort((a, b) => a.agent.localeCompare(b.agent));
3648
- if (!this.classSpawnEnabled())
3649
- this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
3650
- }
2749
+ /** {@link ConnectorInventory.inspectConnectorsAtBoot}. */
2750
+ inspectConnectorsAtBoot(...args) { return this.connectorInventoryComponent.inspectConnectorsAtBoot(...args); }
3651
2751
  /** Install and verify the hosted Claude wake channel, or report the cause and remedy. */
3652
2752
  async prepareClaudeWake() {
3653
2753
  try {
@@ -3717,218 +2817,22 @@ export class Manager {
3717
2817
  /** {@link SeatLaunch.classSpawnEnabled}. */
3718
2818
  classSpawnEnabled() { return this.seatLaunch.classSpawnEnabled(); }
3719
2819
  omitClassCommands() { return this.seatLaunch.omitClassCommands(); }
3720
- /** The harness binaries a managed launch runs, as boot resolved them, or the refusal naming what is
3721
- * missing. Spawn, resume and the model catalog all take it, so a seat launches from the same files
3722
- * whichever path starts it and the catalog never disagrees with a launch about whether the harness
3723
- * is there. Callers recheck unavailable rows first; available rows retain their resolved files.
3724
- * A connector registered after boot has no inventory row and is checked on PATH now. */
3725
- launchHarness(connector) {
3726
- const row = this.connectorStatuses.find((status) => status.agent === connector.name);
3727
- if (row?.state === "unavailable")
3728
- return { refusal: row.reason ?? `${connector.name} harness is unavailable` };
3729
- if (row)
3730
- return { binaries: row.binaries };
3731
- const { reason } = resolveHarness(connector.name, connector.requires ?? []);
3732
- return reason ? { refusal: reason } : {};
3733
- }
3734
- /** The launch fields the host supplies rather than the seat. Spawn and resume both take them from
3735
- * here, so a resumed seat launches under the same host policy, `eventsRequired` included, as the
3736
- * same seat spawned fresh. The caller passes the cotal config it judged the launch by, so the
3737
- * servers and env allowlist come from the contents its checks read. */
3738
- hostLaunchFields(cotalConfig, agent, shareTools, harness) {
3739
- return {
3740
- space: this.space,
3741
- servers: this.servers,
3742
- // Declared overrides plus the connector's native default, unless this spawn explicitly
3743
- // restricts sharing. An empty selection is deliberate isolation, not the default.
3744
- mcpServers: connectorServers(cotalConfig, agent, shareTools),
3745
- mcpServersExclusive: shareTools !== undefined,
3746
- // The operator's spawn-env policy travels the same route: absent means no extras (the OS
3747
- // allow-list + operator knobs + connector-declared inputs), present means those names too.
3748
- // A connector never reads the config itself.
3749
- envAllow: spawnEnvAllow(cotalConfig),
3750
- resolvedBinaries: harness.binaries,
3751
- eventsRequired: this.eventsRequired,
3752
- ...(this.eventPayloadsWithheld ? { eventPayloads: false } : {}),
3753
- // So a connector that keeps per-agent local state can root it at the workspace, not the
3754
- // (possibly per-agent) launch cwd.
3755
- workspaceRoot: this.workspaceRoot,
3756
- };
3757
- }
3758
- /** The refusal for a launch choice the connector cannot honour. Spawn and resume both ask before
3759
- * a seat's launch is built, so a rule changed here holds on both paths. */
3760
- capabilityRefusal(connector, launch) {
3761
- if (launch.variant && !connector.supportsModelVariant)
3762
- return `${connector.name} connector does not support model variants (variant)`;
3763
- if (launch.prompt !== undefined && !connector.supportsPrompt)
3764
- return `${connector.name} connector does not support an initial prompt (prompt)`;
3765
- if (launch.exact && (!connector.supportsSessionReopen || !connector.supportsSessionContinuation))
3766
- return `${connector.name} connector does not support exact session continuity (continuity: exact)`;
3767
- return undefined;
3768
- }
2820
+ /** {@link HarnessResolution.launchHarness}. */
2821
+ launchHarness(...args) { return this.harnessResolutionComponent.launchHarness(...args); }
2822
+ /** {@link HarnessResolution.hostLaunchFields}. */
2823
+ hostLaunchFields(...args) { return this.harnessResolutionComponent.hostLaunchFields(...args); }
2824
+ /** {@link HarnessResolution.capabilityRefusal}. */
2825
+ capabilityRefusal(...args) { return this.harnessResolutionComponent.capabilityRefusal(...args); }
3769
2826
  /** {@link SeatLaunch.onceRefusal}. */
3770
2827
  onceRefusal(connector, runtime, launch, spawner, hooks) { return this.seatLaunch.onceRefusal(connector, runtime, launch, spawner, hooks); }
3771
- /** The refusal for an event-plane choice the registration policy or the connector cannot meet.
3772
- * Spawn and resume both ask before a seat's launch is built, so a seat retained without the
3773
- * plane cannot come back on a space that now requires it. An absent choice arms supported planes. */
3774
- eventsRefusal(connector, events) {
3775
- if (this.eventsRequired && events === false)
3776
- return `space "${this.space}" requires the event plane by registration policy; --no-events (events: false on the start op) is not allowed`;
3777
- if ((this.eventsRequired || events === true) && !connector.eventChannel)
3778
- return this.eventsRequired
3779
- ? `space "${this.space}" requires the event plane by registration policy, but connector "${connector.name}" does not publish one`
3780
- : `connector "${connector.name}" does not publish an AG-UI event plane; omit --events to launch it without one`;
3781
- return undefined;
3782
- }
3783
- /** Return connector-provided model catalogs for selector UIs. Optional by connector: a host with no
3784
- * local model-list API reports `supported:false` rather than blocking the manager. A connector that
3785
- * fails to import shows an `error:` row (from manifest enumeration) and never blocks the others. */
3786
- async opModels(args) {
3787
- if (this.execution === "none")
3788
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
3789
- const requested = String(args.agent ?? "").trim();
3790
- const refresh = args.refresh === true;
3791
- const one = async (connector) => {
3792
- await this.refreshUnavailableConnectors(connector.name, true);
3793
- const harness = this.launchHarness(connector);
3794
- if (!connector.listModels)
3795
- return { agent: connector.name, supported: false, models: [] };
3796
- if ("refusal" in harness)
3797
- return { agent: connector.name, supported: true, models: [], error: harness.refusal };
3798
- try {
3799
- const catalog = await connector.listModels({ refresh, resolvedBinaries: harness.binaries });
3800
- return { agent: connector.name, supported: catalog.unavailable === undefined, ...catalog };
3801
- }
3802
- catch (e) {
3803
- return { agent: connector.name, supported: true, models: [], error: rejectionText(e) };
3804
- }
3805
- };
3806
- if (requested) {
3807
- let connector;
3808
- try {
3809
- connector = await this.resolveConnector(requested);
3810
- }
3811
- catch (e) {
3812
- return { ok: false, error: rejectionText(e) };
3813
- }
3814
- const result = await one(connector);
3815
- return result.error ? { ok: false, error: result.error } : { ok: true, data: result };
3816
- }
3817
- // Enumerate from the manifest (published binary) so a connector that fails to import still gets
3818
- // a row — `registry.all` can't list one that never registered. Each resolves lazily; an import
3819
- // failure becomes an `error:` catalog row and never blocks the healthy ones.
3820
- const catalogs = await Promise.all(this.connectorNames().map(async (name) => {
3821
- let connector;
3822
- try {
3823
- connector = await this.resolveConnector(name);
3824
- }
3825
- catch (e) {
3826
- return { agent: name, supported: false, models: [], error: rejectionText(e) };
3827
- }
3828
- return one(connector);
3829
- }));
3830
- return { ok: true, data: catalogs };
3831
- }
3832
- /** The owner-domain bound on `ps`/`status` metadata: on a USER mesh, a privileged-tier caller
3833
- * sees only agents under its OWN subject-pinned owner. Two ways to see ALL owners: the admin
3834
- * TIER (operator), or a fresh ledger `admin` SCOPE on the caller's row — the SAME authority that
3835
- * lets `stop`/`attach` reach cross-owner agents ({@link authorizeNamedControl}). Without this the
3836
- * two surfaces disagree: an admin operator could cross-owner stop an agent it could not list.
3837
- * Read fresh so a revoked admin loses visibility on its next call; a read failure and an
3838
- * unparseable caller both fall closed (own-owner / matches-nothing). Static meshes are unbounded. */
3839
- async psOwnerFilter(caller, admin) {
3840
- if (!this.userMode || admin)
3841
- return undefined;
3842
- if (this.remoteAuthority)
3843
- return (await this.epAdminReach(caller)) ? undefined : caller.owner;
3844
- try {
3845
- const scope = await resolveAuthProvider().actorScope({
3846
- dir: userAuthStateDir(this.workspaceRoot, this.space),
3847
- owner: caller.owner,
3848
- actor: caller.actor,
3849
- });
3850
- if (scope?.includes("admin"))
3851
- return undefined;
3852
- }
3853
- catch {
3854
- /* unreadable ledger authorizes nothing extra: fall through to the own-owner bound */
3855
- }
3856
- return caller.owner;
3857
- }
3858
- /** Boot one resolved agent from a mesh-manifest launch spec, for `cotal spawn -f` onto a RUNNING
3859
- * manager. The request carries `{ runId, name }` — plus, for a deploy from another checkout or
3860
- * host, the resolved `spec` itself inline (validated as untrusted input and persisted under THIS
3861
- * manager's `.cotal/run/` first) — NEVER a path: the manager derives + validates
3862
- * `.cotal/run/<runId>.json` itself ({@link launchSpecForRun} — token-safe id, no-follow,
3863
- * `loadLaunchSpec`'s untrusted-input + `validateLaunchPolicy` contract), materializes the named
3864
- * agent's transient persona, and spawns via the same `startAgent({ resolved })` path as
3865
- * `supervise --launch`. The reply is enriched for the ownership ledger: the SPAWNED
3866
- * (collision-numbered) name + nkey id creds are filed under, plus the manifest `requested` name,
3867
- * `runId`, and resolved `hash`. USER mesh: a privileged-tier launch is owner-equality-authorized
3868
- * (spec owner === caller owner) before any side effect; the admin tier keeps operator behavior. */
3869
- async opLaunch(args, caller, admin, hooks, route = "inst") {
3870
- if (this.execution === "none")
3871
- return { ok: false, error: this.executionRefusal() };
3872
- const runId = String(args.runId ?? "").trim();
3873
- const name = String(args.name ?? "").trim();
3874
- if (!runId || !name)
3875
- return { ok: false, error: "launch requires runId + name" };
3876
- let spec;
3877
- if (args.spec !== undefined) {
3878
- // REMOTE deploy: the caller pushes the resolved spec inline over the control plane instead of
3879
- // sharing this checkout's disk. Same untrusted-input contract as the file path (strict schema,
3880
- // safe names, policy re-validation), then persisted under OUR `.cotal/run/<runId>.json` so
3881
- // stale-restart and retained resume read the same on-disk source either way. Still never a
3882
- // path: the payload is the spec itself, and where it lands is derived here.
3883
- try {
3884
- spec = parseLaunchSpec(args.spec, `inline launch spec (run ${runId})`);
3885
- if (spec.runId !== runId)
3886
- return { ok: false, error: `inline launch spec runId "${spec.runId}" does not match requested "${runId}"` };
3887
- hooks?.onEffect?.();
3888
- persistLaunchSpec(this.workspaceRoot, spec);
3889
- }
3890
- catch (e) {
3891
- return { ok: false, error: rejectionText(e) };
3892
- }
3893
- }
3894
- else {
3895
- try {
3896
- spec = launchSpecForRun(this.workspaceRoot, runId);
3897
- }
3898
- catch (e) {
3899
- return { ok: false, error: rejectionText(e) };
3900
- }
3901
- }
3902
- const la = spec.agents.find((a) => a.name === name);
3903
- if (!la)
3904
- return { ok: false, error: `no agent "${name}" in launch spec for run ${runId}` };
3905
- // USER mesh: a manifest launch runs under the spec's apply-time owner, never the ctl caller —
3906
- // fail loud on a spec without one rather than guess (core `MeshLaunchSpec.owner`).
3907
- if (this.userMode && !spec.owner)
3908
- return { ok: false, error: `user-auth space "${this.space}": launch spec for run ${runId} carries no owner - re-apply the manifest as a logged-in operator` };
3909
- if (this.userMode) {
3910
- // Privileged-tier user-mode launch: owner-equality (spec owner === caller owner), decided by
3911
- // the pure policy BEFORE materializePersona or any other side effect, so a denied
3912
- // cross-owner launch writes nothing. Admin tier passes through it unchanged.
3913
- const denied = authorizeLaunch({ specOwner: spec.owner, caller, admin, runId });
3914
- if (denied)
3915
- return { ok: false, error: denied };
3916
- }
3917
- let configPath;
3918
- try {
3919
- hooks?.onEffect?.();
3920
- configPath = materializePersona(this.workspaceRoot, runId, la);
3921
- }
3922
- catch (e) {
3923
- return { ok: false, error: rejectionText(e) };
3924
- }
3925
- const reply = await this.startAgent({ ...launchAgentToStartOpts(la, configPath, spec.owner, runId), route }, caller, hooks);
3926
- if (reply.ok)
3927
- // `data.name` stays the spawned (numbered) identity — what creds are filed under and the ledger
3928
- // keys on; `requested`/`runId`/`hash` give the CLI the manifest name + drift hash for the ledger.
3929
- reply.data = { ...reply.data, requested: la.name, runId, hash: la.hash, newlyStarted: true };
3930
- return reply;
3931
- }
2828
+ /** {@link HarnessResolution.eventsRefusal}. */
2829
+ eventsRefusal(...args) { return this.harnessResolutionComponent.eventsRefusal(...args); }
2830
+ /** {@link StatusAndModels.opModels}. */
2831
+ opModels(...args) { return this.statusAndModelsComponent.opModels(...args); }
2832
+ /** {@link StatusAndModels.psOwnerFilter}. */
2833
+ psOwnerFilter(...args) { return this.statusAndModelsComponent.psOwnerFilter(...args); }
2834
+ /** {@link StartDoors.opLaunch}. */
2835
+ opLaunch(...args) { return this.startDoorsComponent.opLaunch(...args); }
3932
2836
  /** Spawn and supervise one agent. The single spawn path: both the control-plane
3933
2837
  * `start` op and declarative roster boot call this. Mints scoped creds in auth mode,
3934
2838
  * resolves the agent file, launches via the connector + runtime, and records the handle.
@@ -4690,223 +3594,12 @@ export class Manager {
4690
3594
  }
4691
3595
  onPresence();
4692
3596
  }
4693
- /** #159 B1: wait for a detached launch to reach a REAL outcome before replying — never a liveness-
4694
- * inferring timer. Races three:
4695
- * • the assigned id joins presence (live) → **started** — the honest signal (the manager owns mesh
4696
- * lifecycle, not app health, so `ok:true` means "it joined the mesh", not "fully healthy");
4697
- * • the child process exits → **failed** — surface its last output and reap the slot;
4698
- * • neither within {@link readinessTimeoutMs} → **uncertain** — a non-success diagnostic that does NOT
4699
- * deprovision (it may still be booting; the caller keeps {@link watchExit} wired so a later death is
4700
- * still reaped).
4701
- * Presence is keyed on the EXACT freshly-minted id, never the name — a fresh id has no prior record, so
4702
- * any live presence for it is from THIS launch (stale/same-name records can't false-start it). The
4703
- * `"presence"` event is only a wake; the roster is re-read as the source of truth (subscribe-then-check
4704
- * catches a join/exit that landed before we subscribed). A runtime whose `attach()` throws (an external
4705
- * surface) streams no output or exit, so its exit leg polls the runtime's exit proof ({@link pollProvedExit}),
4706
- * reads it once more when the window closes, and its failure carries no last output; one that cannot prove an
4707
- * exit either races presence-vs-backstop only.
4708
- * A launch that waits for the operator at `opts.operator`, a screen its connector names, is ready once a
4709
- * process this runtime owns has run for {@link OPERATOR_READINESS_MS} without exiting. An uncertain verdict
4710
- * says whether a process this runtime owns is still running. */
4711
- async awaitReadiness(a, readinessTimeoutMs, opts = {}) {
4712
- let session;
4713
- try {
4714
- session = a.handle.attach();
4715
- }
4716
- catch {
4717
- /* external surfaces stream no output or exit; their exit is polled below */
4718
- }
4719
- const s = session;
4720
- // Presence cards carry the wire PRINCIPAL dot-form (`<owner>.<actor>`), never a raw nkey — match
4721
- // through managedPrincipal or a static launch can never be seen joining (every static spawn would
4722
- // resolve "uncertain"; caught by the lifecycle e2e).
4723
- const wanted = this.managedPrincipal(a);
4724
- // READINESS LIFECYCLE FENCE (SPEC 13.1): match the exact principal AND the exact lifecycle uid
4725
- // the manager minted for THIS spawn (presence carries it, §6). The endpoint's own
4726
- // register-only broker proof is gated on the CLIENT-authored `card.kind`, which a managed child
4727
- // holding a valid agent credential could set to "endpoint" to skip - so it is defense-in-depth,
4728
- // NOT the authority boundary. This equality is: the manager (not the child) owns the expected
4729
- // uid, so a ghost that advertises a wrong/absent uid never reports STARTED, whatever kind it
4730
- // claims. The manager threads the uid into EVERY mode's launch (open included), so the child
4731
- // adopts it over a self-mint and publishes it in presence; the uid is absent only from a peer
4732
- // the manager never launched (a pure operator/daemon connection that never registers).
4733
- // A supervised restart keeps the same principal+uid, so a SIGKILL'd child's still-live
4734
- // presence row would otherwise satisfy this equality. `joinedAfter` is one millisecond
4735
- // past that row's last heartbeat: only a later heartbeat counts as THIS replacement joining.
4736
- const joined = () => this.ep.getRoster().some((p) => p.card.id === wanted
4737
- && p.status !== "offline"
4738
- && p.lifecycleUid === a.lifecycleUid
4739
- && (opts.joinedAfter === undefined || p.ts >= opts.joinedAfter));
4740
- return await new Promise((resolve) => {
4741
- let done = false;
4742
- let timer;
4743
- let unsubExit = () => { };
4744
- let joinedPoll;
4745
- let operatorTimer;
4746
- const finish = (r) => {
4747
- if (done)
4748
- return;
4749
- done = true;
4750
- if (!r.ok && r.uncertain) {
4751
- a.joinIssue = r.detail;
4752
- console.error(`seat join degraded: ${r.detail}`);
4753
- }
4754
- else if (r.ok) {
4755
- a.joinIssue = undefined;
4756
- }
4757
- clearTimeout(timer);
4758
- clearTimeout(operatorTimer);
4759
- if (joinedPoll !== undefined)
4760
- clearInterval(joinedPoll);
4761
- this.ep.off("presence", onPresence);
4762
- this.shutdownReadiness.signal.removeEventListener("abort", onShutdown);
4763
- unsubExit();
4764
- resolve(r);
4765
- };
4766
- const onPresence = () => {
4767
- if (joined())
4768
- finish({ ok: true });
4769
- };
4770
- // Shutdown owns the seat's stop and retirement after the lifecycle ticket drains. Do not
4771
- // keep that ticket waiting on a connector's readiness window while shutdown waits on it.
4772
- const onShutdown = () => finish({ ok: false, deliberate: true, detail: `${a.name} was stopped before it reported ready` });
4773
- if (opts.joinedAfter !== undefined) {
4774
- // Heartbeats bump roster.ts without emitting "presence" (same status/uid/activity).
4775
- // A supervised restart needs that bump, so poll joined() rather than waiting on the event.
4776
- joinedPoll = setInterval(onPresence, 50);
4777
- }
4778
- // Process exit → failed. Clear the backstop FIRST (synchronously) so it can't resolve UNCERTAIN while
4779
- // the backlog reads async — the process is known dead, that's a failure, not an unknown. Reap through
4780
- // onAgentExit so a child the launcher spawned in the window is reaped too.
4781
- const onExit = () => {
4782
- if (done)
4783
- return;
4784
- clearTimeout(timer);
4785
- clearTimeout(operatorTimer);
4786
- // `stopHandle` sets `terminalizing` synchronously before it kills, and `onAgentExit` sets it
4787
- // through `freeSlot` when it retires the seat, so only a read before the await and the reap
4788
- // tells a deliberate stop from a launch failure.
4789
- const deliberate = a.terminalizing === true;
4790
- void (async () => {
4791
- // A closed stream or a reader failure must not prevent settlement, or read as empty output.
4792
- let tail = "";
4793
- try {
4794
- if (s)
4795
- tail = await this.tail(s);
4796
- }
4797
- catch (error) {
4798
- console.error(`! ${a.name}: last output unavailable: ${rejectionText(error)}`);
4799
- }
4800
- if (opts.reapOnExit !== false)
4801
- this.onAgentExit(a);
4802
- // The despawn path owns this goal's terminal (`cancel`), and this promise still settles
4803
- // as the `deliberate` variant so the caller commits none: the readiness timer is already
4804
- // cleared, and the spawn's lifecycle ticket is released only on settle.
4805
- if (deliberate) {
4806
- finish({ ok: false, deliberate: true, detail: `${a.name} was stopped before it reported ready` });
4807
- return;
4808
- }
4809
- // The screen's last row can be a dialog footer, so the exit's diagnostic is named beside it:
4810
- // it carries the runtime's own reason when it stopped the seat. A connector that ends on its
4811
- // diagnostic already shows it as the last row, and it is not repeated.
4812
- let exitDetail = "";
4813
- try {
4814
- const diagnostic = a.handle.exitInfo?.()?.diagnostic;
4815
- if (diagnostic && diagnostic !== tail)
4816
- exitDetail = `; diagnostic: ${diagnostic}`;
4817
- }
4818
- catch (e) {
4819
- // The backstop is already cleared, so a reader that throws must still let this settle.
4820
- exitDetail = `; exit detail unreadable from runtime "${a.handle.kind}": ${rejectionText(e)}`;
4821
- }
4822
- // A runtime's text can carry a lone surrogate, which is not I-JSON, and the failed terminal
4823
- // this detail becomes is refused with it.
4824
- exitDetail = exitDetail.replace(/\p{Cs}/gu, "\uFFFD");
4825
- finish({ ok: false, detail: `${a.name} exited on launch${tail ? ` - last output: ${tail}` : ""}${exitDetail}` });
4826
- })();
4827
- };
4828
- // A process this runtime owns reports its own exit, so one still running here is running.
4829
- const uncertain = () => {
4830
- const running = s !== undefined && a.handle.status() === "running";
4831
- finish({
4832
- ok: false,
4833
- uncertain: true,
4834
- running,
4835
- detail: running
4836
- ? `${a.name} (${a.id}): launch status uncertain - its process is running but did not join the mesh within ${readinessTimeoutMs}ms; it may still be starting or waiting at a prompt. Inspect with \`cotal attach ${a.name}\` / \`cotal ps\`; do not stop it solely because this bounded wait elapsed.`
4837
- : `${a.name} (${a.id}): launch status uncertain - no process exit and no mesh presence within ${readinessTimeoutMs}ms; it may still be booting or stuck before connector startup. Inspect with \`cotal attach ${a.name}\` / \`cotal ps\`; do not stop it solely because this bounded wait elapsed.`,
4838
- });
4839
- };
4840
- if (opts.operator !== undefined && s)
4841
- operatorTimer = setTimeout(() => { if (a.handle.status() === "running")
4842
- finish({ ok: true, operator: opts.operator }); }, OPERATOR_READINESS_MS);
4843
- // The exit poll read the runtime up to a poll ago, and a window can be shorter than a poll, so
4844
- // the window closes on a fresh read: a child that exited by then is reported as exited. Nothing
4845
- // bounds how long a runtime's proof takes, so it gets one more poll before the launch is uncertain.
4846
- timer = setTimeout(() => {
4847
- const proof = s ? undefined : exitProof(a.handle);
4848
- if (!proof) {
4849
- uncertain();
4850
- return;
4851
- }
4852
- timer = setTimeout(uncertain, READINESS_EXIT_POLL_MS);
4853
- proof.then(onExit, uncertain);
4854
- }, readinessTimeoutMs);
4855
- // The poll stops once the race is done, so it needs no unsubscribe.
4856
- if (s)
4857
- unsubExit = s.onExit(onExit);
4858
- else
4859
- pollProvedExit(a.handle, onExit, () => !done, READINESS_EXIT_POLL_MS);
4860
- this.ep.on("presence", onPresence);
4861
- this.shutdownReadiness.signal.addEventListener("abort", onShutdown, { once: true });
4862
- // Subscribe-then-check (TOCTOU): a join or an exit that already landed before we subscribed.
4863
- if (this.shutdownReadiness.signal.aborted)
4864
- onShutdown();
4865
- else if (s && a.handle.status() === "exited")
4866
- onExit();
4867
- else
4868
- onPresence();
4869
- });
4870
- }
4871
- /** Last non-empty line of the session's rendered backlog as a single trimmed snippet (≤160 chars)
4872
- * — a readable one-line cause for an early-exit diagnostic. The backlog repaints cells a TUI
4873
- * skipped with cursor moves, so it is rendered and the line is read off the terminal; stripping
4874
- * its escapes would glue the words those moves separate. */
4875
- async tail(session) {
4876
- const backlog = await session.backlog();
4877
- // Sized after the snapshot: a custodial seat's snapshot carries the geometry it was taken at.
4878
- // The headless build exposes `buffer` only as proposed API.
4879
- const term = new Headless.Terminal({ cols: session.cols, rows: session.rows, allowProposedApi: true });
4880
- await new Promise((done) => term.write(backlog, done));
4881
- const screen = term.buffer.active;
4882
- let text = "";
4883
- for (let y = screen.length - 1; y >= 0; y--) {
4884
- const row = screen.getLine(y);
4885
- // A line wider than the screen continues across wrapped rows, so it is read whole.
4886
- text = row.translateToString(text === "") + text;
4887
- if (row.isWrapped)
4888
- continue;
4889
- // Blanks a program painted survive the right trim, so a line of only blanks is skipped.
4890
- if (text.trim())
4891
- break;
4892
- text = "";
4893
- }
4894
- term.dispose();
4895
- text = text.trim();
4896
- // Cut on code points: half a surrogate pair is not I-JSON, and a launch terminal carrying it is refused.
4897
- const chars = [...text];
4898
- return chars.length > 160 ? `…${chars.slice(-160).join("")}` : text;
4899
- }
4900
- /** Subscribe to a managed agent's process-exit so a self-driven exit frees its slot and reaps
4901
- * its children (P4b/P4c). The watch is bound to the current handle: a restart swaps in a new one
4902
- * and watches it, so a late exit proved for the old handle must not retire the row. */
4903
- watchExit(a) {
4904
- const handle = a.handle;
4905
- const current = () => this.agents.get(a.name) === a && a.handle === handle;
4906
- const watched = watchProvedExit(handle, () => this.onAgentExit(a), current);
4907
- if (!watched)
4908
- console.error(`! ${a.name}: runtime "${handle.kind}" cannot prove a child exit (AgentHandle.waitForExit is not implemented) - it stays managed after it exits, until it is stopped`);
4909
- }
3597
+ /** {@link ReadinessWait.awaitReadiness}. */
3598
+ awaitReadiness(...args) { return this.readinessWaitComponent.awaitReadiness(...args); }
3599
+ /** {@link ReadinessWait.tail}. */
3600
+ tail(...args) { return this.readinessWaitComponent.tail(...args); }
3601
+ /** {@link ReadinessWait.watchExit}. */
3602
+ watchExit(...args) { return this.readinessWaitComponent.watchExit(...args); }
4910
3603
  occupancy() { return this.namesCapacity.occupancy(); }
4911
3604
  occupancyText(o) { return this.namesCapacity.occupancyText(o); }
4912
3605
  capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
@@ -4926,191 +3619,22 @@ export class Manager {
4926
3619
  retireDelegatedAgent(name, intentId) { return this.seatStopComponent.retireDelegatedAgent(name, intentId); }
4927
3620
  /** {@link SeatStop.findManagedByTarget}. */
4928
3621
  findManagedByTarget(...args) { return this.seatStopComponent.findManagedByTarget(...args); }
4929
- /** Run one static §13.1 lifecycle OPERATION over an ephemeral, key-pinned `lifecycle-executor`
4930
- * connection: the credential's grants name exactly ONE incarnation's head/uid/gate/
4931
- * cred-family/slot keys, so the write authority exists only for this operation's window and
4932
- * can move nothing else. The transport is the direct-KV binding the shared core saga drives. */
4933
- async withLifecycleExecutor(pin, fn) {
4934
- if (!this.auth)
4935
- throw new Error("withLifecycleExecutor: no space auth (an open mesh has no lifecycle registry)");
4936
- const identity = newIdentity();
4937
- const creds = await mintCreds(this.auth, identity, "lifecycle-executor", {
4938
- lifecycleExecutor: { owner: pin.owner, actor: pin.actor, lifecycleUid: pin.lifecycleUid, alias: pin.alias },
4939
- });
4940
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
4941
- try {
4942
- const kvm = new Kvm(nc);
4943
- const recordsKv = await kvm.open(recordsBucket(this.space));
4944
- const authKv = await kvm.open(epAuthBucket(this.space));
4945
- return await fn(staticLifecycleTransport(recordsKv, authKv));
4946
- }
4947
- finally {
4948
- await drainAndClose(nc);
4949
- }
4950
- }
4951
- /** Run one SPEC 13.15 issuance operation over an ephemeral `issuer` connection: the evidence
4952
- * stage/release of one mint, or the retirement walk of one lifecycle's issuances. The store
4953
- * handle and the accepted-row KV live only for this window; the standing supervisor holds no
4954
- * grant on either bucket. */
4955
- async withIssuer(fn) {
4956
- if (!this.auth)
4957
- throw new Error("withIssuer: no space auth (an open mesh issues nothing)");
4958
- const creds = await mintCreds(this.auth, newIdentity(), "issuer");
4959
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
4960
- try {
4961
- const kvm = new Kvm(nc);
4962
- return await fn(await bindIssuedStores(kvm, await jetstreamManager(nc), this.space));
4963
- }
4964
- finally {
4965
- await drainAndClose(nc);
4966
- }
4967
- }
4968
- /** The issuance seam of ONE static credential mint (SPEC 13.15): the evidence is bound to the
4969
- * incarnation's own `cred.<uid>` ledger family, so the family's revocation (the static
4970
- * terminal) retires every issuance that named it. The finalizer is the §13.1 ledger append
4971
- * (slot credentialId + `cred.<uid>.<credId>` row); release runs it, then activates. */
4972
- issuanceSeam(i, mode, a, exp) {
4973
- return {
4974
- mode,
4975
- store: i.store,
4976
- accepted: i.accepted,
4977
- sources: mode === "issue" ? [{ space: this.space, bucket: epAuthBucket(this.space), key: `cred.${a.lifecycleUid}` }] : [],
4978
- finalize: async (credentialId) => {
4979
- await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: a.id, lifecycleUid: a.lifecycleUid, alias: a.name }, async (t) => {
4980
- await recordSlotCredential(t, DEV_OWNER, a.name, a.lifecycleUid, credentialId);
4981
- await appendStaticCredentialRow(t, { lifecycleUid: a.lifecycleUid, credentialId, holderPrincipal: principalKey(DEV_OWNER, a.id).key, exp });
4982
- });
4983
- },
4984
- };
4985
- }
4986
- /** Run one §13.1 endpoint-instance maintenance operation over an ephemeral,
4987
- * key-pinned `endpoint-serve-executor` connection: the credential's grants name exactly the
4988
- * manager instance's `epgate`/`epcred` keys plus its registration's two records keys, so the
4989
- * gate CAS, mint fence, spec/governance writes, and clean deregistration ride a one-shot scoped
4990
- * authority. The remote boot goal-index sweep instead uses the authenticated host-owned scan.
4991
- * This is NEVER the manager's standing seed/supervisor connection. */
4992
- async withEndpointServeExecutor(fn) {
4993
- const identity = this.remoteAuthority?.identities.executor ?? newIdentity();
4994
- if (this.remoteAuthority && (!this.remoteExecutorCreds || inspectCredHealth(this.remoteExecutorCreds).state !== "healthy")) {
4995
- // Shutdown has drained and discarded the standing serve context. Renew only its scoped
4996
- // maintenance executor through the existing host operation; never resurrect standing duties.
4997
- if (this.leaseStopping)
4998
- await this.renewRemoteExecutor(true);
4999
- else if (this.remoteAuthority.renewStandingBundle) {
5000
- // The renewal drains old handlers after adopting. A handler waiting here must be
5001
- // released at adoption, not after its own completion is required by that drain.
5002
- const renewal = this.renewRemoteStandingBundle(true);
5003
- void renewal.catch((error) => console.error(`! remote manager standing renewal completion: ${rejectionText(error)}`));
5004
- await this.remoteBundleAdoption;
5005
- if (!this.remoteExecutorCreds || inspectCredHealth(this.remoteExecutorCreds).state !== "healthy") {
5006
- await renewal;
5007
- throw new Error("standing renewal did not adopt a healthy scoped executor");
5008
- }
5009
- }
5010
- else
5011
- await this.renewRemoteExecutor(true);
5012
- }
5013
- const creds = this.remoteExecutorCreds ?? (this.auth
5014
- ? await mintCreds(this.auth, identity, "endpoint-serve-executor", {
5015
- endpointServeExecutor: { endpoint: MANAGER_ENDPOINT, instanceId: this.managerInstanceId },
5016
- ...(this.endpointServeExecutorExpiresInSeconds !== undefined
5017
- ? { expiresInSeconds: this.endpointServeExecutorExpiresInSeconds }
5018
- : {}),
5019
- })
5020
- : undefined);
5021
- if (!creds)
5022
- throw new Error("withEndpointServeExecutor: no scoped executor authority (an open mesh must use the bare path)");
5023
- const nc = await this.dial({ ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 });
5024
- try {
5025
- const kvm = new Kvm(nc);
5026
- return await fn({ recordsKv: await kvm.open(recordsBucket(this.space)), authKv: await kvm.open(epAuthBucket(this.space)), nc });
5027
- }
5028
- finally {
5029
- await drainAndClose(nc);
5030
- }
5031
- }
5032
- /** The open-mesh counterpart of {@link withEndpointServeExecutor}: an OPEN mesh has no
5033
- * credential system, so there is no scoped executor to mint - the same §13.1 gate/records
5034
- * writes ride a bare one-shot connection (the broker enforces nothing on an open mesh; the
5035
- * ceremony still produces the real gate, epoch, and registration the serve rails run on). */
5036
- async withOpenServeConnection(fn) {
5037
- if (this.auth || this.remoteAuthority)
5038
- throw new Error("withOpenServeConnection: an authenticated mesh must use the scoped endpoint-serve executor");
5039
- const nc = await this.dial({ maxReconnectAttempts: 0 });
5040
- try {
5041
- const kvm = new Kvm(nc);
5042
- // An open mesh may be a RAW broker (no `cotal up` provisioning ran), and `Kvm.open` binds
5043
- // lazily without checking the stream exists — create-or-verify the §13.12 authority stores
5044
- // first (the same mode-neutral treatment {@link registerManagerService} gives the contract
5045
- // store), or the first gate write dies "stream not found".
5046
- await ensureAuthorityStores(await jetstreamManager(nc), kvm, this.space);
5047
- return await fn({ recordsKv: await kvm.open(recordsBucket(this.space)), authKv: await kvm.open(epAuthBucket(this.space)), nc });
5048
- }
5049
- finally {
5050
- await drainAndClose(nc);
5051
- }
5052
- }
5053
- /** Parent-local inventory read. It does not enter maintenance or change admission. */
5054
- hostedSeatCount() { return this.agents.size; }
5055
- /** Public local-seat facts for the owning machine daemon. No mesh or secret reads. */
5056
- hostedAgents() {
5057
- if (this.agents.size > 50)
5058
- throw new Error("local agent inventory exceeds its bound");
5059
- return [...this.agents.values()].map(a => ({
5060
- name: a.name, application: a.agent, ...(a.launch.model ? { model: a.launch.model } : {}),
5061
- cwd: a.launch.cwd, startedAt: new Date(a.startedAt).toISOString(), state: a.handle.status(),
5062
- }));
5063
- }
5064
- /** The served manager-level health summary. Given an owner, `agentCount` counts only that owner's
5065
- * seats, as `ps` lists them ({@link psOwnerFilter}), so a person reading a shared Manager does not
5066
- * learn how many seats other owners hold on it. */
5067
- managerStatusData(ownerFilter, setupClaude = false) {
5068
- this.refreshUnavailableConnectors(undefined, setupClaude);
5069
- return {
5070
- instanceId: this.managerInstanceId,
5071
- lifecycleUid: this.managerLifecycleUid,
5072
- host: hostname(),
5073
- version: MANAGER_VERSION,
5074
- execution: this.execution,
5075
- runtime: this.runtimeKind,
5076
- custody: this.execution === "none" ? "none" : this.requiredRuntime.kind === "pty" && this.requiredRuntime.supportsRelease === true ? "custodied" : "legacy",
5077
- runHosting: this.execution !== "none" && (this.remoteAuthority ? this.remoteAuthority.runHosting !== undefined : !this.userMode && this.auth !== undefined),
5078
- terminalSessions: this.execution !== "none",
5079
- agentCount: ownerFilter === undefined ? this.agents.size : [...this.agents.values()].filter((a) => a.userOwner === ownerFilter).length,
5080
- uptimeMs: Date.now() - this.startedAtMs,
5081
- connectors: this.connectorStatuses.map((row) => ({ ...row, binaries: { ...row.binaries } })),
5082
- classSpawn: this.classSpawnEnabled(),
5083
- staticReconciliation: this.staticReconciliationStatus(),
5084
- stopImpact: {
5085
- agentScope: ownerFilter === undefined ? "manager" : "owner-filtered",
5086
- observedAt: new Date().toISOString(),
5087
- maintenance: this.maintenanceState,
5088
- resumeRequired: this.resumeRequired,
5089
- stopping: this.leaseStopping,
5090
- lifecycleInFlight: this.lifecycleInFlight,
5091
- reservedLaunches: this.namesCapacity.reservedCount,
5092
- retirementsPending: this.retirement.pendingCount,
5093
- deprovisioningInFlight: this.retirement.inFlightCount,
5094
- staticReconciliationInFlight: this.staticLifecycle.sweepsInFlight,
5095
- agents: [...this.agents.values()]
5096
- .filter((a) => ownerFilter === undefined || a.userOwner === ownerFilter)
5097
- .map((a) => ({
5098
- name: a.name,
5099
- id: a.id,
5100
- lifecycleUid: a.lifecycleUid,
5101
- mode: a.handle.kind,
5102
- defaultAction: this.maintenanceState !== "active" || this.resumeRequired
5103
- ? "stop-retaining-state" : this.isProcessBoundSeat(a) ? "stop" : "release-custody",
5104
- withAgentsAction: this.maintenanceState !== "active" || this.resumeRequired ? "stop-retaining-state" : "stop",
5105
- })),
5106
- // The same digest form `opResumePreserved` binds, so a preserved-exit stop and the later
5107
- // resume name one inventory.
5108
- ...(this.maintenanceState !== "active" && this.preservationAttemptId && this.preservationInventory
5109
- ? { preservation: { attemptId: this.preservationAttemptId, inventorySha256: createHash("sha256").update(JSON.stringify(this.preservationInventory)).digest("hex") } }
5110
- : {}),
5111
- },
5112
- };
5113
- }
3622
+ /** {@link BrokerTransport.withLifecycleExecutor}. */
3623
+ withLifecycleExecutor(pin, fn) { return this.brokerTransportComponent.withLifecycleExecutor(pin, fn); }
3624
+ /** {@link BrokerTransport.withIssuer}. */
3625
+ withIssuer(fn) { return this.brokerTransportComponent.withIssuer(fn); }
3626
+ /** {@link BrokerTransport.issuanceSeam}. */
3627
+ issuanceSeam(...args) { return this.brokerTransportComponent.issuanceSeam(...args); }
3628
+ /** {@link BrokerTransport.withEndpointServeExecutor}. */
3629
+ withEndpointServeExecutor(fn) { return this.brokerTransportComponent.withEndpointServeExecutor(fn); }
3630
+ /** {@link BrokerTransport.withOpenServeConnection}. */
3631
+ withOpenServeConnection(fn) { return this.brokerTransportComponent.withOpenServeConnection(fn); }
3632
+ /** {@link StatusAndModels.hostedSeatCount}. */
3633
+ hostedSeatCount(...args) { return this.statusAndModelsComponent.hostedSeatCount(...args); }
3634
+ /** {@link StatusAndModels.hostedAgents}. */
3635
+ hostedAgents(...args) { return this.statusAndModelsComponent.hostedAgents(...args); }
3636
+ /** {@link StatusAndModels.managerStatusData}. */
3637
+ managerStatusData(...args) { return this.statusAndModelsComponent.managerStatusData(...args); }
5114
3638
  staticReconciliationStatus() {
5115
3639
  return this.staticLifecycle.staticReconciliationStatus();
5116
3640
  }
@@ -5177,315 +3701,12 @@ export class Manager {
5177
3701
  emitGoalProgress(...args) { return this.goalWriterComponent.emitGoalProgress(...args); }
5178
3702
  /** {@link GoalWriter.assertGoalWriterEpochCurrent}. */
5179
3703
  assertGoalWriterEpochCurrent(...args) { return this.goalWriterComponent.assertGoalWriterEpochCurrent(...args); }
5180
- /** A spawn's refusal reaches only its caller's terminal, so the manager also writes one line for it
5181
- * to its own log, naming the request ID the caller printed, the persona and the reason. */
5182
- async loggedSpawnRefusal(ctx, serve) {
5183
- try {
5184
- return await serve();
5185
- }
5186
- catch (e) {
5187
- const persona = ctx.request.args?.name;
5188
- console.error(oneLine(`! spawn request ${ctx.request.id} for persona "${String(persona ?? "")}" refused (${e instanceof EpEnvelopeError ? e.code : "error"}): ${rejectionText(e)}`));
5189
- throw e;
5190
- }
5191
- }
5192
- /** Serve `spawn`/`launch` as an ACTION. Authz already ran in {@link serveGated}. The
5193
- * accept path runs INLINE on the handler ({@link startAgent} with hooks): the goal binds + the
5194
- * acceptance replies the moment the identity is minted, BEFORE any provision, or on the
5195
- * hosted enrollment arm once the host has enrolled the agent; progress and the terminal are driven
5196
- * OFF-handler, so the ~30s readiness wait no longer blocks the reply.
5197
- * Returns the acceptance floor payload {name, owner, actor, uid, goalId, fingerprint, executor}
5198
- * (the ALLOCATED identity). goalId = the request id (env.id). */
5199
- async serveSpawnGoal(ctx, run) {
5200
- // These four refuse before anything is accepted or allocated, so they state it (SPEC 13.3).
5201
- if (this.execution === "none")
5202
- throw new EpEnvelopeError("unimplemented", this.executionRefusal(), undefined, "not-executed");
5203
- const gw = this.goalWriter;
5204
- if (!gw)
5205
- throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; spawn-as-action cannot accept (SPEC 13.6)", undefined, "not-executed");
5206
- // Refuse to accept until the boot reconcile of inherited goals completes, so a fresh
5207
- // acceptance never races the sweep (settling a live goal mid-flight would steal its real terminal).
5208
- if (!this.goalReconcileDone)
5209
- throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; retry shortly (SPEC 13.6)", undefined, "not-executed");
5210
- const goalId = ctx.request.id;
5211
- const { fingerprint } = submissionFingerprint(ctx.request, ctx.subject);
5212
- const ref = goalRefOf(ctx.subject, goalId);
5213
- const key = goalKey(ref);
5214
- const executor = { lifecycleUid: this.managerInstanceId, epoch: this.serviceServe?.grant.epoch ?? 0 };
5215
- const epoch = executor.epoch;
5216
- const acceptedAt = Date.now();
5217
- // Idempotent same-goalId retry (a client re-send): serve the IDENTICAL acceptance without
5218
- // re-running the accept path — so a HARD-PINNED retry does not trip the same-name refuse and no
5219
- // name is re-allocated. Same-incarnation rides the live map; the create-only bindGoal in onAccepted
5220
- // still fences a CONCURRENT same-goalId race (the loser aborts and serves the winner's acceptance).
5221
- const prior = this.goalAcceptances.get(key);
5222
- // A goal that already ENDED is answered from its committed terminal and never accepted again.
5223
- // Running the accept for it allocates a fresh name and identity, then refuses at the index
5224
- // CAS, because the entry its terminal cleared cannot be created twice, and that refusal tells
5225
- // the caller to reconcile the store. A retry that outlived its entry above must not reach it.
5226
- const ended = prior === undefined ? await readGoalResult(gw.ctx, ref) : undefined;
5227
- const accepted = prior ?? ended;
5228
- if (accepted !== undefined) {
5229
- if (accepted.fingerprint !== fingerprint)
5230
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted under a different submission; one goalId never carries two specs (SPEC 13.6)`, undefined, "not-executed");
5231
- return prior ?? this.cachedSpawnAcceptance(ref, goalId, fingerprint, executor);
5232
- }
5233
- let resolveAccept;
5234
- let rejectAccept;
5235
- const acceptP = new Promise((res, rej) => { resolveAccept = res; rejectAccept = rej; });
5236
- let acceptance;
5237
- let readinessTimeoutMs = this.readinessTimeoutMs;
5238
- // H1: set the instant the terminal path is ENTERED, not when it succeeds — the post-accept
5239
- // fallback below must fire only when `onOutcome` never ran at all, never as a second attempt
5240
- // behind a commit that threw.
5241
- let terminalEntered = false;
5242
- // TWO DIFFERENT QUESTIONS, DELIBERATELY NOT ONE FLAG.
5243
- //
5244
- // `terminalEntered` HAS this goal already been settled (or claimed) by someone?
5245
- // `ownsGoal` MAY THIS ATTEMPT settle it at all?
5246
- //
5247
- // The second is the authority, and it is default-CLOSED: an attempt earns it by WINNING the
5248
- // create-only `bindGoal` CAS below, and nothing else grants it. That matters because the
5249
- // post-accept fallback exists to settle a goal nobody answered, so every new way of leaving
5250
- // this function is opted INTO committing a terminal unless something stops it. Deriving the
5251
- // right from the claim instead of from a running record means a losing attempt CANNOT commit
5252
- // down any unwind path, including ones added later that never thought about this. Collapsing
5253
- // the two into one boolean is what let a duplicate-goal loser steal the winner's terminal
5254
- // (#357): it had entered no terminal, so the fallback wrote one for it, using its own abort
5255
- // message as the caller-visible outcome.
5256
- let ownsGoal = false;
5257
- // Set by onEffect. A refusal that arrives with it still false changed nothing.
5258
- let effectStarted = false;
5259
- // Set by onUndone: the host's code for a later refusal that left nothing behind.
5260
- let undone;
5261
- // The task of a once spawn, once accepted.
5262
- let onceRef;
5263
- // The terminal commits OFF-handler on the goal-writer connection (manager-only authority; a
5264
- // caller cannot publish it). TWO COMPOSED FENCES (defense in depth): (a) reads THIS
5265
- // incarnation's OWN gate epoch and REFUSES a superseded commit (the currency belt), and (b)
5266
- // barrier-revoke evicts this connection on takeover. The terminal lands on the ONE subject
5267
- // SPEC §13.2 (reserved subjects) reserves; first-terminal-fact-wins is global, so a committed outcome is visible
5268
- // to every reader in every incarnation. On success the reconcile-index entry is cleared.
5269
- //
5270
- // Named rather than inlined into the hooks below so the H1 post-accept fallback drives THIS
5271
- // path — one commit site, so the progress event, the index clear and the `agentGoals` cleanup
5272
- // cannot drift between a normal outcome and a recovered one.
5273
- const onOutcome = async (o) => {
5274
- // THE AUTHORITY CHECK, and the only one. An attempt that never won the bind provisioned
5275
- // nothing and has no outcome to report: the goal belongs to whoever won it, in this
5276
- // incarnation or a sibling. Refusing here rather than at each unwind site is the point --
5277
- // there is exactly one commit path, so this fences every route into it, present and future.
5278
- if (!ownsGoal)
5279
- return false;
5280
- terminalEntered = true; // entered, not succeeded — see the catch below
5281
- // A once spawn that did not succeed never served its task (delivery opens only with a
5282
- // succeeded verdict), so the task is cancelled now rather than at the seat's exit. A launched
5283
- // seat's debt is still settled by its exit, which proves the seat gone first; a spawn that
5284
- // never launched one owes nothing more.
5285
- if (o.kind !== "succeeded" && onceRef !== undefined) {
5286
- const reason = o.kind === "uncertain" ? "readiness-timeout" : "launch-failed";
5287
- if (this.onceWatched.has(goalKey(onceRef)))
5288
- void this.commitOnceCancel(onceRef, reason).catch((e) => console.error(`! once task ${onceRef.goalId} (${reason}): ${rejectionText(e)}; its seat's exit cancels it`));
5289
- else
5290
- void this.settleOnceTurn(onceRef, reason);
5291
- }
5292
- try {
5293
- await this.assertGoalWriterEpochCurrent(epoch); // a superseded corpse never commits
5294
- let fact;
5295
- if (o.kind === "succeeded") {
5296
- this.emitGoalProgress(ref, epoch, { phase: "presence" });
5297
- ({ fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "complete", state: "succeeded", data: o.data, committer: { instanceId: this.managerInstanceId, epoch } }));
5298
- }
5299
- else if (o.kind === "failed") {
5300
- ({ fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "complete", state: "failed", data: o.data, committer: { instanceId: this.managerInstanceId, epoch } }));
5301
- }
5302
- else {
5303
- // Forward the readiness detail as the terminal's reason: this manager owns the deadline,
5304
- // so it owns what elapsing it MEANS. Absent, core commits its own generic line (#605).
5305
- const { reason: why, running } = (o.data ?? {});
5306
- ({ fact } = await settleGoalUncertain(gw.ctx, { ref, now: Date.now(), committer: { instanceId: this.managerInstanceId, epoch }, ...(typeof why === "string" && why.length > 0 ? { reason: why } : {}), ...(running === true ? { running: true } : {}) }));
5307
- }
5308
- this.expireGoalAcceptance(ref);
5309
- this.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
5310
- await clearGoalIndex(gw.ctx, ref); // terminal reached - the successor never reconciles it
5311
- if (acceptance)
5312
- this.agentGoals.delete(acceptance.name); // goal terminal - no cancel path left
5313
- return true;
5314
- }
5315
- catch (e) {
5316
- // THE NARROWER LEG, LEFT OPEN DELIBERATELY. If the COMMIT ITSELF throws (the currency belt
5317
- // refused a superseded commit, or the broker failed) there is genuinely no terminal, and the
5318
- // H1 fallback must NOT retry it: a retry either loses the same way or overwrites a real
5319
- // supersession refusal with a manufactured outcome. That is why `terminalEntered` is set on
5320
- // ENTRY. This leg is infrastructure-class and converges through the reconcile index at the
5321
- // next boot, which is why the index is NOT cleared above on this path. Do not "close" it
5322
- // here with a retry loop.
5323
- console.error(`! goal terminal commit for ${goalId} failed: ${rejectionText(e)}`);
5324
- return false;
5325
- }
5326
- };
5327
- const bg = run({
5328
- onAccepted: async ({ name, agentTriple }) => {
5329
- // Record the goal in the reconcile index BEFORE the bind (index-CAS-before-bind),
5330
- // so a successor incarnation finds + settles this goal if we crash before its terminal. A
5331
- // crash between this write and the bind leaves an index entry whose goal status is absent —
5332
- // the sweep clears it as a no-goal; a crash before it leaves no entry (never durable). A
5333
- // Carry THIS incarnation's instanceId (the executor coord) so a multi-instance sweep can skip a live sibling's goal.
5334
- //
5335
- // H2, THE ACCEPTANCE FLOOR: the allocated identity is written HERE, before the bind and so
5336
- // before the acceptance is acked, because this entry is the only durable record of it that
5337
- // exists that early — the goal spec does not carry it and the terminal does not exist yet.
5338
- // A same-goalId attempt that loses the bind while the winner is still in flight can then
5339
- // serve what the winner actually allocated instead of inventing an empty identity.
5340
- const idx = await recordGoalIndex(gw.ctx, ref, executor.lifecycleUid, { name, owner: agentTriple.owner, actor: agentTriple.actor, uid: agentTriple.uid, readinessDeadlineMs: readinessTimeoutMs });
5341
- // A create loss is an idempotent retry ONLY for the same incarnation. A FOREIGN iid means a
5342
- // sibling instance accepted this goalId (the live vector is a client retry over ANYCAST, not
5343
- // a journal consumer): this attempt provisions nothing and answers with the winner's floor,
5344
- // or refuses if that instance never persisted one.
5345
- if (!idx.recorded && idx.existing.iid !== executor.lifecycleUid) {
5346
- acceptance = await this.acceptanceFromIndex(idx.existing, ref, goalId, fingerprint, executor);
5347
- resolveAccept(acceptance);
5348
- // No claim needed here: `ownsGoal` is still false, so the commit path refuses this attempt.
5349
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" was accepted by instance "${idx.existing.iid}"; that instance's acceptance is served and this attempt provisions nothing (SPEC 13.6)`);
5350
- }
5351
- // Bind AFTER the accept-path checks (name/capacity/persona) + identity mint, BEFORE any provision:
5352
- // a create-only CAS per goalId (a refused accept above left zero bind, zero reserve).
5353
- const b = await bindGoal(gw.ctx, ref, fingerprint);
5354
- if (!b.bound) {
5355
- if (b.existing.fingerprint !== fingerprint)
5356
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" is already bound to a different submission; one goalId never carries two specs (SPEC 13.6)`);
5357
- // Lost a concurrent same-goalId race: serve the winner's acceptance and abort THIS provision
5358
- // (no second spawn). The throw unwinds to the finally, which releases this attempt's reserve.
5359
- acceptance = this.goalAcceptances.get(key) ?? await this.cachedSpawnAcceptance(ref, goalId, fingerprint, executor);
5360
- resolveAccept(acceptance);
5361
- // No claim needed here either. This attempt lost the CAS, so `ownsGoal` is still false and
5362
- // the single check in `onOutcome` refuses it. Before that check existed this site had to
5363
- // remember to claim the terminal by hand, and the one place that forgot is how a loser
5364
- // came to commit `failed` on the winner's goal, using its own abort text as the outcome.
5365
- // Unwind the provision (the acceptance is already served); the code is discarded by the
5366
- // caller (acceptance !== undefined), so it just aborts this attempt's side-effects.
5367
- throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" is already accepted; the cached acceptance is served`);
5368
- }
5369
- // WON the claim: this attempt, and only this attempt, may settle this goal.
5370
- ownsGoal = true;
5371
- await createGoal(gw.ctx, ref, {
5372
- fingerprint,
5373
- command: ctx.subject.command,
5374
- caller: { id: `${ctx.subject.caller.owner}.${ctx.subject.caller.actor}`, lifecycleUid: ctx.subject.caller.uid },
5375
- // The ACCEPTING incarnation's epoch: half of the terminal's attribution pair (§13.6).
5376
- acceptedEpoch: epoch,
5377
- requestId: goalId,
5378
- sourceSeq: 0,
5379
- acceptedAt,
5380
- readinessDeadlineMs: readinessTimeoutMs,
5381
- });
5382
- acceptance = { name, owner: agentTriple.owner, actor: agentTriple.actor, uid: agentTriple.uid, goalId, fingerprint, readinessDeadlineMs: readinessTimeoutMs, executor };
5383
- this.goalAcceptances.set(key, acceptance);
5384
- this.agentGoals.set(name, ref); // A despawn of this name mid-goal drives the cancel path
5385
- resolveAccept(acceptance);
5386
- this.emitGoalProgress(ref, epoch, { phase: "handoff" });
5387
- },
5388
- onLaunched: () => this.emitGoalProgress(ref, epoch, { phase: "launched" }),
5389
- onReadinessWindow: (value) => { readinessTimeoutMs = value; },
5390
- onOutcome,
5391
- // Claim the terminal WITHOUT committing one: the despawn/stop that ended this launch owns
5392
- // it and commits `cancel`. This only stops the non-ok reply below from manufacturing a
5393
- // `failed` that would race that `cancel` (first-terminal-fact-wins).
5394
- onTerminalDeferred: () => { terminalEntered = true; },
5395
- onEffect: () => { effectStarted = true; },
5396
- onUndone: (code) => { undone = code; },
5397
- onOnce: async (task) => {
5398
- try {
5399
- const accepted = await this.acceptOnceTurn({ spawnRef: ref, fingerprint, command: ctx.subject.command, executor, acceptedAt, ...task });
5400
- onceRef = accepted.ref;
5401
- return accepted;
5402
- }
5403
- catch (e) {
5404
- // The spawn goal is already bound, so its refusal is a terminal: nothing has launched.
5405
- await onOutcome({ kind: "failed", data: { error: `the once task was not accepted: ${rejectionText(e)}` } });
5406
- throw e;
5407
- }
5408
- },
5409
- });
5410
- bg.then((reply) => {
5411
- // Refused BEFORE onAccepted (hard-pin collision, capacity, persona-not-found) — no goal bound.
5412
- // Only a refusal before the first effect, or one whose effects were all removed, states
5413
- // `not-executed`; a later one, such as the alias gate that re-drives a teardown, leaves the
5414
- // outcome unknown.
5415
- if (acceptance === undefined) {
5416
- const details = reply.details;
5417
- const code = undone ?? reply.code ?? "failed-precondition";
5418
- rejectAccept(new EpEnvelopeError(code, reply.error ?? "spawn refused at accept", details, effectStarted && undone === undefined ? undefined : "not-executed"));
5419
- return;
5420
- }
5421
- // H1: `run` CATCHES its own body (a throw in buildLaunch/runtime.spawn) and RESOLVES `{ok:false}`
5422
- // rather than rejecting, so a post-accept failure arrives here, not in the catch below, and
5423
- // reaches none of the onOutcome sites. Without this the goal stays accepted-but-unanswered:
5424
- // the caller follows epe to a terminal that never comes, and the reconcile index that would
5425
- // settle it is only swept at BOOT, so a manager that stays up never converges it.
5426
- if (reply.ok === false && !terminalEntered)
5427
- return onOutcome({ kind: "failed", data: failedTerminal(reply.error ?? "spawn failed after accept", reply) });
5428
- }).catch((e) => {
5429
- if (acceptance === undefined) {
5430
- rejectAccept(e);
5431
- return;
5432
- }
5433
- // Same obligation for a genuine rejection (one that escaped `run`'s own catch).
5434
- if (!terminalEntered)
5435
- return onOutcome({ kind: "failed", data: failedTerminal(rejectionText(e), caughtEnvelope(e)) });
5436
- console.error(`! spawn-as-action async body for ${goalId}: ${rejectionText(e)}`);
5437
- }).catch((e) => console.error(`! goal terminal fallback for ${goalId}: ${rejectionText(e)}`));
5438
- return acceptP;
5439
- }
5440
- /** H2: an acceptance served from a WINNER'S durable acceptance floor (the goal-index entry it
5441
- * wrote before its own ack). Refuses `unavailable` rather than inventing one — see
5442
- * {@link cachedSpawnAcceptance} for why an empty identity is never an acceptable answer. */
5443
- async acceptanceFromIndex(entry, ref, goalId, fingerprint, executor) {
5444
- if (entry.allocated?.owner === undefined)
5445
- throw new EpEnvelopeError("unavailable", `goal "${goalId}" was accepted by instance "${entry.iid}", which persisted no acceptance floor naming its owner; its allocated identity is not readable from here (SPEC 13.6)`);
5446
- const readinessDeadlineMs = entry.allocated.readinessDeadlineMs ?? (await readGoalSpec(this.goalWriter.ctx, ref))?.value.readinessDeadlineMs;
5447
- if (readinessDeadlineMs === undefined)
5448
- throw new EpEnvelopeError("unavailable", `goal "${goalId}" is accepted but its readiness deadline is not readable; a synchronous follower cannot bound its wait honestly (SPEC 13.6)`);
5449
- return { name: entry.allocated.name, owner: entry.allocated.owner, actor: entry.allocated.actor, uid: entry.allocated.uid, goalId, fingerprint, readinessDeadlineMs, executor };
5450
- }
5451
- /** Reconstruct a cached acceptance for a same-goalId retry NOT in the live map (a prior incarnation
5452
- * accepted it, or a concurrent winner whose map write this reader has not yet observed).
5453
- *
5454
- * H2 — WHY THIS PREFERS THE INDEX OVER THE TERMINAL. It used to read only the committed terminal
5455
- * and fall back to `{name:"", actor:"", uid:""}` when there was none. That is the common case,
5456
- * not a corner: a client retry over ANYCAST reaches a sibling while the winner is still
5457
- * provisioning, so no terminal exists yet, and the caller was handed an ACCEPTED reply naming an
5458
- * empty agent it can never address. The acceptance floor in the goal index exists from the moment
5459
- * of acceptance, so it answers precisely the window the terminal cannot. Where neither is
5460
- * readable the honest answer is a REFUSAL: an accepted goal whose identity nobody can name is
5461
- * `unavailable` while it runs and its cached outcome once it has ended, never a hollow success. */
5462
- async cachedSpawnAcceptance(ref, goalId, fingerprint, executor) {
5463
- const entry = await readGoalIndex(this.goalWriter.ctx, ref);
5464
- if (entry?.allocated !== undefined)
5465
- return this.acceptanceFromIndex(entry, ref, goalId, fingerprint, executor);
5466
- // The index is CLEARED at terminal, so a settled goal legitimately has no entry: fall back to
5467
- // the terminal's data, which carries the same identity for exactly that case.
5468
- const result = await readGoalResult(this.goalWriter.ctx, ref);
5469
- const d = (result?.data ?? {});
5470
- const spec = await readGoalSpec(this.goalWriter.ctx, ref);
5471
- const readinessDeadlineMs = spec?.value.readinessDeadlineMs;
5472
- // The terminal names the agent by its slot id: the `owner.actor` principal in user mode, the
5473
- // bare nkey under DEV_OWNER on a static mesh.
5474
- const principal = typeof d.id !== "string" || d.id.length === 0 ? null : this.userMode ? parsePrincipalKey(d.id) : { owner: DEV_OWNER, actor: d.id };
5475
- if (typeof d.name === "string" && d.name.length > 0 && principal !== null && typeof d.lifecycleUid === "string" && d.lifecycleUid.length > 0 && readinessDeadlineMs !== undefined)
5476
- return { name: d.name, owner: principal.owner, actor: principal.actor, uid: d.lifecycleUid, goalId, fingerprint, readinessDeadlineMs, executor };
5477
- // Only a `succeeded` terminal names the agent. Any other ended goal has its outcome as its
5478
- // whole durable answer, and no retry will make an identity readable (SPEC 13.6 item 5).
5479
- if (result !== undefined)
5480
- throw goalAlreadyTerminal(goalId, result);
5481
- throw new EpEnvelopeError("unavailable", `goal "${goalId}" is already accepted but its allocated identity is not readable (no acceptance floor, and no terminal carrying one); retry (SPEC 13.6)`);
5482
- }
5483
- /** Drop a goal's acceptance {@link goalAcceptanceRetentionMs} after its terminal committed. A
5484
- * retry after that reads the terminal, so only a goal that has one may be passed here. */
5485
- expireGoalAcceptance(ref) {
5486
- const key = goalKey(ref);
5487
- setTimeout(() => this.goalAcceptances.delete(key), this.goalAcceptanceRetentionMs).unref?.();
5488
- }
3704
+ /** {@link SpawnGoal.loggedSpawnRefusal}. */
3705
+ loggedSpawnRefusal(ctx, serve) { return this.spawnGoalComponent.loggedSpawnRefusal(ctx, serve); }
3706
+ /** {@link SpawnGoal.serveSpawnGoal}. */
3707
+ serveSpawnGoal(...args) { return this.spawnGoalComponent.serveSpawnGoal(...args); }
3708
+ /** {@link SpawnGoal.expireGoalAcceptance}. */
3709
+ expireGoalAcceptance(...args) { return this.spawnGoalComponent.expireGoalAcceptance(...args); }
5489
3710
  // ---- the turn relay (§8 durable actions) ------------------------------------------------------
5490
3711
  //
5491
3712
  // A seat is NOT an endpoint: a run's `turn(agent, payload)` rides the manager, which accepts it
@@ -5721,663 +3942,31 @@ export class Manager {
5721
3942
  }
5722
3943
  /** {@link SeatStop.lifecycleMembershipRefusal}. */
5723
3944
  lifecycleMembershipRefusal(...args) { return this.seatStopComponent.lifecycleMembershipRefusal(...args); }
5724
- /** Open a short-lived PROVISIONER connection, run the onboarding ops on it, and drain it (closure (ii),
5725
- * residual 2). The DM/DLV consumer-create surface — the irreducible onboarding power — lives only for
5726
- * this window, never as a standing grant on the long-lived supervisor. A provision-only endpoint
5727
- * (no presence/consume/channel-watch) connected with memory-only `provisioner` creds; it sets its own
5728
- * `inboxPrefix` so JS-API replies land on the `_INBOX_<id>.>` the provisioner cred subscribes. */
5729
- async withProvisioner(fn) {
5730
- if (!this.auth)
5731
- throw new Error("withProvisioner: no space auth (an open mesh has no scoped creds)");
5732
- // Onboarding runs several provisioning ops, so it keeps the provisioner profile's five-minute window.
5733
- return withScopedEndpoint({ space: this.space, servers: this.servers ?? DEFAULT_SERVER, auth: this.auth }, "provisioner", "provisioner", fn, 5 * 60);
5734
- }
5735
- /** A connection holding this instance's transfer reader grants (docs/design/resume-transfer.md
5736
- * section 6) for this one receive or sweep: minted from the space's signing seed, or issued by the
5737
- * host to a remote manager. An open mesh enforces no grants, so a bare one-shot connection is that
5738
- * reader there. */
5739
- async withTransferReader(fn) {
5740
- const issue = this.remoteAuthority?.mintTransferReader;
5741
- if (this.remoteAuthority && !issue)
5742
- throw new Error("withTransferReader: this manager's remote authority issues no transfer reader");
5743
- const identity = newIdentity();
5744
- const creds = issue
5745
- ? await issue(identity)
5746
- : this.auth && await mintCreds(this.auth, identity, "transfer-reader", { transferReader: { instanceId: this.managerInstanceId } });
5747
- const nc = await this.dial(creds
5748
- ? { ...standaloneConnectOpts({ creds, /* not yet wired to a recorded transport */ tls: false }), maxReconnectAttempts: 0 }
5749
- : { maxReconnectAttempts: 0 });
5750
- try {
5751
- return await fn(nc);
5752
- }
5753
- finally {
5754
- await drainAndClose(nc);
5755
- }
5756
- }
3945
+ /** {@link BrokerTransport.withProvisioner}. */
3946
+ withProvisioner(fn) { return this.brokerTransportComponent.withProvisioner(fn); }
3947
+ /** {@link BrokerTransport.withTransferReader}. */
3948
+ withTransferReader(fn) { return this.brokerTransportComponent.withTransferReader(fn); }
5757
3949
  /** {@link SeatStop.opPurge}. */
5758
3950
  opPurge(...args) { return this.seatStopComponent.opPurge(...args); }
5759
- /** Persist a peer-defined persona as config. After this, `start name` auto-discovers
5760
- * .cotal/agents/<name>.md and the connector applies its persona/model at spawn.
5761
- *
5762
- * CONTENT vs POLICY: `owner` has no slot, so a peer cannot claim ownership, and the
5763
- * capabilities the written persona carries, a saved list a redefine keeps included, are bounded
5764
- * against the definer before the write, so a peer can put only what it holds into a persona that
5765
- * a wider spawner might later launch. Channel grants, role, and agent are content: they may
5766
- * arrive as explicit arguments or as a leading frontmatter block inside `persona`. A prompt
5767
- * that starts with `---` is parsed and merged (explicit args win) so the written file has one
5768
- * frontmatter block; a malformed block is refused by name rather than wrapped. A fresh name is
5769
- * created with the owner {@link personaOwner} records. Redefining an EXISTING file is allowed on
5770
- * the privileged tier only if `file.owner == caller`, else admin is required. Fail-closed: an
5771
- * ownerless file (legacy / operator-written) is admin-only. */
5772
- async opDefinePersona(args, caller, admin, authenticated) {
5773
- if (this.execution === "none")
5774
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
5775
- const name = String(args.name ?? "").trim();
5776
- if (!name)
5777
- return { ok: false, error: "name required" };
5778
- const nameErr = this.nameError(name);
5779
- if (nameErr)
5780
- return { ok: false, error: nameErr };
5781
- const persona = String(args.persona ?? "").trim();
5782
- if (!persona)
5783
- return { ok: false, error: "persona required" };
5784
- const path = agentFilePath(this.workspaceRoot, name);
5785
- const strList = (v) => {
5786
- if (v === undefined || v === null)
5787
- return undefined;
5788
- return (Array.isArray(v) ? v : [v]).map((x) => String(x));
5789
- };
5790
- const capabilities = strList(args.capabilities);
5791
- let endpointArg;
5792
- try {
5793
- endpointArg = parsePersonaEndpoints(args.endpoints, "define-persona");
5794
- }
5795
- catch (e) {
5796
- return { ok: false, error: rejectionText(e) };
5797
- }
5798
- // Read, authorize and compose against the catalog as it is now. Nothing yields between this and
5799
- // the write, so no other call in this manager can change the file in between. The handler does
5800
- // not serialize with other processes; their writes are outside this single-manager guarantee.
5801
- const compose = () => {
5802
- let existing;
5803
- if (existsSync(path)) {
5804
- try {
5805
- existing = loadAgentFile(path);
5806
- }
5807
- catch (e) {
5808
- return { reply: { ok: false, error: rejectionText(e) } };
5809
- }
5810
- if (!admin && existing.owner !== caller) {
5811
- const owner = existing.owner ? `owned by ${existing.owner}` : "operator-owned (legacy file - no agent owner)";
5812
- return { reply: {
5813
- ok: false, code: "permission-denied", outcome: "not-executed",
5814
- error: `not authorized to redefine ${name}: ${owner}; only its owner or an operator can`,
5815
- details: [{ kind: "ai.cotal.persona-ownership-refused", operatorOwned: existing.owner === undefined }],
5816
- } };
5817
- }
5818
- }
5819
- try {
5820
- return {
5821
- def: composeWirePersona({
5822
- name,
5823
- owner: this.personaOwner(caller),
5824
- prompt: persona,
5825
- model: args.model,
5826
- role: args.role,
5827
- agent: args.agent,
5828
- subscribe: strList(args.subscribe),
5829
- allowSubscribe: strList(args.allowSubscribe),
5830
- allowPublish: strList(args.allowPublish),
5831
- capabilities,
5832
- endpoints: copyPersonaEndpoints(endpointArg),
5833
- }, existing),
5834
- };
5835
- }
5836
- catch (e) {
5837
- return { reply: { ok: false, error: rejectionText(e) } };
5838
- }
5839
- };
5840
- let composed = compose();
5841
- if ("reply" in composed)
5842
- return composed.reply;
5843
- // The bound reads the persona as written, so a redefine that omits `capabilities` or `endpoints`
5844
- // has the list it keeps checked too. Resolving the definer's grant yields, so the catalog is read
5845
- // again after it.
5846
- if (composed.def.capabilities?.length || composed.def.endpoints !== undefined) {
5847
- const refusal = await this.definerGrantRefusal(caller, authenticated);
5848
- composed = compose();
5849
- if ("reply" in composed)
5850
- return composed.reply;
5851
- const kept = composed.def.capabilities ?? [];
5852
- const keptEndpoints = lowerPersonaEndpoints(composed.def.endpoints);
5853
- // A user-auth persona may not name the field at all; elsewhere `[]` hands on nothing to bound.
5854
- const namesEndpoints = composed.def.endpoints !== undefined;
5855
- const refused = kept.length || keptEndpoints.length || (namesEndpoints && this.meshMode === "user")
5856
- ? refusal({ capabilities: kept, endpoints: keptEndpoints, namesEndpoints })
5857
- : undefined;
5858
- if (refused) {
5859
- const fromSaved = [
5860
- ...(capabilities === undefined && kept.length ? ["capabilities"] : []),
5861
- ...(endpointArg === undefined && composed.def.endpoints?.length ? ["endpoints"] : []),
5862
- ];
5863
- return {
5864
- ok: false,
5865
- code: "permission-denied",
5866
- error: fromSaved.length
5867
- ? `${refused} ${fromSaved.map((f) => `\`${f}\``).join(" and ")} come${fromSaved.length === 1 ? "s" : ""} from the saved persona, which a redefine that omits ${fromSaved.length === 1 ? "it keeps" : "them keeps"}; pass what the definer holds, or [] to clear ${fromSaved.length === 1 ? "it" : "them"}.`
5868
- : refused,
5869
- };
5870
- }
5871
- }
5872
- try {
5873
- saveAgentFile(path, composed.def);
5874
- }
5875
- catch (e) {
5876
- return { ok: false, error: rejectionText(e) };
5877
- }
5878
- return { ok: true, data: { name, path } };
5879
- }
5880
- /** Resolve what a persona's definer may put into it, as a check that returns the refusal for
5881
- * capabilities or endpoint commands it does not hold, or `undefined` when it holds them all. The
5882
- * check itself does not yield. An open mesh mints no credential, so nothing is bounded there. A
5883
- * static definer is bounded by its issued evidence, as a spawner is; a user-auth definer by its
5884
- * own ledger row's scope, under the ledger's token rule, with `admin` exempt. A user-auth persona
5885
- * cannot name `endpoints` at all, `[]` included (SPEC 13.15). A hosted manager reads no ledger, so
5886
- * it refuses. A later spawn of the persona is bounded again against its own spawner. */
5887
- async definerGrantRefusal(caller, authenticated) {
5888
- if (this.meshMode === "open")
5889
- return () => undefined;
5890
- if (this.meshMode === "static") {
5891
- const run = await this.spawnRun(authenticated, undefined);
5892
- const bound = await this.staticSpawnBound(authenticated, run !== undefined && "admission" in run ? run : undefined);
5893
- return ({ capabilities, endpoints }) => this.spawnBoundRefusal(bound, { capabilities, ...(endpoints.length ? { endpoints } : {}) }, false, "define-persona");
5894
- }
5895
- if (this.remoteAuthority)
5896
- return ({ capabilities, namesEndpoints }) => namesEndpoints
5897
- ? userMeshEndpointsRefusal("define-persona")
5898
- : capabilities.length ? "define-persona: this manager's user authority is hosted, so it cannot read the definer's grant and its persona can grant no capabilities." : undefined;
5899
- const p = parsePrincipalKey(caller);
5900
- const scope = p ? await resolveAuthProvider().actorScope({ dir: userAuthStateDir(this.workspaceRoot, this.space), owner: p.owner, actor: p.actor }) : undefined;
5901
- return ({ capabilities, namesEndpoints }) => {
5902
- if (namesEndpoints)
5903
- return userMeshEndpointsRefusal("define-persona");
5904
- if (scope?.includes("admin"))
5905
- return undefined;
5906
- const over = capabilities.filter((c) => !capabilityWithin(scope ?? [], c));
5907
- if (!over.length)
5908
- return undefined;
5909
- return scope === undefined
5910
- ? `define-persona: the definer ${caller} has no grant in this space, so its persona can grant nothing. This persona asks for capabilities ${over.join(", ")}.`
5911
- : `define-persona: this persona grants more than the definer holds: capabilities ${over.join(", ")} beyond [${scope.join(", ") || "none"}]. Drop these from the persona, or have the operator widen the definer's grant.`;
5912
- };
5913
- }
5914
- /** Remove one machine-local persona definition without touching any running lifecycle that was
5915
- * launched from it. Removal accepts the catalog's safe filename alphabet without applying the
5916
- * current spawn-name length or user-mode actor rules, so an obsolete invalid-name entry remains
5917
- * repairable. Ownership matches redefine: the recorded owner, or admin for an ownerless file. */
5918
- opRemovePersona(args, caller, admin) {
5919
- if (this.execution === "none")
5920
- throw new EpEnvelopeError("unimplemented", this.executionRefusal());
5921
- const name = String(args.name ?? "").trim();
5922
- if (!name)
5923
- return { ok: false, code: "bad-request", error: "name required" };
5924
- if (!/^[A-Za-z0-9_-]+$/.test(name))
5925
- return { ok: false, code: "bad-request", error: `unsafe persona name ${JSON.stringify(name)} (allowed: letters, digits, _ -)` };
5926
- const path = agentFilePath(this.workspaceRoot, name);
5927
- if (!existsSync(path))
5928
- return { ok: false, code: "not-found", error: `no persona "${name}"` };
5929
- let owner;
5930
- try {
5931
- owner = loadAgentFile(path).owner;
5932
- }
5933
- catch {
5934
- // A catalog entry may be invalid for launch solely because an older release admitted a name
5935
- // above today's identity limit. Read only its frontmatter owner without asking the launch
5936
- // parser to accept the identity. This does not make the file spawnable or readable.
5937
- try {
5938
- const source = readFileSync(path, "utf8").replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
5939
- const match = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(source);
5940
- if (!match)
5941
- throw new Error("missing frontmatter");
5942
- const frontmatter = parseYaml(match[1]);
5943
- if (!frontmatter || typeof frontmatter !== "object" || Array.isArray(frontmatter))
5944
- throw new Error("frontmatter is not a mapping");
5945
- const fields = frontmatter;
5946
- if (String(fields.name ?? "") !== name)
5947
- throw new Error("frontmatter name differs from the catalog entry");
5948
- if (fields.owner !== undefined && typeof fields.owner !== "string")
5949
- throw new Error("owner is not a string");
5950
- owner = fields.owner;
5951
- }
5952
- catch {
5953
- return { ok: false, code: "not-found", error: `no persona "${name}"` };
5954
- }
5955
- }
5956
- if (!admin && owner !== caller) {
5957
- const heldBy = owner ? `owned by ${owner}` : "operator-owned (legacy file - no agent owner)";
5958
- return { ok: false, code: "permission-denied", error: `not authorized to remove ${name}: ${heldBy}; only its owner or an operator can` };
5959
- }
5960
- try {
5961
- rmSync(path);
5962
- }
5963
- catch (e) {
5964
- if (!existsSync(path))
5965
- return { ok: false, code: "not-found", error: `no persona "${name}"` };
5966
- return { ok: false, error: rejectionText(e) };
5967
- }
5968
- return { ok: true, data: { name } };
5969
- }
5970
- /** The owner a fresh wire-defined persona records. A user-auth caller's principal is stable, and
5971
- * so is one of this manager's own seats for its life. Any other static caller, such as the CLI's
5972
- * operator instrument minted for one call, would leave an owner no later call matches, so it
5973
- * records none and the file is operator-owned, as a local `persona create` writes it. A peer
5974
- * joined with its own credential is such a caller too. */
5975
- personaOwner(caller) {
5976
- if (this.userMode)
5977
- return caller;
5978
- for (const a of this.agents.values())
5979
- if (this.managedPrincipal(a) === caller)
5980
- return caller;
5981
- return undefined;
5982
- }
5983
- /** Whether this caller may READ a catalog card's details (role/model/description/body). Same
5984
- * ownership rule as redefine: owner == caller, or admin. Ownerless / operator-written files are
5985
- * admin-only. Names of parseable files still appear on the list so a definer can see a taken
5986
- * spawn name; details stay off the wire unless this is true. */
5987
- canReadPersona(owner, caller, admin) {
5988
- return personaCatalogReadable(owner, caller, admin);
5989
- }
5990
- /** Mesh-side catalog list (#402). Every parseable name is returned so a definer can see a taken
5991
- * spawn name. Role / model / description / owner ride only when the caller could redefine the
5992
- * file (same ownership as `definePersona`); other cards are name-only, so a peer cannot read a
5993
- * prompt it does not own. Unparseable files are omitted for non-admin (no existence leak of a
5994
- * broken card). */
5995
- opListPersonas(caller, admin) {
5996
- const personas = [];
5997
- for (const e of listPersonaCatalog(this.workspaceRoot)) {
5998
- if (e.error) {
5999
- if (!admin)
6000
- continue;
6001
- personas.push({ name: e.name, error: "unparseable" });
6002
- continue;
6003
- }
6004
- const def = e.def;
6005
- if (!this.canReadPersona(def.owner, caller, admin)) {
6006
- personas.push({ name: e.name });
6007
- continue;
6008
- }
6009
- const description = personaCatalogDescription(def);
6010
- personas.push({
6011
- name: e.name,
6012
- ...(def.role ? { role: def.role } : {}),
6013
- ...(def.model ? { model: def.model } : {}),
6014
- ...(description ? { description } : {}),
6015
- ...(def.owner ? { owner: def.owner } : {}),
6016
- });
6017
- }
6018
- return { ok: true, data: { personas } };
6019
- }
6020
- /** Mesh-side catalog show (#402). Same ownership as list. Unknown, unauthorized, or unparseable
6021
- * names are not-found (no existence or parser-diagnostic leak). The body is included so a peer can
6022
- * inspect a prompt it owns before spawn; policy fields stay off the wire. */
6023
- opShowPersona(args, caller, admin) {
6024
- const name = String(args.name ?? "").trim();
6025
- if (!name)
6026
- return { ok: false, error: "name required" };
6027
- const nameErr = this.nameError(name);
6028
- if (nameErr)
6029
- return { ok: false, error: nameErr };
6030
- const path = agentFilePath(this.workspaceRoot, name);
6031
- if (!existsSync(path))
6032
- return { ok: false, error: `no persona "${name}"` };
6033
- let def;
6034
- try {
6035
- def = loadAgentFile(path);
6036
- }
6037
- catch {
6038
- return { ok: false, error: `no persona "${name}"` };
6039
- }
6040
- if (!this.canReadPersona(def.owner, caller, admin))
6041
- return { ok: false, error: `no persona "${name}"` };
6042
- const description = personaCatalogDescription(def);
6043
- return {
6044
- ok: true,
6045
- data: {
6046
- name,
6047
- ...(def.role ? { role: def.role } : {}),
6048
- ...(def.model ? { model: def.model } : {}),
6049
- ...(description ? { description } : {}),
6050
- ...(def.owner ? { owner: def.owner } : {}),
6051
- ...(def.persona ? { persona: def.persona } : {}),
6052
- },
6053
- };
6054
- }
6055
- /** The post-authorization `input` effect (C3): type `text` into the seat's terminal as if a human
6056
- * had. The single call an external UI needs to deliver a harness command (`/compact`, `/clear`,
6057
- * `/model`) without holding a terminal open on the caller's side.
6058
- *
6059
- * Why the runtime HANDLE and not an attach session: a session is a stream (backlog, subscriber
6060
- * set, a lifetime the session plane accounts for and caps). Opening and discarding one per
6061
- * keystroke line would burn a session slot for a write, and would put a capacity refusal in the
6062
- * path of an operation that has no capacity cost. {@link AgentHandle.write} is the one-shot
6063
- * sibling of `interrupt()`, which already writes into the same pty.
6064
- *
6065
- * Three refusals, each for a different reason and each with its own code, so a caller can tell
6066
- * "never going to work" from "not right now":
6067
- * - the name was refilled while authorization awaited: act on the incarnation the caller was
6068
- * authorized for or on nothing at all (the same guard {@link attachAuthorized} carries, for
6069
- * the same reason: a name is a reusable slot and `authorizeNamed` can await a ledger read);
6070
- * - the agent is not running: there is no terminal to type into;
6071
- * - the runtime cannot write (tmux/cmux/orca/herdr attach to an externally-owned process, so
6072
- * they own no input stream for it): `unimplemented`, named by runtime kind. NOT a fallback
6073
- * to an attach session and NOT a silent success - a dropped keystroke would leave the caller
6074
- * believing a command was delivered that never was.
6075
- *
6076
- * `enter` defaults to true: a harness command typed but not submitted has not been delivered.
6077
- * Nothing is echoed back; the caller reads the resulting turns from the event plane. */
6078
- async inputAuthorized(a, args) {
6079
- // These three refuse before the first write, so nothing was typed (SPEC 13.3). A write the
6080
- // runtime rejects below states no outcome: the runtime contract does not say a rejected write
6081
- // delivered nothing, and an earlier slice may already have reached the seat.
6082
- if (this.agents.get(a.name) !== a)
6083
- throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" was replaced during authorization - retry`, undefined, "not-executed");
6084
- if (a.handle.status() !== "running")
6085
- throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" is not running (${a.handle.status()}); nothing to type into`, undefined, "not-executed");
6086
- const write = a.handle.write?.bind(a.handle);
6087
- if (!write)
6088
- throw new EpEnvelopeError("unimplemented", `input is not supported by runtime ${a.handle.kind}`, undefined, "not-executed");
6089
- if (a.agent === "claude") {
6090
- // AskUserQuestion ignores bracketed text at its choice menu, but the following Enter
6091
- // confirms the highlighted option. Refuse rather than answer a different question choice.
6092
- const handle = a.handle;
6093
- let selection = false;
6094
- try {
6095
- const session = handle.attach();
6096
- const backlog = await session.backlog();
6097
- const term = new Headless.Terminal({ cols: session.cols, rows: session.rows, allowProposedApi: true });
6098
- try {
6099
- await new Promise((done) => term.write(backlog, done));
6100
- const screen = term.buffer.active;
6101
- const lines = Array.from({ length: term.rows }, (_, y) => screen.getLine(screen.baseY + y)?.translateToString(true).trim() ?? "");
6102
- selection = lines.some((line) => /^❯\s+\d+\./u.test(line))
6103
- && lines.some((line) => line.includes("Enter to select") && line.includes("↑/↓ to navigate") && line.includes("Esc to cancel"));
6104
- }
6105
- finally {
6106
- term.dispose();
6107
- }
6108
- }
6109
- catch {
6110
- throw new EpEnvelopeError("failed-precondition", `cannot inspect Claude input for seat "${a.name}"; use \`cotal attach --name ${a.name}\` to inspect and type directly`, undefined, "not-executed");
6111
- }
6112
- if (selection)
6113
- throw new EpEnvelopeError("failed-precondition", `Claude is showing a selection menu for seat "${a.name}"; input text cannot safely select an option. Use \`cotal attach --name ${a.name}\`, then arrow keys and Enter; nothing was typed`, undefined, "not-executed");
6114
- // Snapshot parsing awaits I/O. Keep this write bound to the authorized incarnation and handle.
6115
- if (this.agents.get(a.name) !== a || a.handle !== handle || handle.status() !== "running")
6116
- throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" changed while inspecting its terminal; nothing was typed`, undefined, "not-executed");
6117
- }
6118
- // The contract validated `text` (non-empty, <= 64KiB) and `enter` (boolean) before this ran, so
6119
- // the only decision left is the carriage return. `!== false` and not `?? true`: an ABSENT enter
6120
- // and an explicit `true` must behave identically, and only `false` may suppress the return.
6121
- //
6122
- // THE TEXT IS DELIVERED AS A BRACKETED PASTE AND THE RETURN FOLLOWS IT AS ITS OWN WRITE, and
6123
- // that is the whole of issue #1649. A TUI harness reads keystrokes, so a return fused onto the
6124
- // tail of the text (`${text}\r`) is the text's last character rather than the submit key: the
6125
- // line waits in the composer and the NEXT call's return submits the PREVIOUS call's text, so
6126
- // every delivery runs one call behind while the op still reports the full byte count.
6127
- //
6128
- // Separating the return is necessary and NOT sufficient, which is the part that cost a second
6129
- // round of measurement. A TUI classifies a fast burst of input as a PASTE and eats the newline
6130
- // that trails it (Jcode spells this `paste_guard::consume_paste_trailing_enter`), so a text big
6131
- // enough to need more than one write is still one call behind even when the return is written
6132
- // alone. Measured on a real seat, delivering in 2048-char slices with a yield before the return:
6133
- // 120 and 700 bytes submitted on their own call, 2500 and 3100 bytes did not - each appeared
6134
- // only when the NEXT call's return arrived. That is the reported symptom exactly.
6135
- //
6136
- // Bracketed paste states the boundary instead of guessing at it. `ESC[200~ text ESC[201~`
6137
- // delimits the pasted block, so the return after it is unambiguously a keystroke and the guard
6138
- // has no trailing newline to consume. This is a CLASSIFIER, not a race, so a sleep would be the
6139
- // wrong instrument: measured on a real seat, a 250ms pause before the return still lost the
6140
- // submission while 1000ms carried it, and any margin chosen from those numbers is a guess a
6141
- // loaded host breaks. Bracketed delivery submitted 120, 2600 and 5912 bytes (the issue's own
6142
- // size) each on its own call. The terminal advertises support by enabling DECSET 2004, which
6143
- // Jcode's TUI does.
6144
- //
6145
- // The bytes the SEAT receives as text are unchanged, and the receipt still counts the text plus
6146
- // the return: the paste markers are framing this op adds, never content the caller asked to
6147
- // deliver, so counting them would make `bytes` disagree with what the caller sent.
6148
- const text = String(args.text);
6149
- const submit = args.enter !== false;
6150
- const intendedBytes = Buffer.byteLength(text, "utf8") + (submit ? 1 : 0);
6151
- const parts = [{ data: PASTE_START, counted: false }];
6152
- for (let i = 0; i < text.length; i += INPUT_SLICE_CHARS)
6153
- parts.push({ data: text.slice(i, i + INPUT_SLICE_CHARS), counted: true });
6154
- parts.push({ data: PASTE_END, counted: false });
6155
- // `enter:false` still presses nothing: the text is delivered into the composer and left there.
6156
- if (submit)
6157
- parts.push({ data: "\r", counted: true });
6158
- let bytes = 0;
6159
- for (const [i, part] of parts.entries()) {
6160
- // Yield BEFORE each write but the first, so the child drains the previous slice rather than
6161
- // the pty buffer merging them. `setImmediate` runs after I/O, which a microtask would not.
6162
- if (i > 0)
6163
- await new Promise((resolve) => setImmediate(resolve));
6164
- let accepted;
6165
- try {
6166
- accepted = await write(part.data);
6167
- }
6168
- catch (error) {
6169
- throw new EpEnvelopeError("unavailable", `input for seat "${a.name}" failed: ${rejectionText(error)}`);
6170
- }
6171
- if (!Number.isSafeInteger(accepted)) {
6172
- throw new EpEnvelopeError("unavailable", `input for seat "${a.name}" failed: runtime accepted ${String(accepted)} of ${intendedBytes} bytes`);
6173
- }
6174
- // A short write on ANY part is a failed delivery, including a marker: a paste block that was
6175
- // opened but not closed would leave the seat's composer in paste mode.
6176
- if (accepted !== Buffer.byteLength(part.data, "utf8"))
6177
- throw new EpEnvelopeError("unavailable", `input for seat "${a.name}" failed: runtime accepted ${accepted} of ${Buffer.byteLength(part.data, "utf8")} bytes of one write`);
6178
- if (part.counted)
6179
- bytes += accepted;
6180
- }
6181
- if (bytes !== intendedBytes)
6182
- throw new EpEnvelopeError("unavailable", `input for seat "${a.name}" failed: runtime accepted ${String(bytes)} of ${intendedBytes} bytes`);
6183
- return { name: a.name, bytes };
6184
- }
6185
- /** The post-authorization attach effect: mint the holder-bound §13.6 offer, redeem it
6186
- * through the ONE session plane (one-use CAS + presenter-equality), and stand up the PTY bridge —
6187
- * atomically. The reply is the SIGNED grant (no ws:// URL, non-bearer, never logged); the caller
6188
- * redeems it over the mesh with a per-session rails-only cred it mints itself. Only streamable
6189
- * backends (pty/host) attach; an external runtime's attach() throws with per-runtime guidance. */
6190
- async attachAuthorized(a, caller) {
6191
- // Every refusal before establishAttach below has opened no session, so it states that (SPEC 13.3).
6192
- if (!this.sessionPlane)
6193
- throw new EpEnvelopeError("failed-precondition", "the manager session plane is not available (the manager is not fully started)", undefined, "not-executed");
6194
- // A name is a reusable slot and the authorization above can await (user mode reads the ledger).
6195
- // The ep target is incarnation-pinned, so `a` cannot BE a successor — but the slot it names can
6196
- // have been stopped and refilled while we waited, and everything below must act on the
6197
- // incarnation this caller was actually authorized for, never on whoever holds the name now.
6198
- if (this.agents.get(a.name) !== a)
6199
- throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" was replaced during authorization - retry`, undefined, "not-executed");
6200
- // Never establish a session over a dead agent — a doomed session (the caller would get an
6201
- // immediate process-exit at best, a confusing empty terminal at worst). Refuse honestly.
6202
- if (a.handle.status() !== "running")
6203
- throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" is not running (${a.handle.status()}); nothing to attach`, undefined, "not-executed");
6204
- // CLAIM the session slot BEFORE attaching the target's PTY, matching the console door: this door
6205
- // used to attach first and check capacity inside establishAttach, so a `resource-exhausted`
6206
- // refusal landed AFTER the attach. The claim is carried INTO establishAttach, so one reservation
6207
- // spans the attach and the establishment, and it is released on every refusal below.
6208
- //
6209
- // RESIDUAL, NAMED: no shipped runtime acquires anything at attach time — pty's `attach()` returns
6210
- // a pure view (it registers a data subscriber only when `onData` is called) and tmux/cmux/orca
6211
- // throw — so an attach nobody bridges is a garbage-collectible object, not a held resource, and
6212
- // ordering alone suffices. A future runtime that DOES acquire something in `attach()` reopens
6213
- // this: it would need a release on the failure paths, and `AttachSession` has no close today.
6214
- const slot = this.sessionPlane.claimSlot();
6215
- let session;
6216
- try {
6217
- session = a.handle.attach();
6218
- }
6219
- catch (e) {
6220
- slot.release();
6221
- // The external runtimes refuse attach() before acquiring anything (see the residual above).
6222
- //
6223
- // A runtime that streams NO terminal is `unimplemented` and not a precondition: asking again
6224
- // cannot change it, and a caller that reads this as transient retries a refusal forever. The
6225
- // runtime's own throw is the guidance for watching the agent where it really runs, so it is
6226
- // carried through verbatim, and the namespaced detail lets a caller act on the one fact
6227
- // without reading the wording. This is the same answer `input` gives a runtime that cannot
6228
- // write, for the same reason.
6229
- if (!this.runtimeFor(a.handle.kind).streamsTerminal)
6230
- throw new EpEnvelopeError("unimplemented", `the ${a.handle.kind} runtime streams no terminal, so agent "${a.name}" has none to attach: ${rejectionText(e)}`, [{ kind: RUNTIME_NO_TERMINAL_DETAIL, runtime: a.handle.kind }], "not-executed");
6231
- throw new EpEnvelopeError("failed-precondition", rejectionText(e), undefined, "not-executed");
6232
- }
6233
- // establishAttach releases the claim it was handed on every exit; nothing to unwind here.
6234
- const { grant } = await this.sessionPlane.establishAttach(caller, { name: a.name, lifecycleUid: a.lifecycleUid }, session, slot);
6235
- const carried = a.launch.resumed?.host;
6236
- return { ok: true, data: { grant, ...(carried ? { resumedFrom: { host: carried, source: a.launch.resumed.source } } : {}) } };
6237
- }
6238
- /** The console's mesh §13.6 session establisher (backing `POST /session/<name>` on the
6239
- * loopback face). Drives THE ONE plane — same establishAttach as the ep `attach` command — with
6240
- * the loopback OPERATOR as holder (same-host trust boundary), then hands the browser everything it
6241
- * needs to open the caller rail over the broker ws listener: the holder-bound grant, a per-session
6242
- * RAILS-ONLY caller cred (static mints from the seed, TTL-bound to the session; an open mesh has no
6243
- * credential system so the browser connects bare), and the ws URL. NO 127.0.0.1 terminal transport
6244
- * — the terminal rides the mesh session. Injected only when a wsPort exists (see the constructor). */
6245
- async establishConsoleSession(name) {
6246
- if (!this.sessionPlane)
6247
- throw new Error("the manager session plane is not available (the manager is not fully started)");
6248
- if (this.wsPort === undefined)
6249
- throw new Error("the broker websocket port is not configured; the console cannot open a mesh session");
6250
- // CLAIM the session slot here, before the PTY attach and before this establisher goes on to
6251
- // mint a seed-signed `session-caller` credential: a capacity refusal must land before anything
6252
- // with a side effect or a cost. The claim is carried INTO establishAttach, so the reservation
6253
- // spans the whole establishment rather than being a check that a concurrent caller can race.
6254
- // (See attachAuthorized for why the attach itself needs no unwind on any shipped runtime.)
6255
- const slot = this.sessionPlane.claimSlot();
6256
- try {
6257
- const a = this.agents.get(name);
6258
- if (!a)
6259
- throw new Error(`no managed agent "${name}"`);
6260
- if (a.handle.status() !== "running")
6261
- throw new Error(`agent "${name}" is not running (${a.handle.status()}); nothing to attach`);
6262
- const session = a.handle.attach(); // throws for non-streamable runtimes — surfaced to the browser as a 500
6263
- // The loopback operator is the console's holder (same-host trust boundary).
6264
- const caller = { owner: DEV_OWNER, actor: "console", uid: this.managerLifecycleUid };
6265
- const { grant } = await this.sessionPlane.establishAttach(caller, { name: a.name, lifecycleUid: a.lifecycleUid }, session, slot);
6266
- // The caller credential is minted ONLY after a session is really live, so a refused or failed
6267
- // establishment never yields a seed-signed JWT. (A failure HERE would leave a live session the
6268
- // browser never reaches, holding its slot until the grant expires — unreachable in practice,
6269
- // because the SERVING mint above signs from this same `this.auth` first and would have failed
6270
- // before any session existed.)
6271
- const creds = this.auth
6272
- ? await mintCreds(this.auth, newIdentity(), "session-caller", {
6273
- sessionCaller: { endpoint: MANAGER_ENDPOINT, sessionId: grant.sessionId, epoch: grant.serving.epoch },
6274
- expiresAt: Math.floor(grant.exp / 1000), // grant.exp is ms (now+ttlMs); the JWT exp is seconds
6275
- })
6276
- : "";
6277
- return { grant, wsUrl: `ws://127.0.0.1:${this.wsPort}`, creds };
6278
- }
6279
- catch (e) {
6280
- slot.release(); // idempotent with establishAttach's own release
6281
- throw e;
6282
- }
6283
- }
6284
- /** Managed agents cross-referenced with live presence (the manager sees the roster).
6285
- *
6286
- * `ownerFilter`: restrict to agents whose spawn-time stored `userOwner` equals it (the ps/status
6287
- * owner-domain bound); undefined = unbounded. {@link NO_OWNER_MATCHES} matches nothing. */
6288
- list(ownerFilter) {
6289
- const roster = new Map(this.ep.getRoster().map((p) => [p.card.name, p]));
6290
- const observedAt = Date.now();
6291
- // The roster is only evidence while THIS observer's presence watch is fresh. A stale view
6292
- // (whole-bucket silence past TTL) or an unpopulated one (snapshot not yet replayed) cannot
6293
- // support "offline" or "absent" for anyone: a live deployment on 2026-09-09 rendered every live seat as
6294
- // one of those for hours after the presence stream was recreated under a still-open watch.
6295
- // Carry the view state on the row so the renderer can say "unknown" instead of a verdict.
6296
- // An endpoint that reports no view (test doubles built on `getRoster` alone) is read as
6297
- // `current`: that is exactly what every row meant before the field existed.
6298
- const view = typeof this.ep.presenceView === "function" ? this.ep.presenceView() : { state: "current" };
6299
- return [...this.agents.values()].filter((a) => ownerFilter === undefined || a.userOwner === ownerFilter).map((a) => {
6300
- // USER MODE: a detached agent's bearer-refresh death is silent everywhere except here — its
6301
- // bearer command writes each attempt's outcome to the health file, and `ps` renders it
6302
- // FAIL-CLOSED: a failed record is the failure + repair sentence; a missing/malformed or
6303
- // stale record on a live agent is auth-unknown/auth-stale, NEVER silently healthy.
6304
- const health = a.userOwner
6305
- ? agentAuthState(a.secretPaths?.health ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, a.name, a.lifecycleUid).health)
6306
- : undefined;
6307
- // The connector-reported provider from presence (#785): the live roster card's `meta.provider`,
6308
- // when it is a non-empty string. Absent when the connector reported none — never fabricated.
6309
- const seen = roster.get(a.name);
6310
- const presenceIdentityVerified = this.isOwnPresence(a, seen);
6311
- const providerMeta = seen?.card.meta?.provider;
6312
- const provider = typeof providerMeta === "string" && providerMeta ? providerMeta : undefined;
6313
- // The harness-reported condition beside the mesh status (#618): a turn that died upstream reads
6314
- // `waiting` with `rate_limit` here, not a bare `waiting`. Absent when the connector reported none.
6315
- // Projected field by field like `provider`: a malformed peer row must not fail this reply's schema.
6316
- const reported = roster.get(a.name)?.condition;
6317
- const condition = reported && typeof reported.code === "string" && reported.code
6318
- ? {
6319
- code: reported.code,
6320
- ...(typeof reported.source === "string" ? { source: reported.source } : {}),
6321
- ...(typeof reported.message === "string" ? { message: reported.message } : {}),
6322
- ...(typeof reported.since === "number" && Number.isFinite(reported.since) ? { since: reported.since } : {}),
6323
- }
6324
- : undefined;
6325
- // The seat's last harness-reported work progress (#618). `ts` is only its heartbeat, so a turn
6326
- // that stopped advancing reads as an old `activeAt` beside a live process. Absent when none was reported.
6327
- const activeAtReported = roster.get(a.name)?.activeAt;
6328
- const activeAt = typeof activeAtReported === "number" && Number.isFinite(activeAtReported) ? activeAtReported : undefined;
6329
- // How long an offline verdict has stood (#1208): the seat's last heartbeat before it went
6330
- // offline. Only beside a verdict, since a stale or unpopulated view dates nothing, only from the
6331
- // seat's own record, since `seen` is matched by name and a same-named foreign peer or an older
6332
- // incarnation must not date this seat, and only when the seat's unvalidated `ts` fits the row
6333
- // schema, so one odd record cannot fail the reply.
6334
- const offlineSince = view.state === "current" && this.isOwnPresence(a, seen) && seen.status === "offline" && Number.isSafeInteger(seen.ts) && seen.ts >= 0
6335
- ? seen.ts
6336
- : undefined;
6337
- return {
6338
- name: a.name,
6339
- // The spawned agent's id (nkey, or the user-mode principal) — lets an operator tool (e.g.
6340
- // `cotal down -f`) match a ledger entry by name AND id before stopping, so it never stops a
6341
- // same-named foreign agent.
6342
- id: a.id,
6343
- role: a.role,
6344
- agent: a.agent,
6345
- space: this.space,
6346
- mode: a.handle.kind,
6347
- status: a.handle.status(),
6348
- uptimeMs: Date.now() - a.startedAt,
6349
- mesh: seen?.status ?? "absent",
6350
- ...(a.joinIssue ? { joinHealth: { state: "degraded", reason: a.joinIssue } } : {}),
6351
- ...(condition ? { condition } : {}),
6352
- ...(a.startupNotice !== undefined ? { startupNotice: a.startupNotice } : {}),
6353
- ...(activeAt !== undefined ? { activeAt } : {}),
6354
- // `current` is the only state in which `mesh` is a verdict; the other two are the
6355
- // observer's own condition and travel on the row (older CLIs ignore the field).
6356
- meshView: view.state,
6357
- presenceIdentityVerified,
6358
- ...(view.state === "current" && presenceIdentityVerified ? { presenceObservedAt: observedAt } : {}),
6359
- ...(offlineSince !== undefined ? { offlineSince } : {}),
6360
- // The incarnation coordinate (SPEC 13.1) — with `id`, exactly what a v0.4 caller needs to
6361
- // build a targeted (`despawn`/`attach`) request against THIS incarnation.
6362
- lifecycleUid: a.lifecycleUid,
6363
- // #651 enrichment: per-seat facts the manager ALREADY holds, carried on the row so `ps
6364
- // --wide`/`--json` can surface them without a new collection path. All optional in the row
6365
- // schema: a fact this backend did not record serializes absent, never fabricated (the
6366
- // pid is absent on runtimes that do not own a real process; a launch may pin no model).
6367
- model: a.launch.model,
6368
- variant: a.launch.variant,
6369
- ...(provider ? { provider } : {}),
6370
- cwd: a.launch.cwd,
6371
- pid: a.handle.pid,
6372
- spawner: a.spawner,
6373
- instanceId: this.managerInstanceId,
6374
- host: hostname(),
6375
- // #1500: the session a `--resume` seat forked, with its title and transcript hash once the
6376
- // seat has recorded them.
6377
- ...(a.launch.forkSource ? { resume: this.forkProvenance(a) ?? { source: a.launch.forkSource } } : {}),
6378
- ...(health && health.state !== "ok" ? { authHealth: health.state, authReason: health.reason } : {}),
6379
- };
6380
- });
6381
- }
3951
+ /** {@link PersonaCatalog.opDefinePersona}. */
3952
+ opDefinePersona(...args) { return this.personaCatalogComponent.opDefinePersona(...args); }
3953
+ /** {@link PersonaCatalog.opRemovePersona}. */
3954
+ opRemovePersona(...args) { return this.personaCatalogComponent.opRemovePersona(...args); }
3955
+ /** {@link PersonaCatalog.personaOwner}. */
3956
+ personaOwner(...args) { return this.personaCatalogComponent.personaOwner(...args); }
3957
+ /** {@link PersonaCatalog.canReadPersona}. */
3958
+ canReadPersona(...args) { return this.personaCatalogComponent.canReadPersona(...args); }
3959
+ /** {@link PersonaCatalog.opListPersonas}. */
3960
+ opListPersonas(...args) { return this.personaCatalogComponent.opListPersonas(...args); }
3961
+ /** {@link PersonaCatalog.opShowPersona}. */
3962
+ opShowPersona(...args) { return this.personaCatalogComponent.opShowPersona(...args); }
3963
+ /** {@link TerminalInput.inputAuthorized}. */
3964
+ inputAuthorized(...args) { return this.terminalInputComponent.inputAuthorized(...args); }
3965
+ /** {@link TerminalInput.attachAuthorized}. */
3966
+ attachAuthorized(...args) { return this.terminalInputComponent.attachAuthorized(...args); }
3967
+ /** {@link TerminalInput.establishConsoleSession}. */
3968
+ establishConsoleSession(...args) { return this.terminalInputComponent.establishConsoleSession(...args); }
3969
+ /** {@link StatusAndModels.list}. */
3970
+ list(...args) { return this.statusAndModelsComponent.list(...args); }
6382
3971
  }
6383
3972
  //# sourceMappingURL=manager.js.map