@cotal-ai/manager 0.171.2 → 0.171.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.js CHANGED
@@ -5,9 +5,8 @@ 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
8
  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";
9
+ import { CotalEndpoint, copyPersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, injectedSecretStoreIdentity, dialerFor, connectorServers, spawnEnvAllow, idFromCreds, identityFromCreds, inspectCredHealth, loadAgentFile, loadCotalConfig, mintCreds, bindIssuedStores, mintLifecycleUid, newIdentity, oneLine, parsePrincipalKey, principalKey, probeConnect, registry, resolveAuthProvider, } from "@cotal-ai/core";
11
10
  import { retainConnectorSeat } from "@cotal-ai/workspace";
12
11
  import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
13
12
  import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
@@ -27,13 +26,18 @@ import { SessionRecovery } from "./session-recovery.js";
27
26
  import { SeatCustody, watchConnectorHolder } from "./seat-custody.js";
28
27
  import { GoalWriter } from "./goal-writer.js";
29
28
  import { DEPROVISION_TIMEOUT_MS, SeatStop } from "./seat-stop.js";
29
+ import { CommandDispatch, participantKey } from "./command-dispatch.js";
30
+ import { SpawnGoal } from "./spawn-goal.js";
31
+ import { PersonaCatalog } from "./persona-catalog.js";
32
+ import { TerminalInput } from "./terminal-input.js";
33
+ export { PASTE_END, PASTE_START, RUNTIME_NO_TERMINAL_DETAIL } from "./terminal-input.js";
30
34
  import { CredentialRenewal, credRenewIntervalMs, REMOTE_STANDING_BUDGET_MS, remoteStandingTimeLeft, sameStrings } from "./credential-renewal.js";
31
- import { SeatLaunch, foreignEventChannels, userMeshEndpointsRefusal } from "./seat-launch.js";
35
+ import { SeatLaunch, foreignEventChannels } from "./seat-launch.js";
32
36
  import { withTimeout } from "./manager-timeout.js";
33
37
  import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
34
38
  import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, parseLaunchSpec, persistLaunchSpec } from "./launch.js";
35
39
  import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
36
- import { RunHosting, servedRequestSubject } from "./run-hosting.js";
40
+ import { RunHosting } from "./run-hosting.js";
37
41
  import { rejectionText, attemptCleanup } from "@cotal-ai/core";
38
42
  import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs, readReleasedSeatReference, readSeatRecord, writeReleasedSeatReference, writeSeatRecord } from "./resume.js";
39
43
  import { TranscriptReceiver } from "./transcript-receive.js";
@@ -49,10 +53,9 @@ import { ManagerSessionPlane } from "./session/index.js";
49
53
  // The manager as an ordinary v0.4 `service` endpoint — the §13.1
50
54
  // endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
51
55
  // 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
+ import { epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, listGoalIndex, MAX_SCHEDULE_MS, turnNoticeSubject, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom } from "@cotal-ai/core";
57
+ import { MANAGER_ENDPOINT } from "./manager-service-contract.js";
58
+ import { staticLifecycleTransport, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, } from "./static-lifecycle.js";
56
59
  // Capture the loaded package version before an installation can replace its files.
57
60
  const MANAGER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
58
61
  /** A `once` spawn's task deadline when the caller names none: one hour from the spawn's accept. */
@@ -100,23 +103,6 @@ const PRESERVE_STOP_TIMEOUT_MS = 10_000;
100
103
  /** How long a resume waits for a reaped orphan's principal to leave presence. Presence rows age
101
104
  * out after their 6s TTL, so three TTLs covers a killed seat that never published its leave. */
102
105
  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
106
  /** Startup reconciliation overlaps control-service registration. A spawn or attach for one of
121
107
  * these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
122
108
  * a reuse. */
@@ -151,24 +137,6 @@ function openMeshFrozenGateRefusal(e, instanceId) {
151
137
  return e;
152
138
  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
139
  }
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
140
  /** The start of every agent's bearer command: node, its loader flags and this manager's entry,
173
141
  * resolved through every symlink. The agent runs that command for each renewal for as long as it
174
142
  * lives, and an install can replace the bin link meanwhile: get.cotal.ai writes a shell launcher
@@ -177,9 +145,6 @@ function bearerEntryArgv() {
177
145
  return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
178
146
  }
179
147
  const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
180
- function participantKey(owner, actor, uid) {
181
- return `${owner}.${actor}.${uid}`;
182
- }
183
148
  /** One connector's declared harness binaries resolved on PATH now. The refusal sentence is built only
184
149
  * here, so the boot row and the check for a connector registered after boot can never word it apart. */
