@cotal-ai/manager 0.169.0 → 0.170.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/manager.d.ts +40 -456
- package/dist/manager.d.ts.map +1 -1
- package/dist/manager.js +232 -673
- package/dist/manager.js.map +1 -1
- package/dist/names-capacity.d.ts +34 -2
- package/dist/names-capacity.d.ts.map +1 -1
- package/dist/names-capacity.js +53 -1
- package/dist/names-capacity.js.map +1 -1
- package/dist/run-hosting.d.ts +1 -0
- package/dist/run-hosting.d.ts.map +1 -1
- package/dist/run-hosting.js +18 -2
- package/dist/run-hosting.js.map +1 -1
- package/dist/seat-custody.d.ts +2 -0
- package/dist/seat-custody.d.ts.map +1 -1
- package/dist/seat-custody.js +10 -1
- package/dist/seat-custody.js.map +1 -1
- package/dist/seat-launch.d.ts +185 -0
- package/dist/seat-launch.d.ts.map +1 -0
- package/dist/seat-launch.js +522 -0
- package/dist/seat-launch.js.map +1 -0
- package/dist/seat-types.d.ts +362 -0
- package/dist/seat-types.d.ts.map +1 -0
- package/dist/seat-types.js +2 -0
- package/dist/seat-types.js.map +1 -0
- package/package.json +12 -12
package/dist/manager.js
CHANGED
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
import { UserProvision } from "./user-provision.js";
|
|
2
|
-
import { TurnRelay, goalKey, caughtEnvelope, TURN_ANSWER_RETENTION_MS
|
|
2
|
+
import { TurnRelay, goalKey, caughtEnvelope, TURN_ANSWER_RETENTION_MS } from "./turn-relay.js";
|
|
3
3
|
import { createHash, randomBytes } from "node:crypto";
|
|
4
4
|
import { checkEventStartup, EventStateConflictError, isPermissionDenied, chatStream, drainAndClose, requestSafeReconnect } from "@cotal-ai/core";
|
|
5
|
-
import { hostname
|
|
6
|
-
import { listDirectory } from "./list-dir.js";
|
|
5
|
+
import { hostname } from "node:os";
|
|
7
6
|
import { credsAuthenticator, RequestError } from "@nats-io/transport-node";
|
|
8
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync
|
|
9
|
-
import {
|
|
7
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync } from "node:fs";
|
|
8
|
+
import { join, resolve } from "node:path";
|
|
10
9
|
import { parse as parseYaml } from "yaml";
|
|
11
10
|
import Headless from "@xterm/headless";
|
|
12
|
-
import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC,
|
|
13
|
-
import {
|
|
11
|
+
import { CotalEndpoint, canonicalJson, copyPersonaEndpoints, lowerPersonaEndpoints, parsePersonaEndpoints, accountFromCreds, credsClaims, DEFAULT_SERVER, DEV_OWNER, MANAGER_LEASE_RENEW_MS, STANDING_RENEWABLE_TTL_SEC, discardLaunchArtifacts, divergentSecretStoreNotice, injectedSecretStoreIdentity, parseDaemonStoreAnswer, parseSecretStoreIdentity, sameSecretStoreIdentity, agentFilePath, clearSpaceHistory, dialerFor, connectorServers, spawnEnvAllow, fenceLifecycleAcl, isConcreteChannel, isChannelFamily, deprovisionTargetPrincipal, idFromCreds, identityFromCreds, inspectCredHealth, credsRenewalDelayMs, composeWirePersona, loadAgentFile, listPersonaCatalog, personaCatalogDescription, personaCatalogReadable, loadCotalConfig, modelPolicyRefusal, mintCreds, mintGeneration, mintAcceptedToken, bindIssuedStores, mintLifecycleUid, managedRetirementOpId, newIdentity, oneLine, actionContext, parsePrincipalKey, principalKey, probeConnect, provisionAgent, registry, resolveAuthProvider, resolveReadAcl, saveAgentFile, eventChannelPrincipal, capabilityWithin, grantOverreach, } from "@cotal-ai/core";
|
|
12
|
+
import { retainConnectorSeat } from "@cotal-ai/workspace";
|
|
14
13
|
import { logicalExecutionEntry, OFFICIAL_CONNECTORS } from "@cotal-ai/workspace";
|
|
15
|
-
import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, remintDaemonCreds,
|
|
14
|
+
import { agentAuthState, agentCredsDir, agentLifecycleSecretFilePaths, agentSecretFilePaths, agentSecretKeyForFile, authDir, claimIdentityRecord, connectorInstallHint, DEFAULT_SEAT_CAP, DELIVERY_CREDS_KIND, extensionConnectors, findCotalRoot, getSpaceAuth, hasUserAuthState, loadExtensionsManifest, loadManagerInstanceIdentity, loadMeshes, localTrustOfSpace, manifestExtensionNames, materializeFromManifest, materializeSecretToFile, MEMBERSHIP_RW_CREDS_KIND, mergeLaunchOptions, remintDaemonCreds, resolveOnPath, runtimeInstallHint, createManagerInstanceIdentity, spaceKey, spaceMaterialKey, SYSTEM_CREDS_FILES, userAuthStateDir, workspaceSecretStore, writeRenewalRecord } from "@cotal-ai/workspace";
|
|
16
15
|
import { createRuntime, exitProof, isCustodialRuntime, pollProvedExit, requireRuntimeAdopt, requireRuntimeReap, watchProvedExit, } from "./runtime/index.js";
|
|
17
16
|
import { Retirement } from "./retirement.js";
|
|
18
17
|
import { ServePlane } from "./serve-plane.js";
|
|
@@ -25,10 +24,11 @@ export { STATIC_RECONCILE_RETRY_DELAYS_MS } from "./managed-static-lifecycle.js"
|
|
|
25
24
|
import { LeaseKeeper } from "./lease-keeper.js";
|
|
26
25
|
export { ManagerInstanceLeaseHeld } from "./lease-keeper.js";
|
|
27
26
|
import { SessionRecovery } from "./session-recovery.js";
|
|
28
|
-
import { SeatCustody } from "./seat-custody.js";
|
|
27
|
+
import { SeatCustody, watchConnectorHolder } from "./seat-custody.js";
|
|
28
|
+
import { SeatLaunch, ownLists, ownPersona, userMeshEndpointsRefusal } from "./seat-launch.js";
|
|
29
29
|
import { withTimeout } from "./manager-timeout.js";
|
|
30
30
|
import { GateReconcileRefused, reconcileEndpointGate } from "./reconcile-gate.js";
|
|
31
|
-
import {
|
|
31
|
+
import { inlineSnapshotPath, launchSpecForRun, materializePersona, launchAgentToStartOpts, removeInlineSnapshot, writeInlineSnapshot, parseLaunchSpec, persistLaunchSpec, readContinuityAssignment } from "./launch.js";
|
|
32
32
|
import { authorizeLaunch, authorizeNamedControl } from "./authorize.js";
|
|
33
33
|
import { controlShutdown } from "./control-shutdown.js";
|
|
34
34
|
import { RunHosting, servedRequestSubject } from "./run-hosting.js";
|
|
@@ -48,7 +48,7 @@ import { ManagerSessionPlane } from "./session/index.js";
|
|
|
48
48
|
// The manager as an ordinary v0.4 `service` endpoint — the §13.1
|
|
49
49
|
// endpoint-serve credential subsystem (gate provisioning, registration barrier, mint fence) plus
|
|
50
50
|
// the register/authorize/serve seams, all driven over a scoped one-shot executor connection.
|
|
51
|
-
import { serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, MAX_SCHEDULE_MS, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked,
|
|
51
|
+
import { serveIssuanceGateKv, commitSiblingIssuance, epgateKey, parseEndpointGate, readEndpointGateGeneration, deregisterServiceInstance, bindGoal, createGoal, transitionGoal, commitGoalResult, goalAlreadyTerminal, settleGoalUncertain, readGoalResult, readGoalStatus, readGoalSpec, recordGoalIndex, readGoalIndex, clearGoalIndex, listGoalIndex, MAX_SCHEDULE_MS, GOAL_TERMINAL_STATES, goalRefOf, goalProgressTopic, turnNoticeSubject, epeSubject, submissionFingerprint, EpEnvelopeError, lifecycleBlocked, lifecycleBlockedFrom, renderLifecycleBlocked, controlReplyFromThrown } from "@cotal-ai/core";
|
|
52
52
|
import { MANAGER_ENDPOINT, managerCommandDefs } from "./manager-service-contract.js";
|
|
53
53
|
import { measureManagerVitals } from "./vitals.js";
|
|
54
54
|
import { staticLifecycleTransport, activateStaticLifecycle, readStaticSlot, casStaticSlot, recordSlotCredential, appendStaticCredentialRow, ownedBySibling, observeStaticSlot, listStaticSlotObservations, renderStaticSlotObservation, StaticSlotReadError, STATIC_SLOT_READ_FAILED_DETAIL, } from "./static-lifecycle.js";
|
|
@@ -60,9 +60,6 @@ const ONCE_DEFAULT_DEADLINE_MS = 60 * 60_000;
|
|
|
60
60
|
/** The bound on one {@link Connector.retireAfterExit} call. An expired bound is not proof: the debt
|
|
61
61
|
* stays and the turn sweep asks again. */
|
|
62
62
|
const ONCE_RETIRE_MS = 60_000;
|
|
63
|
-
/** The goal index's bound on a relay note (core `GOAL_INDEX_NOTE_MAX`). A once task's note must
|
|
64
|
-
* fit it, and is refused at admission when it cannot. */
|
|
65
|
-
const TURN_NOTE_MAX = 65536;
|
|
66
63
|
/** Backstop for the detached-launch readiness race (#159 B1). `startAgent` waits on two REAL outcomes —
|
|
67
64
|
* the assigned id joining the mesh (presence) = started, the child process exiting = failed — NOT a
|
|
68
65
|
* liveness-inferring timer. This is only the last-resort bound for "neither happened in time": the launch
|
|
@@ -220,37 +217,6 @@ function sameStrings(a, b) {
|
|
|
220
217
|
function bearerEntryArgv() {
|
|
221
218
|
return [process.execPath, ...process.execArgv, realpathSync(process.argv[1])];
|
|
222
219
|
}
|
|
223
|
-
/** The caller keeps the arrays it passed, so a launch form is admitted with its own copies: a later
|
|
224
|
-
* write to the caller's array cannot change what the manager grants, shares or preserves. */
|
|
225
|
-
function ownLists(form) {
|
|
226
|
-
return {
|
|
227
|
-
...form,
|
|
228
|
-
...(form.subscribe && { subscribe: [...form.subscribe] }),
|
|
229
|
-
...(form.allowSubscribe && { allowSubscribe: [...form.allowSubscribe] }),
|
|
230
|
-
...(form.allowPublish && { allowPublish: [...form.allowPublish] }),
|
|
231
|
-
...(form.capabilities && { capabilities: [...form.capabilities] }),
|
|
232
|
-
...(form.shareTools && { shareTools: [...form.shareTools] }),
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
/** The inline record is admitted the same way, one level deeper: the record itself, its lists, and
|
|
236
|
-
* each `endpoints` entry with its commands. It is still untrusted here, so a shape the validator
|
|
237
|
-
* will refuse is copied as far as it goes and refused where it is read. */
|
|
238
|
-
function ownPersona(record) {
|
|
239
|
-
if (record === null || typeof record !== "object" || Array.isArray(record))
|
|
240
|
-
return record;
|
|
241
|
-
const owned = ownLists({ ...record });
|
|
242
|
-
const endpoints = owned.endpoints;
|
|
243
|
-
if (Array.isArray(endpoints))
|
|
244
|
-
owned.endpoints = endpoints.map((e) => {
|
|
245
|
-
if (e === null || typeof e !== "object" || Array.isArray(e))
|
|
246
|
-
return e;
|
|
247
|
-
const entry = { ...e };
|
|
248
|
-
if (Array.isArray(entry.commands))
|
|
249
|
-
entry.commands = [...entry.commands];
|
|
250
|
-
return entry;
|
|
251
|
-
});
|
|
252
|
-
return owned;
|
|
253
|
-
}
|
|
254
220
|
/** Operator-facing phrasing per cause. Kept beside the union so adding a member without a sentence
|
|
255
221
|
* is a type error rather than a blank in the log. The stop family's sentences carry the principal
|
|
256
222
|
* from the cause, so they render through {@link STOP_CAUSE_TEXT} under the same exhaustive-Record
|
|
@@ -295,71 +261,6 @@ function onceStopReason(cause) {
|
|
|
295
261
|
default: return cause;
|
|
296
262
|
}
|
|
297
263
|
}
|
|
298
|
-
/** Why a revoked run starts no helper, the same words wherever the marker is read. */
|
|
299
|
-
function revokedRunRefusal(runId, revoked) {
|
|
300
|
-
return `run ${runId} was revoked by ${revoked.by} (${revoked.reason}); a revoked run starts no helper (SPEC 14.8)`;
|
|
301
|
-
}
|
|
302
|
-
const INLINE_PERSONA_KEYS = ["prompt", "role", "model", "variant", "description", "subscribe", "allowSubscribe", "allowPublish", "capabilities", "endpoints", "save"];
|
|
303
|
-
/** Read an inline persona into the definition a catalog file would load as, refusing what a file
|
|
304
|
-
* load refuses plus any shape the closed record does not take. The body is literal text: nothing in
|
|
305
|
-
* it becomes a field, so a body that starts with `---` stays body. */
|
|
306
|
-
function inlinePersonaDef(name, raw) {
|
|
307
|
-
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
|
|
308
|
-
throw new Error("persona: expected an object");
|
|
309
|
-
const rec = raw;
|
|
310
|
-
const extra = Object.keys(rec).filter((k) => !INLINE_PERSONA_KEYS.includes(k));
|
|
311
|
-
if (extra.length)
|
|
312
|
-
throw new Error(`persona: unknown key ${extra[0]}; it takes ${INLINE_PERSONA_KEYS.join(", ")}`);
|
|
313
|
-
const text = (k) => {
|
|
314
|
-
const v = rec[k];
|
|
315
|
-
if (v === undefined)
|
|
316
|
-
return undefined;
|
|
317
|
-
if (typeof v !== "string" || !v.trim())
|
|
318
|
-
throw new Error(`persona.${k}: expected a non-blank string`);
|
|
319
|
-
return v;
|
|
320
|
-
};
|
|
321
|
-
const list = (k) => {
|
|
322
|
-
const v = rec[k];
|
|
323
|
-
if (v === undefined)
|
|
324
|
-
return undefined;
|
|
325
|
-
if (!Array.isArray(v) || v.some((x) => typeof x !== "string"))
|
|
326
|
-
throw new Error(`persona.${k}: expected an array of strings`);
|
|
327
|
-
return [...v];
|
|
328
|
-
};
|
|
329
|
-
const prompt = text("prompt");
|
|
330
|
-
if (prompt === undefined)
|
|
331
|
-
throw new Error("persona.prompt: required; it is the persona body");
|
|
332
|
-
if (rec.save !== undefined && typeof rec.save !== "boolean")
|
|
333
|
-
throw new Error("persona.save: expected a boolean");
|
|
334
|
-
const def = {
|
|
335
|
-
name,
|
|
336
|
-
persona: prompt.trim(),
|
|
337
|
-
role: text("role"),
|
|
338
|
-
model: text("model"),
|
|
339
|
-
variant: text("variant"),
|
|
340
|
-
description: text("description"),
|
|
341
|
-
subscribe: list("subscribe"),
|
|
342
|
-
allowSubscribe: list("allowSubscribe"),
|
|
343
|
-
allowPublish: list("allowPublish"),
|
|
344
|
-
capabilities: list("capabilities"),
|
|
345
|
-
endpoints: parsePersonaEndpoints(rec.endpoints, "persona"),
|
|
346
|
-
};
|
|
347
|
-
// The checks a file load makes on these fields: channel names, and the read set within the read ACL.
|
|
348
|
-
try {
|
|
349
|
-
for (const ch of [...(def.subscribe ?? []), ...(def.allowSubscribe ?? []), ...(def.allowPublish ?? [])])
|
|
350
|
-
assertValidChannel(ch);
|
|
351
|
-
resolveReadAcl(def.subscribe ?? [], def.allowSubscribe);
|
|
352
|
-
}
|
|
353
|
-
catch (e) {
|
|
354
|
-
throw new Error(`persona: ${rejectionText(e)}`);
|
|
355
|
-
}
|
|
356
|
-
return { def, save: rec.save === true };
|
|
357
|
-
}
|
|
358
|
-
/** The refusal a user-auth mesh gives a persona that names `endpoints`. */
|
|
359
|
-
function userMeshEndpointsRefusal(door) {
|
|
360
|
-
return `${door}: this mesh has per-user auth, where endpoint access comes from the service owner's grants and a persona cannot hand it on (SPEC 13.15). ` +
|
|
361
|
-
"Drop `endpoints` from the persona, and ask the operator to grant the helper with `cotal service-endpoint grant` once it runs.";
|
|
362
|
-
}
|
|
363
264
|
class LegacyEventCountPermissionError extends Error {
|
|
364
265
|
}
|
|
365
266
|
const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
|
|
@@ -418,6 +319,31 @@ class DeliveryAdminUnanswered extends Error {
|
|
|
418
319
|
}
|
|
419
320
|
/** How long one store challenge waits for the delivery daemon's answer. */
|
|
420
321
|
const STORE_CHALLENGE_TIMEOUT_MS = 5_000;
|
|
322
|
+
/** The refusal a control instance with `execution: none` gives every launch, hosting, model and write door. */
|
|
323
|
+
const EXECUTION_NONE_REFUSAL = "execution: none forbids seat launch, workflow hosting, model inspection and caller-driven writes on this control instance; select the participant Manager with an instance-pinned manager-caller view";
|
|
324
|
+
/** The sha256 hex digest of a file's bytes. */
|
|
325
|
+
function fileDigest(path) {
|
|
326
|
+
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
327
|
+
}
|
|
328
|
+
/** The wire PRINCIPAL dot-form a managed agent's presence/control identity carries: user-mode
|
|
329
|
+
* entries already store it in `id`; static mints store the raw nkey there (the durable/teardown
|
|
330
|
+
* key), so the wire form derives under DEV_OWNER. Every comparison against an AUTHENTICATED wire
|
|
331
|
+
* id (presence card.id, control from.id) must go through this, never raw `a.id`. */
|
|
332
|
+
function managedPrincipal(a) {
|
|
333
|
+
return a.userOwner ? a.id : principalKey(DEV_OWNER, a.id).key;
|
|
334
|
+
}
|
|
335
|
+
/** How a once seat's startup watch ended, waited for until {@link STARTUP_OUTCOME_MS} after its
|
|
336
|
+
* launch or the readiness window, whichever is longer. A watch that has not ended by then, or a
|
|
337
|
+
* seat being stopped, answers what the handle reports at that moment. */
|
|
338
|
+
async function awaitStartupOutcome(a, launchedAt, readinessTimeoutMs, stopping) {
|
|
339
|
+
const until = launchedAt + Math.max(readinessTimeoutMs, STARTUP_OUTCOME_MS);
|
|
340
|
+
for (;;) {
|
|
341
|
+
const outcome = a.handle.startupOutcome?.() ?? "pending";
|
|
342
|
+
if (outcome !== "pending" || a.terminalizing || stopping() || Date.now() >= until)
|
|
343
|
+
return outcome;
|
|
344
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
345
|
+
}
|
|
346
|
+
}
|
|
421
347
|
/**
|
|
422
348
|
* The agent supervisor: a long-lived mesh node that owns agent process lifecycle.
|
|
423
349
|
* It serves control requests on the "manager" service and spawns/kills agents
|
|
@@ -579,10 +505,11 @@ export class Manager {
|
|
|
579
505
|
onceWatched = new Set();
|
|
580
506
|
/** Process start, for the served `status` uptime. */
|
|
581
507
|
startedAtMs = Date.now();
|
|
582
|
-
/** Connector harness inventory. Available paths stay pinned;
|
|
508
|
+
/** Connector harness inventory. Available paths stay pinned; unavailable rows are retried when
|
|
583
509
|
* launch, model lookup or status asks, without stopping unrelated Manager work. */
|
|
584
510
|
connectorStatuses = [];
|
|
585
511
|
connectorRequirements = new Map();
|
|
512
|
+
claudeWakeRecheck;
|
|
586
513
|
/** The boot inventory's warnings, printed once start completes, so a refused start prints none. */
|
|
587
514
|
bootNotes = [];
|
|
588
515
|
/** The complete boot task. stop() joins it after fencing static reconciliation, so a registration
|
|
@@ -615,6 +542,9 @@ export class Manager {
|
|
|
615
542
|
userMode = false;
|
|
616
543
|
namesCapacity = new NamesCapacity({
|
|
617
544
|
userMode: () => this.userMode,
|
|
545
|
+
seatCap: () => this.seatCap,
|
|
546
|
+
managerInstanceId: () => this.managerInstanceId,
|
|
547
|
+
agents: () => this.agents.values(),
|
|
618
548
|
authEnabled: () => this.auth !== undefined,
|
|
619
549
|
maintenanceActive: () => this.maintenanceState === "active",
|
|
620
550
|
roster: () => this.ep.getRoster(),
|
|
@@ -927,6 +857,28 @@ export class Manager {
|
|
|
927
857
|
shredUserSecrets: (failures, family) => this.shredUserSecrets(failures, family),
|
|
928
858
|
bearerEntryArgv,
|
|
929
859
|
});
|
|
860
|
+
/** The launch pipeline's leaf steps. Every dependency reads through at its use. */
|
|
861
|
+
seatLaunch = new SeatLaunch({
|
|
862
|
+
space: () => this.space,
|
|
863
|
+
servers: () => this.servers,
|
|
864
|
+
workspaceRoot: () => this.workspaceRoot,
|
|
865
|
+
installedExtensions: () => this.installedExtensions,
|
|
866
|
+
ep: () => this.ep,
|
|
867
|
+
auth: () => this.auth,
|
|
868
|
+
userMode: () => this.userMode,
|
|
869
|
+
managerInstanceId: () => this.managerInstanceId,
|
|
870
|
+
serviceServe: () => this.serviceServe,
|
|
871
|
+
runHosting: () => this.runHosting,
|
|
872
|
+
connectorStatuses: () => this.connectorStatuses,
|
|
873
|
+
execution: () => this.execution,
|
|
874
|
+
requiredRuntime: () => this.requiredRuntime,
|
|
875
|
+
meshMode: () => this.meshMode,
|
|
876
|
+
executionRefusal: () => this.executionRefusal(),
|
|
877
|
+
nameError: (name) => this.nameError(name),
|
|
878
|
+
canReadPersona: (owner, caller, admin) => this.canReadPersona(owner, caller, admin),
|
|
879
|
+
epAdminReach: (caller) => this.epAdminReach(caller),
|
|
880
|
+
startAgent: (opts) => this.startAgent(opts),
|
|
881
|
+
});
|
|
930
882
|
constructor(opts) {
|
|
931
883
|
if (opts.expectedConnectorGeneration !== undefined && opts.expectedConnectorGeneration !== MANAGER_VERSION)
|
|
932
884
|
throw new Error(`expected connector generation ${opts.expectedConnectorGeneration} differs from this Manager's loaded generation ${MANAGER_VERSION}; restart from the installed CLI`);
|
|
@@ -1027,7 +979,7 @@ export class Manager {
|
|
|
1027
979
|
return this.executionState.kind;
|
|
1028
980
|
}
|
|
1029
981
|
executionRefusal() {
|
|
1030
|
-
return
|
|
982
|
+
return EXECUTION_NONE_REFUSAL;
|
|
1031
983
|
}
|
|
1032
984
|
/** A defensive last barrier, not a substitute Runtime. Entry admission runs before effects. */
|
|
1033
985
|
get requiredRuntime() {
|
|
@@ -2591,9 +2543,7 @@ export class Manager {
|
|
|
2591
2543
|
}
|
|
2592
2544
|
return undefined;
|
|
2593
2545
|
}
|
|
2594
|
-
fileDigest(path) {
|
|
2595
|
-
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
2596
|
-
}
|
|
2546
|
+
fileDigest(path) { return fileDigest(path); }
|
|
2597
2547
|
fileDigestOrEmpty(path) {
|
|
2598
2548
|
try {
|
|
2599
2549
|
return this.fileDigest(path);
|
|
@@ -3333,7 +3283,7 @@ export class Manager {
|
|
|
3333
3283
|
* readiness reads the same status; the maintenance fence refuses every other command in both
|
|
3334
3284
|
* states. The read is counted in `lifecycleInFlight` like any admitted operation and released in
|
|
3335
3285
|
* `finally`, so a drain waits at most for one status snapshot; the membership gate still
|
|
3336
|
-
* applies. `preserving` and a stopping manager stay fenced.
|
|
3286
|
+
* applies. `preserving` and a stopping manager stay fenced. */
|
|
3337
3287
|
async serveObservation(ctx, fn) {
|
|
3338
3288
|
const preserved = this.maintenanceState === "preserved" && !this.resumeRequired;
|
|
3339
3289
|
const resumePending = this.maintenanceState === "active" && this.resumeRequired;
|
|
@@ -3604,7 +3554,12 @@ export class Manager {
|
|
|
3604
3554
|
vitals: (ctx) => this.serveGated(ctx, () => measureManagerVitals()),
|
|
3605
3555
|
// A remote Manager files every seat under its own owner, so only a user mesh's shared local
|
|
3606
3556
|
// Manager narrows the count, and status never waits on a remote admin check.
|
|
3607
|
-
status: (ctx) => this.serveObservation(ctx, async () =>
|
|
3557
|
+
status: (ctx) => this.serveObservation(ctx, async () => {
|
|
3558
|
+
const ownerFilter = this.remoteAuthority ? undefined : await this.psOwnerFilter(ctx.subject.caller, false);
|
|
3559
|
+
// The daemon's status deadline is shorter than an install. Report the current inventory
|
|
3560
|
+
// without waiting for the install, which has its own lifecycle admission below.
|
|
3561
|
+
return this.managerStatusData(ownerFilter, !this.resumeRequired);
|
|
3562
|
+
}),
|
|
3608
3563
|
ps: (ctx) => this.serveGated(ctx, async () => this.list(await this.psOwnerFilter(ctx.subject.caller, false))),
|
|
3609
3564
|
inspect: (ctx) => this.serveGated(ctx, async () => {
|
|
3610
3565
|
const name = String(args(ctx).name ?? "").trim();
|
|
@@ -3910,13 +3865,8 @@ export class Manager {
|
|
|
3910
3865
|
scopeOf: (owner, actor) => resolveAuthProvider().actorScope({ dir: userAuthStateDir(this.workspaceRoot, this.space), owner, actor }),
|
|
3911
3866
|
});
|
|
3912
3867
|
}
|
|
3913
|
-
/** The wire
|
|
3914
|
-
|
|
3915
|
-
* key), so the wire form derives under DEV_OWNER. Every comparison against an AUTHENTICATED wire
|
|
3916
|
-
* id (presence card.id, control from.id) must go through this, never raw `a.id`. */
|
|
3917
|
-
managedPrincipal(a) {
|
|
3918
|
-
return a.userOwner ? a.id : principalKey(DEV_OWNER, a.id).key;
|
|
3919
|
-
}
|
|
3868
|
+
/** The wire principal of a managed agent: {@link managedPrincipal}. */
|
|
3869
|
+
managedPrincipal(a) { return managedPrincipal(a); }
|
|
3920
3870
|
resumeLivenessErrors(inventory, roster) {
|
|
3921
3871
|
const inactive = [];
|
|
3922
3872
|
const expectedNames = new Set(inventory.agents.map((entry) => entry.name));
|
|
@@ -4103,7 +4053,6 @@ export class Manager {
|
|
|
4103
4053
|
})
|
|
4104
4054
|
.finally(() => this.releaseLifecycle());
|
|
4105
4055
|
}
|
|
4106
|
-
servedSpawnRequest(served, caller) { return this.userProvision.servedSpawnRequest(served, caller); }
|
|
4107
4056
|
provisionUserAgent(name, opts) { return this.userProvision.provisionUserAgent(name, opts); }
|
|
4108
4057
|
/** Shred a user agent's secret family from the store and from disk. Every removal is attempted,
|
|
4109
4058
|
* and each failure joins `unshredded`, so one fault cannot leave the rest of the family behind. */
|
|
@@ -4115,8 +4064,6 @@ export class Manager {
|
|
|
4115
4064
|
if (path)
|
|
4116
4065
|
await attemptCleanup(unshredded, `file ${path}`, () => rmSync(path, { force: true }));
|
|
4117
4066
|
}
|
|
4118
|
-
delegatedMeshRecord() { return this.userProvision.delegatedMeshRecord(); }
|
|
4119
|
-
composeManagedHandoff(enrolled, actorToken) { return this.userProvision.composeManagedHandoff(enrolled, actorToken); }
|
|
4120
4067
|
/**
|
|
4121
4068
|
* WHY A SEAT LEFT — one line, at the one place every free path passes through.
|
|
4122
4069
|
*
|
|
@@ -4280,12 +4227,6 @@ export class Manager {
|
|
|
4280
4227
|
forkProvenance(a) {
|
|
4281
4228
|
return this.sessionRecovery.forkProvenance(a);
|
|
4282
4229
|
}
|
|
4283
|
-
refuseCarriedFork(a, timeoutMs) {
|
|
4284
|
-
return this.sessionRecovery.refuseCarriedFork(a, timeoutMs);
|
|
4285
|
-
}
|
|
4286
|
-
refuseLateCarriedFork(a, timeoutMs) {
|
|
4287
|
-
return this.sessionRecovery.refuseLateCarriedFork(a, timeoutMs);
|
|
4288
|
-
}
|
|
4289
4230
|
readManagedSession(a) {
|
|
4290
4231
|
return this.sessionRecovery.readManagedSession(a);
|
|
4291
4232
|
}
|
|
@@ -4365,13 +4306,11 @@ export class Manager {
|
|
|
4365
4306
|
this.reapChildrenOf(this.managedPrincipal(a));
|
|
4366
4307
|
}
|
|
4367
4308
|
nameError(name) { return this.namesCapacity.nameError(name); }
|
|
4368
|
-
nameInUse(name, live) { return this.namesCapacity.nameInUse(name, live); }
|
|
4369
|
-
uniqueName(base, unavailable = new Set()) { return this.namesCapacity.uniqueName(base, unavailable); }
|
|
4370
4309
|
/** Spawn a teammate by persona ref (`name` loads `.cotal/agents/<name>.md`; the peer presents
|
|
4371
4310
|
* under that file's own `name:`), as if a peer asked via the control plane. Used to pre-spawn the
|
|
4372
4311
|
* demo's experts at startup so the manager owns them. */
|
|
4373
4312
|
async startByName(name) {
|
|
4374
|
-
return this.
|
|
4313
|
+
return this.seatLaunch.startByName(name);
|
|
4375
4314
|
}
|
|
4376
4315
|
/** Resolve once `name` shows up on the mesh roster (presence registered), or after `timeoutMs`.
|
|
4377
4316
|
* Lets the pre-spawn loop stagger heavy agent cold-starts so they don't all boot at once.
|
|
@@ -4379,13 +4318,7 @@ export class Manager {
|
|
|
4379
4318
|
* resolution: a same-named *unmanaged* peer already present could satisfy this early. That's
|
|
4380
4319
|
* acceptable for cold-start staggering; it never routes anything. */
|
|
4381
4320
|
async waitForPresence(name, timeoutMs = 30_000) {
|
|
4382
|
-
|
|
4383
|
-
while (Date.now() < deadline) {
|
|
4384
|
-
if (this.ep.getRoster().some((p) => p.card.name === name))
|
|
4385
|
-
return true;
|
|
4386
|
-
await new Promise((r) => setTimeout(r, 1_000));
|
|
4387
|
-
}
|
|
4388
|
-
return false;
|
|
4321
|
+
return this.seatLaunch.waitForPresence(name, timeoutMs);
|
|
4389
4322
|
}
|
|
4390
4323
|
/** Parse a served `spawn` request into {@link StartAgentOpts}. The compiled spawn input contract
|
|
4391
4324
|
* is the shape check: it already refused a non-mapping `launchOptions`, a `supervise` that is not
|
|
@@ -4476,57 +4409,11 @@ export class Manager {
|
|
|
4476
4409
|
...(served !== undefined ? { served } : {}),
|
|
4477
4410
|
}, caller, hooks, authenticatedCaller);
|
|
4478
4411
|
}
|
|
4479
|
-
/**
|
|
4480
|
-
|
|
4481
|
-
|
|
4482
|
-
|
|
4483
|
-
|
|
4484
|
-
try {
|
|
4485
|
-
cwd = realpathSync(resolved);
|
|
4486
|
-
}
|
|
4487
|
-
catch (error) {
|
|
4488
|
-
return { refusal: `path cannot be resolved: ${rejectionText(error)}` };
|
|
4489
|
-
}
|
|
4490
|
-
try {
|
|
4491
|
-
if (!statSync(cwd).isDirectory())
|
|
4492
|
-
return { refusal: "path is not a directory" };
|
|
4493
|
-
}
|
|
4494
|
-
catch (error) {
|
|
4495
|
-
return { refusal: rejectionText(error) };
|
|
4496
|
-
}
|
|
4497
|
-
return { cwd, host: hostname() };
|
|
4498
|
-
}
|
|
4499
|
-
/** Refuse host directory reads before lookup when seats cannot use this host. */
|
|
4500
|
-
assertHostDirectoryExecution() {
|
|
4501
|
-
if (this.execution === "none")
|
|
4502
|
-
throw new EpEnvelopeError("unimplemented", this.executionRefusal());
|
|
4503
|
-
if (this.execution === "runtime" && this.requiredRuntime.spawnDelegated)
|
|
4504
|
-
throw new EpEnvelopeError("failed-precondition", `runtime "${this.requiredRuntime.kind}" starts seats outside this host, so it cannot resolve a directory on this host's filesystem (cwd); the seat runs in its runtime resource's own directory`);
|
|
4505
|
-
}
|
|
4506
|
-
async listSpawnDirectory(args) {
|
|
4507
|
-
this.assertHostDirectoryExecution();
|
|
4508
|
-
const { cwd } = this.resolveSpawnCwd(args.path ?? homedir());
|
|
4509
|
-
try {
|
|
4510
|
-
return await listDirectory(cwd, args.includeHidden === true, typeof args.limit === "number" ? args.limit : 200);
|
|
4511
|
-
}
|
|
4512
|
-
catch (error) {
|
|
4513
|
-
throw new EpEnvelopeError("failed-precondition", `directory cannot be listed on this host: ${JSON.stringify(cwd)} (${rejectionText(error)})`);
|
|
4514
|
-
}
|
|
4515
|
-
}
|
|
4516
|
-
/** Resolve a placed spawn directory without creating or substituting a workspace. */
|
|
4517
|
-
resolveSpawnCwd(value) {
|
|
4518
|
-
this.assertHostDirectoryExecution();
|
|
4519
|
-
const asked = typeof value === "string" ? value : String(value ?? "");
|
|
4520
|
-
const refuse = (reason) => {
|
|
4521
|
-
throw new EpEnvelopeError("failed-precondition", `cwd does not resolve on this host: ${JSON.stringify(asked)} (${reason})`);
|
|
4522
|
-
};
|
|
4523
|
-
if (!isAbsolute(asked))
|
|
4524
|
-
refuse("expected an absolute path");
|
|
4525
|
-
const result = this.checkSpawnCwd(asked);
|
|
4526
|
-
if ("refusal" in result)
|
|
4527
|
-
return refuse(result.refusal);
|
|
4528
|
-
return result;
|
|
4529
|
-
}
|
|
4412
|
+
/** {@link SeatLaunch.checkSpawnCwd}. */
|
|
4413
|
+
checkSpawnCwd(resolved) { return this.seatLaunch.checkSpawnCwd(resolved); }
|
|
4414
|
+
listSpawnDirectory(args) { return this.seatLaunch.listSpawnDirectory(args); }
|
|
4415
|
+
/** {@link SeatLaunch.resolveSpawnCwd}. */
|
|
4416
|
+
resolveSpawnCwd(value) { return this.seatLaunch.resolveSpawnCwd(value); }
|
|
4530
4417
|
/** Resolve a connector by agent type. Library composition (installedExtensions off) → a registry
|
|
4531
4418
|
* hit, exactly as before (the composition root imported what it wants). The published binary gates
|
|
4532
4419
|
* on MANIFEST membership FIRST — so a live `cotal ext remove` is honored even though the registry
|
|
@@ -4542,11 +4429,8 @@ export class Manager {
|
|
|
4542
4429
|
throw new Error(connectorInstallHint(name));
|
|
4543
4430
|
return materializeFromManifest({ kind: "connector", name }, { hint: (ref) => connectorInstallHint(ref.name), expectedGeneration: this.expectedConnectorGeneration });
|
|
4544
4431
|
}
|
|
4545
|
-
/**
|
|
4546
|
-
|
|
4547
|
-
connectorNames() {
|
|
4548
|
-
return this.installedExtensions ? manifestExtensionNames("connector") : registry.all("connector").map((c) => c.name);
|
|
4549
|
-
}
|
|
4432
|
+
/** {@link SeatLaunch.connectorNames}. */
|
|
4433
|
+
connectorNames() { return this.seatLaunch.connectorNames(); }
|
|
4550
4434
|
/** Resolve every installed/registered connector's declared harness binaries before the manager
|
|
4551
4435
|
* reports ready. A missing harness degrades only that connector, never unrelated lifecycle work:
|
|
4552
4436
|
* boot continues, names it once start completes and records it on both manager status surfaces. */
|
|
@@ -4577,27 +4461,12 @@ export class Manager {
|
|
|
4577
4461
|
eventPlane: connector.eventChannel !== undefined,
|
|
4578
4462
|
}));
|
|
4579
4463
|
}
|
|
4580
|
-
this.connectorRequirements = new Map(declared.map(({ name, requires }) => [name,
|
|
4581
|
-
|
|
4464
|
+
this.connectorRequirements = new Map(declared.map(({ name, requires, pkg }) => [name, {
|
|
4465
|
+
requires, needsClaudeWake: !!this.machineSetupCommand && name === "claude" && pkg === OFFICIAL_CONNECTORS.claude,
|
|
4466
|
+
}]));
|
|
4467
|
+
for (const { name, requires, eventPlane } of declared) {
|
|
4582
4468
|
const { binaries, reason: missing } = resolveHarness(name, requires);
|
|
4583
|
-
|
|
4584
|
-
if (!reason && this.machineSetupCommand && name === "claude" && pkg === OFFICIAL_CONNECTORS.claude) {
|
|
4585
|
-
try {
|
|
4586
|
-
const connector = await this.resolveConnector(name);
|
|
4587
|
-
if (!connector.setup)
|
|
4588
|
-
throw new Error("Claude connector has no setup provider");
|
|
4589
|
-
const provider = await materializeFromManifest(connector.setup, { expectedGeneration: this.expectedConnectorGeneration });
|
|
4590
|
-
if (!provider.connector)
|
|
4591
|
-
throw new Error("Claude connector has no install action");
|
|
4592
|
-
const cotal = bearerEntryArgv();
|
|
4593
|
-
cotal[cotal.length - 1] = logicalExecutionEntry() ?? cotal.at(-1);
|
|
4594
|
-
await provider.connector.run({ cotal, machineHost: true });
|
|
4595
|
-
}
|
|
4596
|
-
catch (error) {
|
|
4597
|
-
const detail = oneLine(rejectionText(error).replace(/eyJ[A-Za-z0-9_.-]*/g, "<redacted>").slice(0, 800));
|
|
4598
|
-
reason = `Claude wake channel setup failed: ${detail}. Correct the cause and run \`${this.machineSetupCommand}\` on this computer.`;
|
|
4599
|
-
}
|
|
4600
|
-
}
|
|
4469
|
+
const reason = missing ?? (this.connectorRequirements.get(name)?.needsClaudeWake ? await this.prepareClaudeWake() : undefined);
|
|
4601
4470
|
if (reason) {
|
|
4602
4471
|
rows.push({ agent: name, state: "unavailable", binaries, eventPlane, reason });
|
|
4603
4472
|
this.bootNotes.push(`! manager boot: connector ${name} unavailable - ${reason}`);
|
|
@@ -4610,55 +4479,83 @@ export class Manager {
|
|
|
4610
4479
|
if (!this.classSpawnEnabled())
|
|
4611
4480
|
this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
|
|
4612
4481
|
}
|
|
4613
|
-
/**
|
|
4614
|
-
|
|
4482
|
+
/** Install and verify the hosted Claude wake channel, or report the cause and remedy. */
|
|
4483
|
+
async prepareClaudeWake() {
|
|
4484
|
+
try {
|
|
4485
|
+
const connector = await this.resolveConnector("claude");
|
|
4486
|
+
if (!connector.setup)
|
|
4487
|
+
throw new Error("Claude connector has no setup provider");
|
|
4488
|
+
const provider = await materializeFromManifest(connector.setup, { expectedGeneration: this.expectedConnectorGeneration });
|
|
4489
|
+
if (!provider.connector)
|
|
4490
|
+
throw new Error("Claude connector has no install action");
|
|
4491
|
+
const cotal = bearerEntryArgv();
|
|
4492
|
+
cotal[cotal.length - 1] = logicalExecutionEntry() ?? cotal.at(-1);
|
|
4493
|
+
await provider.connector.run({ cotal, machineHost: true });
|
|
4494
|
+
}
|
|
4495
|
+
catch (error) {
|
|
4496
|
+
const detail = oneLine(rejectionText(error).replace(/eyJ[A-Za-z0-9_.-]*/g, "<redacted>").slice(0, 800));
|
|
4497
|
+
return `Claude wake channel setup failed: ${detail}. Correct the cause and run \`${this.machineSetupCommand}\` on this computer.`;
|
|
4498
|
+
}
|
|
4499
|
+
}
|
|
4500
|
+
/** Retry unavailable applications without changing resolved available rows. Claude launches
|
|
4501
|
+
* join the status or launch that started wake setup, before any name or capacity is reserved. */
|
|
4502
|
+
refreshUnavailableConnectors(name, setupClaude = false) {
|
|
4615
4503
|
const wasEnabled = this.classSpawnEnabled();
|
|
4504
|
+
let pending;
|
|
4616
4505
|
for (const row of this.connectorStatuses) {
|
|
4617
4506
|
if (row.state !== "unavailable" || (name !== undefined && row.agent !== name))
|
|
4618
4507
|
continue;
|
|
4619
|
-
const
|
|
4620
|
-
if (!
|
|
4508
|
+
const requirements = this.connectorRequirements.get(row.agent);
|
|
4509
|
+
if (!requirements)
|
|
4621
4510
|
continue;
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
|
|
4511
|
+
if (requirements.needsClaudeWake && this.claudeWakeRecheck) {
|
|
4512
|
+
pending = this.claudeWakeRecheck;
|
|
4513
|
+
continue;
|
|
4514
|
+
}
|
|
4515
|
+
const { binaries, reason } = resolveHarness(row.agent, requirements.requires);
|
|
4516
|
+
if (reason) {
|
|
4517
|
+
row.binaries = binaries;
|
|
4625
4518
|
row.reason = reason;
|
|
4519
|
+
}
|
|
4520
|
+
else if (requirements.needsClaudeWake) {
|
|
4521
|
+
const release = setupClaude ? this.beginLifecycle(true) : undefined;
|
|
4522
|
+
if (!release)
|
|
4523
|
+
continue;
|
|
4524
|
+
pending = this.claudeWakeRecheck = this.prepareClaudeWake().then((failure) => {
|
|
4525
|
+
row.binaries = binaries;
|
|
4526
|
+
if (failure) {
|
|
4527
|
+
row.reason = failure;
|
|
4528
|
+
return;
|
|
4529
|
+
}
|
|
4530
|
+
const alreadyEnabled = this.classSpawnEnabled();
|
|
4531
|
+
row.state = "available";
|
|
4532
|
+
delete row.reason;
|
|
4533
|
+
if (!alreadyEnabled)
|
|
4534
|
+
this.servePlane.enableClassSpawn();
|
|
4535
|
+
}).finally(() => { this.claudeWakeRecheck = undefined; release(); });
|
|
4536
|
+
void pending.catch((error) => console.error(`! manager: Claude recheck failed: ${rejectionText(error)}`));
|
|
4537
|
+
}
|
|
4626
4538
|
else {
|
|
4539
|
+
row.binaries = binaries;
|
|
4627
4540
|
row.state = "available";
|
|
4628
4541
|
delete row.reason;
|
|
4629
4542
|
}
|
|
4630
4543
|
}
|
|
4631
4544
|
if (!wasEnabled && this.classSpawnEnabled())
|
|
4632
4545
|
this.servePlane.enableClassSpawn();
|
|
4546
|
+
return pending;
|
|
4633
4547
|
}
|
|
4634
|
-
/**
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
return false;
|
|
4640
|
-
return this.connectorStatuses.some((row) => row.state === "available");
|
|
4641
|
-
}
|
|
4642
|
-
omitClassCommands() {
|
|
4643
|
-
return this.classSpawnEnabled() ? undefined : ["spawn", "launch"];
|
|
4644
|
-
}
|
|
4645
|
-
/** Named harness-unavailable refusal. On the class rail a partial inventory must not look
|
|
4646
|
-
* like the space cannot launch: name `--on` so the caller can pin a sibling. The standing
|
|
4647
|
-
* serve credential cannot enumerate sibling `svc.*.status` inventories, so the residual
|
|
4648
|
-
* is the flag, not a list of capable instance ids. Instance-pinned calls keep the local
|
|
4649
|
-
* reason only. */
|
|
4650
|
-
harnessUnavailableError(reason, route) {
|
|
4651
|
-
if (route !== "one")
|
|
4652
|
-
return reason;
|
|
4653
|
-
return `${reason}. This manager cannot launch that harness. The space may have other managers; pin one with --on <instance> (the whole id, as ps prints it)`;
|
|
4654
|
-
}
|
|
4548
|
+
/** {@link SeatLaunch.classSpawnEnabled}. */
|
|
4549
|
+
classSpawnEnabled() { return this.seatLaunch.classSpawnEnabled(); }
|
|
4550
|
+
omitClassCommands() { return this.seatLaunch.omitClassCommands(); }
|
|
4551
|
+
/** {@link SeatLaunch.harnessUnavailableError}. */
|
|
4552
|
+
harnessUnavailableError(reason, route) { return this.seatLaunch.harnessUnavailableError(reason, route); }
|
|
4655
4553
|
/** The harness binaries a managed launch runs, as boot resolved them, or the refusal naming what is
|
|
4656
4554
|
* missing. Spawn, resume and the model catalog all take it, so a seat launches from the same files
|
|
4657
4555
|
* whichever path starts it and the catalog never disagrees with a launch about whether the harness
|
|
4658
|
-
* is there.
|
|
4556
|
+
* is there. Callers recheck unavailable rows first; available rows retain their resolved files.
|
|
4659
4557
|
* A connector registered after boot has no inventory row and is checked on PATH now. */
|
|
4660
4558
|
launchHarness(connector) {
|
|
4661
|
-
this.refreshUnavailableConnectors(connector.name);
|
|
4662
4559
|
const row = this.connectorStatuses.find((status) => status.agent === connector.name);
|
|
4663
4560
|
if (row?.state === "unavailable")
|
|
4664
4561
|
return { refusal: row.reason ?? `${connector.name} harness is unavailable` };
|
|
@@ -4702,49 +4599,10 @@ export class Manager {
|
|
|
4702
4599
|
return `${connector.name} connector does not support exact session continuity (continuity: exact)`;
|
|
4703
4600
|
return undefined;
|
|
4704
4601
|
}
|
|
4705
|
-
/**
|
|
4706
|
-
|
|
4707
|
-
|
|
4708
|
-
|
|
4709
|
-
return "once: a once task rides the spawn action, which this launch door is not";
|
|
4710
|
-
if (launch.prompt === undefined || launch.prompt.trim() === "")
|
|
4711
|
-
return "once: needs a prompt, which is the task";
|
|
4712
|
-
if (launch.supervise !== undefined)
|
|
4713
|
-
return "once: a once seat is never restarted, so it cannot carry supervise";
|
|
4714
|
-
if (!connector.supportsTurnRelay)
|
|
4715
|
-
return `once: the ${connector.name} connector cannot take a once task${connector.turnRelayRefusal ? `: ${connector.turnRelayRefusal}` : ""}`;
|
|
4716
|
-
if (connector.onceNeedsConfirmed !== undefined && !runtime.reportsStartupOutcome)
|
|
4717
|
-
return `once: runtime "${runtime.kind}" does not report how a seat's startup ended, which a once seat on the ${connector.name} connector needs`;
|
|
4718
|
-
if (runtime.spawnDelegated)
|
|
4719
|
-
return `once: runtime "${runtime.kind}" starts seats outside this host, where this manager cannot prove the seat's exit`;
|
|
4720
|
-
const operator = connector.waitsForOperator?.(launch.launchOptions);
|
|
4721
|
-
if (operator !== undefined)
|
|
4722
|
-
return `once: these launch options make the seat wait at ${operator} before it starts, so nothing could take its task`;
|
|
4723
|
-
// The task's relay record, measured with the widest deadline it could carry.
|
|
4724
|
-
const { note, payload } = onceTurnNote({
|
|
4725
|
-
prompt: launch.prompt, spawner: this.spawnerName(spawner),
|
|
4726
|
-
...(launch.once.deadlineMs !== undefined ? { deadlineAt: MAX_SCHEDULE_MS, holdToken: turnHoldToken("") } : {}),
|
|
4727
|
-
holdEpoch: this.serviceServe?.grant.epoch ?? 0,
|
|
4728
|
-
...(connector.retireAfterExit ? { retire: connector.name } : {}),
|
|
4729
|
-
// The longest id token core accepts (endpoint-subjects `assertIdToken`).
|
|
4730
|
-
spawn: "x".repeat(64),
|
|
4731
|
-
});
|
|
4732
|
-
if (note.length > TURN_NOTE_MAX)
|
|
4733
|
-
return `once: the prompt is too long for one task (its relay record is ${note.length} characters, over ${TURN_NOTE_MAX})`;
|
|
4734
|
-
if (connector.turnFrameLimit !== undefined) {
|
|
4735
|
-
// The text the seat shows, rendered by the seat's own function with the widest values it could
|
|
4736
|
-
// carry: the task's goal id is a digest token, and a deadline renders as one ISO instant.
|
|
4737
|
-
const text = renderOnceTask({ goalId: digestIdToken("once"), payload, spawner: this.spawnerName(spawner), ...(launch.once.deadlineMs !== undefined ? { deadlineAt: MAX_SCHEDULE_MS } : {}) });
|
|
4738
|
-
if (text.length > connector.turnFrameLimit)
|
|
4739
|
-
return `once: the prompt is too long for one ${connector.name} turn (the task renders to ${text.length} characters, over ${connector.turnFrameLimit})`;
|
|
4740
|
-
}
|
|
4741
|
-
return undefined;
|
|
4742
|
-
}
|
|
4743
|
-
/** How a once task names who sent it: the spawner's roster name, or its principal when that name is missing or only whitespace. */
|
|
4744
|
-
spawnerName(spawner) {
|
|
4745
|
-
const id = spawner ?? this.ep.ref().id;
|
|
4746
|
-
return shownSpawner(this.ep.getRoster().find((p) => p.card.id === id)?.card.name, id);
|
|
4747
|
-
}
|
|
4602
|
+
/** {@link SeatLaunch.onceRefusal}. */
|
|
4603
|
+
onceRefusal(connector, runtime, launch, spawner, hooks) { return this.seatLaunch.onceRefusal(connector, runtime, launch, spawner, hooks); }
|
|
4604
|
+
/** {@link SeatLaunch.spawnerName}. */
|
|
4605
|
+
spawnerName(spawner) { return this.seatLaunch.spawnerName(spawner); }
|
|
4748
4606
|
/** The refusal for an event-plane choice the registration policy or the connector cannot meet.
|
|
4749
4607
|
* Spawn and resume both ask before a seat's launch is built, so a seat retained without the
|
|
4750
4608
|
* plane cannot come back on a space that now requires it. An absent choice arms supported planes. */
|
|
@@ -4766,6 +4624,7 @@ export class Manager {
|
|
|
4766
4624
|
const requested = String(args.agent ?? "").trim();
|
|
4767
4625
|
const refresh = args.refresh === true;
|
|
4768
4626
|
const one = async (connector) => {
|
|
4627
|
+
await this.refreshUnavailableConnectors(connector.name, true);
|
|
4769
4628
|
const harness = this.launchHarness(connector);
|
|
4770
4629
|
if (!connector.listModels)
|
|
4771
4630
|
return { agent: connector.name, supported: false, models: [] };
|
|
@@ -4924,271 +4783,16 @@ export class Manager {
|
|
|
4924
4783
|
release();
|
|
4925
4784
|
}
|
|
4926
4785
|
}
|
|
4927
|
-
/**
|
|
4928
|
-
|
|
4929
|
-
|
|
4930
|
-
|
|
4931
|
-
|
|
4932
|
-
|
|
4933
|
-
|
|
4934
|
-
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
// a path via `--config`. It is NOT the mesh identity: the identity comes from inside the file
|
|
4938
|
-
// (`name:`), so a persona can be filed descriptively (review-critic.md) yet present under a
|
|
4939
|
-
// free-form name (socrates) — the same model `cotal spawn` already uses. You always spawn by
|
|
4940
|
-
// filename (unique on disk); two files can't collide on the key.
|
|
4941
|
-
const ref = opts.name.trim();
|
|
4942
|
-
if (!ref)
|
|
4943
|
-
return { error: "name required" };
|
|
4944
|
-
// An inline persona is its own definition, read here like a file so every later check sees a
|
|
4945
|
-
// def. It has no file until its snapshot is written, once the seat's lifecycle uid is final.
|
|
4946
|
-
if (opts.persona !== undefined) {
|
|
4947
|
-
if (opts.resolved || opts.config !== undefined || opts.identity !== undefined)
|
|
4948
|
-
return { error: "persona: an inline persona names the helper itself, so it takes no config, identity or manifest launch", code: "bad-request" };
|
|
4949
|
-
const refErr = this.nameError(ref);
|
|
4950
|
-
if (refErr)
|
|
4951
|
-
return { error: refErr };
|
|
4952
|
-
let inline;
|
|
4953
|
-
try {
|
|
4954
|
-
inline = inlinePersonaDef(ref, opts.persona);
|
|
4955
|
-
}
|
|
4956
|
-
catch (e) {
|
|
4957
|
-
return { error: rejectionText(e), code: "bad-request" };
|
|
4958
|
-
}
|
|
4959
|
-
// A save under a name the catalog already holds is refused here, before anything is allocated,
|
|
4960
|
-
// so the refusal starts nothing. The create-only write after the grant settles a race.
|
|
4961
|
-
if (inline.save) {
|
|
4962
|
-
const target = agentFilePath(this.workspaceRoot, ref);
|
|
4963
|
-
let taken = true;
|
|
4964
|
-
try {
|
|
4965
|
-
lstatSync(target);
|
|
4966
|
-
}
|
|
4967
|
-
catch (e) {
|
|
4968
|
-
if (e.code !== "ENOENT")
|
|
4969
|
-
return { error: `persona.save: ${rejectionText(e)}` };
|
|
4970
|
-
taken = false;
|
|
4971
|
-
}
|
|
4972
|
-
if (taken)
|
|
4973
|
-
return { error: `persona.save: the catalog already holds a persona named "${ref}" (${target}). Spawn that persona by name, or pick another name to save this one under` };
|
|
4974
|
-
}
|
|
4975
|
-
return { ref, def: inline.def, agent: resolveAgentType({ flag: opts.agent, pin: undefined, callerDefault: opts.defaultAgent }), inline: { save: inline.save } };
|
|
4976
|
-
}
|
|
4977
|
-
// A bare ref maps to `.cotal/agents/<ref>.md`, so it must be a safe token (no path traversal); a
|
|
4978
|
-
// `--config` path is validated by existsSync below instead.
|
|
4979
|
-
if (!opts.config) {
|
|
4980
|
-
const refErr = this.nameError(ref);
|
|
4981
|
-
if (refErr)
|
|
4982
|
-
return { error: refErr };
|
|
4983
|
-
}
|
|
4984
|
-
// Resolve the persona file (fail loud — NO silent default-ACL fallback). A missing persona used
|
|
4985
|
-
// to mint DEFAULT creds (read `general` only, default-deny publish, no capabilities), so a
|
|
4986
|
-
// typo'd / renamed / spawned-by-display-name agent became live with silently-wrong ACLs — a
|
|
4987
|
-
// behavioral/security bug. Fail loud instead, matching `cotal spawn` (loadAgentFile throws).
|
|
4988
|
-
// This runs BEFORE the spawn path resolves its connector: the file's `agent:` pin participates in
|
|
4989
|
-
// the harness choice (flag > file > COTAL_DEFAULT_AGENT > default, #869), which is impossible if
|
|
4990
|
-
// the connector is materialized first.
|
|
4991
|
-
let configPath;
|
|
4992
|
-
if (opts.config) {
|
|
4993
|
-
configPath = agentFilePath(this.workspaceRoot, opts.config);
|
|
4994
|
-
if (!existsSync(configPath))
|
|
4995
|
-
return { error: `agent file not found: ${configPath}` };
|
|
4996
|
-
}
|
|
4997
|
-
else {
|
|
4998
|
-
configPath = agentFilePath(this.workspaceRoot, ref);
|
|
4999
|
-
if (!existsSync(configPath))
|
|
5000
|
-
return { error: `no persona "${ref}" in the catalog of manager ${this.managerInstanceId} on host ${hostname()}: ${configPath} not found; create it there` };
|
|
5001
|
-
}
|
|
5002
|
-
// An inline snapshot belongs to its own seat's lifecycle, which removes it at retirement and
|
|
5003
|
-
// refuses a restart once it changed, so no other launch may read it. Compared after symlinks
|
|
5004
|
-
// resolve, for a config path and a catalog entry alike.
|
|
5005
|
-
if (!opts.resolved && this.insideInlineDir(configPath))
|
|
5006
|
-
return { error: `${configPath} is an inline persona's snapshot, which belongs to the seat it was written for; spawn a saved persona by name, or pass the persona inline` };
|
|
5007
|
-
// Load the persona ONCE, here, ahead of the connector choice. The file's `agent:` pin feeds the
|
|
5008
|
-
// harness resolution below; the spawn path's identity/ACL profile block consumes the SAME def (no
|
|
5009
|
-
// second load). A manifest launch (`resolved`) materializes its own transient persona and the
|
|
5010
|
-
// file is NOT its authority, so its def (and its agent pin) is deliberately not consulted here —
|
|
5011
|
-
// the manifest's own `agent:` field drove the launch object already.
|
|
5012
|
-
let def;
|
|
5013
|
-
if (!opts.resolved) {
|
|
5014
|
-
try {
|
|
5015
|
-
def = loadLaunchPersonaFile(configPath);
|
|
5016
|
-
}
|
|
5017
|
-
catch (e) {
|
|
5018
|
-
return { error: rejectionText(e), ...(e instanceof PersonaSourceError ? { code: "bad-request" } : {}) };
|
|
5019
|
-
}
|
|
5020
|
-
// Shared operator files remain launchable. Owned content follows the catalog's visibility
|
|
5021
|
-
// decision before connector loading or any allocation. A hosted run acts for its admission;
|
|
5022
|
-
// only a complete authenticated caller can request the current ledger's admin decision.
|
|
5023
|
-
if (this.userMode && def.owner !== undefined) {
|
|
5024
|
-
const acting = authenticatedCaller === undefined ? undefined
|
|
5025
|
-
: this.runHosting?.admittedCaller(authenticatedCaller) ?? authenticatedCaller;
|
|
5026
|
-
const personaCaller = acting === undefined ? spawner ?? "" : principalKey(acting.owner, acting.actor).key;
|
|
5027
|
-
const admin = authenticatedCaller !== undefined && await this.epAdminReach(authenticatedCaller);
|
|
5028
|
-
if (!this.canReadPersona(def.owner, personaCaller, admin))
|
|
5029
|
-
return { error: `no persona "${ref}"` };
|
|
5030
|
-
}
|
|
5031
|
-
}
|
|
5032
|
-
return { ref, configPath, def, agent: resolveAgentType({ flag: opts.agent, pin: def?.agent, callerDefault: opts.defaultAgent }) };
|
|
5033
|
-
}
|
|
5034
|
-
/** Whether a persona path resolves into the inline snapshot directory, the directory itself
|
|
5035
|
-
* included. A directory that does not exist holds nothing. */
|
|
5036
|
-
insideInlineDir(path) {
|
|
5037
|
-
const dir = inlinePersonaDir(this.workspaceRoot);
|
|
5038
|
-
if (!existsSync(dir))
|
|
5039
|
-
return false;
|
|
5040
|
-
const real = realpathSync(path);
|
|
5041
|
-
const realDir = realpathSync(dir);
|
|
5042
|
-
return real === realDir || real.startsWith(realDir + sep);
|
|
5043
|
-
}
|
|
5044
|
-
/** The run a spawn acts for (SPEC 14.8). The run this manager drives under `caller` answers from
|
|
5045
|
-
* memory. On a static mesh, a spawn from a run hosted elsewhere names its run, whether the program
|
|
5046
|
-
* placed it here or the class queue delivered it, and its caller must be that run's driver, whose
|
|
5047
|
-
* triple derives from the run id; the run's admission and revocation marker are then read
|
|
5048
|
-
* leader-served, so the helper is bounded as the hosting manager bounds it. Elsewhere the run id
|
|
5049
|
-
* is not read: a user-auth run's issuing host bounds the helper, and an open mesh bounds none.
|
|
5050
|
-
* `undefined` for a spawn that acts for no run. */
|
|
5051
|
-
async spawnRun(caller, runId) {
|
|
5052
|
-
const hosted = caller !== undefined ? this.runHosting?.runAdmission(caller) : undefined;
|
|
5053
|
-
if (hosted !== undefined) {
|
|
5054
|
-
if (runId !== undefined && runId !== hosted.runId)
|
|
5055
|
-
return { refused: `it names run ${runId}, but its caller drives run ${hosted.runId}` };
|
|
5056
|
-
return { admission: hosted, hosted: true };
|
|
5057
|
-
}
|
|
5058
|
-
if (runId === undefined || this.meshMode !== "static")
|
|
5059
|
-
return undefined;
|
|
5060
|
-
let driver;
|
|
5061
|
-
try {
|
|
5062
|
-
driver = caller !== undefined ? runDriverCaller(runId, caller.owner) : undefined;
|
|
5063
|
-
}
|
|
5064
|
-
catch (e) {
|
|
5065
|
-
return { refused: `runId ${JSON.stringify(runId)} is not a run id (${rejectionText(e)})` };
|
|
5066
|
-
}
|
|
5067
|
-
if (driver === undefined || driver.actor !== caller.actor || driver.uid !== caller.uid)
|
|
5068
|
-
return { refused: `it names run ${runId}, but its caller is not that run's driver` };
|
|
5069
|
-
if (this.runHosting === undefined)
|
|
5070
|
-
return { refused: `run ${runId} asked this manager for a helper, but this manager hosts no runs, so it cannot read the run's admission` };
|
|
5071
|
-
let view;
|
|
5072
|
-
try {
|
|
5073
|
-
view = await this.runHosting.admission(runId);
|
|
5074
|
-
}
|
|
5075
|
-
catch (e) {
|
|
5076
|
-
return { refused: `run ${runId}'s admission and revocation marker could not be read (${rejectionText(e)}), so it starts no helper (SPEC 14.8)` };
|
|
5077
|
-
}
|
|
5078
|
-
if (view.revoked !== undefined)
|
|
5079
|
-
return { refused: revokedRunRefusal(runId, view.revoked) };
|
|
5080
|
-
return { admission: view.admission, hosted: false };
|
|
5081
|
-
}
|
|
5082
|
-
/**
|
|
5083
|
-
* Resolve what bounds a spawn's grant on a STATIC mesh: the caller's issued evidence, read the way
|
|
5084
|
-
* keyed runs read it. A user-auth mesh bounds the mint on its ledger instead, and an open mesh
|
|
5085
|
-
* mints no grant, so both return `exempt`. So does a call with no authenticated caller, which is
|
|
5086
|
-
* the manager's own composition root (roster boot, a manifest `launch`, which a static mesh mints
|
|
5087
|
-
* only into operator instruments). A workflow run's spawn, whether this manager hosts the run or
|
|
5088
|
-
* its spawn reached this manager from another host ({@link spawnRun}), is bounded by the run's admission (SPEC 14.8):
|
|
5089
|
-
* the ceiling it recorded, at the starter's coordinate, unless the starter was exempt then. That
|
|
5090
|
-
* ceiling is the starter's evidence as resolved at admission, or for a local run the channels the
|
|
5091
|
-
* operator named. Any other caller with no issued generation, or whose evidence does not resolve,
|
|
5092
|
-
* hands on no grant. The evidence's own standing decides the rest.
|
|
5093
|
-
*/
|
|
5094
|
-
async staticSpawnBound(caller, run) {
|
|
5095
|
-
if (this.meshMode !== "static" || caller === undefined)
|
|
5096
|
-
return { kind: "exempt" };
|
|
5097
|
-
// The driver's own credential is not the run's authority, and the starter's evidence may have
|
|
5098
|
-
// expired or changed since: the admission recorded both the ceiling and the verdict.
|
|
5099
|
-
if (run !== undefined) {
|
|
5100
|
-
const admission = run.admission;
|
|
5101
|
-
// Read leader-served before each of the run's spawns, so a run revoked mid-step starts no
|
|
5102
|
-
// helper, and a marker this manager cannot read refuses the spawn too. The marker of a run
|
|
5103
|
-
// hosted elsewhere was read with its admission.
|
|
5104
|
-
let refusal;
|
|
5105
|
-
if (run.hosted)
|
|
5106
|
-
try {
|
|
5107
|
-
const revoked = (await this.runHosting.admission(admission.runId)).revoked;
|
|
5108
|
-
if (revoked !== undefined)
|
|
5109
|
-
refusal = revokedRunRefusal(admission.runId, revoked);
|
|
5110
|
-
}
|
|
5111
|
-
catch (e) {
|
|
5112
|
-
refusal = `run ${admission.runId}'s revocation marker could not be read (${rejectionText(e)}), so it starts no helper (SPEC 14.8)`;
|
|
5113
|
-
}
|
|
5114
|
-
if (refusal !== undefined)
|
|
5115
|
-
return { kind: "refused", reason: refusal };
|
|
5116
|
-
if (admission.spawnExempt)
|
|
5117
|
-
return { kind: "exempt" };
|
|
5118
|
-
// The helper is projected at the admitted coordinate, which needs a lifecycle token. A local
|
|
5119
|
-
// admission written before its uid was one records the CLI's own holder id, and bounds nothing.
|
|
5120
|
-
try {
|
|
5121
|
-
assertLifecycleToken(admission.caller.uid);
|
|
5122
|
-
}
|
|
5123
|
-
catch {
|
|
5124
|
-
return { kind: "refused", reason: `run ${admission.runId}'s admission records caller uid ${JSON.stringify(admission.caller.uid)}, which is not a lifecycle token, so its helpers cannot be measured and it starts none. Start the run again (SPEC 14.8)` };
|
|
5125
|
-
}
|
|
5126
|
-
return { kind: "bounded", caller: admission.caller, ceiling: admission.ceiling, run: admission.runId };
|
|
5127
|
-
}
|
|
5128
|
-
if (!isIssuedCaller(caller))
|
|
5129
|
-
return { kind: "none", reason: "its credential carries no issued generation (an unissued mint or a legacy rail)" };
|
|
5130
|
-
const ref = { space: this.space, owner: caller.owner, actor: caller.actor, uid: caller.uid, generation: caller.generation };
|
|
5131
|
-
try {
|
|
5132
|
-
const { evidence } = await withIssuerSession({ servers: this.servers ?? DEFAULT_SERVER, space: this.space, auth: this.auth, tls: false }, (s) => s.store.resolve(ref, s.sourceIsLive));
|
|
5133
|
-
return issuedSpawnerStanding(evidence) === "bounded" ? { kind: "bounded", caller, ceiling: evidence.permissions } : { kind: "exempt" };
|
|
5134
|
-
}
|
|
5135
|
-
catch (e) {
|
|
5136
|
-
return { kind: "none", reason: `its issued evidence does not resolve: ${rejectionText(e)}` };
|
|
5137
|
-
}
|
|
5138
|
-
}
|
|
5139
|
-
/** The refusal for a grant its static spawner does not hold, or `undefined` when it holds all of
|
|
5140
|
-
* it. Each part is named, so the caller can drop exactly what overreached. `armsEvents` is whether
|
|
5141
|
-
* the helper's own event plane will be minted: that row is keyed on a principal allocated later,
|
|
5142
|
-
* so it is measured as the spawner's own, the rule the ledger applies. `door` names the command
|
|
5143
|
-
* being bounded: a persona definition is bounded against its definer as a spawn is. */
|
|
5144
|
-
spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") {
|
|
5145
|
-
if (bound.kind === "exempt")
|
|
5146
|
-
return undefined;
|
|
5147
|
-
if (bound.kind === "refused")
|
|
5148
|
-
return `${door}: ${bound.reason}`;
|
|
5149
|
-
let over;
|
|
5150
|
-
let eventsOver;
|
|
5151
|
-
try {
|
|
5152
|
-
over = bound.kind === "none" ? grantParts(grant) : grantOverreach(this.space, bound.caller, bound.ceiling, grant);
|
|
5153
|
-
eventsOver = armsEvents && (bound.kind === "none"
|
|
5154
|
-
|| grantOverreach(this.space, bound.caller, bound.ceiling, { allowPublish: [eventChannel({ owner: bound.caller.owner, actor: bound.caller.actor })] }).length > 0);
|
|
5155
|
-
}
|
|
5156
|
-
catch (e) {
|
|
5157
|
-
return `${door}: ${rejectionText(e)}`;
|
|
5158
|
-
}
|
|
5159
|
-
if (!over.length && !eventsOver)
|
|
5160
|
-
return undefined;
|
|
5161
|
-
const named = [
|
|
5162
|
-
// A role is handed on by a spawner whose credential binds that role's task queue: its own
|
|
5163
|
-
// role, or a `role:<r>` token in its capabilities.
|
|
5164
|
-
...over.map((o) => o.field === "role" ? `role ${o.value} (a spawner hands on a role it was given as its own or as the \`role:${o.value}\` capability)` : `${o.field} ${o.value}`),
|
|
5165
|
-
...(eventsOver ? ["events (the helper's own event plane; pass events: false to spawn without it)"] : []),
|
|
5166
|
-
].join(", ");
|
|
5167
|
-
if (door === "define-persona")
|
|
5168
|
-
return bound.kind === "none"
|
|
5169
|
-
? `define-persona: the definer holds no issued evidence (SPEC 13.15), so its persona can grant nothing: ${bound.reason}. This persona asks for ${named}. ` +
|
|
5170
|
-
`Define it without these, or start the definer under a manager (\`cotal spawn --detach\`), whose seats carry issued evidence.`
|
|
5171
|
-
: `define-persona: this persona grants more than the definer holds: ${named}. A definer hands on only what its own issued credential carries (SPEC 13.15). ` +
|
|
5172
|
-
`Drop these from the persona, or have the operator widen the definer's own persona.`;
|
|
5173
|
-
if (bound.kind === "bounded" && bound.run !== undefined)
|
|
5174
|
-
return `spawn: this spawn hands its helper more than run ${bound.run}'s starter held when the run was admitted: ${named}. ` +
|
|
5175
|
-
`A run hands on only what its admission recorded: its starter's issued credential, or for a \`--local\` run the channels named by \`--admit-read\` and \`--admit-publish\` (SPEC 14.8). ` +
|
|
5176
|
-
`Drop these from the persona or the spawn, or start the run from a caller that holds them.`;
|
|
5177
|
-
return bound.kind === "none"
|
|
5178
|
-
? `spawn: the spawner holds no issued evidence (SPEC 13.15), so it hands on no grant: ${bound.reason}. This spawn asks for ${named}. ` +
|
|
5179
|
-
`Spawn a persona that names none of these, or start the spawner under a manager (\`cotal spawn --detach\`), whose seats carry issued evidence.`
|
|
5180
|
-
: `spawn: this spawn hands its helper more than the spawner holds: ${named}. A spawner hands on only what its own issued credential carries (SPEC 13.15). ` +
|
|
5181
|
-
`Drop these from the persona or the spawn, or have the operator widen the spawner's own persona.`;
|
|
5182
|
-
}
|
|
5183
|
-
/** Ordinary static control seats can read their holding instance. A run's recorded ceiling is
|
|
5184
|
-
* authoritative, so its helpers receive no additional instance reads. */
|
|
5185
|
-
managedStaticInstanceReads(capabilities) {
|
|
5186
|
-
if (this.meshMode !== "static" || !this.managerInstanceId || !capabilities?.some(c => c === "spawn" || c === "run" || c === "admin"))
|
|
5187
|
-
return [];
|
|
5188
|
-
return ["describe", "inspect"].map(command => ({
|
|
5189
|
-
endpoint: MANAGER_ENDPOINT, command, instanceId: this.managerInstanceId, instanceOnly: true,
|
|
5190
|
-
}));
|
|
5191
|
-
}
|
|
4786
|
+
/** {@link SeatLaunch.spawnPersona}. */
|
|
4787
|
+
spawnPersona(...args) { return this.seatLaunch.spawnPersona(...args); }
|
|
4788
|
+
/** {@link SeatLaunch.spawnRun}. */
|
|
4789
|
+
spawnRun(caller, runId) { return this.seatLaunch.spawnRun(caller, runId); }
|
|
4790
|
+
/** {@link SeatLaunch.staticSpawnBound}. */
|
|
4791
|
+
staticSpawnBound(caller, run) { return this.seatLaunch.staticSpawnBound(caller, run); }
|
|
4792
|
+
/** {@link SeatLaunch.spawnBoundRefusal}. */
|
|
4793
|
+
spawnBoundRefusal(bound, grant, armsEvents, door = "spawn") { return this.seatLaunch.spawnBoundRefusal(bound, grant, armsEvents, door); }
|
|
4794
|
+
/** {@link SeatLaunch.managedStaticInstanceReads}. */
|
|
4795
|
+
managedStaticInstanceReads(capabilities) { return this.seatLaunch.managedStaticInstanceReads(capabilities); }
|
|
5192
4796
|
async startAgentActive(opts, spawner, hooks, authenticatedCaller) {
|
|
5193
4797
|
// Before the first await, so the grant, the launch, the retained form and the restart slot all read
|
|
5194
4798
|
// the lists and the restart policy as admitted.
|
|
@@ -5256,13 +4860,19 @@ export class Manager {
|
|
|
5256
4860
|
const readinessTimeoutMs = connector.readinessTimeoutMs ?? this.readinessTimeoutMs;
|
|
5257
4861
|
if (!Number.isSafeInteger(readinessTimeoutMs) || readinessTimeoutMs <= 0)
|
|
5258
4862
|
return { ok: false, error: `connector ${connector.name} declares invalid readinessTimeoutMs ${JSON.stringify(connector.readinessTimeoutMs)}; expected a positive safe integer` };
|
|
5259
|
-
//
|
|
5260
|
-
//
|
|
5261
|
-
//
|
|
5262
|
-
|
|
5263
|
-
const occupancy = this.occupancy(); // prunes expired cooling stamps; counts each name once
|
|
4863
|
+
// Fail fast when full. If hosted Claude has to await wake setup, resample capacity after it.
|
|
4864
|
+
// The final capacity check and the reserve below stay in the same tick or two concurrent
|
|
4865
|
+
// spawns could overshoot the ceiling or pick the same name.
|
|
4866
|
+
let occupancy = this.namesCapacity.occupancy(); // prunes expired cooling stamps; counts each name once
|
|
5264
4867
|
if (occupancy.used >= MAX_AGENTS)
|
|
5265
|
-
return { ok: false, error: this.capacityRefusal(occupancy) };
|
|
4868
|
+
return { ok: false, error: this.namesCapacity.capacityRefusal(occupancy) };
|
|
4869
|
+
const recheck = this.refreshUnavailableConnectors(connector.name, true);
|
|
4870
|
+
if (recheck) {
|
|
4871
|
+
await recheck;
|
|
4872
|
+
occupancy = this.namesCapacity.occupancy();
|
|
4873
|
+
if (occupancy.used >= MAX_AGENTS)
|
|
4874
|
+
return { ok: false, error: this.namesCapacity.capacityRefusal(occupancy) };
|
|
4875
|
+
}
|
|
5266
4876
|
// Harness preflight before reserving a slot or minting — a missing `claude`/`opencode` binary
|
|
5267
4877
|
// fails here with a clear name, not obscurely at process spawn. No fallback. All synchronous, so
|
|
5268
4878
|
// the reserve gate stays atomic. (The connector itself was resolved up top, before the capacity gate.)
|
|
@@ -5332,7 +4942,7 @@ export class Manager {
|
|
|
5332
4942
|
if (!this.remoteAuthority?.enrollManagedAgent)
|
|
5333
4943
|
return { ok: false, error: `${delegatedBy}, which needs a host that enrolls managed agents (remoteAuthority.enrollManagedAgent); a delegated seat has no local grant path` };
|
|
5334
4944
|
try {
|
|
5335
|
-
this.delegatedMeshRecord();
|
|
4945
|
+
this.userProvision.delegatedMeshRecord();
|
|
5336
4946
|
}
|
|
5337
4947
|
catch (e) {
|
|
5338
4948
|
return { ok: false, error: rejectionText(e) };
|
|
@@ -5513,7 +5123,7 @@ export class Manager {
|
|
|
5513
5123
|
return { ok: false, error: "model: must not be empty" };
|
|
5514
5124
|
if (variant !== undefined && !variant.trim())
|
|
5515
5125
|
return { ok: false, error: "variant: must not be empty" };
|
|
5516
|
-
const idErr = this.nameError(identityName);
|
|
5126
|
+
const idErr = this.namesCapacity.nameError(identityName);
|
|
5517
5127
|
if (idErr)
|
|
5518
5128
|
return { ok: false, error: opts.resolved ? `launch agent: ${idErr}` : `persona ${where}: ${idErr}` };
|
|
5519
5129
|
// #966: a seat labelled `manager` that cannot spawn is a worker wearing a label, and the label
|
|
@@ -5569,7 +5179,7 @@ export class Manager {
|
|
|
5569
5179
|
const held = this.retirement.held(identityName);
|
|
5570
5180
|
if (held !== undefined) {
|
|
5571
5181
|
hooks?.onEffect?.();
|
|
5572
|
-
void this.deprovision(held.target).catch(() => { });
|
|
5182
|
+
void this.retirement.deprovision(held.target).catch(() => { });
|
|
5573
5183
|
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" });
|
|
5574
5184
|
return { ok: false, error: renderLifecycleBlocked(err.message, err), details: err.details };
|
|
5575
5185
|
}
|
|
@@ -5625,13 +5235,13 @@ export class Manager {
|
|
|
5625
5235
|
let name;
|
|
5626
5236
|
for (;;) {
|
|
5627
5237
|
if (hardPinned) {
|
|
5628
|
-
if (this.nameInUse(identityName))
|
|
5238
|
+
if (this.namesCapacity.nameInUse(identityName))
|
|
5629
5239
|
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` };
|
|
5630
5240
|
name = identityName;
|
|
5631
5241
|
}
|
|
5632
5242
|
else {
|
|
5633
5243
|
try {
|
|
5634
|
-
name = this.uniqueName(identityName, unavailable);
|
|
5244
|
+
name = this.namesCapacity.uniqueName(identityName, unavailable);
|
|
5635
5245
|
}
|
|
5636
5246
|
catch (e) {
|
|
5637
5247
|
return { ok: false, error: rejectionText(e) };
|
|
@@ -5672,7 +5282,7 @@ export class Manager {
|
|
|
5672
5282
|
}
|
|
5673
5283
|
// Another spawn may have reserved the candidate while the disk/broker proof awaited.
|
|
5674
5284
|
// Recheck in the same synchronous window as the cap and reservation below.
|
|
5675
|
-
if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
|
|
5285
|
+
if (this.namesCapacity.nameInUse(name) || (!hardPinned && name !== identityName && this.namesCapacity.numberedIssued(name))) {
|
|
5676
5286
|
if (!hardPinned)
|
|
5677
5287
|
continue;
|
|
5678
5288
|
return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
|
|
@@ -5733,7 +5343,7 @@ export class Manager {
|
|
|
5733
5343
|
// launch. Minting it inside `runtime.spawn` (as it used to be) put the processes on disk
|
|
5734
5344
|
// before anything recorded how to address them, so a crash in that window left a live seat
|
|
5735
5345
|
// outside every manager and the successor retired the slot over it.
|
|
5736
|
-
const custody = this.reserveCustody(runtime);
|
|
5346
|
+
const custody = this.seatCustody.reserveCustody(runtime);
|
|
5737
5347
|
// ACCEPT SEAM (spawn-as-action): the incarnation identity is minted and NOTHING has
|
|
5738
5348
|
// been provisioned yet — the action serve path binds the goal + replies the acceptance HERE. A
|
|
5739
5349
|
// throw (bind conflict / duplicate goalId) aborts the spawn before provisioning: the catch below
|
|
@@ -5831,7 +5441,7 @@ export class Manager {
|
|
|
5831
5441
|
lifecycleUid,
|
|
5832
5442
|
enrollmentCaller: authenticatedCaller ? { owner: authenticatedCaller.owner, actor: authenticatedCaller.actor } : undefined,
|
|
5833
5443
|
delegatedIntent: opts.delegatedIntent,
|
|
5834
|
-
...(opts.served !== undefined ? { spawnRequest: this.servedSpawnRequest(opts.served, authenticatedCaller) } : {}),
|
|
5444
|
+
...(opts.served !== undefined ? { spawnRequest: this.userProvision.servedSpawnRequest(opts.served, authenticatedCaller) } : {}),
|
|
5835
5445
|
// Hold the name at the UID the host enrolled for the intent's user before any later local
|
|
5836
5446
|
// step runs, so no later failure, its refusal included, releases a lifecycle that only that
|
|
5837
5447
|
// user's retirement intent retires.
|
|
@@ -5994,13 +5604,13 @@ export class Manager {
|
|
|
5994
5604
|
let spec;
|
|
5995
5605
|
let handle;
|
|
5996
5606
|
if (runtime.spawnDelegated) {
|
|
5997
|
-
const handoff = this.composeManagedHandoff(enrolled.material, enrolled.actorToken);
|
|
5607
|
+
const handoff = this.userProvision.composeManagedHandoff(enrolled.material, enrolled.actorToken);
|
|
5998
5608
|
if (this.delegatedLaunched.has(lifecycleUid))
|
|
5999
5609
|
throw new Error(`lifecycle ${lifecycleUid} was already handed to runtime "${runtime.kind}"; a lifecycle is handed off at most once`);
|
|
6000
5610
|
this.delegatedLaunched.add(lifecycleUid);
|
|
6001
5611
|
const holder = retainConnectorSeat(this.managerInstanceId, name);
|
|
6002
5612
|
handle = runtime.spawnDelegated({ agent, persona: readFileSync(configPath, "utf8"), managerInstanceId: this.managerInstanceId, role, model, variant, prompt, launchOptions: launchOptions, events, eventPayloads }, handoff);
|
|
6003
|
-
|
|
5613
|
+
watchConnectorHolder(handle, holder);
|
|
6004
5614
|
}
|
|
6005
5615
|
else {
|
|
6006
5616
|
if (carried) {
|
|
@@ -6012,7 +5622,7 @@ export class Manager {
|
|
|
6012
5622
|
if (carried)
|
|
6013
5623
|
this.transcripts.consume(opts.resumeClaim, opts.resume);
|
|
6014
5624
|
spec.env = { ...spec.env, COTAL_MANAGER_INSTANCE: this.managerInstanceId };
|
|
6015
|
-
handle = await this.spawnCustodied(runtime, name, spec, cwd, custody);
|
|
5625
|
+
handle = await this.seatCustody.spawnCustodied(runtime, name, spec, cwd, custody);
|
|
6016
5626
|
}
|
|
6017
5627
|
if (onceTask && !handle.waitForExit)
|
|
6018
5628
|
throw new Error(`once: runtime "${handle.kind}" cannot prove the seat's exit, which is what ends its task when the seat goes first`);
|
|
@@ -6106,8 +5716,7 @@ export class Manager {
|
|
|
6106
5716
|
await casStaticSlot(t, { ...slot.row, phase: "active", ...(handle.reference ? { runtime: handle.reference } : {}) }, slot.revision);
|
|
6107
5717
|
});
|
|
6108
5718
|
}
|
|
6109
|
-
this.
|
|
6110
|
-
this.namesCapacity.placed(name);
|
|
5719
|
+
this.place(name, managed);
|
|
6111
5720
|
if (managed.once)
|
|
6112
5721
|
this.watchOnceExit(managed);
|
|
6113
5722
|
// The live slot now owns teardown — freeSlot deprovisions this identity on exit — so the
|
|
@@ -6145,13 +5754,12 @@ export class Manager {
|
|
|
6145
5754
|
if (!readiness.ok) {
|
|
6146
5755
|
this.watchExit(managed);
|
|
6147
5756
|
if (managed.launch.carried)
|
|
6148
|
-
void this.refuseLateCarriedFork(managed, readinessTimeoutMs);
|
|
5757
|
+
void this.sessionRecovery.refuseLateCarriedFork(managed, readinessTimeoutMs);
|
|
6149
5758
|
// A once seat is never left running with nothing to do, and its stop does not wait on the
|
|
6150
5759
|
// spawn's terminal, whose write can stall. The spawn keeps that terminal: the stop lets go
|
|
6151
5760
|
// of the spawn goal first. Its task was never served and is cancelled with the verdict.
|
|
6152
5761
|
if (managed.once) {
|
|
6153
|
-
this.
|
|
6154
|
-
this.stopOnceSeat(managed, "readiness-timeout");
|
|
5762
|
+
this.endOnceBeforeServe(managed, "readiness-timeout");
|
|
6155
5763
|
}
|
|
6156
5764
|
await hooks?.onOutcome?.({ kind: "uncertain", data: { reason: readiness.detail, ...(readiness.running ? { running: true } : {}) } });
|
|
6157
5765
|
return { ok: false, error: readiness.detail };
|
|
@@ -6169,9 +5777,7 @@ export class Manager {
|
|
|
6169
5777
|
const watch = { ready: "opened its input screen without the prompt", failed: "failed", exited: "saw the seat exit", pending: "had not ended" }[startup];
|
|
6170
5778
|
const error = `${name} joined, but ${connector.onceNeedsConfirmed}: its startup watch ${watch}, so it cannot take a once task`;
|
|
6171
5779
|
this.watchExit(managed);
|
|
6172
|
-
this.
|
|
6173
|
-
managed.once.stopReason ??= "launch-failed";
|
|
6174
|
-
this.stopOnceSeat(managed, "launch-failed");
|
|
5780
|
+
this.endOnceBeforeServe(managed, "launch-failed", "launch-failed");
|
|
6175
5781
|
await hooks?.onOutcome?.({ kind: "failed", data: { error } });
|
|
6176
5782
|
return { ok: false, error };
|
|
6177
5783
|
}
|
|
@@ -6191,14 +5797,13 @@ export class Manager {
|
|
|
6191
5797
|
}
|
|
6192
5798
|
}
|
|
6193
5799
|
if (managed.launch.carried) {
|
|
6194
|
-
const refused = await this.refuseCarriedFork(managed, readinessTimeoutMs);
|
|
5800
|
+
const refused = await this.sessionRecovery.refuseCarriedFork(managed, readinessTimeoutMs);
|
|
6195
5801
|
if (refused !== undefined && managed.terminalizing) {
|
|
6196
5802
|
hooks?.onTerminalDeferred?.();
|
|
6197
5803
|
return { ok: false, error: refused };
|
|
6198
5804
|
}
|
|
6199
5805
|
if (refused !== undefined) {
|
|
6200
|
-
this.
|
|
6201
|
-
this.trackStoppedHandle(managed, true, "carried-fork-refused");
|
|
5806
|
+
this.stopAndTrack(managed, "carried-fork-refused");
|
|
6202
5807
|
await hooks?.onOutcome?.({ kind: "failed", data: { error: refused } });
|
|
6203
5808
|
return { ok: false, error: refused };
|
|
6204
5809
|
}
|
|
@@ -6206,23 +5811,22 @@ export class Manager {
|
|
|
6206
5811
|
if (managed.restart) {
|
|
6207
5812
|
if (connector.supportsSessionContinuation) {
|
|
6208
5813
|
try {
|
|
6209
|
-
await this.armSessionRecovery(managed);
|
|
5814
|
+
await this.sessionRecovery.armSessionRecovery(managed);
|
|
6210
5815
|
// The capability flags are only a claim. An exact seat is recorded once the connector
|
|
6211
5816
|
// has proved its session over its authenticated control endpoint, never before.
|
|
6212
5817
|
if (exact && !managed.restart.armed)
|
|
6213
5818
|
throw new Error("continuity: exact needs the connector to prove its session over an authenticated control endpoint, and it supplied none");
|
|
6214
|
-
managed.launch.sessionId = this.readManagedSession(managed);
|
|
5819
|
+
managed.launch.sessionId = this.sessionRecovery.readManagedSession(managed);
|
|
6215
5820
|
if (reopenSession !== undefined && managed.launch.sessionId !== reopenSession)
|
|
6216
5821
|
throw new Error(`continuity: exact asked for session ${reopenSession}, the connector bound ${managed.launch.sessionId}`);
|
|
6217
5822
|
if (exact) {
|
|
6218
5823
|
managed.continuity = { space: this.space, name, connector: agent, cwd };
|
|
6219
|
-
this.recordContinuity(managed, managed.launch.sessionId);
|
|
5824
|
+
this.sessionRecovery.recordContinuity(managed, managed.launch.sessionId);
|
|
6220
5825
|
}
|
|
6221
5826
|
}
|
|
6222
5827
|
catch (error) {
|
|
6223
5828
|
const detail = `${managed.name} joined, but its exact host session could not be bound for supervised recovery: ${rejectionText(error)}`;
|
|
6224
|
-
this.
|
|
6225
|
-
this.trackStoppedHandle(managed, true, "session-bind-failed");
|
|
5829
|
+
this.stopAndTrack(managed, "session-bind-failed");
|
|
6226
5830
|
await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
|
|
6227
5831
|
return { ok: false, error: detail };
|
|
6228
5832
|
}
|
|
@@ -6232,12 +5836,11 @@ export class Manager {
|
|
|
6232
5836
|
}
|
|
6233
5837
|
if (managed.restart.policy) {
|
|
6234
5838
|
try {
|
|
6235
|
-
this.recordSeat(managed);
|
|
5839
|
+
this.seatCustody.recordSeat(managed);
|
|
6236
5840
|
}
|
|
6237
5841
|
catch (error) {
|
|
6238
5842
|
const detail = `${managed.name} joined, but supervise cannot cover a manager restart for it: ${rejectionText(error)}`;
|
|
6239
|
-
this.
|
|
6240
|
-
this.trackStoppedHandle(managed, true, "supervise-record-failed");
|
|
5843
|
+
this.stopAndTrack(managed, "supervise-record-failed");
|
|
6241
5844
|
await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
|
|
6242
5845
|
return { ok: false, error: detail };
|
|
6243
5846
|
}
|
|
@@ -6246,7 +5849,7 @@ export class Manager {
|
|
|
6246
5849
|
// An unsupervised seat a successor could adopt keeps a record too; one that cannot be written
|
|
6247
5850
|
// costs only that adoption, so the spawn stands and the line says so.
|
|
6248
5851
|
if (!managed.restart?.policy)
|
|
6249
|
-
this.refreshSeatRecord(managed);
|
|
5852
|
+
this.seatCustody.refreshSeatRecord(managed);
|
|
6250
5853
|
this.watchExit(managed);
|
|
6251
5854
|
// Reply with the id the slot actually carries (user-mode: the owner.actor principal —
|
|
6252
5855
|
// presence, ps, and the manifest ownership ledger all key on it; the throwaway static nkey
|
|
@@ -6267,9 +5870,7 @@ export class Manager {
|
|
|
6267
5870
|
if (onceTask && committed === true)
|
|
6268
5871
|
this.openOnceDelivery(onceTask.ref);
|
|
6269
5872
|
else if (onceTask) {
|
|
6270
|
-
this.
|
|
6271
|
-
managed.once.stopReason ??= "launch-failed";
|
|
6272
|
-
this.stopOnceSeat(managed, "launch-failed");
|
|
5873
|
+
this.endOnceBeforeServe(managed, "launch-failed", "launch-failed");
|
|
6273
5874
|
}
|
|
6274
5875
|
return { ok: true, data: okData };
|
|
6275
5876
|
}
|
|
@@ -6708,6 +6309,7 @@ export class Manager {
|
|
|
6708
6309
|
catch (e) {
|
|
6709
6310
|
return { ok: false, error: rejectionText(e) };
|
|
6710
6311
|
}
|
|
6312
|
+
await this.refreshUnavailableConnectors(connector.name, true);
|
|
6711
6313
|
const harness = this.launchHarness(connector);
|
|
6712
6314
|
if ("refusal" in harness)
|
|
6713
6315
|
return { ok: false, error: harness.refusal };
|
|
@@ -7262,57 +6864,13 @@ export class Manager {
|
|
|
7262
6864
|
occupancy() { return this.namesCapacity.occupancy(); }
|
|
7263
6865
|
occupancyText(o) { return this.namesCapacity.occupancyText(o); }
|
|
7264
6866
|
capacityRefusal(o) { return this.namesCapacity.capacityRefusal(o); }
|
|
7265
|
-
/**
|
|
7266
|
-
|
|
7267
|
-
|
|
7268
|
-
|
|
7269
|
-
|
|
7270
|
-
|
|
7271
|
-
|
|
7272
|
-
*/
|
|
7273
|
-
launchOwner(opts, spawner) {
|
|
7274
|
-
if (!this.userMode)
|
|
7275
|
-
return DEV_OWNER;
|
|
7276
|
-
const asked = spawner === undefined ? undefined : parsePrincipalKey(spawner)?.owner;
|
|
7277
|
-
return opts.owner ?? (asked?.startsWith("u_") ? asked : DEV_OWNER);
|
|
7278
|
-
}
|
|
7279
|
-
/** The owner of a seat this manager supervises, by the same rule {@link launchOwner} admitted it
|
|
7280
|
-
* under: a user-mode seat records its derived owner, and every other seat is the mesh's one owner. */
|
|
7281
|
-
seatOwner(a) {
|
|
7282
|
-
return a.userOwner ?? DEV_OWNER;
|
|
7283
|
-
}
|
|
7284
|
-
/**
|
|
7285
|
-
* Live seats this manager holds for one owner: the seats it supervises, plus the launches it has
|
|
7286
|
-
* reserved for that owner and not yet placed. It deliberately does NOT count cooling stamps — a
|
|
7287
|
-
* cooling slot is a seat that already freed, and the recycle floor it holds is a global
|
|
7288
|
-
* fork-bomb bound (P4c), not one tenant's occupancy. Mirrors {@link occupancy}'s reserved rule,
|
|
7289
|
-
* so a reservation stops being counted twice the moment its seat reaches `agents`.
|
|
7290
|
-
*/
|
|
7291
|
-
ownerSeats(owner) {
|
|
7292
|
-
let seats = 0;
|
|
7293
|
-
for (const a of this.agents.values())
|
|
7294
|
-
if (this.seatOwner(a) === owner)
|
|
7295
|
-
seats++;
|
|
7296
|
-
seats += this.namesCapacity.ownerReservations(owner);
|
|
7297
|
-
return seats;
|
|
7298
|
-
}
|
|
7299
|
-
/**
|
|
7300
|
-
* The per-owner ceiling, consulted at accept: `undefined` admits the launch, and a refusal
|
|
7301
|
-
* carries the owner's count and the cap so a caller can render a remedy and a script can decide
|
|
7302
|
-
* without re-reading prose. Distinct from {@link capacityRefusal}, which bounds the HOST: that
|
|
7303
|
-
* one frees when anyone stops a seat or a cooling slot expires, this one frees only when THIS
|
|
7304
|
-
* owner stops one of its own, or the operator raises the cap, so they cannot share a sentence.
|
|
7305
|
-
*/
|
|
7306
|
-
seatCapRefusal(owner) {
|
|
7307
|
-
const cap = this.seatCap;
|
|
7308
|
-
if (cap === SEAT_CAP_UNLIMITED)
|
|
7309
|
-
return undefined;
|
|
7310
|
-
const seats = this.ownerSeats(owner);
|
|
7311
|
-
if (seats < cap)
|
|
7312
|
-
return undefined;
|
|
7313
|
-
return seatCapRefused(`owner ${owner} holds ${seats} of the ${cap} seat${cap === 1 ? "" : "s"} manager ${this.managerInstanceId} admits per owner; ` +
|
|
7314
|
-
`stop one of that owner's seats, or ask the operator who runs this manager for a higher seat cap`, { owner, seats, cap });
|
|
7315
|
-
}
|
|
6867
|
+
/** The owner a launch belongs to: {@link NamesCapacity.launchOwner}. */
|
|
6868
|
+
launchOwner(opts, spawner) { return this.namesCapacity.launchOwner(opts, spawner); }
|
|
6869
|
+
/** Live seats this manager holds for one owner: {@link NamesCapacity.ownerSeats}. */
|
|
6870
|
+
// @ts-expect-error TS6133: the seat-cap smoke reads this private count through a structural view.
|
|
6871
|
+
ownerSeats(owner) { return this.namesCapacity.ownerSeats(owner); }
|
|
6872
|
+
/** The per-owner ceiling at accept: {@link NamesCapacity.seatCapRefusal}. */
|
|
6873
|
+
seatCapRefusal(owner) { return this.namesCapacity.seatCapRefusal(owner); }
|
|
7316
6874
|
// @ts-expect-error TS6133: retained fixtures call this private adapter through structural views.
|
|
7317
6875
|
async opStop(args, caller, admin) {
|
|
7318
6876
|
const name = String(args.name ?? "").trim();
|
|
@@ -7563,8 +7121,8 @@ export class Manager {
|
|
|
7563
7121
|
/** The served manager-level health summary. Given an owner, `agentCount` counts only that owner's
|
|
7564
7122
|
* seats, as `ps` lists them ({@link psOwnerFilter}), so a person reading a shared Manager does not
|
|
7565
7123
|
* learn how many seats other owners hold on it. */
|
|
7566
|
-
managerStatusData(ownerFilter) {
|
|
7567
|
-
this.refreshUnavailableConnectors();
|
|
7124
|
+
managerStatusData(ownerFilter, setupClaude = false) {
|
|
7125
|
+
this.refreshUnavailableConnectors(undefined, setupClaude);
|
|
7568
7126
|
return {
|
|
7569
7127
|
instanceId: this.managerInstanceId,
|
|
7570
7128
|
lifecycleUid: this.managerLifecycleUid,
|
|
@@ -8362,17 +7920,9 @@ export class Manager {
|
|
|
8362
7920
|
* no hold; its goal still records the spawn's readiness budget, which a successor needs to settle
|
|
8363
7921
|
* it. */
|
|
8364
7922
|
acceptOnceTurn(o) { return this.turnRelay.acceptOnceTurn(o); }
|
|
8365
|
-
/** How a once seat's startup watch ended
|
|
8366
|
-
|
|
8367
|
-
|
|
8368
|
-
async awaitStartupOutcome(a, launchedAt, readinessTimeoutMs) {
|
|
8369
|
-
const until = launchedAt + Math.max(readinessTimeoutMs, STARTUP_OUTCOME_MS);
|
|
8370
|
-
for (;;) {
|
|
8371
|
-
const outcome = a.handle.startupOutcome?.() ?? "pending";
|
|
8372
|
-
if (outcome !== "pending" || a.terminalizing || this.leaseStopping || Date.now() >= until)
|
|
8373
|
-
return outcome;
|
|
8374
|
-
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
8375
|
-
}
|
|
7923
|
+
/** How a once seat's startup watch ended: {@link awaitStartupOutcome}. */
|
|
7924
|
+
awaitStartupOutcome(a, launchedAt, readinessTimeoutMs) {
|
|
7925
|
+
return awaitStartupOutcome(a, launchedAt, readinessTimeoutMs, () => this.leaseStopping);
|
|
8376
7926
|
}
|
|
8377
7927
|
/** Serve a once task from now on: its spawn's succeeded terminal is written. */
|
|
8378
7928
|
openOnceDelivery(ref) { return this.turnRelay.openOnceDelivery(ref); }
|
|
@@ -8397,6 +7947,25 @@ export class Manager {
|
|
|
8397
7947
|
this.trackStoppedHandle(a, false, cause);
|
|
8398
7948
|
void this.cancelAgentGoal(a.name, "graceful");
|
|
8399
7949
|
}
|
|
7950
|
+
/** Stop a seat this spawn just placed and track its exit: the stop first, so the terminalizing
|
|
7951
|
+
* latch is set before anything awaits, then the exit tracking. Both are synchronous. */
|
|
7952
|
+
stopAndTrack(a, cause) {
|
|
7953
|
+
this.stopHandle(a, false, cause);
|
|
7954
|
+
this.trackStoppedHandle(a, true, cause);
|
|
7955
|
+
}
|
|
7956
|
+
/** End a once seat before its task is served: let go of the spawn goal, record why it stopped if
|
|
7957
|
+
* `stopReason` is given and none is recorded yet, then stop the seat. Synchronous, in that order. */
|
|
7958
|
+
endOnceBeforeServe(a, reason, stopReason) {
|
|
7959
|
+
this.agentGoals.delete(a.name);
|
|
7960
|
+
if (stopReason !== undefined)
|
|
7961
|
+
a.once.stopReason ??= stopReason;
|
|
7962
|
+
this.stopOnceSeat(a, reason);
|
|
7963
|
+
}
|
|
7964
|
+
/** Put a launched seat in the agent table, then mark its reserved name placed. */
|
|
7965
|
+
place(name, a) {
|
|
7966
|
+
this.agents.set(name, a);
|
|
7967
|
+
this.namesCapacity.placed(name);
|
|
7968
|
+
}
|
|
8400
7969
|
/** The once task's exit hook, on the handle the seat was launched with: whichever path ends the
|
|
8401
7970
|
* seat, its proved exit cancels a task that has no terminal yet and discharges the seat's debt. An
|
|
8402
7971
|
* exit that cannot be proved leaves both. */
|
|
@@ -8462,18 +8031,8 @@ export class Manager {
|
|
|
8462
8031
|
spawnCustodied(runtime, name, spec, cwd, reserved) {
|
|
8463
8032
|
return this.seatCustody.spawnCustodied(runtime, name, spec, cwd, reserved);
|
|
8464
8033
|
}
|
|
8465
|
-
/** Keep launch provenance independent of status and runtime wire contracts. */
|
|
8466
|
-
watchConnectorHolder(handle, holder) {
|
|
8467
|
-
if (!holder.active)
|
|
8468
|
-
return;
|
|
8469
|
-
holder.launched(handle.pid);
|
|
8470
|
-
// A released handle may outlive its Manager. Only an authoritative exit removes
|
|
8471
|
-
// identity-less holders, never a release or a failed stop request.
|
|
8472
|
-
watchProvedExit(handle, () => holder.ended(), () => true);
|
|
8473
|
-
}
|
|
8474
|
-
recordSeat(a) {
|
|
8475
|
-
return this.seatCustody.recordSeat(a);
|
|
8476
|
-
}
|
|
8034
|
+
/** Keep launch provenance independent of status and runtime wire contracts: {@link watchConnectorHolder}. */
|
|
8035
|
+
watchConnectorHolder(handle, holder) { watchConnectorHolder(handle, holder); }
|
|
8477
8036
|
refreshSeatRecord(a) {
|
|
8478
8037
|
return this.seatCustody.refreshSeatRecord(a);
|
|
8479
8038
|
}
|