@cotal-ai/manager 0.171.1 → 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/command-dispatch.d.ts +206 -0
- package/dist/command-dispatch.d.ts.map +1 -0
- package/dist/command-dispatch.js +471 -0
- package/dist/command-dispatch.js.map +1 -0
- package/dist/manager.d.ts +48 -283
- package/dist/manager.d.ts.map +1 -1
- package/dist/manager.js +230 -1775
- package/dist/manager.js.map +1 -1
- package/dist/persona-catalog.d.ts +86 -0
- package/dist/persona-catalog.d.ts.map +1 -0
- package/dist/persona-catalog.js +325 -0
- package/dist/persona-catalog.js.map +1 -0
- package/dist/run-hosting.d.ts +5 -2
- package/dist/run-hosting.d.ts.map +1 -1
- package/dist/run-hosting.js +55 -16
- package/dist/run-hosting.js.map +1 -1
- package/dist/runtime/index.d.ts +2 -0
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +22 -0
- package/dist/runtime/index.js.map +1 -1
- package/dist/seat-launch.d.ts +1 -1
- package/dist/seat-launch.d.ts.map +1 -1
- package/dist/seat-launch.js +4 -2
- package/dist/seat-launch.js.map +1 -1
- package/dist/seat-stop.d.ts +232 -0
- package/dist/seat-stop.d.ts.map +1 -0
- package/dist/seat-stop.js +552 -0
- package/dist/seat-stop.js.map +1 -0
- package/dist/service-adapter.d.ts.map +1 -1
- package/dist/service-adapter.js +14 -5
- package/dist/service-adapter.js.map +1 -1
- package/dist/spawn-goal.d.ts +77 -0
- package/dist/spawn-goal.d.ts.map +1 -0
- package/dist/spawn-goal.js +357 -0
- package/dist/spawn-goal.js.map +1 -0
- package/dist/terminal-input.d.ts +82 -0
- package/dist/terminal-input.d.ts.map +1 -0
- package/dist/terminal-input.js +266 -0
- package/dist/terminal-input.js.map +1 -0
- package/package.json +12 -12
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,
|
|
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";
|
|
@@ -26,15 +25,20 @@ export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
|
|
|
26
25
|
import { SessionRecovery } from "./session-recovery.js";
|
|
27
26
|
import { SeatCustody, watchConnectorHolder } from "./seat-custody.js";
|
|
28
27
|
import { GoalWriter } from "./goal-writer.js";
|
|
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";
|
|
29
34
|
import { CredentialRenewal, credRenewIntervalMs, REMOTE_STANDING_BUDGET_MS, remoteStandingTimeLeft, sameStrings } from "./credential-renewal.js";
|
|
30
|
-
import { SeatLaunch, foreignEventChannels
|
|
35
|
+
import { SeatLaunch, foreignEventChannels } from "./seat-launch.js";
|
|
31
36
|
import { withTimeout } from "./manager-timeout.js";
|
|
32
37
|
import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
|
|
33
|
-
import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts,
|
|
38
|
+
import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, parseLaunchSpec, persistLaunchSpec } from "./launch.js";
|
|
34
39
|
import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import { rejectionText, attemptCleanup, describeCleanupFailures } from "@cotal-ai/core";
|
|
40
|
+
import { RunHosting } from "./run-hosting.js";
|
|
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";
|
|
40
44
|
// The static §13.1 lifecycle executor: the shared grammar/stores from core plus the
|
|
@@ -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,
|
|
53
|
-
import { MANAGER_ENDPOINT
|
|
54
|
-
import {
|
|
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. */
|
|
@@ -85,11 +88,6 @@ const LATE_JOIN_POLL_MS = 1_000;
|
|
|
85
88
|
* must run without exiting before it is ready: long enough that a harness refusing its arguments
|
|
86
89
|
* exits first and is reported as failed. */
|
|
87
90
|
const OPERATOR_READINESS_MS = 3_000;
|
|
88
|
-
/** Upper bound on a detached agent-exit deprovision (#159 B2). A wedged broker must not leave the
|
|
89
|
-
* fire-and-forget teardown pending forever with no log — past this it rejects into freeSlot's fail-loud
|
|
90
|
-
* `.catch`. Generous over the helper's 5s connect timeout to allow the two consumer-deletes + ACL purge
|
|
91
|
-
* + drain on a healthy-but-slow broker. */
|
|
92
|
-
const DEPROVISION_TIMEOUT_MS = 15_000;
|
|
93
91
|
/** At most this many retirements run at once (#4965). A retirement dials up to four fresh broker
|
|
94
92
|
* connections in turn and queues an eviction and an inventory on the delivery daemon's admin rail,
|
|
95
93
|
* each against a fixed deadline. A stop that started all 50 seats' retirements together lost most of
|
|
@@ -105,23 +103,6 @@ const PRESERVE_STOP_TIMEOUT_MS = 10_000;
|
|
|
105
103
|
/** How long a resume waits for a reaped orphan's principal to leave presence. Presence rows age
|
|
106
104
|
* out after their 6s TTL, so three TTLs covers a killed seat that never published its leave. */
|
|
107
105
|
const ORPHAN_PRESENCE_CLEAR_MS = 20_000;
|
|
108
|
-
/** How much of an `input` text is written to a seat's pty at a time. Comfortably under the 4096-byte
|
|
109
|
-
* kernel input buffer, so a slice is never re-split at a boundary the manager did not choose: the
|
|
110
|
-
* tail of an oversized write stays queued and swallows the submit key that follows it (issue #1649).
|
|
111
|
-
* Sized in CHARS against a byte buffer on purpose — a multi-byte character can only make a slice
|
|
112
|
-
* shorter in characters than in bytes, never longer, so the margin cannot be eaten from below. */
|
|
113
|
-
const INPUT_SLICE_CHARS = 2048;
|
|
114
|
-
/** Bracketed-paste delimiters (DECSET 2004). `input` wraps a seat's text in these so the return it
|
|
115
|
-
* writes afterwards is a KEYSTROKE rather than the newline trailing a pasted block: a TUI that
|
|
116
|
-
* classifies a fast burst as a paste consumes that trailing newline and the text sits unsubmitted
|
|
117
|
-
* in the composer until the next call's return (issue #1649). Framing, never content - these bytes
|
|
118
|
-
* are not counted into the receipt, so `bytes` still reports what the caller asked to deliver. */
|
|
119
|
-
export const PASTE_START = "\x1b[200~";
|
|
120
|
-
export const PASTE_END = "\x1b[201~";
|
|
121
|
-
/** `details[].kind` on an `attach` refusal raised because the seat's runtime opens no terminal
|
|
122
|
-
* stream. The message carries that runtime's own guidance, which is operator copy and changes; this
|
|
123
|
-
* marker is the contract a caller keys on so it can act without reading the wording. */
|
|
124
|
-
export const RUNTIME_NO_TERMINAL_DETAIL = "ai.cotal.manager.runtime-no-terminal";
|
|
125
106
|
/** Startup reconciliation overlaps control-service registration. A spawn or attach for one of
|
|
126
107
|
* these aliases must wait until THAT alias's exact-op terminal attempt returns rather than racing
|
|
127
108
|
* a reuse. */
|
|
@@ -156,24 +137,6 @@ function openMeshFrozenGateRefusal(e, instanceId) {
|
|
|
156
137
|
return e;
|
|
157
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);
|
|
158
139
|
}
|
|
159
|
-
/** The failed terminal a post-accept fallback commits for `error` and `source`'s optional details.
|
|
160
|
-
* `commitGoalResult` refuses a payload that is not interchangeable JSON, and this terminal must commit
|
|
161
|
-
* whatever failed, so a lone surrogate in the text becomes U+FFFD and details it cannot read or carry
|
|
162
|
-
* (a Proxy's throwing getter, an accessor, a cycle) are dropped. A Proxy can answer the check and the
|
|
163
|
-
* serializer differently, so the detached copy is checked again before it commits. */
|
|
164
|
-
function failedTerminal(error, source) {
|
|
165
|
-
const text = error.replace(/\p{Cs}/gu, "\uFFFD");
|
|
166
|
-
try {
|
|
167
|
-
const details = source?.details;
|
|
168
|
-
if (details) {
|
|
169
|
-
const copy = JSON.parse(canonicalJson(details));
|
|
170
|
-
canonicalJson(copy);
|
|
171
|
-
return { error: text, details: copy };
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
catch { /* unreadable or not interchangeable */ }
|
|
175
|
-
return { error: text };
|
|
176
|
-
}
|
|
177
140
|
/** The start of every agent's bearer command: node, its loader flags and this manager's entry,
|
|
178
141
|
* resolved through every symlink. The agent runs that command for each renewal for as long as it
|
|
179
142
|
* lives, and an install can replace the bin link meanwhile: get.cotal.ai writes a shell launcher
|
|
@@ -181,54 +144,7 @@ function failedTerminal(error, source) {
|
|
|
181
144
|
function bearerEntryArgv() {
|
|
182
145
|
return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
|
|
183
146
|
}
|
|
184
|
-
/** Operator-facing phrasing per cause. Kept beside the union so adding a member without a sentence
|
|
185
|
-
* is a type error rather than a blank in the log. The stop family's sentences carry the principal
|
|
186
|
-
* from the cause, so they render through {@link STOP_CAUSE_TEXT} under the same exhaustive-Record
|
|
187
|
-
* discipline: a new stop kind without a renderer is a type error too. */
|
|
188
|
-
const FREE_SLOT_CAUSE_TEXT = {
|
|
189
|
-
"process-exit": "its own process exited and this manager did not stop it",
|
|
190
|
-
"pi-crash-loop": "this manager retired it after a Pi crash loop",
|
|
191
|
-
"pi-recovery-failed": "this manager retired it after Pi session recovery failed",
|
|
192
|
-
"supervise-crash-loop": "this manager retired it after its supervise restart budget was spent",
|
|
193
|
-
"supervise-recovery-failed": "this manager retired it after a supervised restart failed",
|
|
194
|
-
"session-bind-failed": "this manager stopped it: its host session could not be bound at launch",
|
|
195
|
-
"resume-session-rebind-failed": "this manager stopped it: its host session could not be rebound on resume",
|
|
196
|
-
"carried-fork-refused": "this manager stopped it: it recorded no fork of the carried transcript",
|
|
197
|
-
"resume-custody-unrecorded": "this manager stopped it: its custody reference could not be recorded on resume",
|
|
198
|
-
"supervise-record-failed": "this manager stopped it: its supervise policy could not be recorded for a manager restart",
|
|
199
|
-
"inline-snapshot-changed": "this manager retired it instead of restarting it: its inline persona snapshot changed after launch",
|
|
200
|
-
};
|
|
201
|
-
/** The stop family's sentences — the same job {@link FREE_SLOT_CAUSE_TEXT} does for the string
|
|
202
|
-
* causes, beside it so both stay the single place a cause becomes a sentence. A requested stop's
|
|
203
|
-
* sentence embeds the authenticated principal and a recursive reap's embeds the parent that
|
|
204
|
-
* left, so they cannot sit in a static Record keyed by kind; this exhaustive switch is their
|
|
205
|
-
* single home, and the `satisfies never` default keeps the discipline: a new stop kind without a
|
|
206
|
-
* sentence is a type error rather than a blank in the log. */
|
|
207
|
-
function stopCauseText(cause) {
|
|
208
|
-
switch (cause.kind) {
|
|
209
|
-
case "stopped-requested": return `this manager stopped it at ${cause.requester}'s request`;
|
|
210
|
-
case "stopped-self": return "it stopped itself (self-stop)";
|
|
211
|
-
case "stopped-reap": return `this manager stopped it because its parent ${cause.parent} left (recursive reap)`;
|
|
212
|
-
case "stopped-shutdown": return "this manager stopped it on manager shutdown";
|
|
213
|
-
case "stopped-once": return `this manager stopped it: its once task ended (${cause.reason})`;
|
|
214
|
-
default: return cause;
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
/** The reason a once task is cancelled with when a stop of this kind ends its seat first. */
|
|
218
|
-
function onceStopReason(cause) {
|
|
219
|
-
switch (cause.kind) {
|
|
220
|
-
case "stopped-requested": return "despawned";
|
|
221
|
-
case "stopped-self": return "stopped-itself";
|
|
222
|
-
case "stopped-reap": return "parent-left";
|
|
223
|
-
case "stopped-shutdown": return "manager-shutdown";
|
|
224
|
-
case "stopped-once": return cause.reason;
|
|
225
|
-
default: return cause;
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
147
|
const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
|
|
229
|
-
function participantKey(owner, actor, uid) {
|
|
230
|
-
return `${owner}.${actor}.${uid}`;
|
|
231
|
-
}
|
|
232
148
|
/** One connector's declared harness binaries resolved on PATH now. The refusal sentence is built only
|
|
233
149
|
* here, so the boot row and the check for a connector registered after boot can never word it apart. */
|
|
234
150
|
function resolveHarness(name, requires) {
|
|
@@ -781,6 +697,152 @@ export class Manager {
|
|
|
781
697
|
shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
|
|
782
698
|
bearerEntryArgv,
|
|
783
699
|
});
|
|
700
|
+
/** Seat stop, exit, recursive reap and named despawn. Every dependency reads through at its use. */
|
|
701
|
+
seatStopComponent = new SeatStop({
|
|
702
|
+
agentGoals: () => this.agentGoals,
|
|
703
|
+
agents: () => this.agents,
|
|
704
|
+
auth: () => this.auth,
|
|
705
|
+
ep: () => this.ep,
|
|
706
|
+
execution: () => this.execution,
|
|
707
|
+
goalWriter: () => this.goalWriter,
|
|
708
|
+
lifecycleInFlight: () => this.lifecycleInFlight,
|
|
709
|
+
setLifecycleInFlight: (value) => { this.lifecycleInFlight = value; },
|
|
710
|
+
maintenanceState: () => this.maintenanceState,
|
|
711
|
+
managerInstanceId: () => this.managerInstanceId,
|
|
712
|
+
remoteAuthority: () => this.remoteAuthority,
|
|
713
|
+
retirement: () => this.retirement,
|
|
714
|
+
servers: () => this.servers,
|
|
715
|
+
serviceServe: () => this.serviceServe,
|
|
716
|
+
space: () => this.space,
|
|
717
|
+
unverifiedStops: () => this.unverifiedStops,
|
|
718
|
+
setUnverifiedStops: (value) => { this.unverifiedStops = value; },
|
|
719
|
+
workspaceRoot: () => this.workspaceRoot,
|
|
720
|
+
assertGoalWriterEpochCurrent: (...args) => this.assertGoalWriterEpochCurrent(...args),
|
|
721
|
+
authorizeNamed: (...args) => this.authorizeNamed(...args),
|
|
722
|
+
awaitHandleExit: (...args) => this.awaitHandleExit(...args),
|
|
723
|
+
beginLifecycle: (...args) => this.beginLifecycle(...args),
|
|
724
|
+
confirmRetirement: (...args) => this.confirmRetirement(...args),
|
|
725
|
+
emitGoalProgress: (...args) => this.emitGoalProgress(...args),
|
|
726
|
+
executionRefusal: (...args) => this.executionRefusal(...args),
|
|
727
|
+
expireGoalAcceptance: (...args) => this.expireGoalAcceptance(...args),
|
|
728
|
+
freeSlot: (...args) => this.freeSlot(...args),
|
|
729
|
+
maintenanceError: (...args) => this.maintenanceError(...args),
|
|
730
|
+
managedPrincipal: (...args) => this.managedPrincipal(...args),
|
|
731
|
+
readManagedSessionState: (...args) => this.readManagedSessionState(...args),
|
|
732
|
+
recoverManagedSession: (...args) => this.recoverManagedSession(...args),
|
|
733
|
+
releaseLifecycle: (...args) => this.releaseLifecycle(...args),
|
|
734
|
+
shredUserSecrets: (...args) => this.shredUserSecrets(...args),
|
|
735
|
+
trackDeprovision: (...args) => this.trackDeprovision(...args),
|
|
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
|
+
});
|
|
784
846
|
/** The goal-writer connection and the goal index it reconciles. Every dependency reads through at its use. */
|
|
785
847
|
goalWriterComponent = new GoalWriter({
|
|
786
848
|
auth: () => this.auth,
|
|
@@ -2680,25 +2742,8 @@ export class Manager {
|
|
|
2680
2742
|
return { ok: false, error: rejectionText(e) };
|
|
2681
2743
|
}
|
|
2682
2744
|
}
|
|
2683
|
-
/**
|
|
2684
|
-
|
|
2685
|
-
* ({@link serveGated}): the maintenance/resume fence (`beginLifecycle`: a resume-pending or
|
|
2686
|
-
* non-active manager accepts no ordinary control work) and then the membership gate
|
|
2687
|
-
* ({@link lifecycleMembershipRefusal}: a retiring/terminalizing/retired managed incarnation's
|
|
2688
|
-
* AUTHENTICATED principal holds no control authority even with a valid JWT). Refusal carries
|
|
2689
|
-
* WHICH fence refused so the ep door can map onto the §13.3 catalog; admission returns the
|
|
2690
|
-
* accepted-work release. Never re-implemented per door — a fence on one door is a bypass. */
|
|
2691
|
-
admitControl(caller) {
|
|
2692
|
-
const release = this.beginLifecycle();
|
|
2693
|
-
if (!release)
|
|
2694
|
-
return { refusal: this.maintenanceError(), fence: "maintenance" };
|
|
2695
|
-
const membership = this.lifecycleMembershipRefusal(caller);
|
|
2696
|
-
if (membership) {
|
|
2697
|
-
release();
|
|
2698
|
-
return { refusal: membership, fence: "membership" };
|
|
2699
|
-
}
|
|
2700
|
-
return { release };
|
|
2701
|
-
}
|
|
2745
|
+
/** {@link CommandDispatch.admitControl}. */
|
|
2746
|
+
admitControl(...args) { return this.commandDispatch.admitControl(...args); }
|
|
2702
2747
|
/** Run one v0.4 service-command handler through the SHARED admission chokepoint
|
|
2703
2748
|
* ({@link admitControl}) on the broker-authenticated caller principal, mapping the two fences
|
|
2704
2749
|
* onto the §13.3 catalog: maintenance/resume → `unavailable`, membership →
|
|
@@ -2739,54 +2784,8 @@ export class Manager {
|
|
|
2739
2784
|
this.releaseLifecycle();
|
|
2740
2785
|
}
|
|
2741
2786
|
}
|
|
2742
|
-
/**
|
|
2743
|
-
|
|
2744
|
-
* only into operator instruments (§13.2: `any` is operator-policy-mintable; the agent/spawn
|
|
2745
|
-
* rollups never carry them), so REACHING the handler is holding the admin tier, exactly as
|
|
2746
|
-
* holding `ctl.<admin>` is today. User mesh: the caller's CURRENT ledger scope must carry
|
|
2747
|
-
* `admin`. A local-host manager reads its own ledger fresh. A remote-authority manager relays the
|
|
2748
|
-
* subject-parsed caller tuple to its host-owned authorization callback, with no participant-ledger
|
|
2749
|
-
* fallback. The same fresh authority drives {@link psOwnerFilter}, so a revoked scope demotes the
|
|
2750
|
-
* very next call even on a still-valid bearer. Local ledger read failures authorize nothing;
|
|
2751
|
-
* remote host-state faults throw and fail the operation closed.
|
|
2752
|
-
* NAMED RESIDUAL: the static `true` has no serve-time re-check — a LEAKED static admin
|
|
2753
|
-
* instrument keeps its reach until the credential's bounded
|
|
2754
|
-
* TTL (the one-shot 5-minute profile), the same static-revoke≠reconnect-death class ruled
|
|
2755
|
-
* across this campaign; static revocation is the TTL, not a ledger. */
|
|
2756
|
-
async epAdminReach(caller) {
|
|
2757
|
-
if (!this.userMode)
|
|
2758
|
-
return true;
|
|
2759
|
-
if (this.remoteAuthority) {
|
|
2760
|
-
// A hosted run's own caller is derived from its id and holds no ledger row: it acts for the
|
|
2761
|
-
// caller its run was admitted for, so that caller's current grant decides, and a revoked
|
|
2762
|
-
// login demotes the run's next spawn.
|
|
2763
|
-
const asked = this.runHosting?.admittedCaller(caller) ?? caller;
|
|
2764
|
-
return this.remoteAuthority.authorizeAdmin({ owner: asked.owner, actor: asked.actor, lifecycleUid: asked.uid });
|
|
2765
|
-
}
|
|
2766
|
-
try {
|
|
2767
|
-
const scope = await resolveAuthProvider().actorScope({
|
|
2768
|
-
dir: userAuthStateDir(this.workspaceRoot, this.space),
|
|
2769
|
-
owner: caller.owner,
|
|
2770
|
-
actor: caller.actor,
|
|
2771
|
-
});
|
|
2772
|
-
return scope?.includes("admin") === true;
|
|
2773
|
-
}
|
|
2774
|
-
catch {
|
|
2775
|
-
return false;
|
|
2776
|
-
}
|
|
2777
|
-
}
|
|
2778
|
-
/** A targeted request's admin flag: mode `any` (the operator instrument's cross-agent form,
|
|
2779
|
-
* rev 3) resolves through {@link epAdminReach}; a user-mode any-mode caller whose CURRENT
|
|
2780
|
-
* ledger row lost `admin` since its rows were minted refuses loud rather than silently
|
|
2781
|
-
* downgrading to the owner path (the request's declared mode is honored or denied, never
|
|
2782
|
-
* reinterpreted). Owner mode is always the privileged (own-domain) path. */
|
|
2783
|
-
async epAnyModeAdmin(ctx) {
|
|
2784
|
-
if (ctx.subject.target?.mode !== "any")
|
|
2785
|
-
return false;
|
|
2786
|
-
if (!(await this.epAdminReach(ctx.subject.caller)))
|
|
2787
|
-
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)`);
|
|
2788
|
-
return true;
|
|
2789
|
-
}
|
|
2787
|
+
/** {@link CommandDispatch.epAdminReach}. */
|
|
2788
|
+
epAdminReach(...args) { return this.commandDispatch.epAdminReach(...args); }
|
|
2790
2789
|
/** The run host, or one of three refusals. A remote-authority manager holds no space signer, so
|
|
2791
2790
|
* it cannot mint the per-run driver credential SPEC 14.6 requires without all four closed
|
|
2792
2791
|
* host callbacks. A local user-auth mesh is `unimplemented`: a hosted run's seats
|
|
@@ -2931,310 +2930,8 @@ export class Manager {
|
|
|
2931
2930
|
if (accepted.by !== agent.name)
|
|
2932
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`);
|
|
2933
2932
|
}
|
|
2934
|
-
/**
|
|
2935
|
-
|
|
2936
|
-
* door dispatches (one core, two thin doors). The resume/preservation family
|
|
2937
|
-
* deliberately BYPASSES serveGated — exactly as it sits before {@link admitControl} on the ctl
|
|
2938
|
-
* door (those ops must run while `resumeRequired` fences ordinary work) — riding its own state
|
|
2939
|
-
* fences; its ep gate is the admin-grade `manager.admin` capability grant (static
|
|
2940
|
-
* admin-class commands are capability-gated + untargeted, never a fabricated ledger mode).
|
|
2941
|
-
*
|
|
2942
|
-
* TIER SEMANTICS on the ep door: the tier lives in the CALLER'S
|
|
2943
|
-
* GRANT, refined per-op exactly as the ctl doors refine their subject tier. Owner-mode
|
|
2944
|
-
* `despawn`/`attach` keep the privileged semantics (`admin=false`, own-domain via
|
|
2945
|
-
* {@link authorizeNamed}) — every spawn-capable agent holds those rows. ANY-mode requests are
|
|
2946
|
-
* the operator instrument's cross-agent reach (rev 3): the any-mode subject row is mintable
|
|
2947
|
-
* only under operator policy (§13.2), so on a static mesh holding it IS the admin tier, and in
|
|
2948
|
-
* user mode the caller's CURRENT ledger scope must still carry `admin`
|
|
2949
|
-
* ({@link epAdminReach}, the same fresh-read authority `psOwnerFilter` consults). The
|
|
2950
|
-
* `manager.admin` family (purge + the resume/preservation ops) is capability-gated at mint AND
|
|
2951
|
-
* re-checked at serve time via {@link epAdminReach} (the `adminGated` wrapper) so a user's
|
|
2952
|
-
* revoked scope demotes the next call. `launch` is OWNER-EQUALITY on this door for everyone:
|
|
2953
|
-
* the deploy path is its only consumer and stamps the caller's own owner,
|
|
2954
|
-
* so cross-owner launch was a ctl-tier incidental never exercised, and keying it on the actor's
|
|
2955
|
-
* ledger scope broke the deployer-view attenuation - uniform owner-equality is the safe tier.
|
|
2956
|
-
* TWO DELIBERATE NARROWINGS vs the ctl doors (NOT bit-exact parity): (1)
|
|
2957
|
-
* `define-persona` is `admin=false` for everyone (own-persona discipline; no ep consumer needs
|
|
2958
|
-
* cross-owner persona writes - an operator redefines via config, not the wire), where the ctl
|
|
2959
|
-
* admin tier allowed operator cross-owner redefine; (2) launch is owner-equality-only, above.
|
|
2960
|
-
* Both are least-privilege reductions, never widenings. */
|
|
2961
|
-
managerServiceDefs() {
|
|
2962
|
-
const args = (ctx) => (ctx.request.args ?? {});
|
|
2963
|
-
const callerOf = (ctx) => principalKey(ctx.subject.caller.owner, ctx.subject.caller.actor).key;
|
|
2964
|
-
// A ctl-core failure reply becomes the §13.3 structured error the serve boundary publishes.
|
|
2965
|
-
// The data half of a failure reply (e.g. a degraded resume result) rides the error MESSAGE
|
|
2966
|
-
// only — the action model gives failures a typed channel.
|
|
2967
|
-
const unwrap = (r) => {
|
|
2968
|
-
if (!r.ok)
|
|
2969
|
-
throw new EpEnvelopeError((r.code ?? "failed-precondition"), r.error ?? "the operation failed", r.details, r.outcome);
|
|
2970
|
-
return r.data;
|
|
2971
|
-
};
|
|
2972
|
-
// The admin-family serve gate: every `manager.admin`-class
|
|
2973
|
-
// command re-checks operator reach AT SERVE TIME - static: true (the mint boundary already
|
|
2974
|
-
// gates the rows to instruments); user mesh: the caller's CURRENT ledger scope must still
|
|
2975
|
-
// carry `admin` ({@link epAdminReach}'s fresh read), so a revoked scope demotes the very next
|
|
2976
|
-
// call instead of riding the bearer's remaining JWT-row lifetime. The resume family keeps its
|
|
2977
|
-
// serveGated BYPASS (those ops must run while the maintenance fence holds) but not the gate.
|
|
2978
|
-
const adminGated = async (ctx, fn) => {
|
|
2979
|
-
if (!(await this.epAdminReach(ctx.subject.caller)))
|
|
2980
|
-
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");
|
|
2981
|
-
return fn();
|
|
2982
|
-
};
|
|
2983
|
-
const targetAgent = (ctx) => {
|
|
2984
|
-
if (this.execution === "none")
|
|
2985
|
-
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
2986
|
-
const t = ctx.request.target; // targeted commands only: the serve boundary enforced body-target presence + fresh currency
|
|
2987
|
-
const a = this.findManagedByTarget(t);
|
|
2988
|
-
if (!a)
|
|
2989
|
-
throw new EpEnvelopeError("expired", `target ${t.owner}.${t.actor} (lifecycle ${t.lifecycleUid}) is not a live managed agent of this manager`, undefined, "not-executed");
|
|
2990
|
-
return a;
|
|
2991
|
-
};
|
|
2992
|
-
return managerCommandDefs({
|
|
2993
|
-
vitals: (ctx) => this.serveGated(ctx, () => measureManagerVitals()),
|
|
2994
|
-
// A remote Manager files every seat under its own owner, so only a user mesh's shared local
|
|
2995
|
-
// Manager narrows the count, and status never waits on a remote admin check.
|
|
2996
|
-
status: (ctx) => this.serveObservation(ctx, async () => {
|
|
2997
|
-
const ownerFilter = this.remoteAuthority ? undefined : await this.psOwnerFilter(ctx.subject.caller, false);
|
|
2998
|
-
// The daemon's status deadline is shorter than an install. Report the current inventory
|
|
2999
|
-
// without waiting for the install, which has its own lifecycle admission below.
|
|
3000
|
-
return this.managerStatusData(ownerFilter, !this.resumeRequired);
|
|
3001
|
-
}),
|
|
3002
|
-
ps: (ctx) => this.serveGated(ctx, async () => this.list(await this.psOwnerFilter(ctx.subject.caller, false))),
|
|
3003
|
-
inspect: (ctx) => this.serveGated(ctx, async () => {
|
|
3004
|
-
const name = String(args(ctx).name ?? "").trim();
|
|
3005
|
-
const row = this.list(await this.psOwnerFilter(ctx.subject.caller, false)).find((x) => x.name === name);
|
|
3006
|
-
if (!row) {
|
|
3007
|
-
// The live hit above stays entirely local. Only a miss widens into durable static state,
|
|
3008
|
-
// where `not-found` is honest only after the slot read itself succeeds and returns absent.
|
|
3009
|
-
// User-mode lifecycles have no manager-local mgrslot row; their per-name projection remains
|
|
3010
|
-
// the live map until the auth service exposes an equivalent mediated reader.
|
|
3011
|
-
if (this.auth && !this.userMode) {
|
|
3012
|
-
const recordsKv = this.goalWriter?.ctx.kv;
|
|
3013
|
-
if (!recordsKv)
|
|
3014
|
-
throw new EpEnvelopeError("unavailable", `the durable static slot store is not ready while inspecting "${name}"`, [
|
|
3015
|
-
{ kind: STATIC_SLOT_READ_FAILED_DETAIL, name, record: "slot", operation: "read" },
|
|
3016
|
-
]);
|
|
3017
|
-
let observed;
|
|
3018
|
-
try {
|
|
3019
|
-
observed = await observeStaticSlot(recordsKv, DEV_OWNER, name, this.managerInstanceId);
|
|
3020
|
-
}
|
|
3021
|
-
catch (error) {
|
|
3022
|
-
throw new EpEnvelopeError("unavailable", `the durable static slot state for "${name}" could not be read: ${rejectionText(error)}`, [
|
|
3023
|
-
{ kind: STATIC_SLOT_READ_FAILED_DETAIL, name, record: error instanceof StaticSlotReadError ? error.record : "slot-or-head", operation: "read" },
|
|
3024
|
-
]);
|
|
3025
|
-
}
|
|
3026
|
-
// A retired row affirms that no agent exists now, so it keeps the old `not-found`
|
|
3027
|
-
// result. The changed refusal is reserved for durable NONTERMINAL state that contradicts
|
|
3028
|
-
// the live-map miss and needs operator attention.
|
|
3029
|
-
//
|
|
3030
|
-
// A sibling's nonterminal row is not a contradiction: the name belongs to another
|
|
3031
|
-
// manager instance in this space. In a multi-manager space the class queue hands this
|
|
3032
|
-
// read to either instance, so a plain `not-found` here read the same as a name that
|
|
3033
|
-
// exists nowhere and a caller had no way to tell the two apart (#443).
|
|
3034
|
-
if (observed?.ownerInstanceId !== undefined)
|
|
3035
|
-
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]);
|
|
3036
|
-
if (observed !== undefined && observed.slotPhase !== "retired")
|
|
3037
|
-
throw new EpEnvelopeError("failed-precondition", `no live agent "${name}"; durable state contradicts absence ${renderStaticSlotObservation(observed)}`, [observed]);
|
|
3038
|
-
}
|
|
3039
|
-
throw new EpEnvelopeError("not-found", `no agent "${name}"`, undefined, "not-executed");
|
|
3040
|
-
}
|
|
3041
|
-
return row;
|
|
3042
|
-
}),
|
|
3043
|
-
slots: (ctx) => this.serveGated(ctx, async () => {
|
|
3044
|
-
// No manager-local durable static slot store exists for a user-mode or open manager: an
|
|
3045
|
-
// empty list here would claim nothing is stranded from a store that was never consulted,
|
|
3046
|
-
// the very ambiguity #1274 is about.
|
|
3047
|
-
if (!this.auth || this.userMode)
|
|
3048
|
-
throw new EpEnvelopeError("failed-precondition", "user-mode and open managers own no durable static slot rows; the projection is static-manager local");
|
|
3049
|
-
const recordsKv = this.goalWriter?.ctx.kv;
|
|
3050
|
-
if (!recordsKv)
|
|
3051
|
-
throw new EpEnvelopeError("unavailable", "the durable static slot store is not ready", [
|
|
3052
|
-
{ kind: STATIC_SLOT_READ_FAILED_DETAIL, name: "*", record: "slot", operation: "scan" },
|
|
3053
|
-
]);
|
|
3054
|
-
let observed;
|
|
3055
|
-
try {
|
|
3056
|
-
const query = args(ctx);
|
|
3057
|
-
observed = await listStaticSlotObservations(recordsKv, DEV_OWNER, this.managerInstanceId, {
|
|
3058
|
-
...(query.names === undefined ? {} : { names: query.names }),
|
|
3059
|
-
...(query.includeRetired === true ? { includeRetired: true } : {}),
|
|
3060
|
-
});
|
|
3061
|
-
}
|
|
3062
|
-
catch (error) {
|
|
3063
|
-
throw new EpEnvelopeError("unavailable", `the durable static slot state could not be scanned: ${rejectionText(error)}`, [
|
|
3064
|
-
{ kind: STATIC_SLOT_READ_FAILED_DETAIL, name: "*", record: error instanceof StaticSlotReadError ? error.record : "slot-or-head", operation: "scan" },
|
|
3065
|
-
]);
|
|
3066
|
-
}
|
|
3067
|
-
return observed.map(({ kind: _kind, ...detail }) => ({
|
|
3068
|
-
...detail,
|
|
3069
|
-
live: this.agents.has(detail.name),
|
|
3070
|
-
managerInstanceId: this.managerInstanceId,
|
|
3071
|
-
}));
|
|
3072
|
-
}),
|
|
3073
|
-
models: (ctx) => this.serveGated(ctx, async () => {
|
|
3074
|
-
const data = unwrap(await this.opModels(args(ctx)));
|
|
3075
|
-
return { catalogs: Array.isArray(data) ? data : [data] };
|
|
3076
|
-
}),
|
|
3077
|
-
goalResult: (ctx) => this.serveGated(ctx, async () => {
|
|
3078
|
-
const gw = this.goalWriter;
|
|
3079
|
-
if (!gw || gw.nc.isClosed())
|
|
3080
|
-
throw new EpEnvelopeError("unavailable", "the manager goal-reader connection is not standing; the accepted goal is unaffected");
|
|
3081
|
-
const goalId = args(ctx).goalId;
|
|
3082
|
-
// Only the broker-authenticated caller's full incarnation can name this read. The
|
|
3083
|
-
// trusted goal-writer keeps the raw EPF authority; serveEndpoint derives the reply rail.
|
|
3084
|
-
const result = await readGoalResult(gw.ctx, goalRefOf(ctx.subject, goalId));
|
|
3085
|
-
return { goalId, ...(result === undefined ? {} : { result }) };
|
|
3086
|
-
}),
|
|
3087
|
-
listDir: (ctx) => this.serveGated(ctx, () => this.listSpawnDirectory(args(ctx))),
|
|
3088
|
-
resolveCwd: (ctx) => this.serveGated(ctx, () => this.resolveSpawnCwd(args(ctx).cwd)),
|
|
3089
|
-
resolveAgent: (ctx) => this.serveGated(ctx, async () => {
|
|
3090
|
-
if (this.execution === "none")
|
|
3091
|
-
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
3092
|
-
const persona = await this.spawnPersona(args(ctx), callerOf(ctx), ctx.subject.caller);
|
|
3093
|
-
if ("error" in persona)
|
|
3094
|
-
throw new EpEnvelopeError(persona.code ?? (persona.error.startsWith("no persona") ? "not-found" : "failed-precondition"), persona.error);
|
|
3095
|
-
return { agent: persona.agent };
|
|
3096
|
-
}),
|
|
3097
|
-
// `spawn` is an ACTION - accept a goal + reply the acceptance floor payload, drive
|
|
3098
|
-
// progress + terminal off-handler (no ~30s block). The blocking reply path is gone.
|
|
3099
|
-
// #373: arming the event plane (events: true, or the omission that arms it by default)
|
|
3100
|
-
// follows owner-domain reach on a user mesh. Resolve the caller's admin tier once for
|
|
3101
|
-
// the residual cross-owner case; opStart decides before connector resolution or grant
|
|
3102
|
-
// mutation. Static meshes resolve true and nothing changes.
|
|
3103
|
-
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))))),
|
|
3104
|
-
despawn: (ctx) => this.serveGated(ctx, async () => {
|
|
3105
|
-
const a = targetAgent(ctx);
|
|
3106
|
-
const denied = await this.authorizeNamed(a, callerOf(ctx), await this.epAnyModeAdmin(ctx), ctx.subject.caller);
|
|
3107
|
-
if (denied)
|
|
3108
|
-
throw new EpEnvelopeError("permission-denied", denied, undefined, "not-executed");
|
|
3109
|
-
return unwrap(await this.despawnAuthorized(a, args(ctx).graceful !== false, true, callerOf(ctx)));
|
|
3110
|
-
}),
|
|
3111
|
-
attach: (ctx) => this.serveGated(ctx, async () => {
|
|
3112
|
-
const a = targetAgent(ctx);
|
|
3113
|
-
const denied = await this.authorizeNamed(a, callerOf(ctx), await this.epAnyModeAdmin(ctx), ctx.subject.caller);
|
|
3114
|
-
if (denied)
|
|
3115
|
-
throw new EpEnvelopeError("permission-denied", denied, undefined, "not-executed");
|
|
3116
|
-
return unwrap(await this.attachAuthorized(a, ctx.subject.caller));
|
|
3117
|
-
}),
|
|
3118
|
-
// C3 `input`: the SAME authorization as `attach`, deliberately written out rather than
|
|
3119
|
-
// factored with it - the two share a policy, not a body, and a shared wrapper would be a
|
|
3120
|
-
// place for one of them to quietly acquire a condition the other does not have.
|
|
3121
|
-
input: (ctx) => this.serveGated(ctx, async () => {
|
|
3122
|
-
const a = targetAgent(ctx);
|
|
3123
|
-
const denied = await this.authorizeNamed(a, callerOf(ctx), await this.epAnyModeAdmin(ctx), ctx.subject.caller);
|
|
3124
|
-
if (denied)
|
|
3125
|
-
throw new EpEnvelopeError("permission-denied", denied, undefined, "not-executed");
|
|
3126
|
-
return this.inputAuthorized(a, args(ctx));
|
|
3127
|
-
}),
|
|
3128
|
-
// The turn relay (§8 durable actions): `turn` shares despawn/input's reach policy — the
|
|
3129
|
-
// caller must hold owner-equality or admin over the TARGET seat — written out for the same
|
|
3130
|
-
// reason `input` is (a shared policy, not a shared body).
|
|
3131
|
-
turn: (ctx) => this.serveGated(ctx, async () => {
|
|
3132
|
-
const target = this.turnTarget(ctx);
|
|
3133
|
-
if (target.kind === "managed") {
|
|
3134
|
-
const denied = await this.authorizeNamed(target.agent, callerOf(ctx), await this.epAnyModeAdmin(ctx), ctx.subject.caller);
|
|
3135
|
-
if (denied)
|
|
3136
|
-
throw new EpEnvelopeError("permission-denied", denied, undefined, "not-executed");
|
|
3137
|
-
}
|
|
3138
|
-
else {
|
|
3139
|
-
const admitted = this.runHosting?.admittedCaller(ctx.subject.caller);
|
|
3140
|
-
if (!admitted || admitted.owner !== target.participant.owner || admitted.actor !== target.participant.actor || admitted.uid !== target.participant.uid)
|
|
3141
|
-
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");
|
|
3142
|
-
if (!this.remoteAuthority?.authorizeParticipation)
|
|
3143
|
-
throw new EpEnvelopeError("unimplemented", "the issuing host supplies no closed personal participation authorization", undefined, "not-executed");
|
|
3144
|
-
const authorized = await this.remoteAuthority.authorizeParticipation({
|
|
3145
|
-
owner: target.participant.owner,
|
|
3146
|
-
actor: target.participant.actor,
|
|
3147
|
-
lifecycleUid: target.participant.uid,
|
|
3148
|
-
});
|
|
3149
|
-
if (!authorized) {
|
|
3150
|
-
this.participants.delete(participantKey(target.participant.owner, target.participant.actor, target.participant.uid));
|
|
3151
|
-
throw new EpEnvelopeError("permission-denied", "the exact personal lifecycle is no longer foreground-authorized with run scope", undefined, "not-executed");
|
|
3152
|
-
}
|
|
3153
|
-
}
|
|
3154
|
-
return this.serveTurnGoal(ctx, target);
|
|
3155
|
-
}),
|
|
3156
|
-
// A personal native lifecycle must opt in explicitly. The command is self-targeted and returns
|
|
3157
|
-
// only a finite relay lease. It never inserts a ManagedAgent or grants stop/attach/input custody.
|
|
3158
|
-
turnParticipate: (ctx) => this.serveGated(ctx, () => this.serveTurnParticipation(ctx.subject.caller)),
|
|
3159
|
-
// The seat's own half of the relay (`manager.self`, stop-self's tier): a seat pulls the
|
|
3160
|
-
// turns addressed to ITS incarnation and yields them; no reach beyond itself exists here.
|
|
3161
|
-
turnPending: (ctx) => this.serveGated(ctx, () => this.turnPendingFor(ctx.subject.caller)),
|
|
3162
|
-
turnYield: (ctx) => this.serveGated(ctx, () => this.serveTurnYield(ctx.subject.caller, args(ctx))),
|
|
3163
|
-
turnUnconfirmed: (ctx) => this.serveGated(ctx, () => this.serveTurnUnconfirmed(ctx.subject.caller, args(ctx))),
|
|
3164
|
-
// The reserved goal cancel (SPEC 13.6 item 4), served for the relay: the goal ref is the
|
|
3165
|
-
// authenticated caller's own, so a run withdraws only the turns it submitted.
|
|
3166
|
-
cancel: (ctx) => this.serveGated(ctx, () => this.serveTurnCancel(ctx)),
|
|
3167
|
-
stopSelf: (ctx) => this.serveGated(ctx, async () => unwrap(await this.opStopSelf(callerOf(ctx), args(ctx)))),
|
|
3168
|
-
definePersona: (ctx) => this.serveGated(ctx, async () => unwrap(await this.opDefinePersona(args(ctx), callerOf(ctx), false, ctx.subject.caller))),
|
|
3169
|
-
removePersona: (ctx) => this.serveGated(ctx, () => {
|
|
3170
|
-
const r = this.opRemovePersona(args(ctx), callerOf(ctx), false);
|
|
3171
|
-
if (!r.ok)
|
|
3172
|
-
throw new EpEnvelopeError((r.code ?? "failed-precondition"), r.error ?? "the operation failed", r.details, "not-executed");
|
|
3173
|
-
return r.data;
|
|
3174
|
-
}),
|
|
3175
|
-
// Reach is the broker's: only operator instruments carry these rows. The serve gate is the
|
|
3176
|
-
// maintenance fence, so neither runs while a shutdown or resume holds control.
|
|
3177
|
-
chatSessionOpen: (ctx) => this.serveGated(ctx, () => this.openStaticChatSession(args(ctx))),
|
|
3178
|
-
chatSessionRetire: (ctx) => this.serveGated(ctx, () => this.retireStaticChatSession(args(ctx))),
|
|
3179
|
-
listPersonas: (ctx) => this.serveGated(ctx, () => unwrap(this.opListPersonas(callerOf(ctx), false))),
|
|
3180
|
-
showPersona: (ctx) => this.serveGated(ctx, () => {
|
|
3181
|
-
const r = this.opShowPersona(args(ctx), callerOf(ctx), false);
|
|
3182
|
-
if (!r.ok) {
|
|
3183
|
-
const msg = r.error ?? "not found";
|
|
3184
|
-
if (msg.startsWith("no persona"))
|
|
3185
|
-
throw new EpEnvelopeError("not-found", msg);
|
|
3186
|
-
throw new EpEnvelopeError("failed-precondition", msg);
|
|
3187
|
-
}
|
|
3188
|
-
return r.data;
|
|
3189
|
-
}),
|
|
3190
|
-
purge: (ctx) => this.serveGated(ctx, () => adminGated(ctx, async () => unwrap(await this.opPurge(args(ctx), callerOf(ctx))))),
|
|
3191
|
-
// launch is OWNER-EQUALITY on the ep door for every caller: the deploy
|
|
3192
|
-
// path is the only launch consumer and its spec stamps the CALLER's own owner, so
|
|
3193
|
-
// owner-equality always holds for a legitimate deploy; cross-owner launch was a ctl
|
|
3194
|
-
// admin-tier INCIDENTAL never exercised by a real flow (static is single-owner, so the flag
|
|
3195
|
-
// is a no-op there). Keying admin on epAdminReach read the ACTOR's ledger scope, which does
|
|
3196
|
-
// NOT reflect the deployer VIEW's privileged-tier attenuation - an admin user's stolen
|
|
3197
|
-
// deployer bearer would then bypass owner-equality (operator launch) despite the view holding
|
|
3198
|
-
// no admin rows. Uniform owner-equality removes that divergence in the least-privilege
|
|
3199
|
-
// direction.
|
|
3200
|
-
// Manifest `launch` is an ACTION through the SAME chokepoint as spawn -
|
|
3201
|
-
// the manifest resolve + owner-equality authz run in opLaunch's accept path, then the goal
|
|
3202
|
-
// drives progress + terminal. The acceptance floor is the allocated identity + goal coords.
|
|
3203
|
-
launch: (ctx) => this.serveGated(ctx, () => this.serveSpawnGoal(ctx, (h) => this.opLaunch(args(ctx), callerOf(ctx), false, h, ctx.subject.route))),
|
|
3204
|
-
resumePreserved: (ctx) => adminGated(ctx, async () => unwrap(await this.opResumePreserved(args(ctx)))),
|
|
3205
|
-
commitResume: (ctx) => adminGated(ctx, async () => unwrap(await this.opCommitResume(args(ctx)))),
|
|
3206
|
-
finalizeResume: (ctx) => adminGated(ctx, async () => unwrap(await this.opFinalizeResume(args(ctx)))),
|
|
3207
|
-
// The workflow-run family (SPEC 14.3): the manager hosts the driver. Reach is the broker's
|
|
3208
|
-
// (`run` capability / privileged instrument rows); the serve gate is the maintenance fence.
|
|
3209
|
-
runStart: (ctx) => this.serveGated(ctx, () => this.runHost().start(ctx, args(ctx))),
|
|
3210
|
-
runStartKeyed: (ctx) => this.serveGated(ctx, () => this.runHost().startKeyed(ctx, args(ctx))),
|
|
3211
|
-
runSubmissionStatus: (ctx) => this.serveGated(ctx, () => this.runHost().submissionStatus(ctx, String(args(ctx).submissionId))),
|
|
3212
|
-
runResume: (ctx) => this.serveGated(ctx, () => this.runHost().resume(args(ctx), ctx)),
|
|
3213
|
-
runCancel: (ctx) => {
|
|
3214
|
-
const host = this.runHost();
|
|
3215
|
-
host.validateCancellation(ctx, args(ctx));
|
|
3216
|
-
return this.serveGated(ctx, () => host.cancel(ctx, args(ctx)));
|
|
3217
|
-
},
|
|
3218
|
-
runAnswer: (ctx) => this.serveGated(ctx, () => {
|
|
3219
|
-
const input = args(ctx);
|
|
3220
|
-
if (input.amend === true)
|
|
3221
|
-
return this.runHost().amend(input, this.runAnswerer(ctx), (accepted) => this.authorizeRunAmend(ctx, accepted), ctx);
|
|
3222
|
-
return this.runHost().answer(input, this.runAnswerer(ctx), (open) => this.authorizeRunAnswer(ctx, input, open), ctx);
|
|
3223
|
-
}),
|
|
3224
|
-
runStatus: (ctx) => this.serveGated(ctx, () => this.runHost().status(args(ctx), ctx)),
|
|
3225
|
-
runPs: (ctx) => this.serveGated(ctx, () => this.runHost().list(args(ctx), ctx)),
|
|
3226
|
-
preparePreservation: (ctx) => adminGated(ctx, async () => unwrap(await this.opPreservationCtl("preparePreservation", args(ctx)))),
|
|
3227
|
-
commitPreservation: (ctx) => adminGated(ctx, async () => unwrap(await this.opPreservationCtl("commitPreservation", args(ctx)))),
|
|
3228
|
-
abortPreservation: (ctx) => adminGated(ctx, async () => unwrap(await this.opPreservationCtl("abortPreservation", args(ctx)))),
|
|
3229
|
-
transcriptReceive: (ctx) => this.serveGated(ctx, () => adminGated(ctx, () => {
|
|
3230
|
-
if (this.execution === "none")
|
|
3231
|
-
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
3232
|
-
if (!this.transcripts)
|
|
3233
|
-
throw new EpEnvelopeError("failed-precondition", "transcript-receive: this manager does not receive carried transcripts (its remote authority issues no transfer reader)");
|
|
3234
|
-
return this.transcripts.receive(args(ctx));
|
|
3235
|
-
})),
|
|
3236
|
-
});
|
|
3237
|
-
}
|
|
2933
|
+
/** {@link CommandDispatch.managerServiceDefs}. */
|
|
2934
|
+
managerServiceDefs(...args) { return this.commandDispatch.managerServiceDefs(...args); }
|
|
3238
2935
|
async commitResumeActivation(attemptId) {
|
|
3239
2936
|
if (!this.resumeAwaitingCommit || !this.resumeResult?.ok)
|
|
3240
2937
|
return { ok: false, error: `resume attempt ${attemptId} has no successful activation to commit` };
|
|
@@ -3355,143 +3052,18 @@ export class Manager {
|
|
|
3355
3052
|
}
|
|
3356
3053
|
return inactive;
|
|
3357
3054
|
}
|
|
3358
|
-
/**
|
|
3359
|
-
|
|
3360
|
-
* per spawn + non-forgeable in auth mode), never a peer — so it's structurally incapable of
|
|
3361
|
-
* hitting another agent. Non-managed callers (human CLI, the manager itself, observers) find
|
|
3362
|
-
* no match and get a loud error, not a silent no-op. */
|
|
3363
|
-
opStopSelf(callerId, args) {
|
|
3364
|
-
if (this.execution === "none")
|
|
3365
|
-
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
3366
|
-
const target = [...this.agents.values()].find((a) => this.managedPrincipal(a) === callerId);
|
|
3367
|
-
if (!target)
|
|
3368
|
-
return { ok: false, error: `self-stop: caller ${callerId} is not a managed agent` };
|
|
3369
|
-
const graceful = args.graceful !== false;
|
|
3370
|
-
if (process.platform === "win32" && target.handle.kind === "pty") {
|
|
3371
|
-
return this.stopWindowsSeat(target, graceful, true, { kind: "stopped-self" }).then(() => ({ ok: true, data: { name: target.name, stopped: true, graceful } }));
|
|
3372
|
-
}
|
|
3373
|
-
this.stopHandle(target, graceful, { kind: "stopped-self" });
|
|
3374
|
-
this.trackStoppedHandle(target, true, { kind: "stopped-self" });
|
|
3375
|
-
return { ok: true, data: { name: target.name, stopped: true, graceful } };
|
|
3376
|
-
}
|
|
3055
|
+
/** {@link CommandDispatch.opStopSelf}. */
|
|
3056
|
+
opStopSelf(...args) { return this.commandDispatch.opStopSelf(...args); }
|
|
3377
3057
|
// Plane-3 durable join/leave/list ops moved OFF the manager onto the server-side delivery daemon's
|
|
3378
3058
|
// `ctl.delivery` control service (endpoint.startPlane3 → handleDeliveryControl). The manager is
|
|
3379
3059
|
// lifecycle-only; it records each agent's read ACL at spawn (commitAcl) so the daemon can validate
|
|
3380
3060
|
// those ops against the durable ACL registry — the single source of truth, no in-memory ledger.
|
|
3381
|
-
/**
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
*
|
|
3388
|
-
* Never throws (#159 B2): a runtime hard-stop CAN throw (tmux `closeWindow` / cmux `closeWorkspace`
|
|
3389
|
-
* are direct calls), and a throwing stop must not abort a caller's cleanup and leak the agent's
|
|
3390
|
-
* footprint, nor (in `reapChildrenOf`) abort the reap of later siblings. The failure is logged and
|
|
3391
|
-
* returned: a caller that must prove exit (shutdown, a failed resume) reports it as the cause at
|
|
3392
|
-
* once instead of waiting out a stop the runtime already refused. */
|
|
3393
|
-
stopHandle(a, graceful, cause) {
|
|
3394
|
-
// The TERMINALIZING latch: flipped SYNCHRONOUSLY, before any await anywhere on
|
|
3395
|
-
// this stop path — later renewals refuse, while an already-admitted renewal drains before the
|
|
3396
|
-
// durable terminal begins.
|
|
3397
|
-
a.terminalizing = true;
|
|
3398
|
-
a.stopCause ??= cause;
|
|
3399
|
-
try {
|
|
3400
|
-
// A delegated seat's close runs only inside its retirement, after the host revoked its grant,
|
|
3401
|
-
// so stopping it starts that retirement. Every exit wait on a stop path then settles on that
|
|
3402
|
-
// close; the free path's own teardown joins the same flight.
|
|
3403
|
-
if (a.handedOff)
|
|
3404
|
-
this.trackDeprovision(this.teardownTarget(a));
|
|
3405
|
-
else
|
|
3406
|
-
a.handle.stop({ graceful });
|
|
3407
|
-
// The runtime captured its cohort synchronously before the cooperative
|
|
3408
|
-
// request can let a root exit and orphan its already-running children.
|
|
3409
|
-
if (graceful && process.platform === "win32" && a.control)
|
|
3410
|
-
controlShutdown(a.control);
|
|
3411
|
-
}
|
|
3412
|
-
catch (e) {
|
|
3413
|
-
const failure = rejectionText(e);
|
|
3414
|
-
console.error(`stop ${a.name} (${a.id}): ${failure}`);
|
|
3415
|
-
return failure;
|
|
3416
|
-
}
|
|
3417
|
-
}
|
|
3418
|
-
/** Windows PTY stops release their name only after the captured process cohort and PTY exited. */
|
|
3419
|
-
async stopWindowsSeat(a, graceful, floor, cause) {
|
|
3420
|
-
if (a.once)
|
|
3421
|
-
a.once.stopReason ??= onceStopReason(cause);
|
|
3422
|
-
const failure = this.stopHandle(a, graceful, cause);
|
|
3423
|
-
this.lifecycleInFlight++;
|
|
3424
|
-
try {
|
|
3425
|
-
if (failure !== undefined)
|
|
3426
|
-
throw new Error(failure);
|
|
3427
|
-
await this.awaitHandleExit(a.handle);
|
|
3428
|
-
this.unverifiedStops = this.unverifiedStops.filter((stopped) => stopped.handle !== a.handle);
|
|
3429
|
-
this.freeSlot(a, floor, cause, true);
|
|
3430
|
-
}
|
|
3431
|
-
catch (error) {
|
|
3432
|
-
const detail = `Windows stop could not prove the captured process tree exited: ${rejectionText(error)}`;
|
|
3433
|
-
this.unverifiedStops = this.unverifiedStops.filter((stopped) => stopped.handle !== a.handle);
|
|
3434
|
-
this.unverifiedStops.push({ name: a.name, id: a.id, handle: a.handle, authoritative: true, error: detail });
|
|
3435
|
-
throw new EpEnvelopeError("unavailable", detail, undefined, "unknown");
|
|
3436
|
-
}
|
|
3437
|
-
finally {
|
|
3438
|
-
this.releaseLifecycle();
|
|
3439
|
-
}
|
|
3440
|
-
}
|
|
3441
|
-
/** Keep an accepted stop inside the lifecycle drain until the runtime proves the child is gone,
|
|
3442
|
-
* so a maintenance prepare can never fence ahead of a child that is still dying. The `cause` is
|
|
3443
|
-
* the stop-family cause the door already knows (which door, and who asked); it rides every
|
|
3444
|
-
* freeSlot below so the reap line can say it.
|
|
3445
|
-
*
|
|
3446
|
-
* An operator-accepted stop frees its slot at once: `stop` replying ✓ means `ps` no longer lists
|
|
3447
|
-
* the agent. That cannot omit a still-live child from a cut, because runPreparation drains the
|
|
3448
|
-
* lifecycle BEFORE it reads the roster — the exit proof below is what closes the race, not the
|
|
3449
|
-
* slot lingering. A recursive reap (`requireAuthoritativeExit`) instead keeps the slot until the
|
|
3450
|
-
* wait proves exit: nobody asked for those children to be gone, so they stay managed until the
|
|
3451
|
-
* runtime says otherwise, and a runtime that cannot prove exit records an unverified stop. */
|
|
3452
|
-
trackStoppedHandle(a, floor, cause, requireAuthoritativeExit = false) {
|
|
3453
|
-
if (process.platform === "win32" && a.handle.kind === "pty")
|
|
3454
|
-
requireAuthoritativeExit = true;
|
|
3455
|
-
// What a once seat's task is cancelled with if this stop ends it before the task has a terminal.
|
|
3456
|
-
if (a.once && typeof cause !== "string")
|
|
3457
|
-
a.once.stopReason ??= onceStopReason(cause);
|
|
3458
|
-
if (!a.handle.waitForExit) {
|
|
3459
|
-
// Preserve ordinary external-runtime stop behavior, but retain enough evidence for a later
|
|
3460
|
-
// maintenance prepare to fail if that runtime still cannot prove the surface disappeared.
|
|
3461
|
-
this.unverifiedStops.push({
|
|
3462
|
-
name: a.name,
|
|
3463
|
-
id: a.id,
|
|
3464
|
-
handle: a.handle,
|
|
3465
|
-
authoritative: requireAuthoritativeExit,
|
|
3466
|
-
error: requireAuthoritativeExit
|
|
3467
|
-
? `recursive reap cannot prove exit on runtime "${a.handle.kind}" (AgentHandle.waitForExit is not implemented)`
|
|
3468
|
-
: undefined,
|
|
3469
|
-
});
|
|
3470
|
-
if (requireAuthoritativeExit)
|
|
3471
|
-
return;
|
|
3472
|
-
this.freeSlot(a, floor, cause, true);
|
|
3473
|
-
return;
|
|
3474
|
-
}
|
|
3475
|
-
if (!requireAuthoritativeExit)
|
|
3476
|
-
this.freeSlot(a, floor, cause, true);
|
|
3477
|
-
this.lifecycleInFlight++;
|
|
3478
|
-
void this.awaitHandleExit(a.handle)
|
|
3479
|
-
.then(() => {
|
|
3480
|
-
this.unverifiedStops = this.unverifiedStops.filter((stopped) => stopped.handle !== a.handle);
|
|
3481
|
-
this.freeSlot(a, floor, cause, true);
|
|
3482
|
-
}) // no-op once an accepted stop already freed it
|
|
3483
|
-
.catch((e) => {
|
|
3484
|
-
this.unverifiedStops = this.unverifiedStops.filter((stopped) => stopped.handle !== a.handle);
|
|
3485
|
-
this.unverifiedStops.push({
|
|
3486
|
-
name: a.name,
|
|
3487
|
-
id: a.id,
|
|
3488
|
-
handle: a.handle,
|
|
3489
|
-
authoritative: true,
|
|
3490
|
-
error: `accepted stop could not prove exit: ${rejectionText(e)}`,
|
|
3491
|
-
});
|
|
3492
|
-
})
|
|
3493
|
-
.finally(() => this.releaseLifecycle());
|
|
3494
|
-
}
|
|
3061
|
+
/** {@link SeatStop.stopHandle}. */
|
|
3062
|
+
stopHandle(...args) { return this.seatStopComponent.stopHandle(...args); }
|
|
3063
|
+
/** {@link SeatStop.stopWindowsSeat}. */
|
|
3064
|
+
stopWindowsSeat(...args) { return this.seatStopComponent.stopWindowsSeat(...args); }
|
|
3065
|
+
/** {@link SeatStop.trackStoppedHandle}. */
|
|
3066
|
+
trackStoppedHandle(...args) { return this.seatStopComponent.trackStoppedHandle(...args); }
|
|
3495
3067
|
provisionUserAgent(name, opts) { return this.userProvision.provisionUserAgent(name, opts); }
|
|
3496
3068
|
/** Shred a user agent's secret family from the store and from disk. Every removal is attempted,
|
|
3497
3069
|
* and each failure joins `unshredded`, so one fault cannot leave the rest of the family behind. */
|
|
@@ -3503,96 +3075,17 @@ export class Manager {
|
|
|
3503
3075
|
if (path)
|
|
3504
3076
|
await attemptCleanup(unshredded, `file ${path}`, () => rmSync(path, { force: true }));
|
|
3505
3077
|
}
|
|
3506
|
-
/**
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
* chokepoint for despawn, self-stop, reap and exit, which is why the line lives here rather than
|
|
3513
|
-
* being remembered at each of the six callers.
|
|
3514
|
-
*
|
|
3515
|
-
* THE RUNTIME'S EXIT DETAIL IS OPTIONAL AND ITS ABSENCE IS SAID OUT LOUD. `AgentHandle.exitInfo`
|
|
3516
|
-
* is only implemented by backends that own the child process; the rest genuinely cannot see how
|
|
3517
|
-
* it ended. Printing `code 0` for those would be a fabricated clean exit on exactly the seats
|
|
3518
|
-
* whose death nobody can explain, so an absent answer prints as unavailable and names the runtime
|
|
3519
|
-
* that could not provide it.
|
|
3520
|
-
*/
|
|
3521
|
-
logSeatReaped(a, cause) {
|
|
3522
|
-
const causeText = typeof cause === "string" ? FREE_SLOT_CAUSE_TEXT[cause] : stopCauseText(cause);
|
|
3523
|
-
let detail;
|
|
3524
|
-
try {
|
|
3525
|
-
const info = a.handle.exitInfo?.();
|
|
3526
|
-
detail = info === undefined
|
|
3527
|
-
? `exit detail unavailable from runtime "${a.handle.kind}"`
|
|
3528
|
-
: `exit code ${info.code ?? "unknown"}${info.signal === undefined ? "" : `, signal ${info.signal}`}${info.diagnostic ? `; diagnostic: ${info.diagnostic}` : ""}`;
|
|
3529
|
-
}
|
|
3530
|
-
catch (e) {
|
|
3531
|
-
// A runtime that throws while being asked has told us something real; it must not take the
|
|
3532
|
-
// log line (or the free path it sits on) down with it.
|
|
3533
|
-
detail = `exit detail unreadable from runtime "${a.handle.kind}": ${rejectionText(e)}`;
|
|
3534
|
-
}
|
|
3535
|
-
console.error(`seat reaped: ${a.name} (${a.id}, uid ${a.lifecycleUid}${a.handle.pid !== undefined ? `, pid ${a.handle.pid}` : ""}) - ${causeText}; ${detail}`);
|
|
3536
|
-
}
|
|
3537
|
-
/**
|
|
3538
|
-
* A SEAT THAT LEAVES THE MESH WHILE ITS SLOT IS HELD GETS A LINE, AND SO DOES ITS RETURN.
|
|
3539
|
-
*
|
|
3540
|
-
* Seats once read `running · mesh offline` for many hours with no manager log line, so a watchdog
|
|
3541
|
-
* keyed on process liveness saw nothing wrong and nobody could say when each seat dropped (#1208).
|
|
3542
|
-
* The line follows the same state `ps` reads, checked on every roster change and view transition,
|
|
3543
|
-
* because not every offline record arrives as a presence event: after a reconnect the fresh snapshot
|
|
3544
|
-
* records an already-offline seat quietly. Only a current view is a verdict, so a stale or
|
|
3545
|
-
* unpopulated one logs nothing. The match is {@link isOwnPresence}. A seat being stopped is left to
|
|
3546
|
-
* the reap line. The heartbeat is the seat's own record and nothing validated it, so an unreadable
|
|
3547
|
-
* one prints as unknown instead of throwing inside the watch.
|
|
3548
|
-
*/
|
|
3549
|
-
logSeatMeshTransitions() {
|
|
3550
|
-
if (typeof this.ep.presenceView === "function" && this.ep.presenceView().state !== "current")
|
|
3551
|
-
return;
|
|
3552
|
-
const roster = new Map(this.ep.getRoster().map((p) => [p.card.id, p]));
|
|
3553
|
-
for (const a of this.agents.values()) {
|
|
3554
|
-
const seen = roster.get(this.managedPrincipal(a));
|
|
3555
|
-
if (a.terminalizing || !this.isOwnPresence(a, seen))
|
|
3556
|
-
continue;
|
|
3557
|
-
if (seen.status !== "offline")
|
|
3558
|
-
a.joinIssue = undefined;
|
|
3559
|
-
const who = `${a.name} (${a.id}, uid ${a.lifecycleUid}${a.handle.pid !== undefined ? `, pid ${a.handle.pid}` : ""})`;
|
|
3560
|
-
if (seen.status === "offline" && !a.offMesh) {
|
|
3561
|
-
a.offMesh = true;
|
|
3562
|
-
const ts = seen.ts;
|
|
3563
|
-
const last = typeof ts === "number" && !Number.isNaN(new Date(ts).getTime()) ? new Date(ts).toISOString() : "unknown";
|
|
3564
|
-
console.error(`seat offline on the mesh: ${who} - last heartbeat ${last}; process ${a.handle.status()}`);
|
|
3565
|
-
}
|
|
3566
|
-
else if (seen.status !== "offline" && a.offMesh) {
|
|
3567
|
-
a.offMesh = false;
|
|
3568
|
-
console.error(`seat back on the mesh: ${who}`);
|
|
3569
|
-
}
|
|
3570
|
-
}
|
|
3571
|
-
}
|
|
3572
|
-
/** Whether a roster record is this seat's own: the readiness fence's exact principal and
|
|
3573
|
-
* incarnation, so a same-named foreign peer or an older incarnation never speaks for it (#1208). */
|
|
3574
|
-
isOwnPresence(a, p) {
|
|
3575
|
-
return p !== undefined && p.card.id === this.managedPrincipal(a) && p.lifecycleUid === a.lifecycleUid;
|
|
3576
|
-
}
|
|
3078
|
+
/** {@link SeatStop.logSeatReaped}. */
|
|
3079
|
+
logSeatReaped(...args) { return this.seatStopComponent.logSeatReaped(...args); }
|
|
3080
|
+
/** {@link SeatStop.logSeatMeshTransitions}. */
|
|
3081
|
+
logSeatMeshTransitions(...args) { return this.seatStopComponent.logSeatMeshTransitions(...args); }
|
|
3082
|
+
/** {@link SeatStop.isOwnPresence}. */
|
|
3083
|
+
isOwnPresence(a, p) { return this.seatStopComponent.isOwnPresence(a, p); }
|
|
3577
3084
|
freeSlot(a, floor, cause, acceptedBeforeFence = false) { this.namesCapacity.freeSlot(a, floor, cause, acceptedBeforeFence); }
|
|
3578
|
-
/**
|
|
3579
|
-
|
|
3580
|
-
|
|
3581
|
-
|
|
3582
|
-
try {
|
|
3583
|
-
removeInlineSnapshot(this.workspaceRoot, lifecycleUid);
|
|
3584
|
-
return true;
|
|
3585
|
-
}
|
|
3586
|
-
catch (e) {
|
|
3587
|
-
console.error(`! ${name}: its inline persona snapshot could not be removed: ${rejectionText(e)}`);
|
|
3588
|
-
return false;
|
|
3589
|
-
}
|
|
3590
|
-
}
|
|
3591
|
-
/** A live agent's teardown target, built field by field so the rest of its record (handle, seed,
|
|
3592
|
-
* restart state) never rides into the detached teardown or its single-flight map. */
|
|
3593
|
-
teardownTarget(a) {
|
|
3594
|
-
return { id: a.id, name: a.name, lifecycleUid: a.lifecycleUid, userOwner: a.userOwner, delegated: a.delegated, secretPaths: a.secretPaths, runtime: a.handle?.reference, ...(a.handedOff ? { delegatedHandle: a.handle } : {}), launch: { allowSubscribe: a.launch.allowSubscribe }, staticCredentialRenewal: a.staticCredentialRenewal };
|
|
3595
|
-
}
|
|
3085
|
+
/** {@link SeatStop.dropInlineSnapshot}. */
|
|
3086
|
+
dropInlineSnapshot(...args) { return this.seatStopComponent.dropInlineSnapshot(...args); }
|
|
3087
|
+
/** {@link SeatStop.teardownTarget}. */
|
|
3088
|
+
teardownTarget(...args) { return this.seatStopComponent.teardownTarget(...args); }
|
|
3596
3089
|
deprovision(a) { return this.retirement.deprovision(a); }
|
|
3597
3090
|
/** Run one retirement in a {@link RETIREMENT_CONCURRENCY} slot, oldest first: a seat's deprovision, a
|
|
3598
3091
|
* chat session's terminal and a static reconcile's terminal all take one. No retirement awaits
|
|
@@ -3616,47 +3109,12 @@ export class Manager {
|
|
|
3616
3109
|
}
|
|
3617
3110
|
confirmRetirement(a) { this.retirement.confirmRetirement(a); }
|
|
3618
3111
|
deprovisionBroker(a) { return this.retirement.deprovisionBroker(a); }
|
|
3619
|
-
/**
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
return undefined;
|
|
3626
|
-
}
|
|
3627
|
-
catch (e) {
|
|
3628
|
-
return rejectionText(e);
|
|
3629
|
-
}
|
|
3630
|
-
}
|
|
3631
|
-
/** The retiring lifecycle's durable membership channels, read from the delivery daemon's
|
|
3632
|
-
* `lifecycleMemberships` admin verb (read-only, lifecycle-exact). Incomplete on any refusal. */
|
|
3633
|
-
async lifecycleMembershipInventory(a) {
|
|
3634
|
-
const t = deprovisionTargetPrincipal({ principal: a.id, lifecycleUid: a.lifecycleUid });
|
|
3635
|
-
try {
|
|
3636
|
-
const r = await this.ep.requestDeliveryAdmin("lifecycleMemberships", { principal: principalKey(t.owner, t.actor).key, lifecycleUid: t.lifecycleUid }, 5_000);
|
|
3637
|
-
const data = r.data;
|
|
3638
|
-
if (!r.ok || data?.complete !== true || !Array.isArray(data.channels) || !data.channels.every((c) => typeof c === "string" && (isConcreteChannel(c) || isChannelFamily(c))))
|
|
3639
|
-
return { complete: false, channels: [], reason: r.ok ? "malformed inventory reply" : (r.error ?? "refused") };
|
|
3640
|
-
return { complete: true, channels: data.channels };
|
|
3641
|
-
}
|
|
3642
|
-
catch (e) {
|
|
3643
|
-
return { complete: false, channels: [], reason: rejectionText(e) };
|
|
3644
|
-
}
|
|
3645
|
-
}
|
|
3646
|
-
/** Reap a parent's children on its exit (P4b). Every descendant remains managed until the runtime's
|
|
3647
|
-
* authoritative wait proves exit; the wait participates in the lifecycle drain, so preservation can
|
|
3648
|
-
* never omit a child that may still be alive. Recursive descendants are scheduled before their parent
|
|
3649
|
-
* slot can disappear. */
|
|
3650
|
-
reapChildrenOf(parentId) {
|
|
3651
|
-
for (const child of [...this.agents.values()]) {
|
|
3652
|
-
if (child.spawner !== parentId)
|
|
3653
|
-
continue;
|
|
3654
|
-
this.reapChildrenOf(this.managedPrincipal(child));
|
|
3655
|
-
const cause = { kind: "stopped-reap", parent: parentId };
|
|
3656
|
-
this.stopHandle(child, false, cause);
|
|
3657
|
-
this.trackStoppedHandle(child, true, cause, true);
|
|
3658
|
-
}
|
|
3659
|
-
}
|
|
3112
|
+
/** {@link SeatStop.fenceRetiringAcl}. */
|
|
3113
|
+
fenceRetiringAcl(...args) { return this.seatStopComponent.fenceRetiringAcl(...args); }
|
|
3114
|
+
/** {@link SeatStop.lifecycleMembershipInventory}. */
|
|
3115
|
+
lifecycleMembershipInventory(...args) { return this.seatStopComponent.lifecycleMembershipInventory(...args); }
|
|
3116
|
+
/** {@link SeatStop.reapChildrenOf}. */
|
|
3117
|
+
reapChildrenOf(...args) { return this.seatStopComponent.reapChildrenOf(...args); }
|
|
3660
3118
|
readManagedSessionState(a) {
|
|
3661
3119
|
return this.sessionRecovery.readManagedSessionState(a);
|
|
3662
3120
|
}
|
|
@@ -3708,42 +3166,8 @@ export class Manager {
|
|
|
3708
3166
|
recoverManagedSession(a) {
|
|
3709
3167
|
return this.sessionRecovery.recoverManagedSession(a);
|
|
3710
3168
|
}
|
|
3711
|
-
/**
|
|
3712
|
-
|
|
3713
|
-
* restart in place after readiness; a spawn carrying `supervise` restarts any connector the same
|
|
3714
|
-
* way, without classifying a session-state file. Every other exit follows the existing terminal
|
|
3715
|
-
* path. */
|
|
3716
|
-
onAgentExit(a) {
|
|
3717
|
-
// Preservation owns the child-stop snapshot. Exit watchers must neither delete that snapshot nor
|
|
3718
|
-
// trigger normal deprovision/reap while the cut is being formed.
|
|
3719
|
-
if (this.maintenanceState !== "active")
|
|
3720
|
-
return;
|
|
3721
|
-
// A Windows stop owns the exit proof and its truthful reap cause. The raw
|
|
3722
|
-
// terminal event must not release a slot while cohort verification is pending.
|
|
3723
|
-
if (process.platform === "win32" && a.handle.kind === "pty" && a.terminalizing)
|
|
3724
|
-
return;
|
|
3725
|
-
// A replacement is proving readiness under this row. Its own wait owns a failed
|
|
3726
|
-
// relaunch; treating that exit as a seat death would free the slot mid-recovery.
|
|
3727
|
-
if (a.restart?.recovering && !a.terminalizing)
|
|
3728
|
-
return;
|
|
3729
|
-
if (a.restart?.armed && !a.terminalizing) {
|
|
3730
|
-
if (a.restart.policy !== undefined) {
|
|
3731
|
-
this.recoverManagedSession(a);
|
|
3732
|
-
return;
|
|
3733
|
-
}
|
|
3734
|
-
try {
|
|
3735
|
-
if (this.readManagedSessionState(a).status === "running") {
|
|
3736
|
-
this.recoverManagedSession(a);
|
|
3737
|
-
return;
|
|
3738
|
-
}
|
|
3739
|
-
}
|
|
3740
|
-
catch (error) {
|
|
3741
|
-
console.error(`! ${a.name}: cannot classify Pi process exit for recovery: ${rejectionText(error)} - retiring the seat`);
|
|
3742
|
-
}
|
|
3743
|
-
}
|
|
3744
|
-
this.freeSlot(a, true, a.stopCause ?? "process-exit");
|
|
3745
|
-
this.reapChildrenOf(this.managedPrincipal(a));
|
|
3746
|
-
}
|
|
3169
|
+
/** {@link SeatStop.onAgentExit}. */
|
|
3170
|
+
onAgentExit(...args) { return this.seatStopComponent.onAgentExit(...args); }
|
|
3747
3171
|
nameError(name) { return this.namesCapacity.nameError(name); }
|
|
3748
3172
|
/** Spawn a teammate by persona ref (`name` loads `.cotal/agents/<name>.md`; the peer presents
|
|
3749
3173
|
* under that file's own `name:`), as if a peer asked via the control plane. Used to pre-spawn the
|
|
@@ -5185,118 +4609,15 @@ export class Manager {
|
|
|
5185
4609
|
ownerSeats(owner) { return this.namesCapacity.ownerSeats(owner); }
|
|
5186
4610
|
/** The per-owner ceiling at accept: {@link NamesCapacity.seatCapRefusal}. */
|
|
5187
4611
|
seatCapRefusal(owner) { return this.namesCapacity.seatCapRefusal(owner); }
|
|
4612
|
+
/** {@link SeatStop.opStop}. */
|
|
5188
4613
|
// @ts-expect-error TS6133: retained fixtures call this private adapter through structural views.
|
|
5189
|
-
|
|
5190
|
-
|
|
5191
|
-
|
|
5192
|
-
|
|
5193
|
-
|
|
5194
|
-
|
|
5195
|
-
|
|
5196
|
-
}
|
|
5197
|
-
catch (error) {
|
|
5198
|
-
return { ok: false, error: rejectionText(error) };
|
|
5199
|
-
}
|
|
5200
|
-
}
|
|
5201
|
-
/** The ONE named-terminal core both doors share: the ctl named `stop`
|
|
5202
|
-
* and the v0.4 targeted `despawn` are the same terminal — authorize by the shared policy
|
|
5203
|
-
* ({@link authorizeNamed}: own-child / owner-domain on privileged, any on admin), stop, track.
|
|
5204
|
-
* The ep door runs the SAME two pieces separately so a policy denial surfaces as the §13.3
|
|
5205
|
-
* `permission-denied` (never a generic failure). */
|
|
5206
|
-
async despawnCore(a, caller, admin, graceful) {
|
|
5207
|
-
const denied = await this.authorizeNamed(a, caller, admin);
|
|
5208
|
-
if (denied)
|
|
5209
|
-
return { ok: false, error: denied };
|
|
5210
|
-
return this.despawnAuthorized(a, graceful, !admin, caller);
|
|
5211
|
-
}
|
|
5212
|
-
/** The post-authorization terminal effect (both doors). `trackNonAdmin` mirrors the ctl door's
|
|
5213
|
-
* `trackStoppedHandle(a, !admin)` disposition. The reap line names `caller` — the AUTHENTICATED
|
|
5214
|
-
* wire principal the door already resolved — so an operator reading the log can tell one peer's
|
|
5215
|
-
* despawn from another's. */
|
|
5216
|
-
despawnAuthorized(a, graceful, trackNonAdmin, caller) {
|
|
5217
|
-
if (process.platform === "win32" && a.handle.kind === "pty") {
|
|
5218
|
-
return this.stopWindowsSeat(a, graceful, trackNonAdmin, { kind: "stopped-requested", requester: caller }).then(() => {
|
|
5219
|
-
void this.cancelAgentGoal(a.name, graceful ? "graceful" : "terminate");
|
|
5220
|
-
return { ok: true, data: { name: a.name, stopped: true, graceful } };
|
|
5221
|
-
});
|
|
5222
|
-
}
|
|
5223
|
-
const cause = { kind: "stopped-requested", requester: caller };
|
|
5224
|
-
this.stopHandle(a, graceful, cause);
|
|
5225
|
-
this.trackStoppedHandle(a, trackNonAdmin, cause);
|
|
5226
|
-
void this.cancelAgentGoal(a.name, graceful ? "graceful" : "terminate"); // Cancel a live spawn goal
|
|
5227
|
-
return { ok: true, data: { name: a.name, stopped: true, graceful } };
|
|
5228
|
-
}
|
|
5229
|
-
/** Retire one agent this manager launched under a delegated user intent, through the host
|
|
5230
|
-
* (SPEC 13.16). It sends the user's retirement intent for the UID of the running slot or its
|
|
5231
|
-
* retirement hold, and only on `retired: true` for that exact target stops the slot, shreds the
|
|
5232
|
-
* seat's local secret family and frees the name; every other answer leaves the slot running or
|
|
5233
|
-
* the name held, and a failed shred keeps the name held. It never calls the holder's own prepare
|
|
5234
|
-
* or requester. */
|
|
5235
|
-
async retireDelegatedAgent(name, intentId) {
|
|
5236
|
-
const execute = this.remoteAuthority?.executeDelegatedUserIntent;
|
|
5237
|
-
if (!execute)
|
|
5238
|
-
return { ok: false, error: `this manager has no host execution for a delegated user intent; "${name}" was not retired` };
|
|
5239
|
-
const release = this.beginLifecycle();
|
|
5240
|
-
if (!release)
|
|
5241
|
-
return { ok: false, error: this.maintenanceError() };
|
|
5242
|
-
try {
|
|
5243
|
-
const live = this.agents.get(name);
|
|
5244
|
-
const held = live ? undefined : this.retirement.held(name);
|
|
5245
|
-
const principal = live?.delegated ? parsePrincipalKey(live.id) : held?.target.delegated ? held : null;
|
|
5246
|
-
const lifecycleUid = live?.lifecycleUid ?? held?.target.lifecycleUid;
|
|
5247
|
-
if (!principal || !lifecycleUid)
|
|
5248
|
-
return { ok: false, error: `no agent named "${name}" was launched on this manager under a delegated user intent` };
|
|
5249
|
-
const target = { owner: principal.owner, actor: principal.actor, lifecycleUid };
|
|
5250
|
-
try {
|
|
5251
|
-
const result = await execute({ intentId, operation: "retire", target });
|
|
5252
|
-
if (result.operation !== "retire" || result.intentId !== intentId || result.opId !== managedRetirementOpId(target.lifecycleUid) ||
|
|
5253
|
-
result.target.owner !== target.owner || result.target.actor !== target.actor || result.target.lifecycleUid !== target.lifecycleUid)
|
|
5254
|
-
throw new Error(`the host answered delegated intent ${intentId} with another execution`);
|
|
5255
|
-
if (result.retired !== true)
|
|
5256
|
-
return { ok: false, error: `the host did not confirm the delegated retirement of "${name}" at ${target.lifecycleUid}; "${name}" is unchanged` };
|
|
5257
|
-
}
|
|
5258
|
-
catch (e) {
|
|
5259
|
-
const error = `the delegated retirement under intent ${intentId} did not complete (${rejectionText(e)})`;
|
|
5260
|
-
const hold = this.retirement.held(name);
|
|
5261
|
-
if (hold?.target.lifecycleUid === target.lifecycleUid)
|
|
5262
|
-
hold.lastError = error;
|
|
5263
|
-
return { ok: false, error: `${error}; "${name}" is unchanged` };
|
|
5264
|
-
}
|
|
5265
|
-
// The host's retirement closed this UID's provider handle before its barrier, so the stop only
|
|
5266
|
-
// reaps the slot, and its hold clears with the confirmation.
|
|
5267
|
-
const slot = this.agents.get(name);
|
|
5268
|
-
if (slot?.lifecycleUid === target.lifecycleUid)
|
|
5269
|
-
await this.despawnAuthorized(slot, true, false, `delegated retirement ${intentId}`);
|
|
5270
|
-
// The host owns the grant and the footprint, but the secret family enrollUserAgent wrote here
|
|
5271
|
-
// is this participant's, and no teardown arm of a delegated seat removes it.
|
|
5272
|
-
const unshredded = [];
|
|
5273
|
-
await this.shredUserSecrets(unshredded, (live ?? held?.target)?.secretPaths ?? agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, target.lifecycleUid));
|
|
5274
|
-
if (unshredded.length) {
|
|
5275
|
-
const error = `the host retired "${name}" at ${target.lifecycleUid}, but cleanup failed: ${describeCleanupFailures(unshredded)}; the name stays held until a retried retirement intent removes it`;
|
|
5276
|
-
const hold = this.retirement.held(name);
|
|
5277
|
-
if (hold?.target.lifecycleUid === target.lifecycleUid)
|
|
5278
|
-
hold.lastError = error;
|
|
5279
|
-
return { ok: false, error };
|
|
5280
|
-
}
|
|
5281
|
-
this.confirmRetirement({ id: principalKey(target.owner, target.actor).key, name, lifecycleUid: target.lifecycleUid });
|
|
5282
|
-
return { ok: true, data: { name, lifecycleUid: target.lifecycleUid, retired: true } };
|
|
5283
|
-
}
|
|
5284
|
-
finally {
|
|
5285
|
-
release();
|
|
5286
|
-
}
|
|
5287
|
-
}
|
|
5288
|
-
/** Resolve a v0.4 TARGET triple (owner, actor, lifecycleUid — broker-validated subject/body
|
|
5289
|
-
* agreement, currency re-checked by the serve boundary's resolver) to the live managed agent it
|
|
5290
|
-
* names. Static agents key `(DEV_OWNER, nkey)`; user-mode agents store the principal dot-form
|
|
5291
|
-
* in `id`. A uid mismatch is a superseded incarnation — never resolved to its successor. */
|
|
5292
|
-
findManagedByTarget(t) {
|
|
5293
|
-
for (const a of this.agents.values()) {
|
|
5294
|
-
const matches = a.userOwner ? a.id === principalKey(t.owner, t.actor).key : t.owner === DEV_OWNER && a.id === t.actor;
|
|
5295
|
-
if (matches && a.lifecycleUid === t.lifecycleUid)
|
|
5296
|
-
return a;
|
|
5297
|
-
}
|
|
5298
|
-
return undefined;
|
|
5299
|
-
}
|
|
4614
|
+
opStop(...args) { return this.seatStopComponent.opStop(...args); }
|
|
4615
|
+
/** {@link SeatStop.despawnAuthorized}. */
|
|
4616
|
+
despawnAuthorized(...args) { return this.seatStopComponent.despawnAuthorized(...args); }
|
|
4617
|
+
/** {@link SeatStop.retireDelegatedAgent}. */
|
|
4618
|
+
retireDelegatedAgent(name, intentId) { return this.seatStopComponent.retireDelegatedAgent(name, intentId); }
|
|
4619
|
+
/** {@link SeatStop.findManagedByTarget}. */
|
|
4620
|
+
findManagedByTarget(...args) { return this.seatStopComponent.findManagedByTarget(...args); }
|
|
5300
4621
|
/** Run one static §13.1 lifecycle OPERATION over an ephemeral, key-pinned `lifecycle-executor`
|
|
5301
4622
|
* connection: the credential's grants name exactly ONE incarnation's head/uid/gate/
|
|
5302
4623
|
* cred-family/slot keys, so the write authority exists only for this operation's window and
|
|
@@ -5548,315 +4869,12 @@ export class Manager {
|
|
|
5548
4869
|
emitGoalProgress(...args) { return this.goalWriterComponent.emitGoalProgress(...args); }
|
|
5549
4870
|
/** {@link GoalWriter.assertGoalWriterEpochCurrent}. */
|
|
5550
4871
|
assertGoalWriterEpochCurrent(...args) { return this.goalWriterComponent.assertGoalWriterEpochCurrent(...args); }
|
|
5551
|
-
/**
|
|
5552
|
-
|
|
5553
|
-
|
|
5554
|
-
|
|
5555
|
-
|
|
5556
|
-
|
|
5557
|
-
catch (e) {
|
|
5558
|
-
const persona = ctx.request.args?.name;
|
|
5559
|
-
console.error(oneLine(`! spawn request ${ctx.request.id} for persona "${String(persona ?? "")}" refused (${e instanceof EpEnvelopeError ? e.code : "error"}): ${rejectionText(e)}`));
|
|
5560
|
-
throw e;
|
|
5561
|
-
}
|
|
5562
|
-
}
|
|
5563
|
-
/** Serve `spawn`/`launch` as an ACTION. Authz already ran in {@link serveGated}. The
|
|
5564
|
-
* accept path runs INLINE on the handler ({@link startAgent} with hooks): the goal binds + the
|
|
5565
|
-
* acceptance replies the moment the identity is minted, BEFORE any provision, or on the
|
|
5566
|
-
* hosted enrollment arm once the host has enrolled the agent; progress and the terminal are driven
|
|
5567
|
-
* OFF-handler, so the ~30s readiness wait no longer blocks the reply.
|
|
5568
|
-
* Returns the acceptance floor payload {name, owner, actor, uid, goalId, fingerprint, executor}
|
|
5569
|
-
* (the ALLOCATED identity). goalId = the request id (env.id). */
|
|
5570
|
-
async serveSpawnGoal(ctx, run) {
|
|
5571
|
-
// These four refuse before anything is accepted or allocated, so they state it (SPEC 13.3).
|
|
5572
|
-
if (this.execution === "none")
|
|
5573
|
-
throw new EpEnvelopeError("unimplemented", this.executionRefusal(), undefined, "not-executed");
|
|
5574
|
-
const gw = this.goalWriter;
|
|
5575
|
-
if (!gw)
|
|
5576
|
-
throw new EpEnvelopeError("unavailable", "the manager goal-writer connection is not standing; spawn-as-action cannot accept (SPEC 13.6)", undefined, "not-executed");
|
|
5577
|
-
// Refuse to accept until the boot reconcile of inherited goals completes, so a fresh
|
|
5578
|
-
// acceptance never races the sweep (settling a live goal mid-flight would steal its real terminal).
|
|
5579
|
-
if (!this.goalReconcileDone)
|
|
5580
|
-
throw new EpEnvelopeError("unavailable", "the manager is still reconciling accepted goals at boot; retry shortly (SPEC 13.6)", undefined, "not-executed");
|
|
5581
|
-
const goalId = ctx.request.id;
|
|
5582
|
-
const { fingerprint } = submissionFingerprint(ctx.request, ctx.subject);
|
|
5583
|
-
const ref = goalRefOf(ctx.subject, goalId);
|
|
5584
|
-
const key = goalKey(ref);
|
|
5585
|
-
const executor = { lifecycleUid: this.managerInstanceId, epoch: this.serviceServe?.grant.epoch ?? 0 };
|
|
5586
|
-
const epoch = executor.epoch;
|
|
5587
|
-
const acceptedAt = Date.now();
|
|
5588
|
-
// Idempotent same-goalId retry (a client re-send): serve the IDENTICAL acceptance without
|
|
5589
|
-
// re-running the accept path — so a HARD-PINNED retry does not trip the same-name refuse and no
|
|
5590
|
-
// name is re-allocated. Same-incarnation rides the live map; the create-only bindGoal in onAccepted
|
|
5591
|
-
// still fences a CONCURRENT same-goalId race (the loser aborts and serves the winner's acceptance).
|
|
5592
|
-
const prior = this.goalAcceptances.get(key);
|
|
5593
|
-
// A goal that already ENDED is answered from its committed terminal and never accepted again.
|
|
5594
|
-
// Running the accept for it allocates a fresh name and identity, then refuses at the index
|
|
5595
|
-
// CAS, because the entry its terminal cleared cannot be created twice, and that refusal tells
|
|
5596
|
-
// the caller to reconcile the store. A retry that outlived its entry above must not reach it.
|
|
5597
|
-
const ended = prior === undefined ? await readGoalResult(gw.ctx, ref) : undefined;
|
|
5598
|
-
const accepted = prior ?? ended;
|
|
5599
|
-
if (accepted !== undefined) {
|
|
5600
|
-
if (accepted.fingerprint !== fingerprint)
|
|
5601
|
-
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");
|
|
5602
|
-
return prior ?? this.cachedSpawnAcceptance(ref, goalId, fingerprint, executor);
|
|
5603
|
-
}
|
|
5604
|
-
let resolveAccept;
|
|
5605
|
-
let rejectAccept;
|
|
5606
|
-
const acceptP = new Promise((res, rej) => { resolveAccept = res; rejectAccept = rej; });
|
|
5607
|
-
let acceptance;
|
|
5608
|
-
let readinessTimeoutMs = this.readinessTimeoutMs;
|
|
5609
|
-
// H1: set the instant the terminal path is ENTERED, not when it succeeds — the post-accept
|
|
5610
|
-
// fallback below must fire only when `onOutcome` never ran at all, never as a second attempt
|
|
5611
|
-
// behind a commit that threw.
|
|
5612
|
-
let terminalEntered = false;
|
|
5613
|
-
// TWO DIFFERENT QUESTIONS, DELIBERATELY NOT ONE FLAG.
|
|
5614
|
-
//
|
|
5615
|
-
// `terminalEntered` HAS this goal already been settled (or claimed) by someone?
|
|
5616
|
-
// `ownsGoal` MAY THIS ATTEMPT settle it at all?
|
|
5617
|
-
//
|
|
5618
|
-
// The second is the authority, and it is default-CLOSED: an attempt earns it by WINNING the
|
|
5619
|
-
// create-only `bindGoal` CAS below, and nothing else grants it. That matters because the
|
|
5620
|
-
// post-accept fallback exists to settle a goal nobody answered, so every new way of leaving
|
|
5621
|
-
// this function is opted INTO committing a terminal unless something stops it. Deriving the
|
|
5622
|
-
// right from the claim instead of from a running record means a losing attempt CANNOT commit
|
|
5623
|
-
// down any unwind path, including ones added later that never thought about this. Collapsing
|
|
5624
|
-
// the two into one boolean is what let a duplicate-goal loser steal the winner's terminal
|
|
5625
|
-
// (#357): it had entered no terminal, so the fallback wrote one for it, using its own abort
|
|
5626
|
-
// message as the caller-visible outcome.
|
|
5627
|
-
let ownsGoal = false;
|
|
5628
|
-
// Set by onEffect. A refusal that arrives with it still false changed nothing.
|
|
5629
|
-
let effectStarted = false;
|
|
5630
|
-
// Set by onUndone: the host's code for a later refusal that left nothing behind.
|
|
5631
|
-
let undone;
|
|
5632
|
-
// The task of a once spawn, once accepted.
|
|
5633
|
-
let onceRef;
|
|
5634
|
-
// The terminal commits OFF-handler on the goal-writer connection (manager-only authority; a
|
|
5635
|
-
// caller cannot publish it). TWO COMPOSED FENCES (defense in depth): (a) reads THIS
|
|
5636
|
-
// incarnation's OWN gate epoch and REFUSES a superseded commit (the currency belt), and (b)
|
|
5637
|
-
// barrier-revoke evicts this connection on takeover. The terminal lands on the ONE subject
|
|
5638
|
-
// SPEC §13.2 (reserved subjects) reserves; first-terminal-fact-wins is global, so a committed outcome is visible
|
|
5639
|
-
// to every reader in every incarnation. On success the reconcile-index entry is cleared.
|
|
5640
|
-
//
|
|
5641
|
-
// Named rather than inlined into the hooks below so the H1 post-accept fallback drives THIS
|
|
5642
|
-
// path — one commit site, so the progress event, the index clear and the `agentGoals` cleanup
|
|
5643
|
-
// cannot drift between a normal outcome and a recovered one.
|
|
5644
|
-
const onOutcome = async (o) => {
|
|
5645
|
-
// THE AUTHORITY CHECK, and the only one. An attempt that never won the bind provisioned
|
|
5646
|
-
// nothing and has no outcome to report: the goal belongs to whoever won it, in this
|
|
5647
|
-
// incarnation or a sibling. Refusing here rather than at each unwind site is the point --
|
|
5648
|
-
// there is exactly one commit path, so this fences every route into it, present and future.
|
|
5649
|
-
if (!ownsGoal)
|
|
5650
|
-
return false;
|
|
5651
|
-
terminalEntered = true; // entered, not succeeded — see the catch below
|
|
5652
|
-
// A once spawn that did not succeed never served its task (delivery opens only with a
|
|
5653
|
-
// succeeded verdict), so the task is cancelled now rather than at the seat's exit. A launched
|
|
5654
|
-
// seat's debt is still settled by its exit, which proves the seat gone first; a spawn that
|
|
5655
|
-
// never launched one owes nothing more.
|
|
5656
|
-
if (o.kind !== "succeeded" && onceRef !== undefined) {
|
|
5657
|
-
const reason = o.kind === "uncertain" ? "readiness-timeout" : "launch-failed";
|
|
5658
|
-
if (this.onceWatched.has(goalKey(onceRef)))
|
|
5659
|
-
void this.commitOnceCancel(onceRef, reason).catch((e) => console.error(`! once task ${onceRef.goalId} (${reason}): ${rejectionText(e)}; its seat's exit cancels it`));
|
|
5660
|
-
else
|
|
5661
|
-
void this.settleOnceTurn(onceRef, reason);
|
|
5662
|
-
}
|
|
5663
|
-
try {
|
|
5664
|
-
await this.assertGoalWriterEpochCurrent(epoch); // a superseded corpse never commits
|
|
5665
|
-
let fact;
|
|
5666
|
-
if (o.kind === "succeeded") {
|
|
5667
|
-
this.emitGoalProgress(ref, epoch, { phase: "presence" });
|
|
5668
|
-
({ fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "complete", state: "succeeded", data: o.data, committer: { instanceId: this.managerInstanceId, epoch } }));
|
|
5669
|
-
}
|
|
5670
|
-
else if (o.kind === "failed") {
|
|
5671
|
-
({ fact } = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "complete", state: "failed", data: o.data, committer: { instanceId: this.managerInstanceId, epoch } }));
|
|
5672
|
-
}
|
|
5673
|
-
else {
|
|
5674
|
-
// Forward the readiness detail as the terminal's reason: this manager owns the deadline,
|
|
5675
|
-
// so it owns what elapsing it MEANS. Absent, core commits its own generic line (#605).
|
|
5676
|
-
const { reason: why, running } = (o.data ?? {});
|
|
5677
|
-
({ 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 } : {}) }));
|
|
5678
|
-
}
|
|
5679
|
-
this.expireGoalAcceptance(ref);
|
|
5680
|
-
this.emitGoalProgress(ref, epoch, { phase: "terminal", state: fact.state, ...(fact.data !== undefined ? { data: fact.data } : {}) });
|
|
5681
|
-
await clearGoalIndex(gw.ctx, ref); // terminal reached - the successor never reconciles it
|
|
5682
|
-
if (acceptance)
|
|
5683
|
-
this.agentGoals.delete(acceptance.name); // goal terminal - no cancel path left
|
|
5684
|
-
return true;
|
|
5685
|
-
}
|
|
5686
|
-
catch (e) {
|
|
5687
|
-
// THE NARROWER LEG, LEFT OPEN DELIBERATELY. If the COMMIT ITSELF throws (the currency belt
|
|
5688
|
-
// refused a superseded commit, or the broker failed) there is genuinely no terminal, and the
|
|
5689
|
-
// H1 fallback must NOT retry it: a retry either loses the same way or overwrites a real
|
|
5690
|
-
// supersession refusal with a manufactured outcome. That is why `terminalEntered` is set on
|
|
5691
|
-
// ENTRY. This leg is infrastructure-class and converges through the reconcile index at the
|
|
5692
|
-
// next boot, which is why the index is NOT cleared above on this path. Do not "close" it
|
|
5693
|
-
// here with a retry loop.
|
|
5694
|
-
console.error(`! goal terminal commit for ${goalId} failed: ${rejectionText(e)}`);
|
|
5695
|
-
return false;
|
|
5696
|
-
}
|
|
5697
|
-
};
|
|
5698
|
-
const bg = run({
|
|
5699
|
-
onAccepted: async ({ name, agentTriple }) => {
|
|
5700
|
-
// Record the goal in the reconcile index BEFORE the bind (index-CAS-before-bind),
|
|
5701
|
-
// so a successor incarnation finds + settles this goal if we crash before its terminal. A
|
|
5702
|
-
// crash between this write and the bind leaves an index entry whose goal status is absent —
|
|
5703
|
-
// the sweep clears it as a no-goal; a crash before it leaves no entry (never durable). A
|
|
5704
|
-
// Carry THIS incarnation's instanceId (the executor coord) so a multi-instance sweep can skip a live sibling's goal.
|
|
5705
|
-
//
|
|
5706
|
-
// H2, THE ACCEPTANCE FLOOR: the allocated identity is written HERE, before the bind and so
|
|
5707
|
-
// before the acceptance is acked, because this entry is the only durable record of it that
|
|
5708
|
-
// exists that early — the goal spec does not carry it and the terminal does not exist yet.
|
|
5709
|
-
// A same-goalId attempt that loses the bind while the winner is still in flight can then
|
|
5710
|
-
// serve what the winner actually allocated instead of inventing an empty identity.
|
|
5711
|
-
const idx = await recordGoalIndex(gw.ctx, ref, executor.lifecycleUid, { name, owner: agentTriple.owner, actor: agentTriple.actor, uid: agentTriple.uid, readinessDeadlineMs: readinessTimeoutMs });
|
|
5712
|
-
// A create loss is an idempotent retry ONLY for the same incarnation. A FOREIGN iid means a
|
|
5713
|
-
// sibling instance accepted this goalId (the live vector is a client retry over ANYCAST, not
|
|
5714
|
-
// a journal consumer): this attempt provisions nothing and answers with the winner's floor,
|
|
5715
|
-
// or refuses if that instance never persisted one.
|
|
5716
|
-
if (!idx.recorded && idx.existing.iid !== executor.lifecycleUid) {
|
|
5717
|
-
acceptance = await this.acceptanceFromIndex(idx.existing, ref, goalId, fingerprint, executor);
|
|
5718
|
-
resolveAccept(acceptance);
|
|
5719
|
-
// No claim needed here: `ownsGoal` is still false, so the commit path refuses this attempt.
|
|
5720
|
-
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)`);
|
|
5721
|
-
}
|
|
5722
|
-
// Bind AFTER the accept-path checks (name/capacity/persona) + identity mint, BEFORE any provision:
|
|
5723
|
-
// a create-only CAS per goalId (a refused accept above left zero bind, zero reserve).
|
|
5724
|
-
const b = await bindGoal(gw.ctx, ref, fingerprint);
|
|
5725
|
-
if (!b.bound) {
|
|
5726
|
-
if (b.existing.fingerprint !== fingerprint)
|
|
5727
|
-
throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" is already bound to a different submission; one goalId never carries two specs (SPEC 13.6)`);
|
|
5728
|
-
// Lost a concurrent same-goalId race: serve the winner's acceptance and abort THIS provision
|
|
5729
|
-
// (no second spawn). The throw unwinds to the finally, which releases this attempt's reserve.
|
|
5730
|
-
acceptance = this.goalAcceptances.get(key) ?? await this.cachedSpawnAcceptance(ref, goalId, fingerprint, executor);
|
|
5731
|
-
resolveAccept(acceptance);
|
|
5732
|
-
// No claim needed here either. This attempt lost the CAS, so `ownsGoal` is still false and
|
|
5733
|
-
// the single check in `onOutcome` refuses it. Before that check existed this site had to
|
|
5734
|
-
// remember to claim the terminal by hand, and the one place that forgot is how a loser
|
|
5735
|
-
// came to commit `failed` on the winner's goal, using its own abort text as the outcome.
|
|
5736
|
-
// Unwind the provision (the acceptance is already served); the code is discarded by the
|
|
5737
|
-
// caller (acceptance !== undefined), so it just aborts this attempt's side-effects.
|
|
5738
|
-
throw new EpEnvelopeError("failed-precondition", `goal "${goalId}" is already accepted; the cached acceptance is served`);
|
|
5739
|
-
}
|
|
5740
|
-
// WON the claim: this attempt, and only this attempt, may settle this goal.
|
|
5741
|
-
ownsGoal = true;
|
|
5742
|
-
await createGoal(gw.ctx, ref, {
|
|
5743
|
-
fingerprint,
|
|
5744
|
-
command: ctx.subject.command,
|
|
5745
|
-
caller: { id: `${ctx.subject.caller.owner}.${ctx.subject.caller.actor}`, lifecycleUid: ctx.subject.caller.uid },
|
|
5746
|
-
// The ACCEPTING incarnation's epoch: half of the terminal's attribution pair (§13.6).
|
|
5747
|
-
acceptedEpoch: epoch,
|
|
5748
|
-
requestId: goalId,
|
|
5749
|
-
sourceSeq: 0,
|
|
5750
|
-
acceptedAt,
|
|
5751
|
-
readinessDeadlineMs: readinessTimeoutMs,
|
|
5752
|
-
});
|
|
5753
|
-
acceptance = { name, owner: agentTriple.owner, actor: agentTriple.actor, uid: agentTriple.uid, goalId, fingerprint, readinessDeadlineMs: readinessTimeoutMs, executor };
|
|
5754
|
-
this.goalAcceptances.set(key, acceptance);
|
|
5755
|
-
this.agentGoals.set(name, ref); // A despawn of this name mid-goal drives the cancel path
|
|
5756
|
-
resolveAccept(acceptance);
|
|
5757
|
-
this.emitGoalProgress(ref, epoch, { phase: "handoff" });
|
|
5758
|
-
},
|
|
5759
|
-
onLaunched: () => this.emitGoalProgress(ref, epoch, { phase: "launched" }),
|
|
5760
|
-
onReadinessWindow: (value) => { readinessTimeoutMs = value; },
|
|
5761
|
-
onOutcome,
|
|
5762
|
-
// Claim the terminal WITHOUT committing one: the despawn/stop that ended this launch owns
|
|
5763
|
-
// it and commits `cancel`. This only stops the non-ok reply below from manufacturing a
|
|
5764
|
-
// `failed` that would race that `cancel` (first-terminal-fact-wins).
|
|
5765
|
-
onTerminalDeferred: () => { terminalEntered = true; },
|
|
5766
|
-
onEffect: () => { effectStarted = true; },
|
|
5767
|
-
onUndone: (code) => { undone = code; },
|
|
5768
|
-
onOnce: async (task) => {
|
|
5769
|
-
try {
|
|
5770
|
-
const accepted = await this.acceptOnceTurn({ spawnRef: ref, fingerprint, command: ctx.subject.command, executor, acceptedAt, ...task });
|
|
5771
|
-
onceRef = accepted.ref;
|
|
5772
|
-
return accepted;
|
|
5773
|
-
}
|
|
5774
|
-
catch (e) {
|
|
5775
|
-
// The spawn goal is already bound, so its refusal is a terminal: nothing has launched.
|
|
5776
|
-
await onOutcome({ kind: "failed", data: { error: `the once task was not accepted: ${rejectionText(e)}` } });
|
|
5777
|
-
throw e;
|
|
5778
|
-
}
|
|
5779
|
-
},
|
|
5780
|
-
});
|
|
5781
|
-
bg.then((reply) => {
|
|
5782
|
-
// Refused BEFORE onAccepted (hard-pin collision, capacity, persona-not-found) — no goal bound.
|
|
5783
|
-
// Only a refusal before the first effect, or one whose effects were all removed, states
|
|
5784
|
-
// `not-executed`; a later one, such as the alias gate that re-drives a teardown, leaves the
|
|
5785
|
-
// outcome unknown.
|
|
5786
|
-
if (acceptance === undefined) {
|
|
5787
|
-
const details = reply.details;
|
|
5788
|
-
const code = undone ?? reply.code ?? "failed-precondition";
|
|
5789
|
-
rejectAccept(new EpEnvelopeError(code, reply.error ?? "spawn refused at accept", details, effectStarted && undone === undefined ? undefined : "not-executed"));
|
|
5790
|
-
return;
|
|
5791
|
-
}
|
|
5792
|
-
// H1: `run` CATCHES its own body (a throw in buildLaunch/runtime.spawn) and RESOLVES `{ok:false}`
|
|
5793
|
-
// rather than rejecting, so a post-accept failure arrives here, not in the catch below, and
|
|
5794
|
-
// reaches none of the onOutcome sites. Without this the goal stays accepted-but-unanswered:
|
|
5795
|
-
// the caller follows epe to a terminal that never comes, and the reconcile index that would
|
|
5796
|
-
// settle it is only swept at BOOT, so a manager that stays up never converges it.
|
|
5797
|
-
if (reply.ok === false && !terminalEntered)
|
|
5798
|
-
return onOutcome({ kind: "failed", data: failedTerminal(reply.error ?? "spawn failed after accept", reply) });
|
|
5799
|
-
}).catch((e) => {
|
|
5800
|
-
if (acceptance === undefined) {
|
|
5801
|
-
rejectAccept(e);
|
|
5802
|
-
return;
|
|
5803
|
-
}
|
|
5804
|
-
// Same obligation for a genuine rejection (one that escaped `run`'s own catch).
|
|
5805
|
-
if (!terminalEntered)
|
|
5806
|
-
return onOutcome({ kind: "failed", data: failedTerminal(rejectionText(e), caughtEnvelope(e)) });
|
|
5807
|
-
console.error(`! spawn-as-action async body for ${goalId}: ${rejectionText(e)}`);
|
|
5808
|
-
}).catch((e) => console.error(`! goal terminal fallback for ${goalId}: ${rejectionText(e)}`));
|
|
5809
|
-
return acceptP;
|
|
5810
|
-
}
|
|
5811
|
-
/** H2: an acceptance served from a WINNER'S durable acceptance floor (the goal-index entry it
|
|
5812
|
-
* wrote before its own ack). Refuses `unavailable` rather than inventing one — see
|
|
5813
|
-
* {@link cachedSpawnAcceptance} for why an empty identity is never an acceptable answer. */
|
|
5814
|
-
async acceptanceFromIndex(entry, ref, goalId, fingerprint, executor) {
|
|
5815
|
-
if (entry.allocated?.owner === undefined)
|
|
5816
|
-
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)`);
|
|
5817
|
-
const readinessDeadlineMs = entry.allocated.readinessDeadlineMs ?? (await readGoalSpec(this.goalWriter.ctx, ref))?.value.readinessDeadlineMs;
|
|
5818
|
-
if (readinessDeadlineMs === undefined)
|
|
5819
|
-
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)`);
|
|
5820
|
-
return { name: entry.allocated.name, owner: entry.allocated.owner, actor: entry.allocated.actor, uid: entry.allocated.uid, goalId, fingerprint, readinessDeadlineMs, executor };
|
|
5821
|
-
}
|
|
5822
|
-
/** Reconstruct a cached acceptance for a same-goalId retry NOT in the live map (a prior incarnation
|
|
5823
|
-
* accepted it, or a concurrent winner whose map write this reader has not yet observed).
|
|
5824
|
-
*
|
|
5825
|
-
* H2 — WHY THIS PREFERS THE INDEX OVER THE TERMINAL. It used to read only the committed terminal
|
|
5826
|
-
* and fall back to `{name:"", actor:"", uid:""}` when there was none. That is the common case,
|
|
5827
|
-
* not a corner: a client retry over ANYCAST reaches a sibling while the winner is still
|
|
5828
|
-
* provisioning, so no terminal exists yet, and the caller was handed an ACCEPTED reply naming an
|
|
5829
|
-
* empty agent it can never address. The acceptance floor in the goal index exists from the moment
|
|
5830
|
-
* of acceptance, so it answers precisely the window the terminal cannot. Where neither is
|
|
5831
|
-
* readable the honest answer is a REFUSAL: an accepted goal whose identity nobody can name is
|
|
5832
|
-
* `unavailable` while it runs and its cached outcome once it has ended, never a hollow success. */
|
|
5833
|
-
async cachedSpawnAcceptance(ref, goalId, fingerprint, executor) {
|
|
5834
|
-
const entry = await readGoalIndex(this.goalWriter.ctx, ref);
|
|
5835
|
-
if (entry?.allocated !== undefined)
|
|
5836
|
-
return this.acceptanceFromIndex(entry, ref, goalId, fingerprint, executor);
|
|
5837
|
-
// The index is CLEARED at terminal, so a settled goal legitimately has no entry: fall back to
|
|
5838
|
-
// the terminal's data, which carries the same identity for exactly that case.
|
|
5839
|
-
const result = await readGoalResult(this.goalWriter.ctx, ref);
|
|
5840
|
-
const d = (result?.data ?? {});
|
|
5841
|
-
const spec = await readGoalSpec(this.goalWriter.ctx, ref);
|
|
5842
|
-
const readinessDeadlineMs = spec?.value.readinessDeadlineMs;
|
|
5843
|
-
// The terminal names the agent by its slot id: the `owner.actor` principal in user mode, the
|
|
5844
|
-
// bare nkey under DEV_OWNER on a static mesh.
|
|
5845
|
-
const principal = typeof d.id !== "string" || d.id.length === 0 ? null : this.userMode ? parsePrincipalKey(d.id) : { owner: DEV_OWNER, actor: d.id };
|
|
5846
|
-
if (typeof d.name === "string" && d.name.length > 0 && principal !== null && typeof d.lifecycleUid === "string" && d.lifecycleUid.length > 0 && readinessDeadlineMs !== undefined)
|
|
5847
|
-
return { name: d.name, owner: principal.owner, actor: principal.actor, uid: d.lifecycleUid, goalId, fingerprint, readinessDeadlineMs, executor };
|
|
5848
|
-
// Only a `succeeded` terminal names the agent. Any other ended goal has its outcome as its
|
|
5849
|
-
// whole durable answer, and no retry will make an identity readable (SPEC 13.6 item 5).
|
|
5850
|
-
if (result !== undefined)
|
|
5851
|
-
throw goalAlreadyTerminal(goalId, result);
|
|
5852
|
-
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)`);
|
|
5853
|
-
}
|
|
5854
|
-
/** Drop a goal's acceptance {@link goalAcceptanceRetentionMs} after its terminal committed. A
|
|
5855
|
-
* retry after that reads the terminal, so only a goal that has one may be passed here. */
|
|
5856
|
-
expireGoalAcceptance(ref) {
|
|
5857
|
-
const key = goalKey(ref);
|
|
5858
|
-
setTimeout(() => this.goalAcceptances.delete(key), this.goalAcceptanceRetentionMs).unref?.();
|
|
5859
|
-
}
|
|
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); }
|
|
5860
4878
|
// ---- the turn relay (§8 durable actions) ------------------------------------------------------
|
|
5861
4879
|
//
|
|
5862
4880
|
// A seat is NOT an endpoint: a run's `turn(agent, payload)` rides the manager, which accepts it
|
|
@@ -6018,31 +5036,8 @@ export class Manager {
|
|
|
6018
5036
|
/** Make an adopted seat a once seat again: its exit settles its task, and the task is served to
|
|
6019
5037
|
* it. A task that ended before the restart owes the stop the predecessor may not have made. */
|
|
6020
5038
|
bindOnceSeat(a) { return this.turnRelay.bindOnceSeat(a); }
|
|
6021
|
-
/**
|
|
6022
|
-
|
|
6023
|
-
* wins: if the readiness outcome already committed (succeeded/failed/uncertain) the transition or
|
|
6024
|
-
* the create-only commit loses gracefully and the readiness terminal stands. Fire-and-forget from
|
|
6025
|
-
* despawn (the process teardown is authoritative for the agent; this settles the GOAL honestly).
|
|
6026
|
-
* Cancel rides the despawn's own authorizeNamed reach - there is no cancel-by-goalId. */
|
|
6027
|
-
async cancelAgentGoal(name, mode) {
|
|
6028
|
-
const gw = this.goalWriter;
|
|
6029
|
-
const ref = this.agentGoals.get(name);
|
|
6030
|
-
if (!gw || !ref)
|
|
6031
|
-
return;
|
|
6032
|
-
this.agentGoals.delete(name);
|
|
6033
|
-
const epoch = this.serviceServe?.grant.epoch ?? 0;
|
|
6034
|
-
try {
|
|
6035
|
-
await this.assertGoalWriterEpochCurrent(epoch); // a superseded corpse never commits a cancel terminal either
|
|
6036
|
-
await transitionGoal(gw.ctx, ref, "cancelling", { fields: { cancelMode: mode } });
|
|
6037
|
-
const r = await commitGoalResult(gw.ctx, { ref, now: Date.now(), cause: "cancel", data: { cancelledBy: "despawn" }, committer: { instanceId: this.managerInstanceId, epoch } });
|
|
6038
|
-
this.expireGoalAcceptance(ref);
|
|
6039
|
-
this.emitGoalProgress(ref, epoch, { phase: "terminal", state: r.fact.state, ...(r.fact.data !== undefined ? { data: r.fact.data } : {}) });
|
|
6040
|
-
await clearGoalIndex(gw.ctx, ref); // terminal reached - the successor never reconciles it
|
|
6041
|
-
}
|
|
6042
|
-
catch {
|
|
6043
|
-
// the goal already terminalized (the readiness outcome won the settle race) - nothing to cancel.
|
|
6044
|
-
}
|
|
6045
|
-
}
|
|
5039
|
+
/** {@link SeatStop.cancelAgentGoal}. */
|
|
5040
|
+
cancelAgentGoal(...args) { return this.seatStopComponent.cancelAgentGoal(...args); }
|
|
6046
5041
|
recordSlotRuntime(a) {
|
|
6047
5042
|
return this.seatCustody.recordSlotRuntime(a);
|
|
6048
5043
|
}
|
|
@@ -6113,21 +5108,8 @@ export class Manager {
|
|
|
6113
5108
|
reconcileStaticLifecycles(postAdoption = false) {
|
|
6114
5109
|
return this.staticLifecycle.reconcileStaticLifecycles(postAdoption);
|
|
6115
5110
|
}
|
|
6116
|
-
/**
|
|
6117
|
-
|
|
6118
|
-
* hold or a RETIRED static incarnation refuses even with a tier-valid JWT (the
|
|
6119
|
-
* copied-credential vector — its subject can never collide with a successor's, so this match
|
|
6120
|
-
* is non-forgeable); any OTHER principal is not a managed lifecycle (an operator instrument:
|
|
6121
|
-
* the credential tier governs, exactly as before). Never name alone, never a payload field. */
|
|
6122
|
-
lifecycleMembershipRefusal(caller) {
|
|
6123
|
-
for (const a of this.agents.values()) {
|
|
6124
|
-
if (this.managedPrincipal(a) === caller)
|
|
6125
|
-
return a.terminalizing
|
|
6126
|
-
? `the caller's lifecycle ${a.lifecycleUid} is terminalizing; control is refused from the first terminal step`
|
|
6127
|
-
: undefined;
|
|
6128
|
-
}
|
|
6129
|
-
return this.retirement.membershipRefusal(caller);
|
|
6130
|
-
}
|
|
5111
|
+
/** {@link SeatStop.lifecycleMembershipRefusal}. */
|
|
5112
|
+
lifecycleMembershipRefusal(...args) { return this.seatStopComponent.lifecycleMembershipRefusal(...args); }
|
|
6131
5113
|
/** Open a short-lived PROVISIONER connection, run the onboarding ops on it, and drain it (closure (ii),
|
|
6132
5114
|
* residual 2). The DM/DLV consumer-create surface — the irreducible onboarding power — lives only for
|
|
6133
5115
|
* this window, never as a standing grant on the long-lived supervisor. A provision-only endpoint
|
|
@@ -6161,553 +5143,26 @@ export class Manager {
|
|
|
6161
5143
|
await drainAndClose(nc);
|
|
6162
5144
|
}
|
|
6163
5145
|
}
|
|
6164
|
-
/**
|
|
6165
|
-
|
|
6166
|
-
|
|
6167
|
-
|
|
6168
|
-
|
|
6169
|
-
|
|
6170
|
-
|
|
6171
|
-
|
|
6172
|
-
|
|
6173
|
-
|
|
6174
|
-
|
|
6175
|
-
|
|
6176
|
-
|
|
6177
|
-
|
|
6178
|
-
|
|
6179
|
-
|
|
6180
|
-
|
|
6181
|
-
|
|
6182
|
-
|
|
6183
|
-
|
|
6184
|
-
}
|
|
6185
|
-
}
|
|
6186
|
-
/** Persist a peer-defined persona as config. After this, `start name` auto-discovers
|
|
6187
|
-
* .cotal/agents/<name>.md and the connector applies its persona/model at spawn.
|
|
6188
|
-
*
|
|
6189
|
-
* CONTENT vs POLICY: `owner` has no slot, so a peer cannot claim ownership, and the
|
|
6190
|
-
* capabilities the written persona carries, a saved list a redefine keeps included, are bounded
|
|
6191
|
-
* against the definer before the write, so a peer can put only what it holds into a persona that
|
|
6192
|
-
* a wider spawner might later launch. Channel grants, role, and agent are content: they may
|
|
6193
|
-
* arrive as explicit arguments or as a leading frontmatter block inside `persona`. A prompt
|
|
6194
|
-
* that starts with `---` is parsed and merged (explicit args win) so the written file has one
|
|
6195
|
-
* frontmatter block; a malformed block is refused by name rather than wrapped. A fresh name is
|
|
6196
|
-
* created with the owner {@link personaOwner} records. Redefining an EXISTING file is allowed on
|
|
6197
|
-
* the privileged tier only if `file.owner == caller`, else admin is required. Fail-closed: an
|
|
6198
|
-
* ownerless file (legacy / operator-written) is admin-only. */
|
|
6199
|
-
async opDefinePersona(args, caller, admin, authenticated) {
|
|
6200
|
-
if (this.execution === "none")
|
|
6201
|
-
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
6202
|
-
const name = String(args.name ?? "").trim();
|
|
6203
|
-
if (!name)
|
|
6204
|
-
return { ok: false, error: "name required" };
|
|
6205
|
-
const nameErr = this.nameError(name);
|
|
6206
|
-
if (nameErr)
|
|
6207
|
-
return { ok: false, error: nameErr };
|
|
6208
|
-
const persona = String(args.persona ?? "").trim();
|
|
6209
|
-
if (!persona)
|
|
6210
|
-
return { ok: false, error: "persona required" };
|
|
6211
|
-
const path = agentFilePath(this.workspaceRoot, name);
|
|
6212
|
-
const strList = (v) => {
|
|
6213
|
-
if (v === undefined || v === null)
|
|
6214
|
-
return undefined;
|
|
6215
|
-
return (Array.isArray(v) ? v : [v]).map((x) => String(x));
|
|
6216
|
-
};
|
|
6217
|
-
const capabilities = strList(args.capabilities);
|
|
6218
|
-
let endpointArg;
|
|
6219
|
-
try {
|
|
6220
|
-
endpointArg = parsePersonaEndpoints(args.endpoints, "define-persona");
|
|
6221
|
-
}
|
|
6222
|
-
catch (e) {
|
|
6223
|
-
return { ok: false, error: rejectionText(e) };
|
|
6224
|
-
}
|
|
6225
|
-
// Read, authorize and compose against the catalog as it is now. Nothing yields between this and
|
|
6226
|
-
// the write, so no other call in this manager can change the file in between. The handler does
|
|
6227
|
-
// not serialize with other processes; their writes are outside this single-manager guarantee.
|
|
6228
|
-
const compose = () => {
|
|
6229
|
-
let existing;
|
|
6230
|
-
if (existsSync(path)) {
|
|
6231
|
-
try {
|
|
6232
|
-
existing = loadAgentFile(path);
|
|
6233
|
-
}
|
|
6234
|
-
catch (e) {
|
|
6235
|
-
return { reply: { ok: false, error: rejectionText(e) } };
|
|
6236
|
-
}
|
|
6237
|
-
if (!admin && existing.owner !== caller) {
|
|
6238
|
-
const owner = existing.owner ? `owned by ${existing.owner}` : "operator-owned (legacy file - no agent owner)";
|
|
6239
|
-
return { reply: {
|
|
6240
|
-
ok: false, code: "permission-denied", outcome: "not-executed",
|
|
6241
|
-
error: `not authorized to redefine ${name}: ${owner}; only its owner or an operator can`,
|
|
6242
|
-
details: [{ kind: "ai.cotal.persona-ownership-refused", operatorOwned: existing.owner === undefined }],
|
|
6243
|
-
} };
|
|
6244
|
-
}
|
|
6245
|
-
}
|
|
6246
|
-
try {
|
|
6247
|
-
return {
|
|
6248
|
-
def: composeWirePersona({
|
|
6249
|
-
name,
|
|
6250
|
-
owner: this.personaOwner(caller),
|
|
6251
|
-
prompt: persona,
|
|
6252
|
-
model: args.model,
|
|
6253
|
-
role: args.role,
|
|
6254
|
-
agent: args.agent,
|
|
6255
|
-
subscribe: strList(args.subscribe),
|
|
6256
|
-
allowSubscribe: strList(args.allowSubscribe),
|
|
6257
|
-
allowPublish: strList(args.allowPublish),
|
|
6258
|
-
capabilities,
|
|
6259
|
-
endpoints: copyPersonaEndpoints(endpointArg),
|
|
6260
|
-
}, existing),
|
|
6261
|
-
};
|
|
6262
|
-
}
|
|
6263
|
-
catch (e) {
|
|
6264
|
-
return { reply: { ok: false, error: rejectionText(e) } };
|
|
6265
|
-
}
|
|
6266
|
-
};
|
|
6267
|
-
let composed = compose();
|
|
6268
|
-
if ("reply" in composed)
|
|
6269
|
-
return composed.reply;
|
|
6270
|
-
// The bound reads the persona as written, so a redefine that omits `capabilities` or `endpoints`
|
|
6271
|
-
// has the list it keeps checked too. Resolving the definer's grant yields, so the catalog is read
|
|
6272
|
-
// again after it.
|
|
6273
|
-
if (composed.def.capabilities?.length || composed.def.endpoints !== undefined) {
|
|
6274
|
-
const refusal = await this.definerGrantRefusal(caller, authenticated);
|
|
6275
|
-
composed = compose();
|
|
6276
|
-
if ("reply" in composed)
|
|
6277
|
-
return composed.reply;
|
|
6278
|
-
const kept = composed.def.capabilities ?? [];
|
|
6279
|
-
const keptEndpoints = lowerPersonaEndpoints(composed.def.endpoints);
|
|
6280
|
-
// A user-auth persona may not name the field at all; elsewhere `[]` hands on nothing to bound.
|
|
6281
|
-
const namesEndpoints = composed.def.endpoints !== undefined;
|
|
6282
|
-
const refused = kept.length || keptEndpoints.length || (namesEndpoints && this.meshMode === "user")
|
|
6283
|
-
? refusal({ capabilities: kept, endpoints: keptEndpoints, namesEndpoints })
|
|
6284
|
-
: undefined;
|
|
6285
|
-
if (refused) {
|
|
6286
|
-
const fromSaved = [
|
|
6287
|
-
...(capabilities === undefined && kept.length ? ["capabilities"] : []),
|
|
6288
|
-
...(endpointArg === undefined && composed.def.endpoints?.length ? ["endpoints"] : []),
|
|
6289
|
-
];
|
|
6290
|
-
return {
|
|
6291
|
-
ok: false,
|
|
6292
|
-
code: "permission-denied",
|
|
6293
|
-
error: fromSaved.length
|
|
6294
|
-
? `${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"}.`
|
|
6295
|
-
: refused,
|
|
6296
|
-
};
|
|
6297
|
-
}
|
|
6298
|
-
}
|
|
6299
|
-
try {
|
|
6300
|
-
saveAgentFile(path, composed.def);
|
|
6301
|
-
}
|
|
6302
|
-
catch (e) {
|
|
6303
|
-
return { ok: false, error: rejectionText(e) };
|
|
6304
|
-
}
|
|
6305
|
-
return { ok: true, data: { name, path } };
|
|
6306
|
-
}
|
|
6307
|
-
/** Resolve what a persona's definer may put into it, as a check that returns the refusal for
|
|
6308
|
-
* capabilities or endpoint commands it does not hold, or `undefined` when it holds them all. The
|
|
6309
|
-
* check itself does not yield. An open mesh mints no credential, so nothing is bounded there. A
|
|
6310
|
-
* static definer is bounded by its issued evidence, as a spawner is; a user-auth definer by its
|
|
6311
|
-
* own ledger row's scope, under the ledger's token rule, with `admin` exempt. A user-auth persona
|
|
6312
|
-
* cannot name `endpoints` at all, `[]` included (SPEC 13.15). A hosted manager reads no ledger, so
|
|
6313
|
-
* it refuses. A later spawn of the persona is bounded again against its own spawner. */
|
|
6314
|
-
async definerGrantRefusal(caller, authenticated) {
|
|
6315
|
-
if (this.meshMode === "open")
|
|
6316
|
-
return () => undefined;
|
|
6317
|
-
if (this.meshMode === "static") {
|
|
6318
|
-
const run = await this.spawnRun(authenticated, undefined);
|
|
6319
|
-
const bound = await this.staticSpawnBound(authenticated, run !== undefined && "admission" in run ? run : undefined);
|
|
6320
|
-
return ({ capabilities, endpoints }) => this.spawnBoundRefusal(bound, { capabilities, ...(endpoints.length ? { endpoints } : {}) }, false, "define-persona");
|
|
6321
|
-
}
|
|
6322
|
-
if (this.remoteAuthority)
|
|
6323
|
-
return ({ capabilities, namesEndpoints }) => namesEndpoints
|
|
6324
|
-
? userMeshEndpointsRefusal("define-persona")
|
|
6325
|
-
: 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;
|
|
6326
|
-
const p = parsePrincipalKey(caller);
|
|
6327
|
-
const scope = p ? await resolveAuthProvider().actorScope({ dir: userAuthStateDir(this.workspaceRoot, this.space), owner: p.owner, actor: p.actor }) : undefined;
|
|
6328
|
-
return ({ capabilities, namesEndpoints }) => {
|
|
6329
|
-
if (namesEndpoints)
|
|
6330
|
-
return userMeshEndpointsRefusal("define-persona");
|
|
6331
|
-
if (scope?.includes("admin"))
|
|
6332
|
-
return undefined;
|
|
6333
|
-
const over = capabilities.filter((c) => !capabilityWithin(scope ?? [], c));
|
|
6334
|
-
if (!over.length)
|
|
6335
|
-
return undefined;
|
|
6336
|
-
return scope === undefined
|
|
6337
|
-
? `define-persona: the definer ${caller} has no grant in this space, so its persona can grant nothing. This persona asks for capabilities ${over.join(", ")}.`
|
|
6338
|
-
: `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.`;
|
|
6339
|
-
};
|
|
6340
|
-
}
|
|
6341
|
-
/** Remove one machine-local persona definition without touching any running lifecycle that was
|
|
6342
|
-
* launched from it. Removal accepts the catalog's safe filename alphabet without applying the
|
|
6343
|
-
* current spawn-name length or user-mode actor rules, so an obsolete invalid-name entry remains
|
|
6344
|
-
* repairable. Ownership matches redefine: the recorded owner, or admin for an ownerless file. */
|
|
6345
|
-
opRemovePersona(args, caller, admin) {
|
|
6346
|
-
if (this.execution === "none")
|
|
6347
|
-
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
6348
|
-
const name = String(args.name ?? "").trim();
|
|
6349
|
-
if (!name)
|
|
6350
|
-
return { ok: false, code: "bad-request", error: "name required" };
|
|
6351
|
-
if (!/^[A-Za-z0-9_-]+$/.test(name))
|
|
6352
|
-
return { ok: false, code: "bad-request", error: `unsafe persona name ${JSON.stringify(name)} (allowed: letters, digits, _ -)` };
|
|
6353
|
-
const path = agentFilePath(this.workspaceRoot, name);
|
|
6354
|
-
if (!existsSync(path))
|
|
6355
|
-
return { ok: false, code: "not-found", error: `no persona "${name}"` };
|
|
6356
|
-
let owner;
|
|
6357
|
-
try {
|
|
6358
|
-
owner = loadAgentFile(path).owner;
|
|
6359
|
-
}
|
|
6360
|
-
catch {
|
|
6361
|
-
// A catalog entry may be invalid for launch solely because an older release admitted a name
|
|
6362
|
-
// above today's identity limit. Read only its frontmatter owner without asking the launch
|
|
6363
|
-
// parser to accept the identity. This does not make the file spawnable or readable.
|
|
6364
|
-
try {
|
|
6365
|
-
const source = readFileSync(path, "utf8").replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
|
|
6366
|
-
const match = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(source);
|
|
6367
|
-
if (!match)
|
|
6368
|
-
throw new Error("missing frontmatter");
|
|
6369
|
-
const frontmatter = parseYaml(match[1]);
|
|
6370
|
-
if (!frontmatter || typeof frontmatter !== "object" || Array.isArray(frontmatter))
|
|
6371
|
-
throw new Error("frontmatter is not a mapping");
|
|
6372
|
-
const fields = frontmatter;
|
|
6373
|
-
if (String(fields.name ?? "") !== name)
|
|
6374
|
-
throw new Error("frontmatter name differs from the catalog entry");
|
|
6375
|
-
if (fields.owner !== undefined && typeof fields.owner !== "string")
|
|
6376
|
-
throw new Error("owner is not a string");
|
|
6377
|
-
owner = fields.owner;
|
|
6378
|
-
}
|
|
6379
|
-
catch {
|
|
6380
|
-
return { ok: false, code: "not-found", error: `no persona "${name}"` };
|
|
6381
|
-
}
|
|
6382
|
-
}
|
|
6383
|
-
if (!admin && owner !== caller) {
|
|
6384
|
-
const heldBy = owner ? `owned by ${owner}` : "operator-owned (legacy file - no agent owner)";
|
|
6385
|
-
return { ok: false, code: "permission-denied", error: `not authorized to remove ${name}: ${heldBy}; only its owner or an operator can` };
|
|
6386
|
-
}
|
|
6387
|
-
try {
|
|
6388
|
-
rmSync(path);
|
|
6389
|
-
}
|
|
6390
|
-
catch (e) {
|
|
6391
|
-
if (!existsSync(path))
|
|
6392
|
-
return { ok: false, code: "not-found", error: `no persona "${name}"` };
|
|
6393
|
-
return { ok: false, error: rejectionText(e) };
|
|
6394
|
-
}
|
|
6395
|
-
return { ok: true, data: { name } };
|
|
6396
|
-
}
|
|
6397
|
-
/** The owner a fresh wire-defined persona records. A user-auth caller's principal is stable, and
|
|
6398
|
-
* so is one of this manager's own seats for its life. Any other static caller, such as the CLI's
|
|
6399
|
-
* operator instrument minted for one call, would leave an owner no later call matches, so it
|
|
6400
|
-
* records none and the file is operator-owned, as a local `persona create` writes it. A peer
|
|
6401
|
-
* joined with its own credential is such a caller too. */
|
|
6402
|
-
personaOwner(caller) {
|
|
6403
|
-
if (this.userMode)
|
|
6404
|
-
return caller;
|
|
6405
|
-
for (const a of this.agents.values())
|
|
6406
|
-
if (this.managedPrincipal(a) === caller)
|
|
6407
|
-
return caller;
|
|
6408
|
-
return undefined;
|
|
6409
|
-
}
|
|
6410
|
-
/** Whether this caller may READ a catalog card's details (role/model/description/body). Same
|
|
6411
|
-
* ownership rule as redefine: owner == caller, or admin. Ownerless / operator-written files are
|
|
6412
|
-
* admin-only. Names of parseable files still appear on the list so a definer can see a taken
|
|
6413
|
-
* spawn name; details stay off the wire unless this is true. */
|
|
6414
|
-
canReadPersona(owner, caller, admin) {
|
|
6415
|
-
return personaCatalogReadable(owner, caller, admin);
|
|
6416
|
-
}
|
|
6417
|
-
/** Mesh-side catalog list (#402). Every parseable name is returned so a definer can see a taken
|
|
6418
|
-
* spawn name. Role / model / description / owner ride only when the caller could redefine the
|
|
6419
|
-
* file (same ownership as `definePersona`); other cards are name-only, so a peer cannot read a
|
|
6420
|
-
* prompt it does not own. Unparseable files are omitted for non-admin (no existence leak of a
|
|
6421
|
-
* broken card). */
|
|
6422
|
-
opListPersonas(caller, admin) {
|
|
6423
|
-
const personas = [];
|
|
6424
|
-
for (const e of listPersonaCatalog(this.workspaceRoot)) {
|
|
6425
|
-
if (e.error) {
|
|
6426
|
-
if (!admin)
|
|
6427
|
-
continue;
|
|
6428
|
-
personas.push({ name: e.name, error: "unparseable" });
|
|
6429
|
-
continue;
|
|
6430
|
-
}
|
|
6431
|
-
const def = e.def;
|
|
6432
|
-
if (!this.canReadPersona(def.owner, caller, admin)) {
|
|
6433
|
-
personas.push({ name: e.name });
|
|
6434
|
-
continue;
|
|
6435
|
-
}
|
|
6436
|
-
const description = personaCatalogDescription(def);
|
|
6437
|
-
personas.push({
|
|
6438
|
-
name: e.name,
|
|
6439
|
-
...(def.role ? { role: def.role } : {}),
|
|
6440
|
-
...(def.model ? { model: def.model } : {}),
|
|
6441
|
-
...(description ? { description } : {}),
|
|
6442
|
-
...(def.owner ? { owner: def.owner } : {}),
|
|
6443
|
-
});
|
|
6444
|
-
}
|
|
6445
|
-
return { ok: true, data: { personas } };
|
|
6446
|
-
}
|
|
6447
|
-
/** Mesh-side catalog show (#402). Same ownership as list. Unknown, unauthorized, or unparseable
|
|
6448
|
-
* names are not-found (no existence or parser-diagnostic leak). The body is included so a peer can
|
|
6449
|
-
* inspect a prompt it owns before spawn; policy fields stay off the wire. */
|
|
6450
|
-
opShowPersona(args, caller, admin) {
|
|
6451
|
-
const name = String(args.name ?? "").trim();
|
|
6452
|
-
if (!name)
|
|
6453
|
-
return { ok: false, error: "name required" };
|
|
6454
|
-
const nameErr = this.nameError(name);
|
|
6455
|
-
if (nameErr)
|
|
6456
|
-
return { ok: false, error: nameErr };
|
|
6457
|
-
const path = agentFilePath(this.workspaceRoot, name);
|
|
6458
|
-
if (!existsSync(path))
|
|
6459
|
-
return { ok: false, error: `no persona "${name}"` };
|
|
6460
|
-
let def;
|
|
6461
|
-
try {
|
|
6462
|
-
def = loadAgentFile(path);
|
|
6463
|
-
}
|
|
6464
|
-
catch {
|
|
6465
|
-
return { ok: false, error: `no persona "${name}"` };
|
|
6466
|
-
}
|
|
6467
|
-
if (!this.canReadPersona(def.owner, caller, admin))
|
|
6468
|
-
return { ok: false, error: `no persona "${name}"` };
|
|
6469
|
-
const description = personaCatalogDescription(def);
|
|
6470
|
-
return {
|
|
6471
|
-
ok: true,
|
|
6472
|
-
data: {
|
|
6473
|
-
name,
|
|
6474
|
-
...(def.role ? { role: def.role } : {}),
|
|
6475
|
-
...(def.model ? { model: def.model } : {}),
|
|
6476
|
-
...(description ? { description } : {}),
|
|
6477
|
-
...(def.owner ? { owner: def.owner } : {}),
|
|
6478
|
-
...(def.persona ? { persona: def.persona } : {}),
|
|
6479
|
-
},
|
|
6480
|
-
};
|
|
6481
|
-
}
|
|
6482
|
-
/** The post-authorization `input` effect (C3): type `text` into the seat's terminal as if a human
|
|
6483
|
-
* had. The single call an external UI needs to deliver a harness command (`/compact`, `/clear`,
|
|
6484
|
-
* `/model`) without holding a terminal open on the caller's side.
|
|
6485
|
-
*
|
|
6486
|
-
* Why the runtime HANDLE and not an attach session: a session is a stream (backlog, subscriber
|
|
6487
|
-
* set, a lifetime the session plane accounts for and caps). Opening and discarding one per
|
|
6488
|
-
* keystroke line would burn a session slot for a write, and would put a capacity refusal in the
|
|
6489
|
-
* path of an operation that has no capacity cost. {@link AgentHandle.write} is the one-shot
|
|
6490
|
-
* sibling of `interrupt()`, which already writes into the same pty.
|
|
6491
|
-
*
|
|
6492
|
-
* Three refusals, each for a different reason and each with its own code, so a caller can tell
|
|
6493
|
-
* "never going to work" from "not right now":
|
|
6494
|
-
* - the name was refilled while authorization awaited: act on the incarnation the caller was
|
|
6495
|
-
* authorized for or on nothing at all (the same guard {@link attachAuthorized} carries, for
|
|
6496
|
-
* the same reason: a name is a reusable slot and `authorizeNamed` can await a ledger read);
|
|
6497
|
-
* - the agent is not running: there is no terminal to type into;
|
|
6498
|
-
* - the runtime cannot write (tmux/cmux/orca/herdr attach to an externally-owned process, so
|
|
6499
|
-
* they own no input stream for it): `unimplemented`, named by runtime kind. NOT a fallback
|
|
6500
|
-
* to an attach session and NOT a silent success - a dropped keystroke would leave the caller
|
|
6501
|
-
* believing a command was delivered that never was.
|
|
6502
|
-
*
|
|
6503
|
-
* `enter` defaults to true: a harness command typed but not submitted has not been delivered.
|
|
6504
|
-
* Nothing is echoed back; the caller reads the resulting turns from the event plane. */
|
|
6505
|
-
async inputAuthorized(a, args) {
|
|
6506
|
-
// These three refuse before the first write, so nothing was typed (SPEC 13.3). A write the
|
|
6507
|
-
// runtime rejects below states no outcome: the runtime contract does not say a rejected write
|
|
6508
|
-
// delivered nothing, and an earlier slice may already have reached the seat.
|
|
6509
|
-
if (this.agents.get(a.name) !== a)
|
|
6510
|
-
throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" was replaced during authorization - retry`, undefined, "not-executed");
|
|
6511
|
-
if (a.handle.status() !== "running")
|
|
6512
|
-
throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" is not running (${a.handle.status()}); nothing to type into`, undefined, "not-executed");
|
|
6513
|
-
const write = a.handle.write?.bind(a.handle);
|
|
6514
|
-
if (!write)
|
|
6515
|
-
throw new EpEnvelopeError("unimplemented", `input is not supported by runtime ${a.handle.kind}`, undefined, "not-executed");
|
|
6516
|
-
if (a.agent === "claude") {
|
|
6517
|
-
// AskUserQuestion ignores bracketed text at its choice menu, but the following Enter
|
|
6518
|
-
// confirms the highlighted option. Refuse rather than answer a different question choice.
|
|
6519
|
-
const handle = a.handle;
|
|
6520
|
-
let selection = false;
|
|
6521
|
-
try {
|
|
6522
|
-
const session = handle.attach();
|
|
6523
|
-
const backlog = await session.backlog();
|
|
6524
|
-
const term = new Headless.Terminal({ cols: session.cols, rows: session.rows, allowProposedApi: true });
|
|
6525
|
-
try {
|
|
6526
|
-
await new Promise((done) => term.write(backlog, done));
|
|
6527
|
-
const screen = term.buffer.active;
|
|
6528
|
-
const lines = Array.from({ length: term.rows }, (_, y) => screen.getLine(screen.baseY + y)?.translateToString(true).trim() ?? "");
|
|
6529
|
-
selection = lines.some((line) => /^❯\s+\d+\./u.test(line))
|
|
6530
|
-
&& lines.some((line) => line.includes("Enter to select") && line.includes("↑/↓ to navigate") && line.includes("Esc to cancel"));
|
|
6531
|
-
}
|
|
6532
|
-
finally {
|
|
6533
|
-
term.dispose();
|
|
6534
|
-
}
|
|
6535
|
-
}
|
|
6536
|
-
catch {
|
|
6537
|
-
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");
|
|
6538
|
-
}
|
|
6539
|
-
if (selection)
|
|
6540
|
-
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");
|
|
6541
|
-
// Snapshot parsing awaits I/O. Keep this write bound to the authorized incarnation and handle.
|
|
6542
|
-
if (this.agents.get(a.name) !== a || a.handle !== handle || handle.status() !== "running")
|
|
6543
|
-
throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" changed while inspecting its terminal; nothing was typed`, undefined, "not-executed");
|
|
6544
|
-
}
|
|
6545
|
-
// The contract validated `text` (non-empty, <= 64KiB) and `enter` (boolean) before this ran, so
|
|
6546
|
-
// the only decision left is the carriage return. `!== false` and not `?? true`: an ABSENT enter
|
|
6547
|
-
// and an explicit `true` must behave identically, and only `false` may suppress the return.
|
|
6548
|
-
//
|
|
6549
|
-
// THE TEXT IS DELIVERED AS A BRACKETED PASTE AND THE RETURN FOLLOWS IT AS ITS OWN WRITE, and
|
|
6550
|
-
// that is the whole of issue #1649. A TUI harness reads keystrokes, so a return fused onto the
|
|
6551
|
-
// tail of the text (`${text}\r`) is the text's last character rather than the submit key: the
|
|
6552
|
-
// line waits in the composer and the NEXT call's return submits the PREVIOUS call's text, so
|
|
6553
|
-
// every delivery runs one call behind while the op still reports the full byte count.
|
|
6554
|
-
//
|
|
6555
|
-
// Separating the return is necessary and NOT sufficient, which is the part that cost a second
|
|
6556
|
-
// round of measurement. A TUI classifies a fast burst of input as a PASTE and eats the newline
|
|
6557
|
-
// that trails it (Jcode spells this `paste_guard::consume_paste_trailing_enter`), so a text big
|
|
6558
|
-
// enough to need more than one write is still one call behind even when the return is written
|
|
6559
|
-
// alone. Measured on a real seat, delivering in 2048-char slices with a yield before the return:
|
|
6560
|
-
// 120 and 700 bytes submitted on their own call, 2500 and 3100 bytes did not - each appeared
|
|
6561
|
-
// only when the NEXT call's return arrived. That is the reported symptom exactly.
|
|
6562
|
-
//
|
|
6563
|
-
// Bracketed paste states the boundary instead of guessing at it. `ESC[200~ text ESC[201~`
|
|
6564
|
-
// delimits the pasted block, so the return after it is unambiguously a keystroke and the guard
|
|
6565
|
-
// has no trailing newline to consume. This is a CLASSIFIER, not a race, so a sleep would be the
|
|
6566
|
-
// wrong instrument: measured on a real seat, a 250ms pause before the return still lost the
|
|
6567
|
-
// submission while 1000ms carried it, and any margin chosen from those numbers is a guess a
|
|
6568
|
-
// loaded host breaks. Bracketed delivery submitted 120, 2600 and 5912 bytes (the issue's own
|
|
6569
|
-
// size) each on its own call. The terminal advertises support by enabling DECSET 2004, which
|
|
6570
|
-
// Jcode's TUI does.
|
|
6571
|
-
//
|
|
6572
|
-
// The bytes the SEAT receives as text are unchanged, and the receipt still counts the text plus
|
|
6573
|
-
// the return: the paste markers are framing this op adds, never content the caller asked to
|
|
6574
|
-
// deliver, so counting them would make `bytes` disagree with what the caller sent.
|
|
6575
|
-
const text = String(args.text);
|
|
6576
|
-
const submit = args.enter !== false;
|
|
6577
|
-
const intendedBytes = Buffer.byteLength(text, "utf8") + (submit ? 1 : 0);
|
|
6578
|
-
const parts = [{ data: PASTE_START, counted: false }];
|
|
6579
|
-
for (let i = 0; i < text.length; i += INPUT_SLICE_CHARS)
|
|
6580
|
-
parts.push({ data: text.slice(i, i + INPUT_SLICE_CHARS), counted: true });
|
|
6581
|
-
parts.push({ data: PASTE_END, counted: false });
|
|
6582
|
-
// `enter:false` still presses nothing: the text is delivered into the composer and left there.
|
|
6583
|
-
if (submit)
|
|
6584
|
-
parts.push({ data: "\r", counted: true });
|
|
6585
|
-
let bytes = 0;
|
|
6586
|
-
for (const [i, part] of parts.entries()) {
|
|
6587
|
-
// Yield BEFORE each write but the first, so the child drains the previous slice rather than
|
|
6588
|
-
// the pty buffer merging them. `setImmediate` runs after I/O, which a microtask would not.
|
|
6589
|
-
if (i > 0)
|
|
6590
|
-
await new Promise((resolve) => setImmediate(resolve));
|
|
6591
|
-
let accepted;
|
|
6592
|
-
try {
|
|
6593
|
-
accepted = await write(part.data);
|
|
6594
|
-
}
|
|
6595
|
-
catch (error) {
|
|
6596
|
-
throw new EpEnvelopeError("unavailable", `input for seat "${a.name}" failed: ${rejectionText(error)}`);
|
|
6597
|
-
}
|
|
6598
|
-
if (!Number.isSafeInteger(accepted)) {
|
|
6599
|
-
throw new EpEnvelopeError("unavailable", `input for seat "${a.name}" failed: runtime accepted ${String(accepted)} of ${intendedBytes} bytes`);
|
|
6600
|
-
}
|
|
6601
|
-
// A short write on ANY part is a failed delivery, including a marker: a paste block that was
|
|
6602
|
-
// opened but not closed would leave the seat's composer in paste mode.
|
|
6603
|
-
if (accepted !== Buffer.byteLength(part.data, "utf8"))
|
|
6604
|
-
throw new EpEnvelopeError("unavailable", `input for seat "${a.name}" failed: runtime accepted ${accepted} of ${Buffer.byteLength(part.data, "utf8")} bytes of one write`);
|
|
6605
|
-
if (part.counted)
|
|
6606
|
-
bytes += accepted;
|
|
6607
|
-
}
|
|
6608
|
-
if (bytes !== intendedBytes)
|
|
6609
|
-
throw new EpEnvelopeError("unavailable", `input for seat "${a.name}" failed: runtime accepted ${String(bytes)} of ${intendedBytes} bytes`);
|
|
6610
|
-
return { name: a.name, bytes };
|
|
6611
|
-
}
|
|
6612
|
-
/** The post-authorization attach effect: mint the holder-bound §13.6 offer, redeem it
|
|
6613
|
-
* through the ONE session plane (one-use CAS + presenter-equality), and stand up the PTY bridge —
|
|
6614
|
-
* atomically. The reply is the SIGNED grant (no ws:// URL, non-bearer, never logged); the caller
|
|
6615
|
-
* redeems it over the mesh with a per-session rails-only cred it mints itself. Only streamable
|
|
6616
|
-
* backends (pty/host) attach; an external runtime's attach() throws with per-runtime guidance. */
|
|
6617
|
-
async attachAuthorized(a, caller) {
|
|
6618
|
-
// Every refusal before establishAttach below has opened no session, so it states that (SPEC 13.3).
|
|
6619
|
-
if (!this.sessionPlane)
|
|
6620
|
-
throw new EpEnvelopeError("failed-precondition", "the manager session plane is not available (the manager is not fully started)", undefined, "not-executed");
|
|
6621
|
-
// A name is a reusable slot and the authorization above can await (user mode reads the ledger).
|
|
6622
|
-
// The ep target is incarnation-pinned, so `a` cannot BE a successor — but the slot it names can
|
|
6623
|
-
// have been stopped and refilled while we waited, and everything below must act on the
|
|
6624
|
-
// incarnation this caller was actually authorized for, never on whoever holds the name now.
|
|
6625
|
-
if (this.agents.get(a.name) !== a)
|
|
6626
|
-
throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" was replaced during authorization - retry`, undefined, "not-executed");
|
|
6627
|
-
// Never establish a session over a dead agent — a doomed session (the caller would get an
|
|
6628
|
-
// immediate process-exit at best, a confusing empty terminal at worst). Refuse honestly.
|
|
6629
|
-
if (a.handle.status() !== "running")
|
|
6630
|
-
throw new EpEnvelopeError("failed-precondition", `agent "${a.name}" is not running (${a.handle.status()}); nothing to attach`, undefined, "not-executed");
|
|
6631
|
-
// CLAIM the session slot BEFORE attaching the target's PTY, matching the console door: this door
|
|
6632
|
-
// used to attach first and check capacity inside establishAttach, so a `resource-exhausted`
|
|
6633
|
-
// refusal landed AFTER the attach. The claim is carried INTO establishAttach, so one reservation
|
|
6634
|
-
// spans the attach and the establishment, and it is released on every refusal below.
|
|
6635
|
-
//
|
|
6636
|
-
// RESIDUAL, NAMED: no shipped runtime acquires anything at attach time — pty's `attach()` returns
|
|
6637
|
-
// a pure view (it registers a data subscriber only when `onData` is called) and tmux/cmux/orca
|
|
6638
|
-
// throw — so an attach nobody bridges is a garbage-collectible object, not a held resource, and
|
|
6639
|
-
// ordering alone suffices. A future runtime that DOES acquire something in `attach()` reopens
|
|
6640
|
-
// this: it would need a release on the failure paths, and `AttachSession` has no close today.
|
|
6641
|
-
const slot = this.sessionPlane.claimSlot();
|
|
6642
|
-
let session;
|
|
6643
|
-
try {
|
|
6644
|
-
session = a.handle.attach();
|
|
6645
|
-
}
|
|
6646
|
-
catch (e) {
|
|
6647
|
-
slot.release();
|
|
6648
|
-
// The external runtimes refuse attach() before acquiring anything (see the residual above).
|
|
6649
|
-
//
|
|
6650
|
-
// A runtime that streams NO terminal is `unimplemented` and not a precondition: asking again
|
|
6651
|
-
// cannot change it, and a caller that reads this as transient retries a refusal forever. The
|
|
6652
|
-
// runtime's own throw is the guidance for watching the agent where it really runs, so it is
|
|
6653
|
-
// carried through verbatim, and the namespaced detail lets a caller act on the one fact
|
|
6654
|
-
// without reading the wording. This is the same answer `input` gives a runtime that cannot
|
|
6655
|
-
// write, for the same reason.
|
|
6656
|
-
if (!this.runtimeFor(a.handle.kind).streamsTerminal)
|
|
6657
|
-
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");
|
|
6658
|
-
throw new EpEnvelopeError("failed-precondition", rejectionText(e), undefined, "not-executed");
|
|
6659
|
-
}
|
|
6660
|
-
// establishAttach releases the claim it was handed on every exit; nothing to unwind here.
|
|
6661
|
-
const { grant } = await this.sessionPlane.establishAttach(caller, { name: a.name, lifecycleUid: a.lifecycleUid }, session, slot);
|
|
6662
|
-
const carried = a.launch.resumed?.host;
|
|
6663
|
-
return { ok: true, data: { grant, ...(carried ? { resumedFrom: { host: carried, source: a.launch.resumed.source } } : {}) } };
|
|
6664
|
-
}
|
|
6665
|
-
/** The console's mesh §13.6 session establisher (backing `POST /session/<name>` on the
|
|
6666
|
-
* loopback face). Drives THE ONE plane — same establishAttach as the ep `attach` command — with
|
|
6667
|
-
* the loopback OPERATOR as holder (same-host trust boundary), then hands the browser everything it
|
|
6668
|
-
* needs to open the caller rail over the broker ws listener: the holder-bound grant, a per-session
|
|
6669
|
-
* RAILS-ONLY caller cred (static mints from the seed, TTL-bound to the session; an open mesh has no
|
|
6670
|
-
* credential system so the browser connects bare), and the ws URL. NO 127.0.0.1 terminal transport
|
|
6671
|
-
* — the terminal rides the mesh session. Injected only when a wsPort exists (see the constructor). */
|
|
6672
|
-
async establishConsoleSession(name) {
|
|
6673
|
-
if (!this.sessionPlane)
|
|
6674
|
-
throw new Error("the manager session plane is not available (the manager is not fully started)");
|
|
6675
|
-
if (this.wsPort === undefined)
|
|
6676
|
-
throw new Error("the broker websocket port is not configured; the console cannot open a mesh session");
|
|
6677
|
-
// CLAIM the session slot here, before the PTY attach and before this establisher goes on to
|
|
6678
|
-
// mint a seed-signed `session-caller` credential: a capacity refusal must land before anything
|
|
6679
|
-
// with a side effect or a cost. The claim is carried INTO establishAttach, so the reservation
|
|
6680
|
-
// spans the whole establishment rather than being a check that a concurrent caller can race.
|
|
6681
|
-
// (See attachAuthorized for why the attach itself needs no unwind on any shipped runtime.)
|
|
6682
|
-
const slot = this.sessionPlane.claimSlot();
|
|
6683
|
-
try {
|
|
6684
|
-
const a = this.agents.get(name);
|
|
6685
|
-
if (!a)
|
|
6686
|
-
throw new Error(`no managed agent "${name}"`);
|
|
6687
|
-
if (a.handle.status() !== "running")
|
|
6688
|
-
throw new Error(`agent "${name}" is not running (${a.handle.status()}); nothing to attach`);
|
|
6689
|
-
const session = a.handle.attach(); // throws for non-streamable runtimes — surfaced to the browser as a 500
|
|
6690
|
-
// The loopback operator is the console's holder (same-host trust boundary).
|
|
6691
|
-
const caller = { owner: DEV_OWNER, actor: "console", uid: this.managerLifecycleUid };
|
|
6692
|
-
const { grant } = await this.sessionPlane.establishAttach(caller, { name: a.name, lifecycleUid: a.lifecycleUid }, session, slot);
|
|
6693
|
-
// The caller credential is minted ONLY after a session is really live, so a refused or failed
|
|
6694
|
-
// establishment never yields a seed-signed JWT. (A failure HERE would leave a live session the
|
|
6695
|
-
// browser never reaches, holding its slot until the grant expires — unreachable in practice,
|
|
6696
|
-
// because the SERVING mint above signs from this same `this.auth` first and would have failed
|
|
6697
|
-
// before any session existed.)
|
|
6698
|
-
const creds = this.auth
|
|
6699
|
-
? await mintCreds(this.auth, newIdentity(), "session-caller", {
|
|
6700
|
-
sessionCaller: { endpoint: MANAGER_ENDPOINT, sessionId: grant.sessionId, epoch: grant.serving.epoch },
|
|
6701
|
-
expiresAt: Math.floor(grant.exp / 1000), // grant.exp is ms (now+ttlMs); the JWT exp is seconds
|
|
6702
|
-
})
|
|
6703
|
-
: "";
|
|
6704
|
-
return { grant, wsUrl: `ws://127.0.0.1:${this.wsPort}`, creds };
|
|
6705
|
-
}
|
|
6706
|
-
catch (e) {
|
|
6707
|
-
slot.release(); // idempotent with establishAttach's own release
|
|
6708
|
-
throw e;
|
|
6709
|
-
}
|
|
6710
|
-
}
|
|
5146
|
+
/** {@link SeatStop.opPurge}. */
|
|
5147
|
+
opPurge(...args) { return this.seatStopComponent.opPurge(...args); }
|
|
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); }
|
|
6711
5166
|
/** Managed agents cross-referenced with live presence (the manager sees the roster).
|
|
6712
5167
|
*
|
|
6713
5168
|
* `ownerFilter`: restrict to agents whose spawn-time stored `userOwner` equals it (the ps/status
|