185
150
  function resolveHarness(name, requires) {
@@ -769,6 +734,115 @@ export class Manager {
769
734
  shredUserSecrets: (...args) => this.shredUserSecrets(...args),
770
735
  trackDeprovision: (...args) => this.trackDeprovision(...args),
771
736
  });
737
+ /** The typed command table and its admission. Every dependency reads through at its use. */
738
+ commandDispatch = new CommandDispatch({
739
+ agents: () => this.agents,
740
+ auth: () => this.auth,
741
+ execution: () => this.execution,
742
+ goalWriter: () => this.goalWriter,
743
+ managerInstanceId: () => this.managerInstanceId,
744
+ participants: () => this.participants,
745
+ remoteAuthority: () => this.remoteAuthority,
746
+ resumeRequired: () => this.resumeRequired,
747
+ runHosting: () => this.runHosting,
748
+ space: () => this.space,
749
+ transcripts: () => this.transcripts,
750
+ userMode: () => this.userMode,
751
+ workspaceRoot: () => this.workspaceRoot,
752
+ attachAuthorized: (...args) => this.attachAuthorized(...args),
753
+ authorizeNamed: (...args) => this.authorizeNamed(...args),
754
+ authorizeRunAmend: (...args) => this.authorizeRunAmend(...args),
755
+ authorizeRunAnswer: (...args) => this.authorizeRunAnswer(...args),
756
+ beginLifecycle: (...args) => this.beginLifecycle(...args),
757
+ despawnAuthorized: (...args) => this.despawnAuthorized(...args),
758
+ executionRefusal: (...args) => this.executionRefusal(...args),
759
+ findManagedByTarget: (...args) => this.findManagedByTarget(...args),
760
+ inputAuthorized: (...args) => this.inputAuthorized(...args),
761
+ lifecycleMembershipRefusal: (...args) => this.lifecycleMembershipRefusal(...args),
762
+ list: (...args) => this.list(...args),
763
+ listSpawnDirectory: (...args) => this.listSpawnDirectory(...args),
764
+ loggedSpawnRefusal: (ctx, fn) => this.loggedSpawnRefusal(ctx, fn),
765
+ maintenanceError: (...args) => this.maintenanceError(...args),
766
+ managedPrincipal: (...args) => this.managedPrincipal(...args),
767
+ managerStatusData: (...args) => this.managerStatusData(...args),
768
+ opCommitResume: (...args) => this.opCommitResume(...args),
769
+ opDefinePersona: (...args) => this.opDefinePersona(...args),
770
+ opFinalizeResume: (...args) => this.opFinalizeResume(...args),
771
+ opLaunch: (...args) => this.opLaunch(...args),
772
+ opListPersonas: (...args) => this.opListPersonas(...args),
773
+ opModels: (...args) => this.opModels(...args),
774
+ opPreservationCtl: (...args) => this.opPreservationCtl(...args),
775
+ opPurge: (...args) => this.opPurge(...args),
776
+ opRemovePersona: (...args) => this.opRemovePersona(...args),
777
+ opResumePreserved: (...args) => this.opResumePreserved(...args),
778
+ opShowPersona: (...args) => this.opShowPersona(...args),
779
+ opStart: (...args) => this.opStart(...args),
780
+ openStaticChatSession: (...args) => this.openStaticChatSession(...args),
781
+ psOwnerFilter: (...args) => this.psOwnerFilter(...args),
782
+ resolveSpawnCwd: (...args) => this.resolveSpawnCwd(...args),
783
+ retireStaticChatSession: (...args) => this.retireStaticChatSession(...args),
784
+ runAnswerer: (...args) => this.runAnswerer(...args),
785
+ runHost: (...args) => this.runHost(...args),
786
+ serveGated: (ctx, fn) => this.serveGated(ctx, fn),
787
+ serveObservation: (ctx, fn) => this.serveObservation(ctx, fn),
788
+ serveSpawnGoal: (...args) => this.serveSpawnGoal(...args),
789
+ serveTurnCancel: (...args) => this.serveTurnCancel(...args),
790
+ serveTurnGoal: (...args) => this.serveTurnGoal(...args),
791
+ serveTurnParticipation: (...args) => this.serveTurnParticipation(...args),
792
+ serveTurnUnconfirmed: (...args) => this.serveTurnUnconfirmed(...args),
793
+ serveTurnYield: (...args) => this.serveTurnYield(...args),
794
+ spawnPersona: (...args) => this.spawnPersona(...args),
795
+ stopHandle: (...args) => this.stopHandle(...args),
796
+ stopWindowsSeat: (...args) => this.stopWindowsSeat(...args),
797
+ trackStoppedHandle: (...args) => this.trackStoppedHandle(...args),
798
+ turnPendingFor: (...args) => this.turnPendingFor(...args),
799
+ turnTarget: (...args) => this.turnTarget(...args),
800
+ });
801
+ /** The spawn and launch goal path. Every dependency reads through at its use. */
802
+ spawnGoalComponent = new SpawnGoal({
803
+ agentGoals: () => this.agentGoals,
804
+ execution: () => this.execution,
805
+ goalAcceptanceRetentionMs: () => this.goalAcceptanceRetentionMs,
806
+ goalAcceptances: () => this.goalAcceptances,
807
+ goalReconcileDone: () => this.goalReconcileDone,
808
+ goalWriter: () => this.goalWriter,
809
+ managerInstanceId: () => this.managerInstanceId,
810
+ onceWatched: () => this.onceWatched,
811
+ readinessTimeoutMs: () => this.readinessTimeoutMs,
812
+ serviceServe: () => this.serviceServe,
813
+ userMode: () => this.userMode,
814
+ acceptOnceTurn: (...args) => this.acceptOnceTurn(...args),
815
+ assertGoalWriterEpochCurrent: (...args) => this.assertGoalWriterEpochCurrent(...args),
816
+ commitOnceCancel: (...args) => this.commitOnceCancel(...args),
817
+ emitGoalProgress: (...args) => this.emitGoalProgress(...args),
818
+ executionRefusal: (...args) => this.executionRefusal(...args),
819
+ settleOnceTurn: (...args) => this.settleOnceTurn(...args),
820
+ });
821
+ /** The persona catalog doors. Every dependency reads through at its use. */
822
+ personaCatalogComponent = new PersonaCatalog({
823
+ agents: () => this.agents,
824
+ execution: () => this.execution,
825
+ meshMode: () => this.meshMode,
826
+ remoteAuthority: () => this.remoteAuthority,
827
+ space: () => this.space,
828
+ userMode: () => this.userMode,
829
+ workspaceRoot: () => this.workspaceRoot,
830
+ executionRefusal: (...args) => this.executionRefusal(...args),
831
+ managedPrincipal: (...args) => this.managedPrincipal(...args),
832
+ nameError: (...args) => this.nameError(...args),
833
+ spawnBoundRefusal: (...args) => this.spawnBoundRefusal(...args),
834
+ spawnRun: (...args) => this.spawnRun(...args),
835
+ staticSpawnBound: (...args) => this.staticSpawnBound(...args),
836
+ });
837
+ /** Seat terminal input and attach sessions. Every dependency reads through at its use. */
838
+ terminalInputComponent = new TerminalInput({
839
+ agents: () => this.agents,
840
+ auth: () => this.auth,
841
+ managerLifecycleUid: () => this.managerLifecycleUid,
842
+ sessionPlane: () => this.sessionPlane,
843
+ wsPort: () => this.wsPort,
844
+ runtimeFor: (...args) => this.runtimeFor(...args),
845
+ });
772
846
  /** The goal-writer connection and the goal index it reconciles. Every dependency reads through at its use. */
