@cotal-ai/manager 0.169.0 → 0.171.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.
@@ -0,0 +1,1208 @@
1
+ import { mkdirSync, readFileSync, rmSync } from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { agentFilePath, chatStream, checkEventStartup, controlReplyFromThrown, copyPersonaEndpoints, describeCleanupFailures, DEV_OWNER, EpEnvelopeError, eventChannelPrincipal, EventStateConflictError, grantOverreach, isPermissionDenied, lifecycleBlocked, loadCotalConfig, lowerPersonaEndpoints, managedRetirementOpId, mintAcceptedToken, mintGeneration, mintLifecycleUid, modelPolicyRefusal, newIdentity, parsePrincipalKey, principalKey, provisionAgent, rejectionText, renderLifecycleBlocked, resolveReadAcl, saveAgentFile, STANDING_RENEWABLE_TTL_SEC as MANAGED_STATIC_TTL_SEC, STATIC_GENERATION_HORIZON_SEC } from "@cotal-ai/core";
5
+ import { agentLifecycleSecretFilePaths, agentSecretKeyForFile, materializeSecretToFile, mergeLaunchOptions, retainConnectorSeat } from "@cotal-ai/workspace";
6
+ import { CHAT_ALIAS_PREFIX } from "./chat-session.js";
7
+ import { readContinuityAssignment, writeInlineSnapshot } from "./launch.js";
8
+ import { enrolledAcl } from "./remote-authority.js";
9
+ import { MAX_AGENTS, supervisePolicy } from "./resume.js";
10
+ import { watchConnectorHolder } from "./seat-custody.js";
11
+ import { foreignEventChannels, ownLists, ownPersona, userMeshEndpointsRefusal } from "./seat-launch.js";
12
+ import { activateStaticLifecycle, casStaticSlot, readStaticSlot } from "./static-lifecycle.js";
13
+ class LegacyEventCountPermissionError extends Error {
14
+ }
15
+ /** The agent-start path: admission, grant, launch, readiness and the rollback of a failed start. */
16
+ export class SeatStart {
17
+ deps;
18
+ launch;
19
+ constructor(deps, launch) {
20
+ this.deps = deps;
21
+ this.launch = launch;
22
+ }
23
+ // The Manager members startActive reads, under their Manager names. Each reads through its dep
24
+ // at use, so a field the Manager assigns later is current and a method a test replaces on the
25
+ // Manager is the one that runs.
26
+ get auth() { return this.deps.auth(); }
27
+ awaitReadiness(...args) { return this.deps.awaitReadiness(...args); }
28
+ awaitStartupOutcome(...args) { return this.deps.awaitStartupOutcome(...args); }
29
+ capabilityRefusal(...args) { return this.deps.capabilityRefusal(...args); }
30
+ get delegatedLaunched() { return this.deps.delegatedLaunched(); }
31
+ dropInlineSnapshot(...args) { return this.deps.dropInlineSnapshot(...args); }
32
+ endOnceBeforeServe(...args) { return this.deps.endOnceBeforeServe(...args); }
33
+ get ep() { return this.deps.ep(); }
34
+ get eventPayloadsWithheld() { return this.deps.eventPayloadsWithheld(); }
35
+ eventsRefusal(...args) { return this.deps.eventsRefusal(...args); }
36
+ get eventsRequired() { return this.deps.eventsRequired(); }
37
+ fileDigest(...args) { return this.deps.fileDigest(...args); }
38
+ hostLaunchFields(...args) { return this.deps.hostLaunchFields(...args); }
39
+ issuanceSeam(...args) { return this.deps.issuanceSeam(...args); }
40
+ launchHarness(...args) { return this.deps.launchHarness(...args); }
41
+ launchOwner(...args) { return this.deps.launchOwner(...args); }
42
+ get leaseStopping() { return this.deps.leaseStopping(); }
43
+ loadSeatRuntime(...args) { return this.deps.loadSeatRuntime(...args); }
44
+ get managerInstanceId() { return this.deps.managerInstanceId(); }
45
+ get managerLifecycleUid() { return this.deps.managerLifecycleUid(); }
46
+ get meshMode() { return this.deps.meshMode(); }
47
+ get namesCapacity() { return this.deps.namesCapacity(); }
48
+ openOnceDelivery(...args) { return this.deps.openOnceDelivery(...args); }
49
+ personaOwner(...args) { return this.deps.personaOwner(...args); }
50
+ place(...args) { return this.deps.place(...args); }
51
+ provisionUserAgent(...args) { return this.deps.provisionUserAgent(...args); }
52
+ readerRemedy(...args) { return this.deps.readerRemedy(...args); }
53
+ get readinessTimeoutMs() { return this.deps.readinessTimeoutMs(); }
54
+ refreshUnavailableConnectors(...args) { return this.deps.refreshUnavailableConnectors(...args); }
55
+ get remoteAuthority() { return this.deps.remoteAuthority(); }
56
+ resolveConnector(...args) { return this.deps.resolveConnector(...args); }
57
+ get retirement() { return this.deps.retirement(); }
58
+ get runHosting() { return this.deps.runHosting(); }
59
+ runtimeFor(...args) { return this.deps.runtimeFor(...args); }
60
+ seatCapRefusal(...args) { return this.deps.seatCapRefusal(...args); }
61
+ get seatCustody() { return this.deps.seatCustody(); }
62
+ get secrets() { return this.deps.secrets(); }
63
+ get sessionRecovery() { return this.deps.sessionRecovery(); }
64
+ shredUserSecrets(...args) { return this.deps.shredUserSecrets(...args); }
65
+ get space() { return this.deps.space(); }
66
+ get staticLifecycle() { return this.deps.staticLifecycle(); }
67
+ stopAndTrack(...args) { return this.deps.stopAndTrack(...args); }
68
+ trackDeprovision(...args) { return this.deps.trackDeprovision(...args); }
69
+ get transcripts() { return this.deps.transcripts(); }
70
+ get userMode() { return this.deps.userMode(); }
71
+ get userProvision() { return this.deps.userProvision(); }
72
+ watchExit(...args) { return this.deps.watchExit(...args); }
73
+ watchOnceExit(...args) { return this.deps.watchOnceExit(...args); }
74
+ withIssuer(fn) { return this.deps.withIssuer(fn); }
75
+ withLifecycleExecutor(pin, fn) { return this.deps.withLifecycleExecutor(pin, fn); }
76
+ withProvisioner(fn) { return this.deps.withProvisioner(fn); }
77
+ get workspaceRoot() { return this.deps.workspaceRoot(); }
78
+ // The SeatLaunch methods startActive calls, under their SeatLaunch names.
79
+ checkSpawnCwd(...args) { return this.launch.checkSpawnCwd(...args); }
80
+ harnessUnavailableError(...args) { return this.launch.harnessUnavailableError(...args); }
81
+ onceRefusal(...args) { return this.launch.onceRefusal(...args); }
82
+ spawnerName(...args) { return this.launch.spawnerName(...args); }
83
+ spawnPersona(...args) { return this.launch.spawnPersona(...args); }
84
+ spawnRun(...args) { return this.launch.spawnRun(...args); }
85
+ staticSpawnBound(...args) { return this.launch.staticSpawnBound(...args); }
86
+ spawnBoundRefusal(...args) { return this.launch.spawnBoundRefusal(...args); }
87
+ managedStaticInstanceReads(...args) { return this.launch.managedStaticInstanceReads(...args); }
88
+ async startActive(opts, spawner, hooks, authenticatedCaller) {
89
+ // Before the first await, so the grant, the launch, the retained form and the restart slot all read
90
+ // the lists and the restart policy as admitted.
91
+ opts = ownLists(opts);
92
+ if (opts.resolved)
93
+ opts.resolved = ownLists(opts.resolved);
94
+ if (opts.persona !== undefined)
95
+ opts.persona = ownPersona(opts.persona);
96
+ if (opts.supervise) {
97
+ opts.supervise = { restarts: opts.supervise.restarts, windowMs: opts.supervise.windowMs };
98
+ // The budget is checked here, where it is held, not only at the wire: an in-process caller of
99
+ // this export is refused before anything launches, rather than getting a seat that joins and is
100
+ // torn down when its seat record will not take the policy (#3298).
101
+ const policy = supervisePolicy.safeParse(opts.supervise);
102
+ if (!policy.success)
103
+ return { ok: false, error: `supervise.${policy.error.issues[0]?.path.join(".")}: expected a positive integer` };
104
+ }
105
+ if (opts.once)
106
+ opts.once = { deadlineMs: opts.once.deadlineMs };
107
+ let runtime;
108
+ try {
109
+ await this.loadSeatRuntime(opts.runtime);
110
+ runtime = this.runtimeFor(opts.runtime);
111
+ }
112
+ catch (e) {
113
+ return { ok: false, error: rejectionText(e) };
114
+ }
115
+ if (opts.delegatedIntent) {
116
+ if (!this.remoteAuthority?.executeDelegatedUserIntent)
117
+ return { ok: false, error: `"${opts.name}" names a delegated user intent, and this manager has no host execution for one` };
118
+ if (opts.supervise)
119
+ return { ok: false, error: `"${opts.name}" names a delegated user intent, and a delegated agent is never restarted (SPEC 13.16)` };
120
+ // A delegated launch's spawner is the user's principal, never the composition root's call.
121
+ spawner = opts.delegatedIntent.parent;
122
+ }
123
+ const persona = await this.spawnPersona(opts, spawner, authenticatedCaller);
124
+ if ("error" in persona)
125
+ return { ok: false, error: persona.error, ...(persona.code ? { code: persona.code } : {}) };
126
+ const { ref, def, agent, inline } = persona;
127
+ // An inline persona's file is its snapshot, written once the lifecycle uid is final; until then
128
+ // a refusal names the persona instead of a path.
129
+ let configPath = persona.configPath;
130
+ const where = configPath ?? `inline persona "${ref}"`;
131
+ // Materialize the requested connector before the capacity/reserve span so its lazy import
132
+ // cannot interleave that synchronous allocation. On the manifest binary this also honors a
133
+ // live `cotal ext remove`: a removed connector is rejected here even if an earlier spawn already
134
+ // imported it. A broken/missing connector fails loud here with a clear name + install hint.
135
+ let connector;
136
+ try {
137
+ connector = await this.resolveConnector(agent);
138
+ }
139
+ catch (e) {
140
+ const error = rejectionText(e);
141
+ // An action refusal here precedes capacity, allocation and onAccepted. Preserve that proof
142
+ // through serveSpawnGoal without changing the direct startAgent ControlReply contract.
143
+ if (hooks?.onAccepted)
144
+ throw new EpEnvelopeError("failed-precondition", error, undefined, "not-executed");
145
+ return { ok: false, error };
146
+ }
147
+ // Read here, beside the connector, so the capacity check and the reserve below take no new await.
148
+ const run = await this.spawnRun(authenticatedCaller, opts.runId);
149
+ if (run !== undefined && "refused" in run)
150
+ return { ok: false, error: `spawn: ${run.refused}` };
151
+ const bound = await this.staticSpawnBound(authenticatedCaller, run);
152
+ const readinessTimeoutMs = connector.readinessTimeoutMs ?? this.readinessTimeoutMs;
153
+ if (!Number.isSafeInteger(readinessTimeoutMs) || readinessTimeoutMs <= 0)
154
+ return { ok: false, error: `connector ${connector.name} declares invalid readinessTimeoutMs ${JSON.stringify(connector.readinessTimeoutMs)}; expected a positive safe integer` };
155
+ // Fail fast when full. If hosted Claude has to await wake setup, resample capacity after it.
156
+ // The final capacity check and the reserve below stay in the same tick or two concurrent
157
+ // spawns could overshoot the ceiling or pick the same name.
158
+ let occupancy = this.namesCapacity.occupancy(); // prunes expired cooling stamps; counts each name once
159
+ if (occupancy.used >= MAX_AGENTS)
160
+ return { ok: false, error: this.namesCapacity.capacityRefusal(occupancy) };
161
+ const recheck = this.refreshUnavailableConnectors(connector.name, true);
162
+ if (recheck) {
163
+ await recheck;
164
+ occupancy = this.namesCapacity.occupancy();
165
+ if (occupancy.used >= MAX_AGENTS)
166
+ return { ok: false, error: this.namesCapacity.capacityRefusal(occupancy) };
167
+ }
168
+ // Harness preflight before reserving a slot or minting — a missing `claude`/`opencode` binary
169
+ // fails here with a clear name, not obscurely at process spawn. No fallback. All synchronous, so
170
+ // the reserve gate stays atomic. (The connector itself was resolved up top, before the capacity gate.)
171
+ const harness = this.launchHarness(connector);
172
+ if ("refusal" in harness)
173
+ return { ok: false, error: this.harnessUnavailableError(harness.refusal, opts.route ?? "inst") };
174
+ // Resume is a connector capability: reject an unsupported resume HERE, before the reserve/mint, so
175
+ // it can never provision creds + durables and then throw at buildLaunch (mint-then-orphan). Same
176
+ // reject-before-side-effects window as the harness preflight above; buildLaunch stays the backstop.
177
+ if (opts.resume && !connector.supportsResume)
178
+ return { ok: false, error: `${agent} connector does not support resuming an existing session (resume)` };
179
+ // A carried resume (#1499) is checked here too, before anything is minted. The claim is only
180
+ // looked at: the connector may still refuse the launch, and a refused launch leaves it unspent.
181
+ let carried;
182
+ if (opts.resumeClaim !== undefined) {
183
+ if (opts.resume === undefined)
184
+ return { ok: false, error: "resumeClaim: names carried bytes of a resume; the launch carries no resume" };
185
+ if (!connector.resumeTranscript)
186
+ return { ok: false, error: `${agent} connector does not take a carried transcript (resumeClaim)` };
187
+ if (opts.resumeAgent !== agent)
188
+ return { ok: false, error: `resumeClaim: the session was carried for agent "${opts.resumeAgent ?? "<none>"}", and this launch resolves agent "${agent}"` };
189
+ if (!this.transcripts)
190
+ return { ok: false, error: "resumeClaim: this manager does not receive carried transcripts" };
191
+ try {
192
+ carried = this.transcripts.peek(opts.resumeClaim, opts.resume);
193
+ }
194
+ catch (e) {
195
+ return { ok: false, error: rejectionText(e) };
196
+ }
197
+ }
198
+ // A restart policy this host cannot honour is refused at accept, never accepted and ignored.
199
+ // External runtimes (tmux/cmux/orca/herdr) attach to a process they do not own and stream no
200
+ // exit, so a name cannot be respawned in place. User-mode seats have no static slot that
201
+ // keeps the incarnation owned across a process death, so the same refusal applies there.
202
+ if (opts.supervise !== undefined) {
203
+ if (runtime.kind !== "pty")
204
+ return { ok: false, error: `supervise is a restart policy this host cannot enforce: runtime "${runtime.kind}" cannot respawn a name in place` };
205
+ if (this.userMode)
206
+ return { ok: false, error: "supervise is a restart policy this host cannot enforce: a user-mode seat has no static slot to keep the incarnation owned across a process death" };
207
+ if (runtime.supportsWorkClosure !== true)
208
+ return { ok: false, error: `supervise is a restart policy this host cannot enforce: runtime "${runtime.kind}" cannot prove prior local work ended` };
209
+ }
210
+ // One read of the cotal config per spawn: the delegated refusal, the model policy and the launch
211
+ // fields below all take this value, so the awaits between the policy check and the launch cannot
212
+ // admit the seat under one file and launch it with another's servers and env allowlist. Read per
213
+ // spawn, so a policy edit reaches the next spawn without a restart. The launch fields are resolved
214
+ // here too, before the spawn is accepted, so a sharing selection that names an undeclared server
215
+ // is refused while there is nothing to roll back.
216
+ let cotalConfig;
217
+ let hostFields;
218
+ try {
219
+ cotalConfig = loadCotalConfig(this.workspaceRoot);
220
+ hostFields = this.hostLaunchFields(cotalConfig, agent, opts.shareTools, harness);
221
+ }
222
+ catch (e) {
223
+ const error = rejectionText(e);
224
+ // An input refusal here precedes allocation and onAccepted, like a connector refusal above:
225
+ // a hosted run proves it not-executed instead of binding a goal to a spawn that never starts.
226
+ if (hooks?.onAccepted)
227
+ throw new EpEnvelopeError("failed-precondition", error, undefined, "not-executed");
228
+ return { ok: false, error };
229
+ }
230
+ // A delegated seat starts outside this host from values alone, so a choice only this host can
231
+ // honour is refused here, before enrollment, and named rather than dropped.
232
+ if (runtime.spawnDelegated) {
233
+ const delegatedBy = `runtime "${runtime.kind}" starts seats outside this host`;
234
+ if (!this.remoteAuthority?.enrollManagedAgent)
235
+ return { ok: false, error: `${delegatedBy}, which needs a host that enrolls managed agents (remoteAuthority.enrollManagedAgent); a delegated seat has no local grant path` };
236
+ try {
237
+ this.userProvision.delegatedMeshRecord();
238
+ }
239
+ catch (e) {
240
+ return { ok: false, error: rejectionText(e) };
241
+ }
242
+ if (opts.resume)
243
+ return { ok: false, error: `${delegatedBy}, so it cannot resume a session held on this host (resume)` };
244
+ if (opts.resolved?.continuity === "exact")
245
+ return { ok: false, error: `${delegatedBy}, so it cannot reopen a session held on this host (continuity: exact)` };
246
+ if (typeof opts.cwd === "string" && opts.cwd !== "")
247
+ return { ok: false, error: `${delegatedBy}, so it cannot run in a directory on this host's filesystem (cwd); the seat runs in its runtime resource's own directory` };
248
+ const shared = Object.keys(hostFields.mcpServers);
249
+ if (shared.length)
250
+ return { ok: false, error: `${delegatedBy}, so it cannot share MCP servers that run on this host (${shared.join(", ")}); pass --share-tools none` };
251
+ }
252
+ // A placed spawn's cwd is checked on this host BEFORE anything is minted or reserved: an absolute
253
+ // path this manager cannot realpath, or one that is not a directory, is refused here with the
254
+ // asked path, the reason and this host, so a misplaced spawn in a multi-manager space is
255
+ // diagnosable at the moment it happens (#385 item 2) instead of failing inside the pty launch.
256
+ // The resolved realpath is threaded to the launch cwd below (`resolvedCwd`) so it is computed once.
257
+ let resolvedCwd;
258
+ if (typeof opts.cwd === "string" && opts.cwd !== "") {
259
+ const asked = opts.cwd;
260
+ const target = resolve(this.workspaceRoot, asked);
261
+ const checked = this.checkSpawnCwd(target);
262
+ if ("refusal" in checked)
263
+ return { ok: false, error: `spawn: cwd does not resolve on this host (${hostname()}): ${JSON.stringify(asked)} (${checked.refusal}); the seat was not launched` };
264
+ resolvedCwd = checked.cwd;
265
+ }
266
+ // Resolve the launch profile: IDENTITY (free-form `name:`) + role + read/post ACL + capabilities
267
+ // + model/variant. Either from a fully-resolved manifest launch object (`opts.resolved`, whose `config`
268
+ // is a materialized transient persona — the file is NOT the access authority), or from the
269
+ // persona file. The number rides the IDENTITY (socrates → socrates_2), not the file ref — a
270
+ // redelivered identical spawn yields a fresh numbered agent (MAX_AGENTS bounds the blast radius).
271
+ let identityName;
272
+ let role;
273
+ let subscribe;
274
+ let allowSubscribe;
275
+ let allowPublish;
276
+ let capabilities;
277
+ // The endpoint commands the persona hands on (SPEC 13.15), as the persona names them and as the
278
+ // mint grants them. A manifest launch carries none: its schema has no slot for them.
279
+ let personaEndpoints;
280
+ let endpoints = [];
281
+ let model = opts.model;
282
+ let variant = opts.variant;
283
+ let launchOptions = opts.launchOptions;
284
+ let prompt = opts.prompt;
285
+ // The read set the persona and the overrides name, before `join` adds to it: what a saved copy keeps.
286
+ let ownSubscribe;
287
+ if (opts.resolved) {
288
+ // A manifest launch is the access + identity authority: imperative overrides arriving
289
+ // alongside `resolved` are a caller contract error, not something to merge (no fallbacks).
290
+ if (opts.subscribe || opts.allowSubscribe || opts.allowPublish || opts.join || opts.callerAcl || opts.prompt || opts.shareTools || opts.identity)
291
+ return { ok: false, error: "a manifest launch (resolved) rejects imperative overrides (identity/subscribe/allow*/join/callerAcl/prompt/shareTools)" };
292
+ const r = opts.resolved;
293
+ identityName = r.name;
294
+ role = opts.role ?? r.role;
295
+ subscribe = r.subscribe;
296
+ allowSubscribe = r.allowSubscribe;
297
+ allowPublish = r.allowPublish;
298
+ capabilities = r.capabilities;
299
+ model = opts.model ?? r.model;
300
+ variant = opts.variant ?? r.variant;
301
+ launchOptions = mergeLaunchOptions(r.launchOptions, opts.launchOptions);
302
+ prompt = r.prompt; // the guard above rejected an imperative prompt — one source
303
+ }
304
+ else {
305
+ // `def` was loaded once above the connector resolution (#869 ordering); consume it here.
306
+ // `resolved` is the only path that skips the load, and this is its opposite branch.
307
+ if (!def)
308
+ return { ok: false, error: "internal: persona definition missing at launch profile" };
309
+ // Identity: the `--name` override wins over the file's `name:` — foreground parity (there,
310
+ // `requested = values.name ?? def.name`). The override is minted into the creds and rides
311
+ // COTAL_NAME below, so the presence identity and its credential can't diverge.
312
+ identityName = opts.identity ?? def.name;
313
+ role = opts.role ?? def.role;
314
+ // Flags > persona file — the same precedence as foreground `cotal spawn`, so the two launch
315
+ // paths of the merged grammar can't diverge. One source feeds BOTH the minted creds and the
316
+ // connector env below.
317
+ // A persona that names no channel field at all is scoped to its spawner's ACL (`callerAcl`,
318
+ // when the door sent one). The spawner's own event channel is dropped from it: that plane is
319
+ // foreign to the child, and the guard below refuses any spawn that asks for one. The joined
320
+ // set is never copied from the spawner: a helper starts on what its persona lists plus what
321
+ // the caller passes in `join`, and nothing else. The ACL is the caller's own report, so on a
322
+ // static mesh it is clamped to what the caller's evidence shows it holds, and a caller with
323
+ // no evidence gets no default at all.
324
+ const personaNamesChannels = def.subscribe !== undefined || def.allowSubscribe !== undefined || def.allowPublish !== undefined;
325
+ const heldChannels = (field, channels) => {
326
+ const own = channels.filter((ch) => eventChannelPrincipal(ch) === null);
327
+ return bound.kind === "bounded" ? own.filter((ch) => grantOverreach(this.space, bound.caller, bound.ceiling, { [field]: [ch] }).length === 0) : own;
328
+ };
329
+ let scoped;
330
+ try {
331
+ scoped = !personaNamesChannels && opts.callerAcl && bound.kind !== "none" ? {
332
+ allowSubscribe: heldChannels("allowSubscribe", opts.callerAcl.allowSubscribe),
333
+ allowPublish: heldChannels("allowPublish", opts.callerAcl.allowPublish),
334
+ } : undefined;
335
+ }
336
+ catch (e) {
337
+ return { ok: false, error: `callerAcl: ${rejectionText(e)}` };
338
+ }
339
+ const base = opts.subscribe ?? def.subscribe;
340
+ ownSubscribe = base;
341
+ subscribe = opts.join?.length ? [...new Set([...(base ?? []), ...opts.join])] : base;
342
+ allowSubscribe = opts.allowSubscribe ?? def.allowSubscribe ?? scoped?.allowSubscribe ?? [];
343
+ allowPublish = opts.allowPublish ?? def.allowPublish ?? scoped?.allowPublish;
344
+ capabilities = def.capabilities;
345
+ personaEndpoints = copyPersonaEndpoints(def.endpoints);
346
+ // A user-auth mesh grants endpoint access through the service owner's records, which a spawn
347
+ // cannot write (SPEC 13.15), so a persona that names the field is refused there, `[]` included,
348
+ // before any bound or exemption reads it.
349
+ if (personaEndpoints !== undefined && this.meshMode === "user")
350
+ return { ok: false, error: userMeshEndpointsRefusal("spawn") };
351
+ endpoints = lowerPersonaEndpoints(personaEndpoints);
352
+ // #651: fold the persona's model into the launch record, mirroring the variant line below
353
+ // and the manifest branch above. Without this, a persona-file model (the common pin source)
354
+ // never reaches `launch.model`, so the connector runs the seat on it while `ps --wide`/`--json`
355
+ // reports the model ABSENT - a false "no model pinned" for a seat that has one.
356
+ model = opts.model ?? def.model;
357
+ variant = opts.variant ?? def.variant;
358
+ launchOptions = mergeLaunchOptions(def.launchOptions, opts.launchOptions);
359
+ }
360
+ // Resolved once for both branches, because this one list is granted, minted, recorded on the
361
+ // launch and forwarded to the session, and each of those must read the list the provisioner does.
362
+ try {
363
+ allowSubscribe = resolveReadAcl(subscribe ?? [], allowSubscribe);
364
+ }
365
+ catch (e) {
366
+ return { ok: false, error: opts.resolved ? `launch agent: ${rejectionText(e)}` : `persona ${where}: ${rejectionText(e)}` };
367
+ }
368
+ // Default events on where the connector supports them, unless the launch explicitly opts out.
369
+ const events = this.eventsRequired || opts.events === true || (opts.events !== false && !!connector.eventChannel);
370
+ if (this.eventPayloadsWithheld && opts.eventPayloads === true)
371
+ return { ok: false, error: "space policy withholds event payloads" };
372
+ const eventPayloads = !this.eventPayloadsWithheld && (opts.eventPayloads ?? def?.eventPayloads) !== false;
373
+ if (run === undefined) {
374
+ const reads = this.managedStaticInstanceReads(capabilities);
375
+ if (bound.kind === "exempt" || (bound.kind === "bounded" && !grantOverreach(this.space, bound.caller, bound.ceiling, { endpoints: reads }).length))
376
+ endpoints.push(...reads);
377
+ }
378
+ // THE DELEGATION BOUND, on the grant as it will be minted: every channel and capability the
379
+ // helper gets, from the persona, the raw overrides and the `callerAcl` default alike, and its own
380
+ // event plane, so no door reaches the mint around it. Before any reserve or mint, so a refusal
381
+ // leaves nothing.
382
+ const boundRefusal = this.spawnBoundRefusal(bound, {
383
+ allowSubscribe,
384
+ ...(allowPublish !== undefined ? { allowPublish } : {}),
385
+ ...(role !== undefined ? { role } : {}),
386
+ ...(capabilities !== undefined ? { capabilities } : {}),
387
+ ...(endpoints.length ? { endpoints } : {}),
388
+ }, events);
389
+ if (boundRefusal)
390
+ return { ok: false, error: boundRefusal };
391
+ // A run saves for the caller it was admitted for, whose catalog reads then find the copy.
392
+ const savedBy = authenticatedCaller === undefined ? undefined : this.runHosting?.admittedCaller(authenticatedCaller);
393
+ // What a saved copy keeps: the grant just checked, without the helper's own event row, which each
394
+ // later spawn derives for its own helper. The file names every channel field, so no later caller's
395
+ // default fills one, and each later spawn of it is still bounded against that caller.
396
+ const catalogCopy = inline?.save
397
+ ? {
398
+ name: ref,
399
+ owner: savedBy !== undefined ? this.personaOwner(principalKey(savedBy.owner, savedBy.actor).key) : spawner === undefined ? undefined : this.personaOwner(spawner),
400
+ role,
401
+ model,
402
+ variant,
403
+ description: def?.description,
404
+ persona: def?.persona,
405
+ subscribe: [...(ownSubscribe ?? [])],
406
+ allowSubscribe: [...allowSubscribe],
407
+ allowPublish: [...(allowPublish ?? [])],
408
+ capabilities: capabilities?.length ? [...capabilities] : undefined,
409
+ endpoints: copyPersonaEndpoints(personaEndpoints?.length ? personaEndpoints : undefined),
410
+ }
411
+ : undefined;
412
+ // Checked after every path has resolved its selectors: a direct `startAgent` call skips the
413
+ // `start` op's checks, and no connector may receive a blank one (#2862).
414
+ if (model !== undefined && !model.trim())
415
+ return { ok: false, error: "model: must not be empty" };
416
+ if (variant !== undefined && !variant.trim())
417
+ return { ok: false, error: "variant: must not be empty" };
418
+ const idErr = this.namesCapacity.nameError(identityName);
419
+ if (idErr)
420
+ return { ok: false, error: opts.resolved ? `launch agent: ${idErr}` : `persona ${where}: ${idErr}` };
421
+ // #966: a seat labelled `manager` that cannot spawn is a worker wearing a label, and the label
422
+ // is what other agents ROUTE on (role is the anycast address). The gap is silent today because
423
+ // the mismatch is only discovered minutes in, when the seat first reaches for a worker. Refuse
424
+ // at accept, before any reserve/mint, naming the remediation for each author: an operator edits
425
+ // the file to add the grant, and the persona's owner may redefine it with the grant only if the
426
+ // owner holds spawn, because define-persona bounds capabilities against the definer. The
427
+ // check keys on the EFFECTIVE role (a spawn-time role: override wins
428
+ // over the file, mirroring the resolution above), not the file's, so the label other agents
429
+ // will actually see is the label that is held to account. `manager` is the label that MEANS
430
+ // spawn-holding: naming it literally keeps this the narrow guard for the observed harm, not a
431
+ // vocabulary any caller can trigger with a synonym (roles are free-form and mostly
432
+ // non-manager: this workspace's own catalog carries worker/reviewer/orchestrator seats with no
433
+ // spawn grant, all legitimate).
434
+ if (role === "manager" && !capabilities?.includes("spawn") && inline)
435
+ return {
436
+ ok: false,
437
+ error: `inline persona "${ref}" would join with role "manager" but no spawn capability: it presents as a manager ` +
438
+ `while being unable to seat workers. Add \`capabilities: [spawn]\` to the inline persona (a spawner hands on only what it holds), or give it another role.`,
439
+ };
440
+ if (role === "manager" && !capabilities?.includes("spawn"))
441
+ return {
442
+ ok: false,
443
+ error: `persona "${ref}" would join with role "manager" but no spawn capability: it presents as a manager ` +
444
+ `while being unable to seat workers, and it would discover that only on first use. ` +
445
+ `An operator adds \`capabilities: [spawn]\` to ${configPath}, or the persona's owner redefines it ` +
446
+ `with \`capabilities: [spawn]\` (cotal_persona) if the owner holds spawn.`,
447
+ };
448
+ // #581: the operator's per-role model allowlist, judged on the EFFECTIVE role and model resolved
449
+ // above, before any reserve or mint. This is where the launch is performed, so no caller can
450
+ // skip it, and a definition pinned to a stale model (or to none) is refused here instead of
451
+ // serving on it.
452
+ const policyRefusal = modelPolicyRefusal(cotalConfig, {
453
+ persona: opts.resolved ? `manifest agent "${ref}"` : configPath ? `persona "${ref}" (${configPath})` : where,
454
+ role, model, variant,
455
+ // A manifest launch carries its own declared model/variant in these options
456
+ // (launchAgentToStartOpts), so there they are the definition's field, never a flag.
457
+ modelFlag: !opts.resolved && opts.model !== undefined,
458
+ variantFlag: !opts.resolved && opts.variant !== undefined,
459
+ launchOptions,
460
+ });
461
+ if (policyRefusal)
462
+ return { ok: false, error: policyRefusal };
463
+ // The alias-reuse gate: a name whose previous agent is still retiring REFUSES
464
+ // legibly (never a silent suffix), and the refusal re-drives the FULL durable teardown so
465
+ // "retry the spawn" is also the nudge. It routes through `deprovision` (not `requestRetirement`
466
+ // alone) so a retry re-drives the standing-authority revoke (INT-2) AND the broker cleanup before
467
+ // any hold-clear (C): the alias must not free while the durable teardown or the revoke is still
468
+ // outstanding. All the teardown ops are idempotent, and the rail request is single-flighted.
469
+ if (this.staticLifecycle.isReconciling(identityName))
470
+ return { ok: false, error: `the name "${identityName}" is still reconciling at manager startup; its prior lifecycle terminal owns this alias until it completes. Retry shortly.` };
471
+ const held = this.retirement.held(identityName);
472
+ if (held !== undefined) {
473
+ hooks?.onEffect?.();
474
+ void this.retirement.deprovision(held.target).catch(() => { });
475
+ const err = lifecycleBlocked("failed-precondition", `the name "${identityName}" is reserved pending retirement: its previous agent's despawn started that lifecycle's teardown (footprint + standing-authority revoke + auth-side retirement), and the name frees only when all of it completes${held.lastError !== undefined ? ` (last attempt: ${held.lastError})` : ""}. NEXT: wait a moment and retry this spawn (retrying re-drives the whole teardown), or pick another name.`, { blockedOp: "retirement", opId: held.opId, remedy: "retry" });
476
+ return { ok: false, error: renderLifecycleBlocked(err.message, err), details: err.details };
477
+ }
478
+ // A manifest `continuity: exact` agent reopens the session this manager last bound to its
479
+ // declared name. Refused before any reserve or mint when the connector cannot reopen an exact
480
+ // session or the recorded assignment does not match this declaration.
481
+ const exact = opts.resolved?.continuity === "exact";
482
+ const unsupported = this.capabilityRefusal(connector, { variant, prompt, exact });
483
+ if (unsupported)
484
+ return { ok: false, error: unsupported };
485
+ const onceRefused = opts.once && this.onceRefusal(connector, runtime, { ...opts, launchOptions, prompt }, spawner, hooks);
486
+ if (onceRefused)
487
+ return { ok: false, error: onceRefused };
488
+ let reopenSession;
489
+ if (exact) {
490
+ try {
491
+ reopenSession = readContinuityAssignment(this.workspaceRoot, { space: this.space, name: identityName, connector: agent, cwd: resolvedCwd ?? this.workspaceRoot });
492
+ }
493
+ catch (e) {
494
+ return { ok: false, error: rejectionText(e) };
495
+ }
496
+ }
497
+ // The child takes launch options as `--opt k=v`, so only string values can cross to it.
498
+ const unportable = runtime.spawnDelegated ? Object.keys(launchOptions ?? {}).filter((k) => typeof launchOptions[k] !== "string") : [];
499
+ if (unportable.length)
500
+ return { ok: false, error: `runtime "${runtime.kind}" starts seats outside this host, so it cannot pass non-string launch options (${unportable.join(", ")})` };
501
+ // An event plane the connector cannot emit is refused HERE, before anything is minted: a
502
+ // connector that cannot emit must fail before provisioning rather than after, as an
503
+ // unsupported `resume` does.
504
+ // The GRANT itself cannot be derived yet. It is keyed on the agent's PRINCIPAL, and in user mode
505
+ // the principal's owner is resolved further down, so deriving it from anything in scope here
506
+ // would mean guessing at the identity the child will actually connect as. It is added at the
507
+ // accept seam below, where the allocated triple exists.
508
+ const eventsRefused = this.eventsRefusal(connector, opts.events);
509
+ if (eventsRefused)
510
+ return { ok: false, error: eventsRefused };
511
+ // The roster the allocation consults must reflect the initial presence snapshot,
512
+ // or a spawn immediately after manager boot races an already-live unmanaged peer and re-opens the
513
+ // very collision black-hole this closes. Await the snapshot (bounded internally, fail-safe on an
514
+ // empty mesh) before allocating; the broker/auth remain the authority downstream. Deliberately
515
+ // unconditional: a half-wired endpoint without the seam must fail loud here, not silently
516
+ // allocate off a pre-snapshot roster.
517
+ await this.ep.waitForPresenceSnapshot();
518
+ // Spawn-as-action: a HARD-PINNED name — an imperative `--name`/identity override
519
+ // or a manifest-declared name (opts.resolved) — that collides with a LIVE/provisioning/reserved
520
+ // incarnation REFUSES loud at accept, BEFORE any reserve/mint/bind, never a silent `_2`
521
+ // suffix (so an address-by-triple caller's pinned name can't be re-pointed). A PERSONA-DERIVED
522
+ // base name (no pin) keeps uniqueName's collision numbering, so multi-peer `spawn reviewer` twice
523
+ // still yields reviewer + reviewer_2. The alias-reuse gate above is orthogonal and already fired.
524
+ const hardPinned = opts.identity !== undefined || opts.resolved !== undefined;
525
+ const owner = this.launchOwner(opts, spawner);
526
+ const unavailable = new Set();
527
+ let name;
528
+ for (;;) {
529
+ if (hardPinned) {
530
+ if (this.namesCapacity.nameInUse(identityName))
531
+ return { ok: false, code: "already-exists", error: `the name "${identityName}" is hard-pinned (${opts.resolved ? "manifest-declared" : "--name/identity override"}) but is already held by a live incarnation (managed here, an unmanaged foreground/connector session, or another manager's agent); a pinned same-name collision refuses at accept - pick another name or despawn the existing one` };
532
+ name = identityName;
533
+ }
534
+ else {
535
+ try {
536
+ name = this.namesCapacity.uniqueName(identityName, unavailable);
537
+ }
538
+ catch (e) {
539
+ return { ok: false, error: rejectionText(e) };
540
+ }
541
+ }
542
+ // In user mode the name is the principal's actor. A fresh nkey in static/open mode
543
+ // cannot collide with an earlier transcript. Use the connector's own startup proof.
544
+ const eventOwner = opts.owner ?? (spawner === undefined ? undefined : parsePrincipalKey(spawner)?.owner);
545
+ if (events && this.userMode && !runtime.spawnDelegated && eventOwner?.startsWith("u_")) {
546
+ try {
547
+ await checkEventStartup({
548
+ workspaceRoot: this.workspaceRoot,
549
+ space: this.space,
550
+ principal: { owner: eventOwner, actor: name },
551
+ retainedMessages: async () => {
552
+ try {
553
+ return (await this.ep.chatRetention()).senders;
554
+ }
555
+ catch (e) {
556
+ // Older hosts do not issue this metadata grant. Do not infer that the name is
557
+ // free or renumber it: preserve the requested candidate and let the launched
558
+ // agent's existing startup check decide. Every other read failure stays loud.
559
+ if (!isPermissionDenied(e))
560
+ throw e;
561
+ console.error(`! event startup name check: missing $JS.API.STREAM.INFO.${chatStream(this.space)} permission; launching "${name}" unchanged so the agent checks its transcript state`);
562
+ throw new LegacyEventCountPermissionError();
563
+ }
564
+ },
565
+ });
566
+ }
567
+ catch (e) {
568
+ if (e instanceof EventStateConflictError && !hardPinned) {
569
+ unavailable.add(name);
570
+ continue;
571
+ }
572
+ if (!(e instanceof LegacyEventCountPermissionError))
573
+ return { ok: false, code: "failed-precondition", error: `cannot check event startup for ${eventOwner}.${name}: ${rejectionText(e)}` };
574
+ }
575
+ // Another spawn may have reserved the candidate while the disk/broker proof awaited.
576
+ // Recheck in the same synchronous window as the cap and reservation below.
577
+ if (this.namesCapacity.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
578
+ if (!hardPinned)
579
+ continue;
580
+ return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
581
+ }
582
+ }
583
+ break;
584
+ }
585
+ // The `chat_` prefix belongs to static chat sessions, whose aliases only `chat-session-open`
586
+ // draws. Checked once the name is fixed by either branch above, so a persona name, a numbered
587
+ // collision, a manifest name and a `--name` override all meet it, and before the reservation.
588
+ if (name.startsWith(CHAT_ALIAS_PREFIX))
589
+ return { ok: false, error: `the name "${name}" starts with "${CHAT_ALIAS_PREFIX}", which is reserved for chat sessions; pick another name` };
590
+ // THE PER-OWNER CEILING, read in the same synchronous window as the reserve below rather than
591
+ // beside the host capacity gate higher up: the count it takes must be the one the reservation
592
+ // lands against, or a burst of concurrent launches for one owner each reads a count taken
593
+ // before any of the others reserved, and they all pass. Nothing between here and the reserve
594
+ // awaits. It refuses BEFORE `onEffect`, so the launch states `not-executed` and leaves no
595
+ // name, no mint and no footprint behind.
596
+ const overCap = this.seatCapRefusal(owner);
597
+ if (overCap)
598
+ return { ok: false, code: overCap.code, error: overCap.message, ...(overCap.details ? { details: overCap.details } : {}) };
599
+ // Set once the agent's footprint (durables + creds, or the user-mode grant + secret files)
600
+ // exists; cleared when a live slot takes ownership. If it survives to `finally`, the spawn threw
601
+ // AFTER provisioning (buildLaunch / runtime.spawn) — the orphan-rollback tears it down. Carries
602
+ // `userOwner` for a user-mode spawn so that rollback runs the revoke+shred branch, not just the
603
+ // static durable teardown, which would leak the managed grant + files.
604
+ // The RESERVED custody reference rides the rollback object: a spawn that launched the seat and
605
+ // then threw (the activation CAS refuses a slot that is not this spawn's intent) reaches the
606
+ // `finally` with the handle only in a local, so without this the terminal has nothing to reap
607
+ // and retires over a live process. The slot row holds the same reference; this is the copy the
608
+ // in-process rollback can actually read.
609
+ let provisioned;
610
+ // A carried resume's seat-private home, removed by the finally unless a live seat took it.
611
+ let seatHome;
612
+ // The lifecycle whose inline snapshot this spawn wrote: removed by the finally unless a live seat
613
+ // took it. A write that failed sets nothing, so the finally never removes a file it did not make.
614
+ let snapshotUid;
615
+ // Taken right before the try so its finally is the only release; a refusal belongs above the
616
+ // allocation, where there is no name to give back.
617
+ hooks?.onEffect?.();
618
+ if (!hardPinned && name !== identityName)
619
+ this.namesCapacity.rememberNumbered(name);
620
+ this.namesCapacity.reserve(name, owner);
621
+ try {
622
+ // A stable nkey identity assigned at spawn: the public key is the agent's card.id (threaded via
623
+ // COTAL_ID); the seed is retained to mint matching creds later.
624
+ const identity = newIdentity();
625
+ // The incarnation's lifecycle UID (SPEC 13.1), minted ONCE per spawn: every lifecycle-keyed
626
+ // broker resource (dm_/dlv_/chathist_ durables, ACL row, memberships) and the teardown
627
+ // credential carry it, so a same-name successor's footprint is name-disjoint by construction.
628
+ //
629
+ // On the HOSTED enrollment arm (#1972) this value is PROVISIONAL. The host selects the
630
+ // authoritative uid, because it alone reads the retirement tombstones that make a uid
631
+ // permanently unusable, and the enrollment below rebinds this binding to what the host
632
+ // returned before anything durable is keyed by it.
633
+ let lifecycleUid = mintLifecycleUid();
634
+ // Reserve the seat's custody reference NOW, before any durable row and long before the
635
+ // launch. Minting it inside `runtime.spawn` (as it used to be) put the processes on disk
636
+ // before anything recorded how to address them, so a crash in that window left a live seat
637
+ // outside every manager and the successor retired the slot over it.
638
+ const custody = this.seatCustody.reserveCustody(runtime);
639
+ // ACCEPT SEAM (spawn-as-action): the incarnation identity is minted and NOTHING has
640
+ // been provisioned yet — the action serve path binds the goal + replies the acceptance HERE. A
641
+ // throw (bind conflict / duplicate goalId) aborts the spawn before provisioning: the catch below
642
+ // returns the failure and the finally releases the reserve, so a refused accept leaves zero
643
+ // footprint. The hosted enrollment arm is the exception, below. Blocking callers
644
+ // (roster boot) pass no hooks and this is a no-op.
645
+ // The ALLOCATED agent's addressing triple (the acceptance floor names what was actually
646
+ // allocated, never the requested-but-unallocated name). Static/open key on DEV_OWNER + the
647
+ // freshly-minted nkey; user mode keys on the derived owner (opts.owner, else a u_-owner spawner)
648
+ // + the alias — derived HERE where the mode and owner source are in scope.
649
+ const agentTriple = this.userMode
650
+ ? { owner, actor: name, uid: lifecycleUid }
651
+ : { owner, actor: identity.id, uid: lifecycleUid };
652
+ // THE EVENT GRANT, derived from the principal that was actually ALLOCATED and never from the
653
+ // display name. A display name is UI convenience: this mesh permits two live agents to carry
654
+ // one, so a name-keyed channel fuses two principals onto one subject and, in auth mode,
655
+ // authorizes both onto it from the same name-only value. `agentTriple` is the triple the child
656
+ // will connect as in both modes, so the grant and the subject the session derives from its own
657
+ // endpoint are the same derivation. Placed here rather than beside the refusal above
658
+ // because this is the first point at which that triple exists, and still before every
659
+ // provisioning call that consumes `allowPublish`.
660
+ // THE OWN-CHANNEL RULE FOR THE EVENT PLANE, and it is the first thing this seam does.
661
+ //
662
+ // An event channel carries a session's tool inputs and outputs, which makes it the most
663
+ // valuable read on the mesh, and `subscribe` / `allowSubscribe` / `allowPublish` are
664
+ // caller-supplied on every spawn door. On a per-user-auth mesh the ledger's spawner envelope
665
+ // already refuses a delegation wider than the spawner's own grant. On a STATIC mesh there is
666
+ // no ledger, so nothing attenuates a caller-supplied ACL at all, and a caller that may spawn
667
+ // may mint its child a read on any subject.
668
+ //
669
+ // What this rule asks is NOT who the caller is. That question has no answer on a static mesh:
670
+ // an untargeted spawn carries no authorization mode, and the admin reach a static caller
671
+ // holds is true by construction for everyone who can reach the handler. It asks whether the
672
+ // event channel being minted BELONGS TO THE AGENT BEING CREATED, which the manager knows
673
+ // because it has just allocated the principal.
674
+ //
675
+ // STATED LIMIT, because a fence whose gap is discovered later is worse than one whose gap is
676
+ // written down. `eventChannelPrincipal` decodes a principal and refuses anything that is not exactly
677
+ // two principal tokens, so a WILDCARD is not an event channel to it: `events.<owner>.>` and
678
+ // `events.>` pass this rule untouched and are governed by ordinary ACL authority, which on a
679
+ // user mesh is the envelope and on a static mesh is the spawn credential itself. So this
680
+ // closes the concrete form and not the wildcard form. It is worth having anyway: it is the
681
+ // form a caller writes when it knows which agent it wants to read, and the wildcard form is
682
+ // the one an operator writes deliberately for an observer.
683
+ const foreign = foreignEventChannels([...allowSubscribe, ...(allowPublish ?? [])], agentTriple.owner, agentTriple.actor);
684
+ if (foreign.length) {
685
+ // Throws rather than returning, because this seam is inside the accept body: the throw
686
+ // unwinds before `onAccepted`, so no goal is bound and no identity is minted, and the
687
+ // enclosing `finally` releases the reserved name. Returning here would be a value nobody
688
+ // reads.
689
+ throw new Error(`this spawn asks for another agent's event channel: ${foreign.join(", ")}. An ` +
690
+ `agent may be granted its OWN event plane and no other, because that plane carries the ` +
691
+ `session's tool inputs and outputs. Grant a reader out of band rather than through a ` +
692
+ `spawn: ${this.readerRemedy(agentTriple.owner, foreign[0])}`);
693
+ }
694
+ if (events)
695
+ allowPublish = [...(allowPublish ?? []), connector.eventChannel({ owner: agentTriple.owner, actor: agentTriple.actor })];
696
+ await hooks?.onReadinessWindow?.(readinessTimeoutMs);
697
+ // The hosted enrollment arm accepts only once the host has answered: the floor names the uid
698
+ // the agent runs at, and before the host picks it there is no such uid to name.
699
+ const hostedEnrollment = this.userMode && (opts.delegatedIntent !== undefined || this.remoteAuthority?.enrollManagedAgent !== undefined);
700
+ // A once spawn's task is accepted with the spawn, before anything launches.
701
+ let onceTask;
702
+ const acceptOnce = async (seat) => {
703
+ if (opts.once === undefined)
704
+ return;
705
+ onceTask = await hooks.onOnce({
706
+ seat: { name, ...seat }, prompt: prompt, spawner: this.spawnerName(spawner), deadlineMs: opts.once.deadlineMs, readinessDeadlineMs: readinessTimeoutMs,
707
+ ...(connector.retireAfterExit ? { retire: connector.name } : {}),
708
+ });
709
+ };
710
+ if (!hostedEnrollment) {
711
+ await hooks?.onAccepted?.({ name, identity, lifecycleUid, agentTriple });
712
+ await acceptOnce(agentTriple);
713
+ }
714
+ // In auth mode, mint the agent's creds from the space signing key and write them where the
715
+ // spawned session reads them (COTAL_CREDS path). Open mesh → no creds. Scope = the resolved
716
+ // subscribe/allowSubscribe (read) + allowPublish (post, default-deny).
717
+ let credsPath;
718
+ let issued;
719
+ let userLaunch;
720
+ let userOwner;
721
+ let enrolled;
722
+ if (this.userMode) {
723
+ const prep = await this.provisionUserAgent(name, {
724
+ eventPayloads,
725
+ spawner,
726
+ specOwner: opts.owner,
727
+ subscribe,
728
+ allowSubscribe,
729
+ allowPublish,
730
+ role,
731
+ capabilities,
732
+ label: ref,
733
+ lifecycleUid,
734
+ enrollmentCaller: authenticatedCaller ? { owner: authenticatedCaller.owner, actor: authenticatedCaller.actor } : undefined,
735
+ delegatedIntent: opts.delegatedIntent,
736
+ ...(opts.served !== undefined ? { spawnRequest: this.userProvision.servedSpawnRequest(opts.served, authenticatedCaller) } : {}),
737
+ // Hold the name at the UID the host enrolled for the intent's user before any later local
738
+ // step runs, so no later failure, its refusal included, releases a lifecycle that only that
739
+ // user's retirement intent retires.
740
+ onEnrolled: opts.delegatedIntent
741
+ ? (enrolled) => {
742
+ provisioned = { id: principalKey(enrolled.owner, name).key, name, lifecycleUid: enrolled.lifecycleUid, userOwner: enrolled.owner, delegated: true, secretPaths: enrolled.files };
743
+ }
744
+ : undefined,
745
+ });
746
+ if ("error" in prep) {
747
+ if (prep.refused !== undefined)
748
+ hooks?.onUndone?.(prep.refused);
749
+ return { ok: false, error: prep.error, ...(prep.refused !== undefined ? { code: prep.refused } : {}), ...(prep.details ? { details: prep.details } : {}) };
750
+ }
751
+ // THE HOST'S UID WINS (#1972). On the local arm this is the value passed in, unchanged. On
752
+ // the hosted enrollment arm the host selected it, and from here every lifecycle-keyed thing
753
+ // this spawn records — the slot, the launch, the managed row, the teardown credential — must
754
+ // carry that value and not the provisional one, or the manager would address a footprint the
755
+ // host never created.
756
+ lifecycleUid = prep.lifecycleUid;
757
+ userLaunch = prep.launch;
758
+ userOwner = prep.owner;
759
+ enrolled = prep.enrolled;
760
+ provisioned = { id: principalKey(prep.owner, name).key, name, lifecycleUid, userOwner: prep.owner, ...(opts.delegatedIntent ? { delegated: true } : {}), secretPaths: prep.files, ...(custody ? { runtime: custody } : {}) };
761
+ if (hostedEnrollment) {
762
+ try {
763
+ await hooks?.onAccepted?.({ name, identity, lifecycleUid, agentTriple: { owner: prep.owner, actor: name, uid: lifecycleUid } });
764
+ await acceptOnce({ owner: prep.owner, actor: name, uid: lifecycleUid });
765
+ }
766
+ catch (e) {
767
+ // A refused accept rolls the enrollment back: the host's grant through `provisioned`, and
768
+ // this participant's secret family here, before the refusal returns. The hosted retirement
769
+ // removes it too, but only once the host's release completes.
770
+ const unshredded = [];
771
+ await this.shredUserSecrets(unshredded, prep.files);
772
+ if (unshredded.length)
773
+ throw new Error(`${rejectionText(e)}; cleanup failed: ${describeCleanupFailures(unshredded)}`, { cause: e });
774
+ throw e;
775
+ }
776
+ }
777
+ }
778
+ else if (this.auth) {
779
+ // §13.1: reserve + activate this incarnation's DURABLE identity BEFORE any
780
+ // broker footprint — the outer spawn intent first (slot row, phase `provisioning`),
781
+ // then the SHARED core activation saga (reserve uid -> gate frozen -> head CAS -> reopen
782
+ // LAST) over the key-pinned executor. The wire AUTHORITY principal is the incarnation-
783
+ // unique nkey; the alias is protected by the name-keyed slot + freeSlot hold.
784
+ await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: identity.id, lifecycleUid, alias: name }, (t) => activateStaticLifecycle(t, { owner: DEV_OWNER, alias: name, actor: identity.id, lifecycleUid, managerInstance: this.managerLifecycleUid, ownerInstanceId: this.managerInstanceId, runtime: custody }));
785
+ // From here the DURABLE registration exists: arm the rollback BEFORE minting, so a throw
786
+ // between activation and provisioning still drives the exact-op static terminal (the
787
+ // finally's deprovision tolerates absent files; the broker teardown is idempotent).
788
+ provisioned = { id: identity.id, name, lifecycleUid, ...(custody ? { runtime: custody } : {}) };
789
+ // Pre-create the agent's bind-only chat (+ DM + role TASK) durables and mint its scoped creds
790
+ // — the shared onboarding step (provisionAgent). It runs on a short-lived PROVISIONER connection
791
+ // (NOT the supervisor's long-lived endpoint), so the DM/DLV consumer-create surface exists only
792
+ // for the provisioning window, never as a standing grant on the always-on daemon (residual 2).
793
+ // The credential is BOUNDED (`expiresAt`) — the manager push-renews it ahead of expiry.
794
+ const now = Math.floor(Date.now() / 1000);
795
+ const exp = now + MANAGED_STATIC_TTL_SEC;
796
+ // The credential is an ISSUANCE (SPEC 13.15): its caller rails carry a fresh generation
797
+ // and its ceiling is recorded as evidence bound to this incarnation's ledger family. The
798
+ // §13.1 ledger append (ledger BEFORE materialization) is the release's finalizer, so the
799
+ // evidence activates only once the row exists, and the row exists only after the evidence
800
+ // was staged. The agent learns the generation by reading the accepted row under its token.
801
+ // The generation's horizon bounds every renewal of this incarnation's credential.
802
+ issued = { generation: mintGeneration(now + STATIC_GENERATION_HORIZON_SEC), acceptedToken: mintAcceptedToken(), listing: true };
803
+ const issuedAgent = { name, id: identity.id, lifecycleUid };
804
+ const creds = await this.withIssuer((i) => this.withProvisioner((prov) => provisionAgent(prov, this.auth, identity, {
805
+ eventPayloads,
806
+ subscribe,
807
+ allowSubscribe,
808
+ allowPublish,
809
+ role,
810
+ capabilities,
811
+ ...(endpoints.length ? { endpointCapabilities: endpoints } : {}),
812
+ lifecycleUid,
813
+ expiresAt: exp,
814
+ issued,
815
+ issuance: this.issuanceSeam(i, "issue", issuedAgent, exp),
816
+ })));
817
+ // Store first (the source of truth), then materialize: `buildLaunch` hands the CHILD this
818
+ // file path, so the cred must exist as a file regardless of the store behind the seam. The
819
+ // manager's ONE store (injected for hosted, workstation FS locally).
820
+ const secrets = this.secrets;
821
+ // LIFECYCLE-KEYED (SPEC 13.1 on the FS): the incarnation's cred file embeds its uid, so a
822
+ // replayed/stale teardown can never address a same-name successor's credential.
823
+ credsPath = agentLifecycleSecretFilePaths(this.workspaceRoot, this.space, name, lifecycleUid).creds;
824
+ await secrets.put(agentSecretKeyForFile(credsPath, this.space), creds);
825
+ await materializeSecretToFile(secrets, agentSecretKeyForFile(credsPath, this.space), credsPath);
826
+ provisioned = { id: identity.id, name, lifecycleUid, secretPaths: { creds: credsPath }, ...(custody ? { runtime: custody } : {}) }; // footprint now exists — the finally rolls it back if the spawn throws
827
+ }
828
+ // Per-agent cwd overrides the manager's shared workspace root, so agents can be rooted at
829
+ // arbitrary folders/repos. A relative path resolves against the workspace root; omitted → the
830
+ // agent shares the workspace root (the prior, unchanged behavior).
831
+ // The realpath the admission check above already resolved (#385 item 2) — never re-resolved here,
832
+ // so the admission refusal and the launch cwd can never disagree on the same request.
833
+ const cwd = resolvedCwd ?? this.workspaceRoot;
834
+ // An inline persona's snapshot, and its catalog copy when saved, are written here: after the
835
+ // grant (the static issuance, the user-auth ledger, a hosted enrollment that may replace the
836
+ // uid) and before launch, so a refused grant leaves neither file and the snapshot carries the
837
+ // final uid. A copy that loses a create race throws, and the finally rolls the grant back.
838
+ if (inline) {
839
+ configPath = writeInlineSnapshot(this.workspaceRoot, lifecycleUid, { name, role, model, variant, description: def.description, body: def.persona });
840
+ snapshotUid = lifecycleUid;
841
+ if (catalogCopy)
842
+ saveAgentFile(agentFilePath(this.workspaceRoot, ref), catalogCopy, { createOnly: true });
843
+ }
844
+ if (configPath === undefined)
845
+ throw new Error("internal: the persona file is missing at launch");
846
+ const configSha256 = this.fileDigest(configPath);
847
+ const manifestPath = opts.launchRef
848
+ ? join(this.workspaceRoot, ".cotal", "run", `${opts.launchRef.runId}.json`)
849
+ : undefined;
850
+ const manifestSha256 = manifestPath ? this.fileDigest(manifestPath) : undefined;
851
+ const launchOpts = {
852
+ ...hostFields,
853
+ name,
854
+ role,
855
+ // User mode: the principal IS the identity (the endpoint derives card.id from owner+actor);
856
+ // no nkey id, no static creds.
857
+ id: userLaunch ? undefined : identity.id,
858
+ creds: credsPath,
859
+ userAuth: userLaunch,
860
+ // The incarnation's lifecycle UID: the agent endpoint binds its lifecycle-keyed dm/dlv/
861
+ // chathist durables by this exact value (its creds pin the same names, so a mismatch fails
862
+ // at the broker, never silently).
863
+ lifecycleUid,
864
+ acceptedToken: issued?.acceptedToken,
865
+ configPath,
866
+ model,
867
+ variant,
868
+ launchOptions,
869
+ // Fork an existing session into the mesh. Taken straight from `opts.resume` (the imperative
870
+ // control arg), never from `opts.resolved` — so the manifest launch path carries no resume by
871
+ // construction. An unsupported connector throws here before any process is spawned.
872
+ resume: opts.resume,
873
+ reopenSession,
874
+ // Initial prompt: the `--prompt` flag, or the manifest entry's `prompt:` on a resolved launch.
875
+ // A reopened session already had its kickoff turn, so it is not submitted again. A once
876
+ // seat gets its prompt as its one relayed task instead.
877
+ prompt: reopenSession === undefined && opts.once === undefined ? prompt : undefined,
878
+ ...(opts.once !== undefined ? { once: true } : {}),
879
+ // The SAME access set the creds were minted from (above) — forwarded so the session's
880
+ // runtime read/post set matches its credentials. Without this a manifest-spawned agent
881
+ // (materialized persona has no access frontmatter) has no channel set to read and joins
882
+ // nothing, even though its creds authorize the manifest's channels.
883
+ subscribe,
884
+ allowSubscribe,
885
+ allowPublish,
886
+ capabilities,
887
+ // Always the list the launch resolved, `[]` included, so the session never reads a persona
888
+ // file that may have changed since.
889
+ endpoints: copyPersonaEndpoints(personaEndpoints) ?? [],
890
+ events,
891
+ eventPayloads,
892
+ cwd,
893
+ };
894
+ // A delegated seat gets no local launch at all: no launch-material file, control token or
895
+ // manager path is produced for it, only the handoff its runtime writes into the child.
896
+ let spec;
897
+ let handle;
898
+ if (runtime.spawnDelegated) {
899
+ const handoff = this.userProvision.composeManagedHandoff(enrolled.material, enrolled.actorToken);
900
+ if (this.delegatedLaunched.has(lifecycleUid))
901
+ throw new Error(`lifecycle ${lifecycleUid} was already handed to runtime "${runtime.kind}"; a lifecycle is handed off at most once`);
902
+ this.delegatedLaunched.add(lifecycleUid);
903
+ const holder = retainConnectorSeat(this.managerInstanceId, name);
904
+ handle = runtime.spawnDelegated({ agent, persona: readFileSync(configPath, "utf8"), managerInstanceId: this.managerInstanceId, role, model, variant, prompt, launchOptions: launchOptions, events, eventPayloads }, handoff);
905
+ watchConnectorHolder(handle, holder);
906
+ }
907
+ else {
908
+ if (carried) {
909
+ seatHome = join(this.workspaceRoot, ".cotal", "seat-homes", lifecycleUid);
910
+ mkdirSync(seatHome, { recursive: true, mode: 0o700 });
911
+ launchOpts.carried = { home: seatHome, transcript: carried.path, cwd };
912
+ }
913
+ spec = connector.buildLaunch(launchOpts);
914
+ if (carried)
915
+ this.transcripts.consume(opts.resumeClaim, opts.resume);
916
+ spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
917
+ handle = await this.seatCustody.spawnCustodied(runtime, name, spec, cwd, custody);
918
+ }
919
+ if (onceTask && !handle.waitForExit)
920
+ throw new Error(`once: runtime "${handle.kind}" cannot prove the seat's exit, which is what ends its task when the seat goes first`);
921
+ const launchedAt = Date.now();
922
+ hooks?.onLaunched?.(); // The "launched" progress edge (process spawned, pre-presence)
923
+ const managed = {
924
+ name,
925
+ role,
926
+ agent,
927
+ ...(seatHome ? { seatHome } : {}),
928
+ id: userLaunch ? principalKey(userLaunch.owner, name).key : identity.id,
929
+ lifecycleUid,
930
+ // The lifecycle-keyed family this spawn just materialized (absent on an open mesh) — the
931
+ // recorded truth teardown/preservation/health consume, never re-derived by name.
932
+ secretPaths: provisioned?.secretPaths,
933
+ ...(userLaunch ? { userOwner } : { seed: identity.seed }),
934
+ ...(opts.delegatedIntent ? { delegated: true } : {}),
935
+ ...(issued ? { issued } : {}),
936
+ spawner: spawner ?? this.ep.ref().id,
937
+ authorityParent: userLaunch && spawner && parsePrincipalKey(spawner) ? spawner : undefined,
938
+ startedAt: Date.now(),
939
+ handle,
940
+ control: spec?.control,
941
+ ...(spec ? {} : { handedOff: true }),
942
+ launch: {
943
+ runtime: runtime.kind,
944
+ source: opts.resolved
945
+ ? {
946
+ kind: "manifest",
947
+ runId: opts.launchRef?.runId,
948
+ requested: opts.launchRef?.requested ?? opts.resolved.name,
949
+ hash: opts.launchRef?.hash ?? opts.resolved.hash,
950
+ configPath,
951
+ configSha256,
952
+ manifestSha256,
953
+ }
954
+ : inline
955
+ ? { kind: "inline", ref, configPath, configSha256 }
956
+ : { kind: "persona", ref: opts.config ? identityName : ref, configPath, configSha256 },
957
+ cwd,
958
+ model,
959
+ variant,
960
+ // The kickoff prompt is part of the launch form: a stale-restart re-submits it, so the
961
+ // recorded launch must carry it for the restart gate (and preserve) to see it. A once
962
+ // seat's prompt is its task, which no relaunch may submit again.
963
+ prompt: onceTask ? undefined : prompt,
964
+ subscribe,
965
+ allowSubscribe,
966
+ allowPublish,
967
+ capabilities,
968
+ ...(personaEndpoints?.length ? { endpoints: copyPersonaEndpoints(personaEndpoints) } : {}),
969
+ events,
970
+ eventPayloads,
971
+ shareTools: opts.shareTools,
972
+ forkSource: opts.resume,
973
+ ...(opts.resume !== undefined && spec?.resumeRecordPath ? { resumeRecordPath: spec.resumeRecordPath } : {}),
974
+ ...(carried ? { carried: { transcriptSha256: carried.sha256, host: carried.sourceHost, transferredAt: carried.stagedAt } } : {}),
975
+ // Opaque values may contain secrets. Preserve only their keys and require the referenced
976
+ // persona/manifest to resolve the values again; imperative overrides have no safe payload.
977
+ unresolvedLaunchOptionKeys: opts.launchOptions && Object.keys(opts.launchOptions).length
978
+ ? Object.keys(opts.launchOptions).sort()
979
+ : undefined,
980
+ },
981
+ // A delegated agent is never restarted (SPEC 13.16), and a once seat never runs its task
982
+ // twice, so neither slot arms recovery.
983
+ ...(onceTask ? { once: { ref: onceTask.ref, ...(connector.retireAfterExit ? { retire: connector.name } : {}) } } : {}),
984
+ ...(spec && (connector.supportsSessionContinuation || opts.supervise !== undefined) && !opts.delegatedIntent && !onceTask
985
+ ? {
986
+ restart: {
987
+ opts: launchOpts,
988
+ sessionStatePath: spec.sessionStatePath,
989
+ crashes: [],
990
+ recovering: false,
991
+ armed: false,
992
+ ...(opts.supervise !== undefined ? { policy: opts.supervise } : {}),
993
+ },
994
+ }
995
+ : {}),
996
+ };
997
+ // The DURABLE slot takes the `active` phase before the in-memory row takes the
998
+ // name — a crash between the two leaves an active-but-unadopted slot the boot sweep
999
+ // terminalizes (never an untracked orphan). Static auth only; a failed CAS fails the spawn
1000
+ // (the finally's rollback then drives the exact-op terminal).
1001
+ if (this.auth && !this.userMode) {
1002
+ await this.withLifecycleExecutor({ owner: DEV_OWNER, actor: managed.id, lifecycleUid, alias: name }, async (t) => {
1003
+ const slot = await readStaticSlot(t, DEV_OWNER, name);
1004
+ if (slot === undefined || slot.row.lifecycleUid !== lifecycleUid || slot.row.phase !== "provisioning")
1005
+ throw new Error(`the static slot for "${name}" is ${slot === undefined ? "absent" : `${slot.row.phase} at uid ${slot.row.lifecycleUid}`}, not this spawn's provisioning intent; refusing to take the slot`);
1006
+ // The custody reference rides the SAME CAS as activation: a crash after this write leaves
1007
+ // an active slot a successor can reap by reference, never a live seat nobody addresses.
1008
+ await casStaticSlot(t, { ...slot.row, phase: "active", ...(handle.reference ? { runtime: handle.reference } : {}) }, slot.revision);
1009
+ });
1010
+ }
1011
+ this.place(name, managed);
1012
+ if (managed.once)
1013
+ this.watchOnceExit(managed);
1014
+ // The live slot now owns teardown — freeSlot deprovisions this identity on exit — so the
1015
+ // orphan-rollback in `finally` no longer applies to it.
1016
+ provisioned = undefined;
1017
+ seatHome = undefined;
1018
+ snapshotUid = undefined;
1019
+ // #159 B1: reply on a REAL outcome, not a timer. Wait for the agent to actually join the mesh
1020
+ // (presence) → started, the child to exit → failed (with its last output; already reaped), or
1021
+ // neither in time → uncertain. `✓ started` therefore means "it joined", never just "a process
1022
+ // launched", except for a launch whose options make the harness wait for the operator first: that
1023
+ // one is ready once its process runs, and its reply names the screen it waits at.
1024
+ const operator = connector.waitsForOperator?.(launchOptions);
1025
+ const readiness = await this.awaitReadiness(managed, readinessTimeoutMs, operator === undefined ? {} : { operator });
1026
+ // Deliberately stopped mid-launch: reaped by onExit, and the despawn/stop path owns the
1027
+ // goal terminal. Return BEFORE the failed/uncertain arms so this emits no competing
1028
+ // outcome and does not re-arm an exit watcher on an agent already gone.
1029
+ if (!readiness.ok && readiness.deliberate) {
1030
+ hooks?.onTerminalDeferred?.();
1031
+ return { ok: false, error: readiness.detail };
1032
+ }
1033
+ if (!readiness.ok && !readiness.uncertain) { // failed → already reaped
1034
+ // A reopen fails before readiness when the host no longer has the recorded session, which
1035
+ // is refused rather than replaced by an empty one; name the record that pins it.
1036
+ const error = reopenSession === undefined ? readiness.detail
1037
+ : `${readiness.detail} (continuity: exact was reopening recorded session ${reopenSession}; if the harness no longer has it, ` +
1038
+ `remove ${join(this.workspaceRoot, ".cotal", "continuity", `${name}.json`)} to start a new session)`;
1039
+ if (managed.once)
1040
+ managed.once.stopReason ??= "launch-failed";
1041
+ await hooks?.onOutcome?.({ kind: "failed", data: { error } });
1042
+ return { ok: false, error };
1043
+ }
1044
+ // Started OR uncertain: the agent stays managed, so wire the ongoing exit reaper (it reaps a later
1045
+ // death — including one that follows an `uncertain` verdict, which deliberately does NOT deprovision).
1046
+ if (!readiness.ok) {
1047
+ this.watchExit(managed);
1048
+ if (managed.launch.carried)
1049
+ void this.sessionRecovery.refuseLateCarriedFork(managed, readinessTimeoutMs);
1050
+ // A once seat is never left running with nothing to do, and its stop does not wait on the
1051
+ // spawn's terminal, whose write can stall. The spawn keeps that terminal: the stop lets go
1052
+ // of the spawn goal first. Its task was never served and is cancelled with the verdict.
1053
+ if (managed.once) {
1054
+ this.endOnceBeforeServe(managed, "readiness-timeout");
1055
+ }
1056
+ await hooks?.onOutcome?.({ kind: "uncertain", data: { reason: readiness.detail, ...(readiness.running ? { running: true } : {}) } });
1057
+ return { ok: false, error: readiness.detail };
1058
+ }
1059
+ // A once seat whose connector needs a confirmed startup is served only on that outcome. Any
1060
+ // other ends it like a seat that never joined: stopped before the failed terminal, and its
1061
+ // task, never served, cancelled with the verdict.
1062
+ if (onceTask && connector.onceNeedsConfirmed !== undefined) {
1063
+ const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
1064
+ if (managed.terminalizing || this.leaseStopping) {
1065
+ hooks?.onTerminalDeferred?.();
1066
+ return { ok: false, error: `${name} was stopped before its startup ended` };
1067
+ }
1068
+ if (startup !== "confirmed") {
1069
+ const watch = { ready: "opened its input screen without the prompt", failed: "failed", exited: "saw the seat exit", pending: "had not ended" }[startup];
1070
+ const error = `${name} joined, but ${connector.onceNeedsConfirmed}: its startup watch ${watch}, so it cannot take a once task`;
1071
+ this.watchExit(managed);
1072
+ this.endOnceBeforeServe(managed, "launch-failed", "launch-failed");
1073
+ await hooks?.onOutcome?.({ kind: "failed", data: { error } });
1074
+ return { ok: false, error };
1075
+ }
1076
+ }
1077
+ // A plain seat on such a connector starts whatever its startup showed. One whose watch opened the
1078
+ // input screen without the prompt is not woken by mesh traffic, and the spawn says so instead of
1079
+ // starting it silently without push (#5737).
1080
+ if (!onceTask && connector.idleWakeNeedsConfirmed !== undefined && runtime.reportsStartupOutcome) {
1081
+ const startup = await this.awaitStartupOutcome(managed, launchedAt, readinessTimeoutMs);
1082
+ if (managed.terminalizing || this.leaseStopping) {
1083
+ hooks?.onTerminalDeferred?.();
1084
+ return { ok: false, error: `${name} was stopped before its startup ended` };
1085
+ }
1086
+ if (startup === "ready") {
1087
+ managed.startupNotice = connector.idleWakeNeedsConfirmed;
1088
+ console.error(`! ${name}: ${connector.idleWakeNeedsConfirmed}`);
1089
+ }
1090
+ }
1091
+ if (managed.launch.carried) {
1092
+ const refused = await this.sessionRecovery.refuseCarriedFork(managed, readinessTimeoutMs);
1093
+ if (refused !== undefined && managed.terminalizing) {
1094
+ hooks?.onTerminalDeferred?.();
1095
+ return { ok: false, error: refused };
1096
+ }
1097
+ if (refused !== undefined) {
1098
+ this.stopAndTrack(managed, "carried-fork-refused");
1099
+ await hooks?.onOutcome?.({ kind: "failed", data: { error: refused } });
1100
+ return { ok: false, error: refused };
1101
+ }
1102
+ }
1103
+ if (managed.restart) {
1104
+ if (connector.supportsSessionContinuation) {
1105
+ try {
1106
+ await this.sessionRecovery.armSessionRecovery(managed);
1107
+ // The capability flags are only a claim. An exact seat is recorded once the connector
1108
+ // has proved its session over its authenticated control endpoint, never before.
1109
+ if (exact && !managed.restart.armed)
1110
+ throw new Error("continuity: exact needs the connector to prove its session over an authenticated control endpoint, and it supplied none");
1111
+ managed.launch.sessionId = this.sessionRecovery.readManagedSession(managed);
1112
+ if (reopenSession !== undefined && managed.launch.sessionId !== reopenSession)
1113
+ throw new Error(`continuity: exact asked for session ${reopenSession}, the connector bound ${managed.launch.sessionId}`);
1114
+ if (exact) {
1115
+ managed.continuity = { space: this.space, name, connector: agent, cwd };
1116
+ this.sessionRecovery.recordContinuity(managed, managed.launch.sessionId);
1117
+ }
1118
+ }
1119
+ catch (error) {
1120
+ const detail = `${managed.name} joined, but its exact host session could not be bound for supervised recovery: ${rejectionText(error)}`;
1121
+ this.stopAndTrack(managed, "session-bind-failed");
1122
+ await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
1123
+ return { ok: false, error: detail };
1124
+ }
1125
+ }
1126
+ else {
1127
+ managed.restart.armed = true;
1128
+ }
1129
+ if (managed.restart.policy) {
1130
+ try {
1131
+ this.seatCustody.recordSeat(managed);
1132
+ }
1133
+ catch (error) {
1134
+ const detail = `${managed.name} joined, but supervise cannot cover a manager restart for it: ${rejectionText(error)}`;
1135
+ this.stopAndTrack(managed, "supervise-record-failed");
1136
+ await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
1137
+ return { ok: false, error: detail };
1138
+ }
1139
+ }
1140
+ }
1141
+ // An unsupervised seat a successor could adopt keeps a record too; one that cannot be written
1142
+ // costs only that adoption, so the spawn stands and the line says so.
1143
+ if (!managed.restart?.policy)
1144
+ this.seatCustody.refreshSeatRecord(managed);
1145
+ this.watchExit(managed);
1146
+ // Reply with the id the slot actually carries (user-mode: the owner.actor principal —
1147
+ // presence, ps, and the manifest ownership ledger all key on it; the throwaway static nkey
1148
+ // would never match and down -f would treat the agent as foreign).
1149
+ // `lifecycleUid` rides the reply so callers that record this spawn (the manifest ledger) can
1150
+ // later address the incarnation's lifecycle-keyed artifacts without re-deriving by name.
1151
+ // OMIT an absent role: the goal terminal commits this data through the strict
1152
+ // canonicalJson (undefined never coerces to null, SPEC 13.6), so a role-less spawn would
1153
+ // otherwise fail its succeeded terminal. The CLI/connector already render an absent role as
1154
+ // "no role", so dropping the key preserves the reply (surfaced by readiness:live).
1155
+ // A host that granted other channels than this spawn asked for: the receipt carries both.
1156
+ const acl = enrolled ? enrolledAcl({ allowSubscribe, allowPublish }, enrolled.material) : undefined;
1157
+ const okData = { name, agent, id: managed.id, mode: handle.kind, streamsTerminal: runtime.streamsTerminal, lifecycleUid, ...(role !== undefined ? { role } : {}), ...(opts.eventsNotice !== undefined ? { eventsNotice: opts.eventsNotice } : {}), ...(managed.startupNotice !== undefined ? { startupNotice: managed.startupNotice } : {}), ...(acl ? { acl } : {}), ...(readiness.operator !== undefined ? { waitingFor: readiness.operator } : {}), ...(onceTask ? { once: { goalId: onceTask.ref.goalId, ...(onceTask.deadlineAt !== undefined ? { deadlineAt: onceTask.deadlineAt } : {}) } } : {}) };
1158
+ // The task is served once the succeeded terminal is written, so a served task always has it
1159
+ // and a successor reads it as the readiness verdict. Every failure arm above ran before it. A
1160
+ // terminal this call did not commit never served the task: the seat is stopped, which cancels it.
1161
+ const committed = await hooks?.onOutcome?.({ kind: "succeeded", data: okData });
1162
+ if (onceTask && committed === true)
1163
+ this.openOnceDelivery(onceTask.ref);
1164
+ else if (onceTask) {
1165
+ this.endOnceBeforeServe(managed, "launch-failed", "launch-failed");
1166
+ }
1167
+ return { ok: true, data: okData };
1168
+ }
1169
+ catch (e) {
1170
+ // Failure after reserve (provision / launch threw): the slot was never live, so no cold-start
1171
+ // was paid — the reserved rollback (finally) is enough, no cooling stamp.
1172
+ // Keep the envelope's code and lifecycle details on the ControlReply so the serve boundary
1173
+ // can carry the refusal's classification and barrier to the caller. An extension can throw
1174
+ // any value, and an envelope's `message` is only typed as a string, so the refusal text always
1175
+ // comes from rejectionText; telling an envelope apart is guarded because a thrown Proxy can
1176
+ // throw from `instanceof` or from its own fields.
1177
+ const error = rejectionText(e);
1178
+ try {
1179
+ if (e instanceof EpEnvelopeError)
1180
+ return controlReplyFromThrown(e, error);
1181
+ }
1182
+ catch { /* not a readable envelope */ }
1183
+ return { ok: false, error };
1184
+ }
1185
+ finally {
1186
+ this.namesCapacity.release(name);
1187
+ if (seatHome)
1188
+ rmSync(seatHome, { recursive: true, force: true });
1189
+ // A failed removal is logged, never thrown, so the grant's teardown below is still scheduled.
1190
+ const snapshotGone = snapshotUid === undefined || this.dropInlineSnapshot(name, snapshotUid);
1191
+ // Minted but never handed to a live slot (buildLaunch / runtime.spawn threw after mint) → tear the
1192
+ // orphan down (detached, fail-loud) so a failed spawn leaves no creds/durables behind (#159 B).
1193
+ if (provisioned) {
1194
+ // Settled when this spawn wrote no snapshot or removed the one it wrote. A file its write
1195
+ // refused is not this lifecycle's, so the terminal leaves the uid's path alone; a removal
1196
+ // that failed is the terminal's to retry and report.
1197
+ const orphan = { ...provisioned, ...(snapshotGone ? { snapshotSettled: true } : {}) };
1198
+ // The host enrolled this UID for the intent's user, so only that user's retirement intent
1199
+ // retires it, and its name stays held for retireDelegatedAgent.
1200
+ const p = orphan.delegated ? parsePrincipalKey(orphan.id) : null;
1201
+ if (p)
1202
+ this.retirement.hold(orphan.name, { opId: managedRetirementOpId(orphan.lifecycleUid), owner: p.owner, actor: p.actor, target: orphan, startedAt: Date.now() });
1203
+ this.trackDeprovision(orphan, "(orphaned spawn)");
1204
+ }
1205
+ }
1206
+ }
1207
+ }
1208
+ //# sourceMappingURL=seat-start.js.map