@cotal-ai/manager 0.171.4 → 0.172.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/boot.d.ts +162 -0
- package/dist/boot.d.ts.map +1 -0
- package/dist/boot.js +627 -0
- package/dist/boot.js.map +1 -0
- package/dist/broker-transport.d.ts +6 -0
- package/dist/broker-transport.d.ts.map +1 -1
- package/dist/broker-transport.js +25 -6
- package/dist/broker-transport.js.map +1 -1
- package/dist/command-dispatch.d.ts +3 -0
- package/dist/command-dispatch.d.ts.map +1 -1
- package/dist/command-dispatch.js +67 -0
- package/dist/command-dispatch.js.map +1 -1
- package/dist/connector-inventory.d.ts +8 -0
- package/dist/connector-inventory.d.ts.map +1 -1
- package/dist/connector-inventory.js +28 -4
- package/dist/connector-inventory.js.map +1 -1
- package/dist/credential-renewal.d.ts +5 -1
- package/dist/credential-renewal.d.ts.map +1 -1
- package/dist/credential-renewal.js +65 -3
- package/dist/credential-renewal.js.map +1 -1
- package/dist/goal-writer.d.ts +3 -0
- package/dist/goal-writer.d.ts.map +1 -1
- package/dist/goal-writer.js +30 -0
- package/dist/goal-writer.js.map +1 -1
- package/dist/harness-resolution.d.ts +3 -0
- package/dist/harness-resolution.d.ts.map +1 -1
- package/dist/harness-resolution.js +14 -0
- package/dist/harness-resolution.js.map +1 -1
- package/dist/lease-keeper.d.ts +4 -0
- package/dist/lease-keeper.d.ts.map +1 -1
- package/dist/lease-keeper.js +10 -0
- package/dist/lease-keeper.js.map +1 -1
- package/dist/managed-static-lifecycle.d.ts +3 -0
- package/dist/managed-static-lifecycle.d.ts.map +1 -1
- package/dist/managed-static-lifecycle.js +42 -0
- package/dist/managed-static-lifecycle.js.map +1 -1
- package/dist/manager-service-contract.d.ts +6 -1
- package/dist/manager-service-contract.d.ts.map +1 -1
- package/dist/manager-service-contract.js +11 -3
- package/dist/manager-service-contract.js.map +1 -1
- package/dist/manager.d.ts +549 -354
- package/dist/manager.d.ts.map +1 -1
- package/dist/manager.js +86 -2222
- package/dist/manager.js.map +1 -1
- package/dist/names-capacity.d.ts +4 -0
- package/dist/names-capacity.d.ts.map +1 -1
- package/dist/names-capacity.js +29 -0
- package/dist/names-capacity.js.map +1 -1
- package/dist/persona-catalog.d.ts +3 -0
- package/dist/persona-catalog.d.ts.map +1 -1
- package/dist/persona-catalog.js +19 -0
- package/dist/persona-catalog.js.map +1 -1
- package/dist/preservation.d.ts +3 -0
- package/dist/preservation.d.ts.map +1 -1
- package/dist/preservation.js +48 -0
- package/dist/preservation.js.map +1 -1
- package/dist/preserved-resume.d.ts +220 -0
- package/dist/preserved-resume.d.ts.map +1 -0
- package/dist/preserved-resume.js +1222 -0
- package/dist/preserved-resume.js.map +1 -0
- package/dist/readiness-wait.d.ts +3 -0
- package/dist/readiness-wait.d.ts.map +1 -1
- package/dist/readiness-wait.js +11 -0
- package/dist/readiness-wait.js.map +1 -1
- package/dist/retirement.d.ts +4 -0
- package/dist/retirement.d.ts.map +1 -1
- package/dist/retirement.js +29 -0
- package/dist/retirement.js.map +1 -1
- package/dist/seat-custody.d.ts +4 -0
- package/dist/seat-custody.d.ts.map +1 -1
- package/dist/seat-custody.js +25 -0
- package/dist/seat-custody.js.map +1 -1
- package/dist/seat-launch.d.ts +3 -0
- package/dist/seat-launch.d.ts.map +1 -1
- package/dist/seat-launch.js +69 -0
- package/dist/seat-launch.js.map +1 -1
- package/dist/seat-stop.d.ts +3 -0
- package/dist/seat-stop.d.ts.map +1 -1
- package/dist/seat-stop.js +40 -0
- package/dist/seat-stop.js.map +1 -1
- package/dist/seat-types.d.ts +6 -6
- package/dist/seat-types.d.ts.map +1 -1
- package/dist/serve-plane.d.ts +5 -0
- package/dist/serve-plane.d.ts.map +1 -1
- package/dist/serve-plane.js +78 -1
- package/dist/serve-plane.js.map +1 -1
- package/dist/session-recovery.d.ts +4 -0
- package/dist/session-recovery.d.ts.map +1 -1
- package/dist/session-recovery.js +31 -0
- package/dist/session-recovery.js.map +1 -1
- package/dist/spawn-goal.d.ts +3 -0
- package/dist/spawn-goal.d.ts.map +1 -1
- package/dist/spawn-goal.js +23 -0
- package/dist/spawn-goal.js.map +1 -1
- package/dist/start-doors.d.ts +3 -0
- package/dist/start-doors.d.ts.map +1 -1
- package/dist/start-doors.js +14 -0
- package/dist/start-doors.js.map +1 -1
- package/dist/status-and-models.d.ts +3 -0
- package/dist/status-and-models.d.ts.map +1 -1
- package/dist/status-and-models.js +42 -1
- package/dist/status-and-models.js.map +1 -1
- package/dist/terminal-input.d.ts +3 -0
- package/dist/terminal-input.d.ts.map +1 -1
- package/dist/terminal-input.js +12 -0
- package/dist/terminal-input.js.map +1 -1
- package/dist/user-provision.d.ts +4 -0
- package/dist/user-provision.d.ts.map +1 -1
- package/dist/user-provision.js +17 -0
- package/dist/user-provision.js.map +1 -1
- package/package.json +12 -12
|
@@ -0,0 +1,1222 @@
|
|
|
1
|
+
import { copyPersonaEndpoints, DEV_OWNER, discardLaunchArtifacts, EpEnvelopeError, identityFromCreds, idFromCreds, loadAgentFile, loadCotalConfig, parsePrincipalKey, principalKey, rejectionText, resolveAuthProvider } from "@cotal-ai/core";
|
|
2
|
+
import { agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, userAuthStateDir } from "@cotal-ai/workspace";
|
|
3
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
4
|
+
import { lstatSync, realpathSync } from "node:fs";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { sameStrings } from "./credential-renewal.js";
|
|
7
|
+
import { launchSpecForRun } from "./launch.js";
|
|
8
|
+
import { MAX_AGENTS, parseResumeCommitArgs, parseResumeControlArgs, parseResumeFinalizeArgs } from "./resume.js";
|
|
9
|
+
import { requireRuntimeReap } from "./runtime/index.js";
|
|
10
|
+
import { foreignEventChannels } from "./seat-launch.js";
|
|
11
|
+
import { ownedBySibling } from "./static-lifecycle.js";
|
|
12
|
+
/** How often a resumed seat whose readiness was uncertain is checked for a join its predecessor's
|
|
13
|
+
* presence row hides (see {@link Manager.watchResumeAdoption}). The wait has no end of its own, so
|
|
14
|
+
* it asks less often than the readiness fence's 50 ms poll. */
|
|
15
|
+
const LATE_JOIN_POLL_MS = 1_000;
|
|
16
|
+
/** How long a resume waits for a reaped orphan's principal to leave presence. Presence rows age
|
|
17
|
+
* out after their 6s TTL, so three TTLs covers a killed seat that never published its leave. */
|
|
18
|
+
const ORPHAN_PRESENCE_CLEAR_MS = 20_000;
|
|
19
|
+
/** The owner a retained seat resumes under: its inventory identity's, which is the same value the
|
|
20
|
+
* adopted seat records as `userOwner`, so a resumed seat is counted against the owner that held
|
|
21
|
+
* it before the restart ({@link Manager.ownerSeats}) and not against the mesh's default one. */
|
|
22
|
+
function resumeOwner(entry) {
|
|
23
|
+
return entry.identity.mode === "user" ? entry.identity.owner : DEV_OWNER;
|
|
24
|
+
}
|
|
25
|
+
/** The start of every agent's bearer command: node, its loader flags and this manager's entry,
|
|
26
|
+
* resolved through every symlink. The agent runs that command for each renewal for as long as it
|
|
27
|
+
* lives, and an install can replace the bin link meanwhile: get.cotal.ai writes a shell launcher
|
|
28
|
+
* over `~/.local/bin/cotal`, which `npm i -g` had made a link to `dist/cotal.js`. */
|
|
29
|
+
export function bearerEntryArgv() {
|
|
30
|
+
return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
|
|
31
|
+
}
|
|
32
|
+
/** Builds the {@link PreservedResumeDeps} for a Manager. It reads Manager members by name at each use, so a
|
|
33
|
+
* field the Manager assigns later is current and a member a test replaces on the instance is the one that runs. */
|
|
34
|
+
export function preservedResumeDeps(m) {
|
|
35
|
+
return {
|
|
36
|
+
agents: () => m["agents"],
|
|
37
|
+
auth: () => m["auth"],
|
|
38
|
+
ep: () => m["ep"],
|
|
39
|
+
eventPayloadsWithheld: () => m["eventPayloadsWithheld"],
|
|
40
|
+
execution: () => m["execution"],
|
|
41
|
+
managerInstanceId: () => m["managerInstanceId"],
|
|
42
|
+
namesCapacity: () => m["namesCapacity"],
|
|
43
|
+
readinessTimeoutMs: () => m["readinessTimeoutMs"],
|
|
44
|
+
remoteAuthority: () => m["remoteAuthority"],
|
|
45
|
+
resumeAttemptId: () => m["resumeAttemptId"],
|
|
46
|
+
resumeDurableCommitToken: () => m["resumeDurableCommitToken"],
|
|
47
|
+
setResumeDurableCommitToken: (value) => { m["resumeDurableCommitToken"] = value; },
|
|
48
|
+
resumeRequired: () => m["resumeRequired"],
|
|
49
|
+
setResumeRequired: (value) => { m["resumeRequired"] = value; },
|
|
50
|
+
retirement: () => m["retirement"],
|
|
51
|
+
secrets: () => m["secrets"],
|
|
52
|
+
space: () => m["space"],
|
|
53
|
+
userMode: () => m["userMode"],
|
|
54
|
+
workspaceRoot: () => m["workspaceRoot"],
|
|
55
|
+
abortPreservation: (...args) => m["abortPreservation"](...args),
|
|
56
|
+
armSessionRecovery: (...args) => m["armSessionRecovery"](...args),
|
|
57
|
+
awaitHandleExit: (...args) => m["awaitHandleExit"](...args),
|
|
58
|
+
awaitReadiness: (...args) => m["awaitReadiness"](...args),
|
|
59
|
+
beginLifecycle: (...args) => m["beginLifecycle"](...args),
|
|
60
|
+
capabilityRefusal: (...args) => m["capabilityRefusal"](...args),
|
|
61
|
+
capacityRefusal: (...args) => m["capacityRefusal"](...args),
|
|
62
|
+
commitPreservation: (...args) => m["commitPreservation"](...args),
|
|
63
|
+
deprovision: (...args) => m["deprovision"](...args),
|
|
64
|
+
eventsRefusal: (...args) => m["eventsRefusal"](...args),
|
|
65
|
+
executionRefusal: (...args) => m["executionRefusal"](...args),
|
|
66
|
+
fileDigestOrEmpty: (...args) => m["fileDigestOrEmpty"](...args),
|
|
67
|
+
forkProvenance: (...args) => m["forkProvenance"](...args),
|
|
68
|
+
freeSlot: (...args) => m["freeSlot"](...args),
|
|
69
|
+
hostLaunchFields: (...args) => m["hostLaunchFields"](...args),
|
|
70
|
+
inventoryReferenceError: (...args) => m["inventoryReferenceError"](...args),
|
|
71
|
+
launchHarness: (...args) => m["launchHarness"](...args),
|
|
72
|
+
loadSeatRuntime: (...args) => m["loadSeatRuntime"](...args),
|
|
73
|
+
maintenanceError: (...args) => m["maintenanceError"](...args),
|
|
74
|
+
managedPrincipal: (...args) => m["managedPrincipal"](...args),
|
|
75
|
+
nameError: (...args) => m["nameError"](...args),
|
|
76
|
+
occupancy: (...args) => m["occupancy"](...args),
|
|
77
|
+
occupancyText: (...args) => m["occupancyText"](...args),
|
|
78
|
+
preparePreservation: (...args) => m["preparePreservation"](...args),
|
|
79
|
+
probeStaticCredential: (...args) => m["probeStaticCredential"](...args),
|
|
80
|
+
readManagedSession: (...args) => m["readManagedSession"](...args),
|
|
81
|
+
readStaticReconcileSlot: (...args) => m["readStaticReconcileSlot"](...args),
|
|
82
|
+
readerRemedy: (...args) => m["readerRemedy"](...args),
|
|
83
|
+
reconcileStaticLifecycles: (...args) => m["reconcileStaticLifecycles"](...args),
|
|
84
|
+
recordContinuity: (...args) => m["recordContinuity"](...args),
|
|
85
|
+
recordContinuityAtStop: (...args) => m["recordContinuityAtStop"](...args),
|
|
86
|
+
recordSlotCustody: (...args) => m["recordSlotCustody"](...args),
|
|
87
|
+
recordSlotRuntime: (...args) => m["recordSlotRuntime"](...args),
|
|
88
|
+
refreshSeatRecord: (...args) => m["refreshSeatRecord"](...args),
|
|
89
|
+
refreshUnavailableConnectors: (...args) => m["refreshUnavailableConnectors"](...args),
|
|
90
|
+
reserveCustody: (...args) => m["reserveCustody"](...args),
|
|
91
|
+
resolveConnector: (...args) => m["resolveConnector"](...args),
|
|
92
|
+
retainedSessionId: (...args) => m["retainedSessionId"](...args),
|
|
93
|
+
runtimeFor: (...args) => m["runtimeFor"](...args),
|
|
94
|
+
spawnCustodied: (...args) => m["spawnCustodied"](...args),
|
|
95
|
+
stopHandle: (...args) => m["stopHandle"](...args),
|
|
96
|
+
watchExit: (...args) => m["watchExit"](...args),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** Resuming a preserved manager: the bound inventory, validating each retained seat's authority, relaunching or adopting it, and the commit and finalize doors. */
|
|
100
|
+
export class PreservedResume {
|
|
101
|
+
deps;
|
|
102
|
+
constructor(deps) {
|
|
103
|
+
this.deps = deps;
|
|
104
|
+
}
|
|
105
|
+
// The Manager members these bodies read, under their Manager names. Each reads through its dep at
|
|
106
|
+
// use, so a field the Manager assigns later is current and a method a test replaces on the Manager
|
|
107
|
+
// is the one that runs.
|
|
108
|
+
get agents() { return this.deps.agents(); }
|
|
109
|
+
get auth() { return this.deps.auth(); }
|
|
110
|
+
get ep() { return this.deps.ep(); }
|
|
111
|
+
get eventPayloadsWithheld() { return this.deps.eventPayloadsWithheld(); }
|
|
112
|
+
get execution() { return this.deps.execution(); }
|
|
113
|
+
get managerInstanceId() { return this.deps.managerInstanceId(); }
|
|
114
|
+
get namesCapacity() { return this.deps.namesCapacity(); }
|
|
115
|
+
get readinessTimeoutMs() { return this.deps.readinessTimeoutMs(); }
|
|
116
|
+
get remoteAuthority() { return this.deps.remoteAuthority(); }
|
|
117
|
+
get resumeAttemptId() { return this.deps.resumeAttemptId(); }
|
|
118
|
+
get resumeDurableCommitToken() { return this.deps.resumeDurableCommitToken(); }
|
|
119
|
+
set resumeDurableCommitToken(value) { this.deps.setResumeDurableCommitToken(value); }
|
|
120
|
+
get resumeRequired() { return this.deps.resumeRequired(); }
|
|
121
|
+
set resumeRequired(value) { this.deps.setResumeRequired(value); }
|
|
122
|
+
get retirement() { return this.deps.retirement(); }
|
|
123
|
+
get secrets() { return this.deps.secrets(); }
|
|
124
|
+
get space() { return this.deps.space(); }
|
|
125
|
+
get userMode() { return this.deps.userMode(); }
|
|
126
|
+
get workspaceRoot() { return this.deps.workspaceRoot(); }
|
|
127
|
+
abortPreservation(...args) { return this.deps.abortPreservation(...args); }
|
|
128
|
+
armSessionRecovery(...args) { return this.deps.armSessionRecovery(...args); }
|
|
129
|
+
awaitHandleExit(...args) { return this.deps.awaitHandleExit(...args); }
|
|
130
|
+
awaitReadiness(...args) { return this.deps.awaitReadiness(...args); }
|
|
131
|
+
beginLifecycle(...args) { return this.deps.beginLifecycle(...args); }
|
|
132
|
+
capabilityRefusal(...args) { return this.deps.capabilityRefusal(...args); }
|
|
133
|
+
capacityRefusal(...args) { return this.deps.capacityRefusal(...args); }
|
|
134
|
+
commitPreservation(...args) { return this.deps.commitPreservation(...args); }
|
|
135
|
+
deprovision(...args) { return this.deps.deprovision(...args); }
|
|
136
|
+
eventsRefusal(...args) { return this.deps.eventsRefusal(...args); }
|
|
137
|
+
executionRefusal(...args) { return this.deps.executionRefusal(...args); }
|
|
138
|
+
fileDigestOrEmpty(...args) { return this.deps.fileDigestOrEmpty(...args); }
|
|
139
|
+
forkProvenance(...args) { return this.deps.forkProvenance(...args); }
|
|
140
|
+
freeSlot(...args) { return this.deps.freeSlot(...args); }
|
|
141
|
+
hostLaunchFields(...args) { return this.deps.hostLaunchFields(...args); }
|
|
142
|
+
inventoryReferenceError(...args) { return this.deps.inventoryReferenceError(...args); }
|
|
143
|
+
launchHarness(...args) { return this.deps.launchHarness(...args); }
|
|
144
|
+
loadSeatRuntime(...args) { return this.deps.loadSeatRuntime(...args); }
|
|
145
|
+
maintenanceError(...args) { return this.deps.maintenanceError(...args); }
|
|
146
|
+
managedPrincipal(...args) { return this.deps.managedPrincipal(...args); }
|
|
147
|
+
nameError(...args) { return this.deps.nameError(...args); }
|
|
148
|
+
occupancy(...args) { return this.deps.occupancy(...args); }
|
|
149
|
+
occupancyText(...args) { return this.deps.occupancyText(...args); }
|
|
150
|
+
preparePreservation(...args) { return this.deps.preparePreservation(...args); }
|
|
151
|
+
probeStaticCredential(...args) { return this.deps.probeStaticCredential(...args); }
|
|
152
|
+
readManagedSession(...args) { return this.deps.readManagedSession(...args); }
|
|
153
|
+
readStaticReconcileSlot(...args) { return this.deps.readStaticReconcileSlot(...args); }
|
|
154
|
+
readerRemedy(...args) { return this.deps.readerRemedy(...args); }
|
|
155
|
+
reconcileStaticLifecycles(...args) { return this.deps.reconcileStaticLifecycles(...args); }
|
|
156
|
+
recordContinuity(...args) { return this.deps.recordContinuity(...args); }
|
|
157
|
+
recordContinuityAtStop(...args) { return this.deps.recordContinuityAtStop(...args); }
|
|
158
|
+
recordSlotCustody(...args) { return this.deps.recordSlotCustody(...args); }
|
|
159
|
+
recordSlotRuntime(...args) { return this.deps.recordSlotRuntime(...args); }
|
|
160
|
+
refreshSeatRecord(...args) { return this.deps.refreshSeatRecord(...args); }
|
|
161
|
+
refreshUnavailableConnectors(...args) { return this.deps.refreshUnavailableConnectors(...args); }
|
|
162
|
+
reserveCustody(...args) { return this.deps.reserveCustody(...args); }
|
|
163
|
+
resolveConnector(...args) { return this.deps.resolveConnector(...args); }
|
|
164
|
+
retainedSessionId(...args) { return this.deps.retainedSessionId(...args); }
|
|
165
|
+
runtimeFor(...args) { return this.deps.runtimeFor(...args); }
|
|
166
|
+
spawnCustodied(...args) { return this.deps.spawnCustodied(...args); }
|
|
167
|
+
stopHandle(...args) { return this.deps.stopHandle(...args); }
|
|
168
|
+
watchExit(...args) { return this.deps.watchExit(...args); }
|
|
169
|
+
resumeCommitted = false;
|
|
170
|
+
resumeFinalized = false;
|
|
171
|
+
resumeInventory;
|
|
172
|
+
resumeCommitTask;
|
|
173
|
+
resumeInventoryDigest;
|
|
174
|
+
resumeTask;
|
|
175
|
+
resumeResult;
|
|
176
|
+
resumedAgentNames = new Set();
|
|
177
|
+
resumeAwaitingCommit = false;
|
|
178
|
+
resumeEntry(a, backfillFloor) {
|
|
179
|
+
// A preservation cut is a stop boundary too, so a manifest launch after it reopens what a resume would.
|
|
180
|
+
this.recordContinuityAtStop(a, "preservation");
|
|
181
|
+
return this.resumeEntryOf(a, backfillFloor);
|
|
182
|
+
}
|
|
183
|
+
/** The resume entry of one live seat, with no side effect: a preservation cut and a supervised
|
|
184
|
+
* seat's record both build it. The entry is its own copy, so a caller's write to the plan it was
|
|
185
|
+
* handed cannot change the launch the manager keeps supervising (#3241). */
|
|
186
|
+
resumeEntryOf(a, backfillFloor) {
|
|
187
|
+
const principal = a.userOwner
|
|
188
|
+
? parsePrincipalKey(a.id)
|
|
189
|
+
: { owner: DEV_OWNER, actor: a.id };
|
|
190
|
+
if (!principal)
|
|
191
|
+
throw new Error(`managed agent ${a.name} has an invalid principal ${a.id}`);
|
|
192
|
+
// The RECORDED secret-family paths (set at spawn or adoption) — never a re-derivation by name:
|
|
193
|
+
// under mixed generations (a name-keyed pre-split incarnation adopted by this manager) the
|
|
194
|
+
// recorded path is the only truth, and re-deriving would preserve a family that isn't there.
|
|
195
|
+
const files = a.secretPaths;
|
|
196
|
+
const identity = a.userOwner
|
|
197
|
+
? (() => {
|
|
198
|
+
if (!files?.actorToken || !files.sentinelCreds || !files.health)
|
|
199
|
+
throw new Error(`managed agent ${a.name} is user-mode but its secret-family paths were not recorded`);
|
|
200
|
+
return {
|
|
201
|
+
mode: "user",
|
|
202
|
+
owner: principal.owner,
|
|
203
|
+
actor: principal.actor,
|
|
204
|
+
lifecycleUid: a.lifecycleUid,
|
|
205
|
+
actorToken: { kind: "file", path: files.actorToken, sha256: this.fileDigestOrEmpty(files.actorToken) },
|
|
206
|
+
sentinelCredential: { kind: "file", path: files.sentinelCreds, sha256: this.fileDigestOrEmpty(files.sentinelCreds) },
|
|
207
|
+
health: { kind: "file", path: files.health },
|
|
208
|
+
};
|
|
209
|
+
})()
|
|
210
|
+
: this.auth
|
|
211
|
+
? (() => {
|
|
212
|
+
if (!files?.creds)
|
|
213
|
+
throw new Error(`managed agent ${a.name} is static-auth but its credential path was not recorded`);
|
|
214
|
+
return { mode: "static", id: principal.actor, lifecycleUid: a.lifecycleUid, credential: { kind: "file", path: files.creds, sha256: this.fileDigestOrEmpty(files.creds) }, ...(a.issued ? { issued: a.issued } : {}) };
|
|
215
|
+
})()
|
|
216
|
+
: { mode: "open", id: principal.actor, lifecycleUid: a.lifecycleUid };
|
|
217
|
+
const dependencies = [a.launch.source.configPath];
|
|
218
|
+
if (a.launch.source.kind === "manifest" && a.launch.source.runId)
|
|
219
|
+
dependencies.unshift(join(this.workspaceRoot, ".cotal", "run", `${a.launch.source.runId}.json`));
|
|
220
|
+
return structuredClone({
|
|
221
|
+
space: this.space,
|
|
222
|
+
name: a.name,
|
|
223
|
+
role: a.role,
|
|
224
|
+
identity,
|
|
225
|
+
launch: {
|
|
226
|
+
connector: a.agent,
|
|
227
|
+
runtime: a.handle.kind,
|
|
228
|
+
cwd: a.launch.cwd,
|
|
229
|
+
source: a.launch.source,
|
|
230
|
+
model: a.launch.model,
|
|
231
|
+
variant: a.launch.variant,
|
|
232
|
+
subscribe: a.launch.subscribe,
|
|
233
|
+
allowSubscribe: a.launch.allowSubscribe,
|
|
234
|
+
allowPublish: a.launch.allowPublish,
|
|
235
|
+
capabilities: a.launch.capabilities,
|
|
236
|
+
...(a.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(a.launch.endpoints) } : {}),
|
|
237
|
+
events: a.launch.events,
|
|
238
|
+
eventPayloads: a.launch.eventPayloads,
|
|
239
|
+
shareTools: a.launch.shareTools,
|
|
240
|
+
forkSource: a.launch.forkSource,
|
|
241
|
+
...(this.forkProvenance(a) ? { resumed: this.forkProvenance(a) } : {}),
|
|
242
|
+
// A supervised seat whose connector keeps no session state is armed with no state file to read.
|
|
243
|
+
sessionId: a.restart?.armed && a.restart.sessionStatePath ? this.readManagedSession(a) : a.launch.sessionId,
|
|
244
|
+
// Additive and only when the connector supplied one. A seat with no pointer records no
|
|
245
|
+
// field, which is what keeps an older inventory and a fresh one the same document shape.
|
|
246
|
+
...(a.restart?.sessionStatePath ? { sessionStatePath: a.restart.sessionStatePath } : {}),
|
|
247
|
+
unresolvedLaunchOptionKeys: a.launch.unresolvedLaunchOptionKeys,
|
|
248
|
+
},
|
|
249
|
+
dependencies,
|
|
250
|
+
spawner: a.spawner,
|
|
251
|
+
authorityParent: a.authorityParent,
|
|
252
|
+
startedAt: new Date(a.startedAt).toISOString(),
|
|
253
|
+
...(backfillFloor !== undefined ? { backfillFloor } : {}),
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
async opFinalizeResume(rawArgs) {
|
|
257
|
+
if (this.execution === "none")
|
|
258
|
+
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
259
|
+
{
|
|
260
|
+
let args;
|
|
261
|
+
try {
|
|
262
|
+
args = parseResumeFinalizeArgs(rawArgs);
|
|
263
|
+
}
|
|
264
|
+
catch (e) {
|
|
265
|
+
return { ok: false, error: rejectionText(e) };
|
|
266
|
+
}
|
|
267
|
+
if (!this.resumeAttemptId || this.resumeAttemptId !== args.attemptId)
|
|
268
|
+
return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId ?? "<none>"}, not ${args.attemptId}` };
|
|
269
|
+
if (!this.resumeCommitted || !this.resumeDurableCommitToken)
|
|
270
|
+
return { ok: false, error: `resume attempt ${args.attemptId} has no successful commit to finalize` };
|
|
271
|
+
if (this.resumeDurableCommitToken !== args.durableCommitToken)
|
|
272
|
+
return { ok: false, error: `resume attempt ${args.attemptId} durable commit token does not match` };
|
|
273
|
+
if (this.resumeFinalized)
|
|
274
|
+
return { ok: true, data: { attemptId: args.attemptId, state: "active" } };
|
|
275
|
+
const inventory = this.resumeInventory;
|
|
276
|
+
if (!inventory)
|
|
277
|
+
return { ok: false, error: `resume attempt ${args.attemptId} has no bound inventory` };
|
|
278
|
+
let inactive;
|
|
279
|
+
try {
|
|
280
|
+
inactive = this.resumeLivenessErrors(inventory, this.ep.getRoster());
|
|
281
|
+
}
|
|
282
|
+
catch (e) {
|
|
283
|
+
return { ok: false, error: `resume attempt ${args.attemptId} cannot verify live principals at finalize: ${rejectionText(e)}` };
|
|
284
|
+
}
|
|
285
|
+
if (inactive.length)
|
|
286
|
+
return { ok: false, error: `resume attempt ${args.attemptId} is not live at finalize: ${inactive.join("; ")}` };
|
|
287
|
+
for (const entry of this.resumeInventory?.agents ?? []) {
|
|
288
|
+
const managed = this.agents.get(entry.name);
|
|
289
|
+
if (managed)
|
|
290
|
+
managed.suppressCleanup = false;
|
|
291
|
+
}
|
|
292
|
+
// distsys/security CONDITIONAL @ 9e13648: the boot sweep DEFERRED every active
|
|
293
|
+
// slot while a resume was pending (it could not know which would be adopted). Now adoption
|
|
294
|
+
// is complete and `this.agents` is EXACTLY the adopted set, so re-sweep to terminalize any
|
|
295
|
+
// active slot the resume did NOT claim — a durable ACTIVE ORPHAN (crashed after slot->active
|
|
296
|
+
// before agents.set, then not in the resumed inventory). This runs while `resumeRequired` is
|
|
297
|
+
// still true, so no ordinary spawn can race it (beginLifecycle refuses non-resume ops), and
|
|
298
|
+
// it closes both the alias wedge AND the membership-gate gap (the orphan's principal enters
|
|
299
|
+
// retiredPrincipals, so a copied JWT is refused). Best-effort + loud: a sweep failure must
|
|
300
|
+
// not fail the finalize (the next non-resume boot re-drives it), but it is never swallowed.
|
|
301
|
+
if (this.auth && !this.userMode)
|
|
302
|
+
await this.reconcileStaticLifecycles(true).catch((e) => console.error(`! post-resume static reconcile: ${rejectionText(e)} - no per-alias retry could be planned; a later manager start re-reads unfinished durable terminals`));
|
|
303
|
+
this.resumeFinalized = true;
|
|
304
|
+
this.resumeRequired = false;
|
|
305
|
+
return { ok: true, data: { attemptId: args.attemptId, state: "active" } };
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
async opCommitResume(rawArgs) {
|
|
309
|
+
if (this.execution === "none")
|
|
310
|
+
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
311
|
+
{
|
|
312
|
+
let attemptId;
|
|
313
|
+
try {
|
|
314
|
+
attemptId = parseResumeCommitArgs(rawArgs).attemptId;
|
|
315
|
+
}
|
|
316
|
+
catch (e) {
|
|
317
|
+
return { ok: false, error: rejectionText(e) };
|
|
318
|
+
}
|
|
319
|
+
if (!this.resumeAttemptId || this.resumeAttemptId !== attemptId)
|
|
320
|
+
return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId ?? "<none>"}, not ${attemptId}` };
|
|
321
|
+
if (this.resumeCommitted)
|
|
322
|
+
return {
|
|
323
|
+
ok: true,
|
|
324
|
+
data: {
|
|
325
|
+
attemptId,
|
|
326
|
+
state: this.resumeFinalized ? "active" : "awaitingFinalize",
|
|
327
|
+
durableCommitToken: this.resumeDurableCommitToken,
|
|
328
|
+
},
|
|
329
|
+
};
|
|
330
|
+
if (this.resumeCommitTask)
|
|
331
|
+
return this.resumeCommitTask;
|
|
332
|
+
const task = this.commitResumeActivation(attemptId);
|
|
333
|
+
this.resumeCommitTask = task;
|
|
334
|
+
try {
|
|
335
|
+
return await task;
|
|
336
|
+
}
|
|
337
|
+
finally {
|
|
338
|
+
if (this.resumeCommitTask === task)
|
|
339
|
+
this.resumeCommitTask = undefined;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
async opResumePreserved(rawArgs) {
|
|
344
|
+
if (this.execution === "none")
|
|
345
|
+
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
346
|
+
{
|
|
347
|
+
try {
|
|
348
|
+
const args = parseResumeControlArgs(rawArgs);
|
|
349
|
+
const inventoryDigest = createHash("sha256").update(JSON.stringify(args.inventory)).digest("hex");
|
|
350
|
+
if (!this.resumeAttemptId)
|
|
351
|
+
return { ok: false, error: "resumePreserved requires a manager started with --resume-attempt" };
|
|
352
|
+
if (this.resumeAttemptId !== args.attemptId)
|
|
353
|
+
return { ok: false, error: `manager expects resume attempt ${this.resumeAttemptId}, not ${args.attemptId}` };
|
|
354
|
+
if (this.resumeInventoryDigest && this.resumeInventoryDigest !== inventoryDigest)
|
|
355
|
+
return { ok: false, error: `resume attempt ${args.attemptId} is already bound to a different inventory` };
|
|
356
|
+
if (!this.resumeInventoryDigest) {
|
|
357
|
+
this.resumeInventoryDigest = inventoryDigest;
|
|
358
|
+
this.resumeInventory = args.inventory;
|
|
359
|
+
}
|
|
360
|
+
if (!this.resumeTask && !this.resumeResult) {
|
|
361
|
+
this.resumeTask = this.resumePreserved(args.inventory).then((result) => {
|
|
362
|
+
if (result.ok || this.resumedAgentNames.size > 0)
|
|
363
|
+
this.resumeResult = result;
|
|
364
|
+
return result;
|
|
365
|
+
}).finally(() => {
|
|
366
|
+
this.resumeTask = undefined;
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
const result = this.resumeResult ?? await this.resumeTask;
|
|
370
|
+
const data = { attemptId: args.attemptId, state: result.ok ? "awaitingCommit" : "degraded", ...result };
|
|
371
|
+
return result.ok
|
|
372
|
+
? { ok: true, data }
|
|
373
|
+
: { ok: false, data, error: result.error ?? "retained-agent resume failed" };
|
|
374
|
+
}
|
|
375
|
+
catch (e) {
|
|
376
|
+
return { ok: false, error: rejectionText(e) };
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
async opPreservationCtl(op, rawArgs) {
|
|
381
|
+
if (this.execution === "none")
|
|
382
|
+
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
383
|
+
if (this.resumeRequired)
|
|
384
|
+
return { ok: false, error: this.maintenanceError() };
|
|
385
|
+
const attemptId = String(rawArgs?.attemptId ?? "").trim();
|
|
386
|
+
if (!attemptId)
|
|
387
|
+
return { ok: false, error: `${op} requires attemptId` };
|
|
388
|
+
try {
|
|
389
|
+
if (op === "abortPreservation") {
|
|
390
|
+
this.abortPreservation(attemptId);
|
|
391
|
+
return { ok: true, data: { attemptId, state: "active" } };
|
|
392
|
+
}
|
|
393
|
+
const result = op === "preparePreservation"
|
|
394
|
+
? await this.preparePreservation(attemptId)
|
|
395
|
+
: await this.commitPreservation(attemptId);
|
|
396
|
+
return result.ok
|
|
397
|
+
? { ok: true, data: result }
|
|
398
|
+
: {
|
|
399
|
+
ok: false,
|
|
400
|
+
data: result,
|
|
401
|
+
error: `preservation incomplete: ${result.failures.map((f) => `${f.name}: ${f.error}`).join("; ")}`,
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
catch (e) {
|
|
405
|
+
return { ok: false, error: rejectionText(e) };
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
async commitResumeActivation(attemptId) {
|
|
409
|
+
if (!this.resumeAwaitingCommit || !this.resumeResult?.ok)
|
|
410
|
+
return { ok: false, error: `resume attempt ${attemptId} has no successful activation to commit` };
|
|
411
|
+
const inventory = this.resumeInventory;
|
|
412
|
+
if (!inventory)
|
|
413
|
+
return { ok: false, error: `resume attempt ${attemptId} has no bound inventory` };
|
|
414
|
+
const authority = await Promise.all(inventory.agents.map(async (entry) => {
|
|
415
|
+
try {
|
|
416
|
+
await this.validateRetainedAuthority(entry);
|
|
417
|
+
return undefined;
|
|
418
|
+
}
|
|
419
|
+
catch (e) {
|
|
420
|
+
return `${entry.name}: ${rejectionText(e)}`;
|
|
421
|
+
}
|
|
422
|
+
}));
|
|
423
|
+
const drift = authority.filter((error) => error !== undefined);
|
|
424
|
+
if (drift.length)
|
|
425
|
+
return { ok: false, error: `resume attempt ${attemptId} retained authority changed before commit: ${drift.join("; ")}` };
|
|
426
|
+
let inactive;
|
|
427
|
+
try {
|
|
428
|
+
inactive = this.resumeLivenessErrors(inventory, this.ep.getRoster());
|
|
429
|
+
}
|
|
430
|
+
catch (e) {
|
|
431
|
+
return { ok: false, error: `resume attempt ${attemptId} cannot verify live principals: ${rejectionText(e)}` };
|
|
432
|
+
}
|
|
433
|
+
if (inactive.length)
|
|
434
|
+
return { ok: false, error: `resume attempt ${attemptId} is not live at commit: ${inactive.join("; ")}` };
|
|
435
|
+
this.resumeAwaitingCommit = false;
|
|
436
|
+
this.resumeCommitted = true;
|
|
437
|
+
this.resumeDurableCommitToken ??= randomBytes(32).toString("hex");
|
|
438
|
+
return {
|
|
439
|
+
ok: true,
|
|
440
|
+
data: { attemptId, state: "awaitingFinalize", durableCommitToken: this.resumeDurableCommitToken },
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
resumeLivenessErrors(inventory, roster) {
|
|
444
|
+
const inactive = [];
|
|
445
|
+
const expectedNames = new Set(inventory.agents.map((entry) => entry.name));
|
|
446
|
+
for (const name of this.resumedAgentNames)
|
|
447
|
+
if (!expectedNames.has(name))
|
|
448
|
+
inactive.push(`${name} is not part of the bound inventory`);
|
|
449
|
+
for (const entry of inventory.agents) {
|
|
450
|
+
const managed = this.agents.get(entry.name);
|
|
451
|
+
if (!managed) {
|
|
452
|
+
inactive.push(`${entry.name} is no longer managed`);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
const expectedId = entry.identity.mode === "user"
|
|
456
|
+
? principalKey(entry.identity.owner, entry.identity.actor).key
|
|
457
|
+
: entry.identity.id;
|
|
458
|
+
const expectedPrincipal = entry.identity.mode === "user"
|
|
459
|
+
? expectedId
|
|
460
|
+
: principalKey(DEV_OWNER, entry.identity.id).key;
|
|
461
|
+
if (managed.id !== expectedId || this.managedPrincipal(managed) !== expectedPrincipal) {
|
|
462
|
+
inactive.push(`${entry.name} no longer holds retained principal ${expectedPrincipal}`);
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
// The late paths (commit/finalize) must prove the SAME incarnation the incarnation-exact
|
|
466
|
+
// readiness fence proved (§13.1): a principal-only match lets a wrong/absent-uid presence under
|
|
467
|
+
// the reused alias satisfy commit/finalize after a readiness timeout, undoing the fence.
|
|
468
|
+
if (managed.lifecycleUid !== entry.identity.lifecycleUid) {
|
|
469
|
+
inactive.push(`${entry.name} manager metadata incarnation ${managed.lifecycleUid} drifted from the inventory's ${entry.identity.lifecycleUid}`);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (managed.handle.name !== entry.name || managed.handle.kind !== entry.launch.runtime) {
|
|
473
|
+
inactive.push(`${entry.name} is not attached to its exact retained ${entry.launch.runtime} handle`);
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
try {
|
|
477
|
+
if (managed.handle.status() !== "running") {
|
|
478
|
+
inactive.push(`${entry.name} runtime is not running`);
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
catch (e) {
|
|
483
|
+
inactive.push(`${entry.name} runtime status failed: ${rejectionText(e)}`);
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
if (!roster.some((presence) => presence.card.id === expectedPrincipal && presence.card.name === entry.name && presence.status !== "offline" &&
|
|
487
|
+
presence.lifecycleUid === entry.identity.lifecycleUid))
|
|
488
|
+
inactive.push(`${entry.name} incarnation ${entry.identity.lifecycleUid} (principal ${expectedPrincipal}) is not exactly present`);
|
|
489
|
+
}
|
|
490
|
+
return inactive;
|
|
491
|
+
}
|
|
492
|
+
/** Preflight the whole inventory before launching its first process, then adopt each exact retained
|
|
493
|
+
* principal without provisioning. A later runtime launch failure is reported per-agent, but malformed
|
|
494
|
+
* or missing inventory material can never produce a partially resumed set. */
|
|
495
|
+
async resumePreserved(inventory) {
|
|
496
|
+
if (this.execution === "none")
|
|
497
|
+
return { ok: false, agents: [], error: this.executionRefusal() };
|
|
498
|
+
const release = this.beginLifecycle(true);
|
|
499
|
+
if (!release)
|
|
500
|
+
return { ok: false, agents: [], error: this.maintenanceError() };
|
|
501
|
+
const batchReservations = [];
|
|
502
|
+
const prepared = new Map();
|
|
503
|
+
try {
|
|
504
|
+
if (inventory.version !== "cotal-manager-resume/v2")
|
|
505
|
+
return { ok: false, agents: [], error: `unsupported manager resume inventory version ${String(inventory.version)}` };
|
|
506
|
+
if (inventory.space !== this.space)
|
|
507
|
+
return { ok: false, agents: [], error: `resume inventory belongs to space "${inventory.space}", not "${this.space}"` };
|
|
508
|
+
// The caller keeps its inventory, so it is copied before the first await: a later write to it
|
|
509
|
+
// cannot change what a resumed seat launches with or what the next preservation retains.
|
|
510
|
+
const entries = structuredClone(inventory.agents);
|
|
511
|
+
const seen = new Set();
|
|
512
|
+
const principals = new Set();
|
|
513
|
+
const orphans = [];
|
|
514
|
+
await this.ep.waitForPresenceSnapshot();
|
|
515
|
+
const liveRoster = this.ep.getRoster().filter((presence) => presence.status !== "offline");
|
|
516
|
+
const occupancy = this.occupancy();
|
|
517
|
+
if (occupancy.used + entries.length > MAX_AGENTS)
|
|
518
|
+
return { ok: false, agents: [], error: `resume inventory of ${entries.length} would exceed manager capacity (${this.occupancyText(occupancy)})` };
|
|
519
|
+
for (const entry of entries) {
|
|
520
|
+
if (seen.has(entry.name))
|
|
521
|
+
return { ok: false, agents: [], error: `resume inventory contains duplicate agent name "${entry.name}"` };
|
|
522
|
+
seen.add(entry.name);
|
|
523
|
+
// A manager-local retirement hold is stronger and more precise than presence. The stopped
|
|
524
|
+
// predecessor can remain roster-live until its TTL/offline update lands, but that stale row
|
|
525
|
+
// must not hide the durable teardown state the manager already owns. Refuse and re-drive the
|
|
526
|
+
// exact held lifecycle before consulting generic principal liveness. A confirmed terminal has
|
|
527
|
+
// already removed the hold, so fresh-lifecycle resume still reaches the fail-closed roster gate.
|
|
528
|
+
const held = this.retirement.held(entry.name);
|
|
529
|
+
if (held) {
|
|
530
|
+
void this.deprovision(held.target).catch(() => { });
|
|
531
|
+
return {
|
|
532
|
+
ok: false,
|
|
533
|
+
agents: [],
|
|
534
|
+
error: `retained agent "${entry.name}" is reserved pending retirement: its previous lifecycle ${held.target.lifecycleUid} still owns the alias${held.lastError ? ` (last attempt: ${held.lastError})` : ""}; retrying re-drives that exact teardown`,
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
let principal;
|
|
538
|
+
try {
|
|
539
|
+
principal = entry.identity.mode === "user"
|
|
540
|
+
? principalKey(entry.identity.owner, entry.identity.actor).key
|
|
541
|
+
: principalKey(DEV_OWNER, entry.identity.id).key;
|
|
542
|
+
}
|
|
543
|
+
catch (e) {
|
|
544
|
+
return { ok: false, agents: [], error: `invalid retained principal for ${entry.name}: ${rejectionText(e)}` };
|
|
545
|
+
}
|
|
546
|
+
if (principals.has(principal))
|
|
547
|
+
return { ok: false, agents: [], error: `resume inventory contains duplicate principal "${principal}"` };
|
|
548
|
+
principals.add(principal);
|
|
549
|
+
const confirmedPredecessor = this.retirement.predecessor(entry.name);
|
|
550
|
+
const principalIsLive = liveRoster.some((presence) => {
|
|
551
|
+
if (presence.card.id !== principal)
|
|
552
|
+
return false;
|
|
553
|
+
return confirmedPredecessor === undefined ||
|
|
554
|
+
confirmedPredecessor.principal !== principal ||
|
|
555
|
+
confirmedPredecessor.lifecycleUid !== presence.lifecycleUid ||
|
|
556
|
+
presence.card.name !== entry.name ||
|
|
557
|
+
entry.identity.lifecycleUid === confirmedPredecessor.lifecycleUid;
|
|
558
|
+
});
|
|
559
|
+
if (principalIsLive) {
|
|
560
|
+
const orphan = await this.orphanedResumeSeat(entry, principal, liveRoster);
|
|
561
|
+
if (!orphan)
|
|
562
|
+
return { ok: false, agents: [], error: `retained principal "${principal}" is already live and this runtime cannot authoritatively adopt it` };
|
|
563
|
+
orphans.push({ principal, reference: orphan });
|
|
564
|
+
}
|
|
565
|
+
if (this.agents.has(entry.name) || this.namesCapacity.isReserved(entry.name))
|
|
566
|
+
return { ok: false, agents: [], error: `retained agent "${entry.name}" is already managed or reserved` };
|
|
567
|
+
}
|
|
568
|
+
for (const entry of entries) {
|
|
569
|
+
this.namesCapacity.reserve(entry.name, resumeOwner(entry));
|
|
570
|
+
batchReservations.push(entry.name);
|
|
571
|
+
}
|
|
572
|
+
const preflight = [];
|
|
573
|
+
for (const entry of entries) {
|
|
574
|
+
const reply = await this.resumePreservedAgent(entry, true, true, prepared);
|
|
575
|
+
preflight.push({ name: entry.name, reply });
|
|
576
|
+
}
|
|
577
|
+
const preflightFailures = preflight.filter(({ reply }) => !reply.ok);
|
|
578
|
+
if (preflightFailures.length)
|
|
579
|
+
return {
|
|
580
|
+
ok: false,
|
|
581
|
+
agents: preflight,
|
|
582
|
+
error: `${preflightFailures.length} retained agent${preflightFailures.length === 1 ? "" : "s"} failed preflight`,
|
|
583
|
+
};
|
|
584
|
+
// Only now, with the whole inventory through preflight, is an orphan reaped: a refused batch
|
|
585
|
+
// leaves every seat as it found it.
|
|
586
|
+
for (const { principal, reference } of orphans) {
|
|
587
|
+
const refusal = await this.reapOrphanedResumeSeat(principal, reference);
|
|
588
|
+
if (refusal)
|
|
589
|
+
return { ok: false, agents: [], error: refusal };
|
|
590
|
+
}
|
|
591
|
+
const agents = [];
|
|
592
|
+
for (let i = 0; i < entries.length; i++) {
|
|
593
|
+
const entry = entries[i];
|
|
594
|
+
const reply = await this.resumePreservedAgent(entry, false, true, prepared);
|
|
595
|
+
agents.push({ name: entry.name, reply });
|
|
596
|
+
if (!reply.ok) {
|
|
597
|
+
for (const skipped of entries.slice(i + 1))
|
|
598
|
+
agents.push({ name: skipped.name, reply: { ok: false, error: `not launched because ${entry.name} failed` } });
|
|
599
|
+
return { ok: false, agents, error: reply.error };
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
if (this.resumeAttemptId)
|
|
603
|
+
this.resumeAwaitingCommit = true;
|
|
604
|
+
return { ok: true, agents };
|
|
605
|
+
}
|
|
606
|
+
finally {
|
|
607
|
+
for (const name of batchReservations) {
|
|
608
|
+
this.namesCapacity.release(name);
|
|
609
|
+
}
|
|
610
|
+
// Preflight builds every launch before any child starts, so a refused batch, a failed launch,
|
|
611
|
+
// or the agents skipped after it leave built specs no runtime ever received.
|
|
612
|
+
for (const { spec, spawned } of prepared.values()) {
|
|
613
|
+
if (spawned)
|
|
614
|
+
continue;
|
|
615
|
+
try {
|
|
616
|
+
discardLaunchArtifacts(spec.artifacts);
|
|
617
|
+
}
|
|
618
|
+
catch (e) {
|
|
619
|
+
console.error(`! resume: ${rejectionText(e)}`);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
release();
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
/** Re-read every retained identity input and its current authority without provisioning. This runs
|
|
626
|
+
* during whole-inventory preflight, immediately before each individual spawn, and at commit. */
|
|
627
|
+
async validateRetainedAuthority(entry) {
|
|
628
|
+
const referenceError = this.inventoryReferenceError(entry);
|
|
629
|
+
if (referenceError)
|
|
630
|
+
throw new Error(`retained agent ${entry.name}: ${referenceError}`);
|
|
631
|
+
// THE OWN-CHANNEL RULE, ON THE RESUME DOOR, and it belongs here rather than beside the launch
|
|
632
|
+
// because BOTH resume paths funnel through this function and neither may skip it.
|
|
633
|
+
//
|
|
634
|
+
// A resume document is admin-supplied JSON. It carries the ACLs the managed row is re-armed
|
|
635
|
+
// from, and `renewManagedStaticCred` re-mints the credential out of that row at half TTL, so a
|
|
636
|
+
// foreign event channel written into an inventory becomes a minted read on another agent's tool
|
|
637
|
+
// inputs and outputs one renewal later. In static mode nothing else stops it: the checks below
|
|
638
|
+
// pin the credential's PATH, its IDENTITY and the broker's acceptance of it, and say nothing at
|
|
639
|
+
// all about its ACL. User mode compares the adopted authority's ACL against the inventory's, so
|
|
640
|
+
// it refuses a divergence on both fields already, but it refuses it as DRIFT rather than as this
|
|
641
|
+
// rule, and an inventory whose record and credential agree with each other and disagree with
|
|
642
|
+
// this rule is exactly the document an operator would not notice.
|
|
643
|
+
//
|
|
644
|
+
// Refuses rather than strips. Silently narrowing an admin document would leave the operator
|
|
645
|
+
// holding a record that says one thing and a mesh that does another, and the whole reason this
|
|
646
|
+
// is reachable is that nobody reads the record.
|
|
647
|
+
{
|
|
648
|
+
const owner = entry.identity.mode === "user" ? entry.identity.owner : DEV_OWNER;
|
|
649
|
+
// The ACTOR HALF IS THE PRINCIPAL, never the display name. In user mode the row this
|
|
650
|
+
// document re-arms is keyed by `identity.actor` (it is what the provider adopts below and
|
|
651
|
+
// what every liveness check reads), and an inventory supplies `name` and `identity.actor`
|
|
652
|
+
// independently, so judging the channel against `name` would judge it against the half that
|
|
653
|
+
// does not own the plane.
|
|
654
|
+
const actor = entry.identity.mode === "user" ? entry.identity.actor : entry.identity.id;
|
|
655
|
+
const foreign = foreignEventChannels([...(entry.launch.allowSubscribe ?? []), ...(entry.launch.allowPublish ?? [])], owner, actor);
|
|
656
|
+
if (foreign.length)
|
|
657
|
+
throw new Error(`retained agent ${entry.name}: its record claims another agent's event channel ` +
|
|
658
|
+
`(${foreign.join(", ")}). An agent may hold its OWN event plane and no other, because that ` +
|
|
659
|
+
`plane carries the session's tool inputs and outputs. Remove it from the inventory and ` +
|
|
660
|
+
`grant the reader out of band instead: ` +
|
|
661
|
+
`${this.readerRemedy(owner, foreign[0])}`);
|
|
662
|
+
}
|
|
663
|
+
if (entry.identity.mode === "open") {
|
|
664
|
+
if (this.auth || this.userMode)
|
|
665
|
+
throw new Error(`retained agent ${entry.name} is open-mode but the current manager is authenticated`);
|
|
666
|
+
return { id: entry.identity.id };
|
|
667
|
+
}
|
|
668
|
+
if (entry.identity.mode === "static") {
|
|
669
|
+
if (!this.auth || this.userMode)
|
|
670
|
+
throw new Error(`retained agent ${entry.name} is static-auth but the current manager is not`);
|
|
671
|
+
// CLOSED candidate set, not an open path: the lifecycle-keyed derivation (this generation's
|
|
672
|
+
// layout) or the name-keyed one (a pre-split inventory being carried across the upgrade).
|
|
673
|
+
// Anything else is a foreign path and refused exactly as before.
|
|
674
|
+
const candidates = [
|
|
675
|
+
resolve(agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, entry.name, entry.identity.lifecycleUid).creds),
|
|
676
|
+
resolve(agentSecretFilePaths(this.workspaceRoot, this.space, entry.name).creds),
|
|
677
|
+
];
|
|
678
|
+
const expected = resolve(entry.identity.credential.path);
|
|
679
|
+
if (!candidates.includes(expected))
|
|
680
|
+
throw new Error(`retained credential reference for ${entry.name} is not a manager-owned path (expected ${candidates.join(" or ")})`);
|
|
681
|
+
let credentialText;
|
|
682
|
+
try {
|
|
683
|
+
// The lstat guards the FS MATERIALIZATION the child will read at launch; the identity check
|
|
684
|
+
// runs on the store's value — the source of truth (byte-identical here, the local FS
|
|
685
|
+
// composition resolves the key to this same path).
|
|
686
|
+
const st = lstatSync(expected);
|
|
687
|
+
if (!st.isFile() || st.isSymbolicLink())
|
|
688
|
+
throw new Error("not a regular non-symlink file");
|
|
689
|
+
const stored = await this.secrets.get(agentSecretKeyForFile(expected, this.space));
|
|
690
|
+
if (stored === undefined)
|
|
691
|
+
throw new Error("the credential is not in the secret store");
|
|
692
|
+
credentialText = stored;
|
|
693
|
+
const actual = idFromCreds(credentialText);
|
|
694
|
+
if (actual !== entry.identity.id)
|
|
695
|
+
throw new Error(`retained credential identity ${actual} does not match inventory principal ${entry.identity.id}`);
|
|
696
|
+
}
|
|
697
|
+
catch (e) {
|
|
698
|
+
throw new Error(`retained credential for ${entry.name} is unusable: ${rejectionText(e)}`);
|
|
699
|
+
}
|
|
700
|
+
const accepted = await this.probeStaticCredential(credentialText);
|
|
701
|
+
if (!accepted.ok)
|
|
702
|
+
throw new Error(`retained credential for ${entry.name} is not accepted by the current broker (${accepted.reason})`);
|
|
703
|
+
return { id: entry.identity.id, creds: expected };
|
|
704
|
+
}
|
|
705
|
+
if (!this.userMode)
|
|
706
|
+
throw new Error(`retained agent ${entry.name} is user-auth but the current manager is not`);
|
|
707
|
+
try {
|
|
708
|
+
const provider = resolveAuthProvider();
|
|
709
|
+
// Mirror the static branch's expected-path discipline, but pin the WHOLE secret FAMILY as ONE
|
|
710
|
+
// unit: all three of {actorToken, sentinelCreds, health} must equal the lifecycle-keyed triple
|
|
711
|
+
// (this generation) OR the name-keyed triple (a pre-split inventory carried across the upgrade).
|
|
712
|
+
// A per-file OR-pin let a corrupt inventory MIX families (lifecycle token + legacy sentinel)
|
|
713
|
+
// and, worse, left `health` UNPINNED entirely — an arbitrary recorded health path flowed into
|
|
714
|
+
// the bearer argv and was `rmSync`'d at terminal teardown (inventory-as-delete-gadget). Pinning
|
|
715
|
+
// the atomic family closes both: `health` is pinned by PATH EQUALITY (never by file existence,
|
|
716
|
+
// so a transiently-absent health file still validates), and the store reads below key off the
|
|
717
|
+
// RECORDED path, so a foreign path can neither pass the pin nor address a different row.
|
|
718
|
+
// Both triples are derived under THIS manager's space, and the key builder is given
|
|
719
|
+
// `this.space` rather than reading the segment out of the recorded path: an inventory row is
|
|
720
|
+
// caller data, and a recorded path may not choose which tenant's material is addressed.
|
|
721
|
+
const lifecycleFiles = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, entry.name, entry.identity.lifecycleUid);
|
|
722
|
+
const legacyFiles = agentSecretFilePaths(this.workspaceRoot, this.space, entry.name);
|
|
723
|
+
const recordedToken = resolve(entry.identity.actorToken.path);
|
|
724
|
+
const recordedSentinel = resolve(entry.identity.sentinelCredential.path);
|
|
725
|
+
const recordedHealth = resolve(entry.identity.health.path);
|
|
726
|
+
const matchesFamily = (f) => recordedToken === resolve(f.actorToken) && recordedSentinel === resolve(f.sentinelCreds) && recordedHealth === resolve(f.health);
|
|
727
|
+
if (!matchesFamily(lifecycleFiles) && !matchesFamily(legacyFiles))
|
|
728
|
+
throw new Error(`retained identity references for ${entry.name} are not one manager-owned secret family: all of actor-token, sentinel, and health must be the lifecycle-<uid> triple or the legacy name-keyed triple under ${agentCredsDir(this.workspaceRoot, this.space)} (no mixed families, no foreign health path)`);
|
|
729
|
+
const secrets = this.secrets;
|
|
730
|
+
const actorToken = await secrets.get(agentSecretKeyForFile(recordedToken, this.space));
|
|
731
|
+
const sentinelCreds = await secrets.get(agentSecretKeyForFile(recordedSentinel, this.space));
|
|
732
|
+
if (actorToken === undefined || sentinelCreds === undefined)
|
|
733
|
+
throw new Error("the retained actor token / sentinel credential is not in the secret store");
|
|
734
|
+
const adopted = this.remoteAuthority
|
|
735
|
+
? await this.remoteAuthority.validateRetainedAgent({
|
|
736
|
+
owner: entry.identity.owner,
|
|
737
|
+
actor: entry.identity.actor,
|
|
738
|
+
lifecycleUid: entry.identity.lifecycleUid,
|
|
739
|
+
actorToken,
|
|
740
|
+
sentinelCreds,
|
|
741
|
+
})
|
|
742
|
+
: await provider.validateRetainedAgent({
|
|
743
|
+
store: secrets,
|
|
744
|
+
dir: userAuthStateDir(this.workspaceRoot, this.space),
|
|
745
|
+
space: this.space,
|
|
746
|
+
owner: entry.identity.owner,
|
|
747
|
+
actor: entry.identity.actor,
|
|
748
|
+
actorToken,
|
|
749
|
+
sentinelCreds,
|
|
750
|
+
});
|
|
751
|
+
if (adopted.owner !== entry.identity.owner || adopted.actor !== entry.identity.actor)
|
|
752
|
+
throw new Error(`auth provider returned a replacement principal; expected ${entry.identity.owner}.${entry.identity.actor}`);
|
|
753
|
+
// Bind the inventory's uid to the CURRENT authority row BEFORE any spawn: a corrupt or
|
|
754
|
+
// admin-supplied inventory naming a different incarnation is refused at pre-effect validation,
|
|
755
|
+
// never left to broker-fail after the child is already running (SPEC §13.1).
|
|
756
|
+
if (adopted.lifecycleUid !== entry.identity.lifecycleUid)
|
|
757
|
+
throw new Error(`retained user authority for ${entry.identity.owner}.${entry.identity.actor} is incarnation ${adopted.lifecycleUid}, not the inventory's ${entry.identity.lifecycleUid}; a resume binds the exact recovered uid before any spawn (SPEC 13.1)`);
|
|
758
|
+
if (!sameStrings(adopted.allowSubscribe, entry.launch.allowSubscribe) ||
|
|
759
|
+
!sameStrings(adopted.allowPublish, entry.launch.allowPublish) ||
|
|
760
|
+
!sameStrings(adopted.scope, entry.launch.capabilities) ||
|
|
761
|
+
adopted.role !== entry.role || adopted.parent !== entry.authorityParent)
|
|
762
|
+
throw new Error(`retained user authority for ${entry.identity.owner}.${entry.identity.actor} no longer matches the inventory`);
|
|
763
|
+
return {
|
|
764
|
+
userAuth: {
|
|
765
|
+
owner: entry.identity.owner,
|
|
766
|
+
actor: entry.identity.actor,
|
|
767
|
+
sentinelCredsPath: entry.identity.sentinelCredential.path,
|
|
768
|
+
bearerCmd: [
|
|
769
|
+
...bearerEntryArgv(),
|
|
770
|
+
provider.agentBearerCommand,
|
|
771
|
+
...(this.remoteAuthority
|
|
772
|
+
? ["--exchange-url", this.remoteAuthority.agentBearerExchangeUrl]
|
|
773
|
+
: ["--dir", userAuthStateDir(this.workspaceRoot, this.space)]),
|
|
774
|
+
"--space", this.space,
|
|
775
|
+
"--owner", entry.identity.owner,
|
|
776
|
+
"--actor", entry.identity.actor,
|
|
777
|
+
"--token-file", entry.identity.actorToken.path,
|
|
778
|
+
"--health-file", entry.identity.health.path,
|
|
779
|
+
],
|
|
780
|
+
},
|
|
781
|
+
};
|
|
782
|
+
}
|
|
783
|
+
catch (e) {
|
|
784
|
+
throw new Error(`retained user principal ${entry.identity.owner}.${entry.identity.actor} could not be reused: ${rejectionText(e)}`);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
/** The seat reference behind a live retained principal, when that seat is provably one a lost
|
|
788
|
+
* manager of this logical instance launched for this exact incarnation. The resume binds the
|
|
789
|
+
* launched handle's reference to the incarnation's active slot before it waits for readiness, and
|
|
790
|
+
* the coordinator journals `resume-active` only after that wait, so a coordinator crash between the
|
|
791
|
+
* two leaves `resume-intent` behind a live seat. Undefined for everything else, which stays refused:
|
|
792
|
+
* another incarnation's presence, a slot another instance owns, a runtime that cannot reap the
|
|
793
|
+
* reference, and user or open meshes, which keep no slot. */
|
|
794
|
+
async orphanedResumeSeat(entry, principal, liveRoster) {
|
|
795
|
+
if (!this.auth || this.userMode || entry.identity.mode !== "static")
|
|
796
|
+
return undefined;
|
|
797
|
+
const runtime = this.runtimeFor(entry.launch.runtime);
|
|
798
|
+
if (typeof runtime.reap !== "function")
|
|
799
|
+
return undefined;
|
|
800
|
+
if (liveRoster.some((p) => p.card.id === principal && p.lifecycleUid !== entry.identity.lifecycleUid))
|
|
801
|
+
return undefined;
|
|
802
|
+
const slot = await this.readStaticReconcileSlot(entry.name);
|
|
803
|
+
if (slot?.phase !== "active" || slot.actor !== entry.identity.id || slot.lifecycleUid !== entry.identity.lifecycleUid)
|
|
804
|
+
return undefined;
|
|
805
|
+
if (ownedBySibling(slot, this.managerInstanceId))
|
|
806
|
+
return undefined;
|
|
807
|
+
return slot.runtime?.kind === runtime.kind ? slot.runtime : undefined;
|
|
808
|
+
}
|
|
809
|
+
/** Reap a seat {@link orphanedResumeSeat} found, then wait for its principal to leave presence so
|
|
810
|
+
* the relaunch's readiness cannot match the dead seat's row. Returns the refusal when the reap
|
|
811
|
+
* proves nothing or the principal stays live, which means another process holds it. */
|
|
812
|
+
async reapOrphanedResumeSeat(principal, reference) {
|
|
813
|
+
try {
|
|
814
|
+
const evidence = await requireRuntimeReap(this.runtimeFor(reference.kind), reference);
|
|
815
|
+
console.error(`resume: reaped orphaned seat ${reference.kind}:${reference.id} of retained principal "${principal}" (${evidence.detail})`);
|
|
816
|
+
}
|
|
817
|
+
catch (e) {
|
|
818
|
+
return `retained principal "${principal}" is already live and its recorded seat ${reference.kind}:${reference.id} could not be reaped: ${rejectionText(e)}`;
|
|
819
|
+
}
|
|
820
|
+
const deadline = Date.now() + ORPHAN_PRESENCE_CLEAR_MS;
|
|
821
|
+
while (this.ep.getRoster().some((p) => p.card.id === principal && p.status !== "offline")) {
|
|
822
|
+
if (Date.now() >= deadline)
|
|
823
|
+
return `retained principal "${principal}" is still live after its recorded seat ${reference.kind}:${reference.id} was reaped, so another process holds it and this runtime cannot authoritatively adopt it`;
|
|
824
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, 250));
|
|
825
|
+
}
|
|
826
|
+
return undefined;
|
|
827
|
+
}
|
|
828
|
+
/** Validate/relaunch one retained inventory entry. Called through resumePreserved so all records
|
|
829
|
+
* pass the same preflight before the first child is exposed, and through restartSupervisedSeat
|
|
830
|
+
* with the one record a crashed manager left (`supervised`). */
|
|
831
|
+
async resumePreservedAgent(entry, preflightOnly = false, batchReserved = false, prepared, supervised) {
|
|
832
|
+
if (this.execution === "none")
|
|
833
|
+
return { ok: false, error: this.executionRefusal() };
|
|
834
|
+
const release = this.beginLifecycle(batchReserved);
|
|
835
|
+
if (!release)
|
|
836
|
+
return { ok: false, error: this.maintenanceError() };
|
|
837
|
+
try {
|
|
838
|
+
if (entry.space !== this.space)
|
|
839
|
+
return { ok: false, error: `retained agent ${entry.name} belongs to space "${entry.space}", not "${this.space}"` };
|
|
840
|
+
try {
|
|
841
|
+
await this.loadSeatRuntime(entry.launch.runtime);
|
|
842
|
+
}
|
|
843
|
+
catch (e) {
|
|
844
|
+
return { ok: false, error: `retained agent ${entry.name} requires runtime "${entry.launch.runtime}", which this manager cannot resolve: ${rejectionText(e)}` };
|
|
845
|
+
}
|
|
846
|
+
if (entry.launch.runtime !== this.runtimeFor(entry.launch.runtime).kind)
|
|
847
|
+
return { ok: false, error: `retained agent ${entry.name} requires runtime "${entry.launch.runtime}", which this manager cannot resolve` };
|
|
848
|
+
const nameErr = this.nameError(entry.name);
|
|
849
|
+
if (nameErr)
|
|
850
|
+
return { ok: false, error: nameErr };
|
|
851
|
+
if (this.agents.has(entry.name) || (!batchReserved && this.namesCapacity.isReserved(entry.name)))
|
|
852
|
+
return { ok: false, error: `retained agent "${entry.name}" is already managed or reserved; same-principal resume never auto-numbers` };
|
|
853
|
+
const occupancy = batchReserved ? undefined : this.occupancy();
|
|
854
|
+
if (occupancy && occupancy.used >= MAX_AGENTS)
|
|
855
|
+
return { ok: false, error: `${this.capacityRefusal(occupancy)}; same-principal resume refused` };
|
|
856
|
+
const cached = prepared?.get(entry.name);
|
|
857
|
+
if (!preflightOnly && cached) {
|
|
858
|
+
try {
|
|
859
|
+
// Do not trust the earlier batch preflight across another agent's sequential readiness wait.
|
|
860
|
+
await this.validateRetainedAuthority(entry);
|
|
861
|
+
}
|
|
862
|
+
catch (e) {
|
|
863
|
+
return { ok: false, error: rejectionText(e) };
|
|
864
|
+
}
|
|
865
|
+
return this.launchPreparedResume(entry, cached, batchReserved, supervised);
|
|
866
|
+
}
|
|
867
|
+
try {
|
|
868
|
+
const cwd = lstatSync(entry.launch.cwd);
|
|
869
|
+
if (!cwd.isDirectory() || cwd.isSymbolicLink())
|
|
870
|
+
return { ok: false, error: `retained cwd is not a real directory: ${entry.launch.cwd}` };
|
|
871
|
+
}
|
|
872
|
+
catch (e) {
|
|
873
|
+
return { ok: false, error: `retained cwd unavailable: ${entry.launch.cwd} (${rejectionText(e)})` };
|
|
874
|
+
}
|
|
875
|
+
let connector;
|
|
876
|
+
try {
|
|
877
|
+
// The SAME resolver the spawn path uses. A bare `registry.resolve` here made preserve→resume
|
|
878
|
+
// fail for EVERY retained agent on the published binary: the resuming manager is a fresh
|
|
879
|
+
// process whose registry is empty (its supervise child runs with the connector seed
|
|
880
|
+
// skipped), so nothing is registered until something materializes it from the ext manifest.
|
|
881
|
+
// That is precisely what `resolveConnector` does and what every spawn path already calls.
|
|
882
|
+
// Resolving bare meant a preserved mesh could never come back — first-party connectors
|
|
883
|
+
// included, since the asymmetry is about materialization, not about which connector it is.
|
|
884
|
+
connector = await this.resolveConnector(entry.launch.connector);
|
|
885
|
+
}
|
|
886
|
+
catch (e) {
|
|
887
|
+
return { ok: false, error: rejectionText(e) };
|
|
888
|
+
}
|
|
889
|
+
await this.refreshUnavailableConnectors(connector.name, true);
|
|
890
|
+
const harness = this.launchHarness(connector);
|
|
891
|
+
if ("refusal" in harness)
|
|
892
|
+
return { ok: false, error: harness.refusal };
|
|
893
|
+
let retainedSession;
|
|
894
|
+
try {
|
|
895
|
+
retainedSession = this.retainedSessionId(entry, connector);
|
|
896
|
+
}
|
|
897
|
+
catch (error) {
|
|
898
|
+
return { ok: false, error: rejectionText(error) };
|
|
899
|
+
}
|
|
900
|
+
if (entry.launch.forkSource && !retainedSession && !connector.supportsResume)
|
|
901
|
+
return { ok: false, error: `${connector.name} connector does not support session fork (resume)` };
|
|
902
|
+
if (retainedSession && !connector.supportsSessionContinuation)
|
|
903
|
+
return { ok: false, error: `${connector.name} connector does not support exact-session continuation` };
|
|
904
|
+
let launchOptions;
|
|
905
|
+
let exact = false;
|
|
906
|
+
if (entry.launch.source.kind === "manifest") {
|
|
907
|
+
const launchSource = entry.launch.source;
|
|
908
|
+
if (!launchSource.runId)
|
|
909
|
+
return { ok: false, error: `retained manifest launch for ${entry.name} has no runId; refusing to guess a .cotal/run source` };
|
|
910
|
+
let spec;
|
|
911
|
+
try {
|
|
912
|
+
const source = launchSpecForRun(this.workspaceRoot, launchSource.runId);
|
|
913
|
+
if (source.space !== this.space)
|
|
914
|
+
return { ok: false, error: `retained launch spec space "${source.space}" does not match manager space "${this.space}"` };
|
|
915
|
+
spec = source.agents.find((a) => a.name === launchSource.requested);
|
|
916
|
+
}
|
|
917
|
+
catch (e) {
|
|
918
|
+
return { ok: false, error: rejectionText(e) };
|
|
919
|
+
}
|
|
920
|
+
if (!spec || spec.hash !== launchSource.hash)
|
|
921
|
+
return { ok: false, error: `retained manifest agent ${launchSource.requested} is missing or its hash changed; refusing same-principal resume` };
|
|
922
|
+
launchOptions = spec.launchOptions;
|
|
923
|
+
exact = spec.continuity === "exact";
|
|
924
|
+
}
|
|
925
|
+
else {
|
|
926
|
+
try {
|
|
927
|
+
launchOptions = loadAgentFile(entry.launch.source.configPath).launchOptions;
|
|
928
|
+
}
|
|
929
|
+
catch (e) {
|
|
930
|
+
return { ok: false, error: rejectionText(e) };
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
// Asked once `exact` is known: an exact seat reopens its retained session or fails, like its
|
|
934
|
+
// manifest launch, so the connector must honor reopenSession before the batch starts any child.
|
|
935
|
+
const unsupported = this.capabilityRefusal(connector, { variant: entry.launch.variant, prompt: entry.launch.prompt, exact });
|
|
936
|
+
if (unsupported)
|
|
937
|
+
return { ok: false, error: unsupported };
|
|
938
|
+
const eventsRefused = this.eventsRefusal(connector, entry.launch.events);
|
|
939
|
+
if (eventsRefused)
|
|
940
|
+
return { ok: false, error: eventsRefused };
|
|
941
|
+
let authority;
|
|
942
|
+
try {
|
|
943
|
+
authority = await this.validateRetainedAuthority(entry);
|
|
944
|
+
}
|
|
945
|
+
catch (e) {
|
|
946
|
+
return { ok: false, error: rejectionText(e) };
|
|
947
|
+
}
|
|
948
|
+
try {
|
|
949
|
+
const launchOpts = {
|
|
950
|
+
...this.hostLaunchFields(loadCotalConfig(this.workspaceRoot), entry.launch.connector, entry.launch.shareTools, harness),
|
|
951
|
+
name: entry.name,
|
|
952
|
+
role: entry.role,
|
|
953
|
+
id: authority.id,
|
|
954
|
+
creds: authority.creds,
|
|
955
|
+
userAuth: authority.userAuth,
|
|
956
|
+
// Recover the ORIGINAL incarnation uid (never a fresh mint on resume): the child endpoint
|
|
957
|
+
// binds its lifecycle-keyed dm/dlv/chathist durables by this exact value, and its creds pin
|
|
958
|
+
// the same names. Omitting it here (as the pre-fix resume path did) leaves the resumed child
|
|
959
|
+
// with no COTAL_LIFECYCLE_UID: static/user fail the connector auth gate and open self-mints a
|
|
960
|
+
// fresh uid that orphans the preserved durables and never matches the readiness fence.
|
|
961
|
+
lifecycleUid: entry.identity.lifecycleUid,
|
|
962
|
+
backfillFloor: entry.backfillFloor,
|
|
963
|
+
acceptedToken: entry.identity.mode === "static" ? entry.identity.issued?.acceptedToken : undefined,
|
|
964
|
+
configPath: entry.launch.source.configPath,
|
|
965
|
+
model: entry.launch.model,
|
|
966
|
+
variant: entry.launch.variant,
|
|
967
|
+
launchOptions,
|
|
968
|
+
resume: retainedSession ? undefined : entry.launch.forkSource,
|
|
969
|
+
continueSession: exact ? undefined : retainedSession,
|
|
970
|
+
reopenSession: exact ? retainedSession : undefined,
|
|
971
|
+
subscribe: entry.launch.subscribe,
|
|
972
|
+
allowSubscribe: entry.launch.allowSubscribe,
|
|
973
|
+
allowPublish: entry.launch.allowPublish,
|
|
974
|
+
capabilities: entry.launch.capabilities,
|
|
975
|
+
endpoints: copyPersonaEndpoints(entry.launch.endpoints) ?? [],
|
|
976
|
+
events: entry.launch.events,
|
|
977
|
+
eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
|
|
978
|
+
cwd: entry.launch.cwd,
|
|
979
|
+
};
|
|
980
|
+
const spec = connector.buildLaunch(launchOpts);
|
|
981
|
+
spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
|
|
982
|
+
const value = { spec, launchOpts, ...authority, exact };
|
|
983
|
+
prepared?.set(entry.name, value);
|
|
984
|
+
if (preflightOnly)
|
|
985
|
+
return { ok: true, data: { name: entry.name, preflight: true } };
|
|
986
|
+
return this.launchPreparedResume(entry, value, batchReserved, supervised);
|
|
987
|
+
}
|
|
988
|
+
catch (e) {
|
|
989
|
+
return { ok: false, error: rejectionText(e) };
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
finally {
|
|
993
|
+
release();
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
async launchPreparedResume(entry, prepared, batchReserved, supervised) {
|
|
997
|
+
if (!batchReserved)
|
|
998
|
+
this.namesCapacity.reserve(entry.name, resumeOwner(entry));
|
|
999
|
+
try {
|
|
1000
|
+
// Recover the STATIC identity's nkey seed from the adopted credential (the
|
|
1001
|
+
// creds file embeds it) so the manager stays this incarnation's RENEWAL OWNER across a
|
|
1002
|
+
// preserve/resume — without it the adopted cred would die loud at its TTL with no remint.
|
|
1003
|
+
let adoptedSeed;
|
|
1004
|
+
if (entry.identity.mode === "static") {
|
|
1005
|
+
const stored = await this.secrets.get(agentSecretKeyForFile(resolve(entry.identity.credential.path), this.space));
|
|
1006
|
+
// The core parser, which reads the creds format's six-dash END marker. A local pattern that
|
|
1007
|
+
// expected five matched no real file, so every resumed seat lost its renewal.
|
|
1008
|
+
try {
|
|
1009
|
+
adoptedSeed = stored === undefined ? undefined : identityFromCreds(stored).seed;
|
|
1010
|
+
}
|
|
1011
|
+
catch {
|
|
1012
|
+
adoptedSeed = undefined;
|
|
1013
|
+
}
|
|
1014
|
+
if (adoptedSeed === undefined)
|
|
1015
|
+
console.error(`! resume ${entry.name}: the adopted credential carries no readable nkey seed - the manager cannot renew it (it dies loud at its exp)`);
|
|
1016
|
+
}
|
|
1017
|
+
const connector = await this.resolveConnector(entry.launch.connector);
|
|
1018
|
+
const readinessTimeoutMs = connector.readinessTimeoutMs ?? this.readinessTimeoutMs;
|
|
1019
|
+
if (!Number.isSafeInteger(readinessTimeoutMs) || readinessTimeoutMs <= 0)
|
|
1020
|
+
return { ok: false, error: `connector ${connector.name} declares invalid readinessTimeoutMs ${JSON.stringify(connector.readinessTimeoutMs)}; expected a positive safe integer` };
|
|
1021
|
+
const resumeId = entry.identity.mode === "user" ? principalKey(entry.identity.owner, entry.identity.actor).key : entry.identity.id;
|
|
1022
|
+
const runtime = this.runtimeFor(entry.launch.runtime);
|
|
1023
|
+
const custody = this.reserveCustody(runtime);
|
|
1024
|
+
if (custody)
|
|
1025
|
+
await this.recordSlotCustody({ name: entry.name, id: resumeId, lifecycleUid: entry.identity.lifecycleUid }, custody);
|
|
1026
|
+
prepared.spawned = true;
|
|
1027
|
+
const handle = await this.spawnCustodied(runtime, entry.name, prepared.spec, entry.launch.cwd, custody);
|
|
1028
|
+
const managed = {
|
|
1029
|
+
name: entry.name,
|
|
1030
|
+
role: entry.role,
|
|
1031
|
+
agent: entry.launch.connector,
|
|
1032
|
+
id: resumeId,
|
|
1033
|
+
seed: adoptedSeed,
|
|
1034
|
+
...(entry.identity.mode === "static" && entry.identity.issued ? { issued: entry.identity.issued } : {}),
|
|
1035
|
+
// Recover the ORIGINAL incarnation uid the durables are keyed by (never a fresh mint on resume).
|
|
1036
|
+
lifecycleUid: entry.identity.lifecycleUid,
|
|
1037
|
+
// Adopt the INVENTORY's recorded family (possibly a pre-split name-keyed layout) — the
|
|
1038
|
+
// validated paths above, so this incarnation's later teardown addresses exactly what its
|
|
1039
|
+
// spawn materialized, never a re-derivation.
|
|
1040
|
+
secretPaths: entry.identity.mode === "user"
|
|
1041
|
+
? { actorToken: entry.identity.actorToken.path, sentinelCreds: entry.identity.sentinelCredential.path, health: entry.identity.health.path }
|
|
1042
|
+
: entry.identity.mode === "static"
|
|
1043
|
+
? { creds: entry.identity.credential.path }
|
|
1044
|
+
: undefined,
|
|
1045
|
+
userOwner: entry.identity.mode === "user" ? entry.identity.owner : undefined,
|
|
1046
|
+
spawner: entry.spawner,
|
|
1047
|
+
authorityParent: entry.authorityParent,
|
|
1048
|
+
startedAt: Date.now(),
|
|
1049
|
+
handle,
|
|
1050
|
+
control: prepared.spec.control,
|
|
1051
|
+
launch: {
|
|
1052
|
+
runtime: entry.launch.runtime,
|
|
1053
|
+
source: entry.launch.source,
|
|
1054
|
+
cwd: entry.launch.cwd,
|
|
1055
|
+
model: entry.launch.model,
|
|
1056
|
+
variant: entry.launch.variant,
|
|
1057
|
+
subscribe: entry.launch.subscribe,
|
|
1058
|
+
allowSubscribe: entry.launch.allowSubscribe,
|
|
1059
|
+
allowPublish: entry.launch.allowPublish,
|
|
1060
|
+
capabilities: entry.launch.capabilities,
|
|
1061
|
+
...(entry.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(entry.launch.endpoints) } : {}),
|
|
1062
|
+
events: entry.launch.events,
|
|
1063
|
+
eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
|
|
1064
|
+
shareTools: entry.launch.shareTools,
|
|
1065
|
+
forkSource: entry.launch.forkSource,
|
|
1066
|
+
...(entry.launch.resumed ? { resumed: entry.launch.resumed } : {}),
|
|
1067
|
+
...(prepared.launchOpts.resume !== undefined && prepared.spec.resumeRecordPath ? { resumeRecordPath: prepared.spec.resumeRecordPath } : {}),
|
|
1068
|
+
sessionId: entry.launch.sessionId,
|
|
1069
|
+
},
|
|
1070
|
+
...(supervised
|
|
1071
|
+
? { restart: { opts: prepared.launchOpts, sessionStatePath: prepared.spec.sessionStatePath, crashes: supervised.crashes, recovering: false, armed: false, policy: supervised.policy } }
|
|
1072
|
+
: prepared.spec.sessionStatePath
|
|
1073
|
+
? { restart: { opts: prepared.launchOpts, sessionStatePath: prepared.spec.sessionStatePath, crashes: [], recovering: false, armed: false } }
|
|
1074
|
+
: {}),
|
|
1075
|
+
suppressCleanup: true,
|
|
1076
|
+
};
|
|
1077
|
+
this.agents.set(entry.name, managed);
|
|
1078
|
+
this.namesCapacity.placed(entry.name);
|
|
1079
|
+
if (this.resumeAttemptId)
|
|
1080
|
+
this.resumedAgentNames.add(entry.name);
|
|
1081
|
+
try {
|
|
1082
|
+
await this.recordSlotRuntime(managed);
|
|
1083
|
+
}
|
|
1084
|
+
catch (error) {
|
|
1085
|
+
return await this.stopFailedResume(managed, "resume-custody-unrecorded", `${managed.name} resumed, but ${rejectionText(error)}`);
|
|
1086
|
+
}
|
|
1087
|
+
const readiness = await this.awaitReadiness(managed, readinessTimeoutMs, supervised ? { joinedAfter: supervised.joinedAfter } : {});
|
|
1088
|
+
if (!readiness.ok && !readiness.uncertain)
|
|
1089
|
+
return { ok: false, error: readiness.detail };
|
|
1090
|
+
if (!readiness.ok) {
|
|
1091
|
+
this.watchExit(managed);
|
|
1092
|
+
// The restart was counted when it launched, so the record carries that crash whether or not
|
|
1093
|
+
// the seat ever joins: a successor reads the record to decide whether another fits the budget.
|
|
1094
|
+
if (supervised)
|
|
1095
|
+
this.refreshSeatRecord(managed);
|
|
1096
|
+
this.watchResumeAdoption(managed, supervised?.joinedAfter, () => this.armLateResume(managed, connector, prepared, supervised));
|
|
1097
|
+
return { ok: false, error: readiness.detail };
|
|
1098
|
+
}
|
|
1099
|
+
const unbound = await this.armResumedSeat(managed, connector, prepared, supervised);
|
|
1100
|
+
if (unbound !== undefined)
|
|
1101
|
+
return await this.stopFailedResume(managed, "resume-session-rebind-failed", unbound);
|
|
1102
|
+
if (!this.resumeAttemptId)
|
|
1103
|
+
managed.suppressCleanup = false;
|
|
1104
|
+
if (supervised)
|
|
1105
|
+
this.refreshSeatRecord(managed);
|
|
1106
|
+
this.watchExit(managed);
|
|
1107
|
+
if (this.agents.get(managed.name) !== managed)
|
|
1108
|
+
return { ok: false, error: `${managed.name} exited immediately after same-principal readiness` };
|
|
1109
|
+
return {
|
|
1110
|
+
ok: true,
|
|
1111
|
+
data: { name: managed.name, role: managed.role, agent: managed.agent, id: managed.id, mode: handle.kind, resumed: true },
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
catch (e) {
|
|
1115
|
+
return { ok: false, error: rejectionText(e) };
|
|
1116
|
+
}
|
|
1117
|
+
finally {
|
|
1118
|
+
if (!batchReserved) {
|
|
1119
|
+
this.namesCapacity.release(entry.name);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
/** Arm a resumed seat's restart once it is ready, whether it joined inside the readiness window or
|
|
1124
|
+
* after it (#4144). A supervised restart arms the way its spawn did: a connector with no session
|
|
1125
|
+
* continuation is armed at readiness, one with it once its session is proved. Returns why the
|
|
1126
|
+
* session could not be rebound, and the caller stops the seat. */
|
|
1127
|
+
async armResumedSeat(managed, connector, prepared, supervised) {
|
|
1128
|
+
if (supervised && managed.restart && !connector.supportsSessionContinuation && !prepared.exact) {
|
|
1129
|
+
managed.restart.armed = true;
|
|
1130
|
+
return undefined;
|
|
1131
|
+
}
|
|
1132
|
+
if (!managed.restart && !prepared.exact)
|
|
1133
|
+
return undefined;
|
|
1134
|
+
try {
|
|
1135
|
+
await this.armSessionRecovery(managed);
|
|
1136
|
+
// As on a manifest launch, an exact seat is recorded only at the session it asked for,
|
|
1137
|
+
// proved over the connector's authenticated control endpoint.
|
|
1138
|
+
if (prepared.exact && !managed.restart?.armed)
|
|
1139
|
+
throw new Error("continuity: exact needs the connector to prove its session over an authenticated control endpoint, and it supplied none");
|
|
1140
|
+
managed.launch.sessionId = this.readManagedSession(managed);
|
|
1141
|
+
const asked = prepared.launchOpts.reopenSession;
|
|
1142
|
+
if (asked !== undefined && managed.launch.sessionId !== asked)
|
|
1143
|
+
throw new Error(`continuity: exact asked for session ${asked}, the connector bound ${managed.launch.sessionId}`);
|
|
1144
|
+
if (prepared.exact) {
|
|
1145
|
+
managed.continuity = { space: this.space, name: managed.name, connector: managed.agent, cwd: managed.launch.cwd };
|
|
1146
|
+
this.recordContinuity(managed, managed.launch.sessionId);
|
|
1147
|
+
}
|
|
1148
|
+
return undefined;
|
|
1149
|
+
}
|
|
1150
|
+
catch (error) {
|
|
1151
|
+
return `${managed.name} resumed, but its exact host session could not be rebound: ${rejectionText(error)}`;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
/** A resumed seat whose readiness was uncertain gets what a ready one gets once it joins: its
|
|
1155
|
+
* restart is armed and its record rewritten. Without this, a supervised seat restarted after a
|
|
1156
|
+
* manager crash that joined late was retired on its next exit instead of restarted. */
|
|
1157
|
+
async armLateResume(managed, connector, prepared, supervised) {
|
|
1158
|
+
const current = () => this.agents.get(managed.name) === managed && !managed.terminalizing;
|
|
1159
|
+
if (!current())
|
|
1160
|
+
return;
|
|
1161
|
+
const unbound = await this.armResumedSeat(managed, connector, prepared, supervised);
|
|
1162
|
+
if (!current())
|
|
1163
|
+
return;
|
|
1164
|
+
if (unbound !== undefined) {
|
|
1165
|
+
const stopped = await this.stopFailedResume(managed, "resume-session-rebind-failed", unbound);
|
|
1166
|
+
if (!stopped.ok)
|
|
1167
|
+
console.error(`! ${stopped.error}`);
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
if (supervised)
|
|
1171
|
+
this.refreshSeatRecord(managed);
|
|
1172
|
+
}
|
|
1173
|
+
/** A resumed seat keeps its retained credentials, so freeing it runs no deprovision and nothing
|
|
1174
|
+
* would reap it: it is freed only once its exit is proved, and otherwise stays managed until it
|
|
1175
|
+
* exits or the manager stops it. */
|
|
1176
|
+
async stopFailedResume(managed, cause, detail) {
|
|
1177
|
+
const refused = this.stopHandle(managed, false, cause);
|
|
1178
|
+
const unproven = refused === undefined
|
|
1179
|
+
? await this.awaitHandleExit(managed.handle).then(() => undefined, rejectionText)
|
|
1180
|
+
: `stop failed: ${refused}`;
|
|
1181
|
+
if (unproven !== undefined) {
|
|
1182
|
+
this.watchExit(managed);
|
|
1183
|
+
return { ok: false, error: `${detail}; it stays managed because its stop is unproven: ${unproven}` };
|
|
1184
|
+
}
|
|
1185
|
+
this.freeSlot(managed, true, cause, true);
|
|
1186
|
+
return { ok: false, error: detail };
|
|
1187
|
+
}
|
|
1188
|
+
/** An uncertain resume remains non-destructive until exact-principal AND exact-incarnation presence
|
|
1189
|
+
* arrives later, and then `adopted` runs. Same predicate as the readiness fence: a principal-only
|
|
1190
|
+
* match would let a wrong/absent-uid presence under the reused alias clear cleanup suppression on
|
|
1191
|
+
* another incarnation. A supervised restart keeps its principal and uid, so it also carries the
|
|
1192
|
+
* fence's `joinedAfter` bound: the row the dead seat left must not stand in for the new process.
|
|
1193
|
+
* A heartbeat on that row moves only its time and emits no presence event, so the bound is polled. */
|
|
1194
|
+
watchResumeAdoption(a, joinedAfter, adopted) {
|
|
1195
|
+
const wanted = this.managedPrincipal(a);
|
|
1196
|
+
let poll;
|
|
1197
|
+
const done = () => {
|
|
1198
|
+
this.ep.off("presence", onPresence);
|
|
1199
|
+
if (poll !== undefined)
|
|
1200
|
+
clearInterval(poll);
|
|
1201
|
+
};
|
|
1202
|
+
const onPresence = () => {
|
|
1203
|
+
if (this.agents.get(a.name) !== a) {
|
|
1204
|
+
done();
|
|
1205
|
+
return;
|
|
1206
|
+
}
|
|
1207
|
+
if (!this.ep.getRoster().some((p) => p.card.id === wanted && p.status !== "offline" && p.lifecycleUid === a.lifecycleUid && (joinedAfter === undefined || p.ts >= joinedAfter)))
|
|
1208
|
+
return;
|
|
1209
|
+
if (!this.resumeRequired)
|
|
1210
|
+
a.suppressCleanup = false;
|
|
1211
|
+
done();
|
|
1212
|
+
adopted().catch((error) => console.error(`! ${a.name}: joined after its readiness window, but ${rejectionText(error)}`));
|
|
1213
|
+
};
|
|
1214
|
+
this.ep.on("presence", onPresence);
|
|
1215
|
+
if (joinedAfter !== undefined) {
|
|
1216
|
+
poll = setInterval(onPresence, LATE_JOIN_POLL_MS);
|
|
1217
|
+
poll.unref?.();
|
|
1218
|
+
}
|
|
1219
|
+
onPresence();
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
//# sourceMappingURL=preserved-resume.js.map
|