773
847
  goalWriterComponent = new GoalWriter({
774
848
  auth: () => this.auth,
@@ -2668,25 +2742,8 @@ export class Manager {
2668
2742
  return { ok: false, error: rejectionText(e) };
2669
2743
  }
2670
2744
  }
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
- }
2745
+ /** {@link CommandDispatch.admitControl}. */
2746
+ admitControl(...args) { return this.commandDispatch.admitControl(...args); }
2690
2747
  /** Run one v0.4 service-command handler through the SHARED admission chokepoint
2691
2748
  * ({@link admitControl}) on the broker-authenticated caller principal, mapping the two fences
2692
2749
  * onto the §13.3 catalog: maintenance/resume → `unavailable`, membership →
@@ -2727,54 +2784,8 @@ export class Manager {
2727
2784
  this.releaseLifecycle();
2728
2785
  }
2729
2786
  }
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
- }
2787
+ /** {@link CommandDispatch.epAdminReach}. */
2788
+ epAdminReach(...args) { return this.commandDispatch.epAdminReach(...args); }
2778
2789
  /** The run host, or one of three refusals. A remote-authority manager holds no space signer, so
2779
2790
  * it cannot mint the per-run driver credential SPEC 14.6 requires without all four closed
2780
2791
  * host callbacks. A local user-auth mesh is `unimplemented`: a hosted run's seats
@@ -2919,310 +2930,8 @@ export class Manager {
2919
2930
  if (accepted.by !== agent.name)
2920
2931
  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
2932
  }
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
- }
2933
+ /** {@link CommandDispatch.managerServiceDefs}. */
2934
+ managerServiceDefs(...args) { return this.commandDispatch.managerServiceDefs(...args); }
3226
2935
  async commitResumeActivation(attemptId) {
3227
2936
  if (!this.resumeAwaitingCommit || !this.resumeResult?.ok)
3228
2937
  return { ok: false, error: `resume attempt ${attemptId} has no successful activation to commit` };
@@ -3343,25 +3052,8 @@ export class Manager {
3343
3052
  }
3344
3053
  return inactive;
3345
3054
  }
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
- }
3055
+ /** {@link CommandDispatch.opStopSelf}. */
3056
+ opStopSelf(...args) { return this.commandDispatch.opStopSelf(...args); }
3365
3057
  // Plane-3 durable join/leave/list ops moved OFF the manager onto the server-side delivery daemon's
3366
3058
  // `ctl.delivery` control service (endpoint.startPlane3 → handleDeliveryControl). The manager is
3367
3059
  // lifecycle-only; it records each agent's read ACL at spawn (commitAcl) so the daemon can validate
@@ -5177,315 +4869,12 @@ export class Manager {
5177
4869
  emitGoalProgress(...args) { return this.goalWriterComponent.emitGoalProgress(...args); }
5178
4870
  /** {@link GoalWriter.assertGoalWriterEpochCurrent}. */
5179
4871
  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
- }
4872
+ /** {@link SpawnGoal.loggedSpawnRefusal}. */
4873
+ loggedSpawnRefusal(ctx, serve) { return this.spawnGoalComponent.loggedSpawnRefusal(ctx, serve); }
4874
+ /** {@link SpawnGoal.serveSpawnGoal}. */
4875
+ serveSpawnGoal(...args) { return this.spawnGoalComponent.serveSpawnGoal(...args); }
4876
+ /** {@link SpawnGoal.expireGoalAcceptance}. */
4877
+ expireGoalAcceptance(...args) { return this.spawnGoalComponent.expireGoalAcceptance(...args); }
5489
4878
  // ---- the turn relay (§8 durable actions) ------------------------------------------------------
5490
4879
  //
5491
4880
  // A seat is NOT an endpoint: a run's `turn(agent, payload)` rides the manager, which accepts it
@@ -5756,531 +5145,24 @@ export class Manager {
5756
5145
  }
5757
5146
  /** {@link SeatStop.opPurge}. */
5758
5147
  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
- }
5148
+ /** {@link PersonaCatalog.opDefinePersona}. */
5149
+ opDefinePersona(...args) { return this.personaCatalogComponent.opDefinePersona(...args); }
5150
+ /** {@link PersonaCatalog.opRemovePersona}. */
5151
+ opRemovePersona(...args) { return this.personaCatalogComponent.opRemovePersona(...args); }
5152
+ /** {@link PersonaCatalog.personaOwner}. */
5153
+ personaOwner(...args) { return this.personaCatalogComponent.personaOwner(...args); }
5154
+ /** {@link PersonaCatalog.canReadPersona}. */
5155
+ canReadPersona(...args) { return this.personaCatalogComponent.canReadPersona(...args); }
5156
+ /** {@link PersonaCatalog.opListPersonas}. */
5157
+ opListPersonas(...args) { return this.personaCatalogComponent.opListPersonas(...args); }
5158
+ /** {@link PersonaCatalog.opShowPersona}. */
5159
+ opShowPersona(...args) { return this.personaCatalogComponent.opShowPersona(...args); }
5160
+ /** {@link TerminalInput.inputAuthorized}. */
5161
+ inputAuthorized(...args) { return this.terminalInputComponent.inputAuthorized(...args); }
5162
+ /** {@link TerminalInput.attachAuthorized}. */
5163
+ attachAuthorized(...args) { return this.terminalInputComponent.attachAuthorized(...args); }
5164
+ /** {@link TerminalInput.establishConsoleSession}. */
5165
+ establishConsoleSession(...args) { return this.terminalInputComponent.establishConsoleSession(...args); }
6284
5166
  /** Managed agents cross-referenced with live presence (the manager sees the roster).
6285
5167
  *
6286
5168
  * `ownerFilter`: restrict to agents whose spawn-time stored `userOwner` equals it (the ps/status