@cotal-ai/manager 0.164.18 → 0.165.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manager.js CHANGED
@@ -164,7 +164,9 @@ export const RUNTIME_NO_TERMINAL_DETAIL = "ai.cotal.manager.runtime-no-terminal"
164
164
  * covered by the caller invoking `renewDaemonCreds` once synchronously before starting the timer,
165
165
  * so no separate floor is needed. The pass is idempotent, since `renewDaemonCreds` no-ops each
166
166
  * credential when its state is `healthy`, so a tick that lands before the window costs one health
167
- * check per owner. */
167
+ * check per owner. A managed seat's credential is judged as of the next tick instead, because the
168
+ * seat re-reads its file only once a minute and nothing pushes the renewal to it: a tick that
169
+ * lands in the window's last minute can come too late for the seat to adopt it. */
168
170
  export function credRenewIntervalMs(ttlSeconds) {
169
171
  return Math.max(1, Math.floor((ttlSeconds / 4) * 1000));
170
172
  }
@@ -330,6 +332,23 @@ const FREE_SLOT_CAUSE_TEXT = {
330
332
  "supervise-record-failed": "this manager stopped it: its supervise policy could not be recorded for a manager restart",
331
333
  "inline-snapshot-changed": "this manager retired it instead of restarting it: its inline persona snapshot changed after launch",
332
334
  };
335
+ /** The SPEC 13.6 end reason a live attach session gets when this cause frees its seat. The causes
336
+ * that free the slot in the same step that saw the seat's own process exit report `process-exit`.
337
+ * A failed recovery frees it later, after its own stop, so it reports `target-despawn` with every
338
+ * manager stop. */
339
+ const FREE_SLOT_ATTACH_END = {
340
+ "process-exit": "process-exit",
341
+ "pi-crash-loop": "process-exit",
342
+ "supervise-crash-loop": "process-exit",
343
+ "inline-snapshot-changed": "process-exit",
344
+ "pi-recovery-failed": "target-despawn",
345
+ "supervise-recovery-failed": "target-despawn",
346
+ "session-bind-failed": "target-despawn",
347
+ "resume-session-rebind-failed": "target-despawn",
348
+ "carried-fork-refused": "target-despawn",
349
+ "resume-custody-unrecorded": "target-despawn",
350
+ "supervise-record-failed": "target-despawn",
351
+ };
333
352
  /** The stop family's sentences — the same job {@link FREE_SLOT_CAUSE_TEXT} does for the string
334
353
  * causes, beside it so both stay the single place a cause becomes a sentence. A requested stop's
335
354
  * sentence embeds the authenticated principal and a recursive reap's embeds the parent that
@@ -1973,6 +1992,14 @@ export class Manager {
1973
1992
  // incarnation; a copied credential cannot drive this and is stranded at its own row's TTL).
1974
1993
  // Same class-2 mechanics as the daemon creds: re-sign the file for the SAME nkey; the
1975
1994
  // agent endpoint's 75% source re-read adopts it.
1995
+ //
1996
+ // Each credential is judged as of the NEXT pass, so one whose renewal point falls before it
1997
+ // is re-signed now, ahead of the endpoint's re-read. Judged as of now, a credential whose
1998
+ // renewal point lands just after a pass waited a whole interval: the endpoint warned every
1999
+ // minute that the file still held the old generation, and when the next pass came in the
2000
+ // credential's last minute, the endpoint's one-minute retry could miss it and the connection
2001
+ // expired.
2002
+ const nextPassSec = Math.floor(Date.now() / 1000) + Math.ceil(credRenewIntervalMs(STANDING_RENEWABLE_TTL_SEC) / 1000);
1976
2003
  if (!this.userMode) {
1977
2004
  for (const a of [...this.agents.values()]) {
1978
2005
  // The `terminalizing` test here is an OPTIMISATION, NOT THE GUARD. There are awaits below
@@ -1987,7 +2014,7 @@ export class Manager {
1987
2014
  const stored = await this.secrets.get(agentSecretKeyForFile(a.secretPaths.creds, this.space));
1988
2015
  if (stored === undefined)
1989
2016
  continue; // no materialized cred (never minted here) - nothing to renew
1990
- const health = inspectCredHealth(stored);
2017
+ const health = inspectCredHealth(stored, nextPassSec);
1991
2018
  if (health.state === "healthy")
1992
2019
  continue;
1993
2020
  if (health.state === "unbounded" || health.state === "unreadable") {
@@ -2699,7 +2726,7 @@ export class Manager {
2699
2726
  this.agents.delete(a.name);
2700
2727
  this.dropSeatRecord(a);
2701
2728
  }
2702
- const refused = this.stopHandle(a, true);
2729
+ const refused = this.stopHandle(a, true, { kind: "stopped-shutdown" });
2703
2730
  if (refused === undefined)
2704
2731
  stopped.push(a);
2705
2732
  else
@@ -4186,7 +4213,7 @@ export class Manager {
4186
4213
  if (process.platform === "win32" && target.handle.kind === "pty") {
4187
4214
  return this.stopWindowsSeat(target, graceful, true, { kind: "stopped-self" }).then(() => ({ ok: true, data: { name: target.name, stopped: true, graceful } }));
4188
4215
  }
4189
- this.stopHandle(target, graceful);
4216
+ this.stopHandle(target, graceful, { kind: "stopped-self" });
4190
4217
  this.trackStoppedHandle(target, true, { kind: "stopped-self" });
4191
4218
  return { ok: true, data: { name: target.name, stopped: true, graceful } };
4192
4219
  }
@@ -4206,11 +4233,12 @@ export class Manager {
4206
4233
  * footprint, nor (in `reapChildrenOf`) abort the reap of later siblings. The failure is logged and
4207
4234
  * returned: a caller that must prove exit (shutdown, a failed resume) reports it as the cause at
4208
4235
  * once instead of waiting out a stop the runtime already refused. */
4209
- stopHandle(a, graceful) {
4236
+ stopHandle(a, graceful, cause) {
4210
4237
  // The TERMINALIZING latch: flipped SYNCHRONOUSLY, before any await anywhere on
4211
4238
  // this stop path — later renewals refuse, while an already-admitted renewal drains before the
4212
4239
  // durable terminal begins.
4213
4240
  a.terminalizing = true;
4241
+ a.stopCause ??= cause;
4214
4242
  try {
4215
4243
  // A delegated seat's close runs only inside its retirement, after the host revoked its grant,
4216
4244
  // so stopping it starts that retirement. Every exit wait on a stop path then settles on that
@@ -4234,7 +4262,7 @@ export class Manager {
4234
4262
  async stopWindowsSeat(a, graceful, floor, cause) {
4235
4263
  if (a.once)
4236
4264
  a.once.stopReason ??= onceStopReason(cause);
4237
- const failure = this.stopHandle(a, graceful);
4265
+ const failure = this.stopHandle(a, graceful, cause);
4238
4266
  this.lifecycleInFlight++;
4239
4267
  try {
4240
4268
  if (failure !== undefined)
@@ -4718,10 +4746,10 @@ export class Manager {
4718
4746
  this.dropSeatRecord(a);
4719
4747
  if (a.seatHome)
4720
4748
  rmSync(a.seatHome, { recursive: true, force: true });
4721
- // End any live §13.6 attach session bound to THIS incarnation with the honest
4722
- // `target-despawn` reason. Fires once per agent on every free path (despawn / self-stop / reap /
4723
- // exit) via the `agents` guard above; a no-op when no plane or no live session for the target.
4724
- this.sessionPlane?.endForTarget(a.name, a.lifecycleUid, "target-despawn");
4749
+ // End any live §13.6 attach session bound to THIS incarnation with the reason its cause names.
4750
+ // Fires once per agent on every free path (despawn / self-stop / reap / exit) via the `agents`
4751
+ // guard above; a no-op when no plane or no live session for the target.
4752
+ this.sessionPlane?.endForTarget(a.name, a.lifecycleUid, typeof cause === "string" ? FREE_SLOT_ATTACH_END[cause] : "target-despawn");
4725
4753
  // The turn relay's reap hook: every pending turn addressed to THIS incarnation is stamped
4726
4754
  // with the death, and its deadline terminal carries it as `agentDownAt`. The addressee is gone
4727
4755
  // and no successor may answer for it; the terminal is still the deadline's, not a new reason.
@@ -5220,8 +5248,9 @@ export class Manager {
5220
5248
  if (child.spawner !== parentId)
5221
5249
  continue;
5222
5250
  this.reapChildrenOf(this.managedPrincipal(child));
5223
- this.stopHandle(child, false);
5224
- this.trackStoppedHandle(child, true, { kind: "stopped-reap", parent: parentId }, true);
5251
+ const cause = { kind: "stopped-reap", parent: parentId };
5252
+ this.stopHandle(child, false, cause);
5253
+ this.trackStoppedHandle(child, true, cause, true);
5225
5254
  }
5226
5255
  }
5227
5256
  readSessionStatePath(path) {
@@ -5328,7 +5357,7 @@ export class Manager {
5328
5357
  if (refused === undefined || a.terminalizing || a.handle.status() === "exited")
5329
5358
  return;
5330
5359
  console.error(`! ${refused}; stopping it`);
5331
- this.stopHandle(a, false);
5360
+ this.stopHandle(a, false, "carried-fork-refused");
5332
5361
  this.trackStoppedHandle(a, true, "carried-fork-refused");
5333
5362
  }
5334
5363
  readManagedSession(a) {
@@ -5585,10 +5614,11 @@ export class Manager {
5585
5614
  }
5586
5615
  })();
5587
5616
  }
5588
- /** A managed agent's process exited on its own (crash, /exit, finished). Continuation-capable Pi
5589
- * seats restart in place after readiness; a spawn carrying `supervise` restarts any connector
5590
- * the same way, without classifying a session-state file. Every other exit follows the existing
5591
- * terminal path. */
5617
+ /** A managed agent's process exited: on its own (crash, /exit, finished), or after a stop this
5618
+ * manager started, whose recorded cause then frees the slot. Continuation-capable Pi seats
5619
+ * restart in place after readiness; a spawn carrying `supervise` restarts any connector the same
5620
+ * way, without classifying a session-state file. Every other exit follows the existing terminal
5621
+ * path. */
5592
5622
  onAgentExit(a) {
5593
5623
  // Preservation owns the child-stop snapshot. Exit watchers must neither delete that snapshot nor
5594
5624
  // trigger normal deprovision/reap while the cut is being formed.
@@ -5617,7 +5647,7 @@ export class Manager {
5617
5647
  console.error(`! ${a.name}: cannot classify Pi process exit for recovery: ${rejectionText(error)} - retiring the seat`);
5618
5648
  }
5619
5649
  }
5620
- this.freeSlot(a, true, "process-exit");
5650
+ this.freeSlot(a, true, a.stopCause ?? "process-exit");
5621
5651
  this.reapChildrenOf(this.managedPrincipal(a));
5622
5652
  }
5623
5653
  /** Agent names become `.cotal/agents/<name>.md` paths and mesh identities, so they must be bare
@@ -5870,7 +5900,7 @@ export class Manager {
5870
5900
  catch (error) {
5871
5901
  const reason = rejectionText(error);
5872
5902
  this.bootNotes.push(`! manager boot: connector inventory unavailable - ${reason}`);
5873
- this.connectorStatuses = [{ agent: "(inventory)", state: "unavailable", binaries: {}, eventPlane: false, reason }];
5903
+ this.connectorStatuses = [{ agent: "(inventory)", state: "unavailable", binaries: {}, eventPlane: false, permissionRequests: false, reason }];
5874
5904
  this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
5875
5905
  return;
5876
5906
  }
@@ -5880,22 +5910,31 @@ export class Manager {
5880
5910
  name: connector.name,
5881
5911
  requires: connector.requires ?? [],
5882
5912
  eventPlane: connector.eventChannel !== undefined,
5913
+ permissionRequests: connector.permissionRequests === true,
5883
5914
  }));
5884
5915
  }
5885
- for (const { name, requires, eventPlane } of declared) {
5916
+ for (const { name, requires, eventPlane, permissionRequests = false } of declared) {
5886
5917
  const { binaries, reason } = resolveHarness(name, requires);
5887
5918
  if (reason) {
5888
- rows.push({ agent: name, state: "unavailable", binaries, eventPlane, reason });
5919
+ rows.push({ agent: name, state: "unavailable", binaries, eventPlane, permissionRequests, reason });
5889
5920
  this.bootNotes.push(`! manager boot: connector ${name} unavailable - ${reason}`);
5890
5921
  }
5891
5922
  else {
5892
- rows.push({ agent: name, state: "available", binaries, eventPlane });
5923
+ rows.push({ agent: name, state: "available", binaries, eventPlane, permissionRequests });
5893
5924
  }
5894
5925
  }
5895
5926
  this.connectorStatuses = rows.sort((a, b) => a.agent.localeCompare(b.agent));
5896
5927
  if (!this.classSpawnEnabled())
5897
5928
  this.bootNotes.push("! manager: no agent application is available here, so a spawn without --on goes to another manager in this space");
5898
5929
  }
5930
+ /** The connector rows a status read serves. A connector relays permission prompts only where an
5931
+ * owner can answer them, and only a user-auth mesh mints the interactive ledger rows that answer
5932
+ * (SPEC §8.2), so on an open or static mesh every row reads false. The mode is known only after
5933
+ * boot inspects the connectors, so it is applied here. */
5934
+ servedConnectorStatuses() {
5935
+ const answerable = this.meshMode === "user";
5936
+ return this.connectorStatuses.map((row) => ({ ...row, binaries: { ...row.binaries }, permissionRequests: answerable && row.permissionRequests }));
5937
+ }
5899
5938
  /** True when at least one declared connector is available. Empty inventory (or a failed
5900
5939
  * inventory load) skips the class `one` subscribe for spawn/launch so this member cannot
5901
5940
  * consume an unpinned request a sibling could serve. */
@@ -6443,6 +6482,15 @@ export class Manager {
6443
6482
  : `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). ` +
6444
6483
  `Drop these from the persona or the spawn, or have the operator widen the spawner's own persona.`;
6445
6484
  }
6485
+ /** Ordinary static control seats can read their holding instance. A run's recorded ceiling is
6486
+ * authoritative, so its helpers receive no additional instance reads. */
6487
+ managedStaticInstanceReads(capabilities) {
6488
+ if (this.meshMode !== "static" || !this.managerInstanceId || !capabilities?.some(c => c === "spawn" || c === "run" || c === "admin"))
6489
+ return [];
6490
+ return ["describe", "inspect"].map(command => ({
6491
+ endpoint: MANAGER_ENDPOINT, command, instanceId: this.managerInstanceId, instanceOnly: true,
6492
+ }));
6493
+ }
6446
6494
  async startAgentActive(opts, spawner, hooks, authenticatedCaller) {
6447
6495
  // Before the first await, so the grant, the launch, the retained form and the restart slot all read
6448
6496
  // the lists and the restart policy as admitted.
@@ -6723,6 +6771,11 @@ export class Manager {
6723
6771
  if (this.eventPayloadsWithheld && opts.eventPayloads === true)
6724
6772
  return { ok: false, error: "space policy withholds event payloads" };
6725
6773
  const eventPayloads = !this.eventPayloadsWithheld && (opts.eventPayloads ?? def?.eventPayloads) !== false;
6774
+ if (run === undefined) {
6775
+ const reads = this.managedStaticInstanceReads(capabilities);
6776
+ if (bound.kind === "exempt" || (bound.kind === "bounded" && !grantOverreach(this.space, bound.caller, bound.ceiling, { endpoints: reads }).length))
6777
+ endpoints.push(...reads);
6778
+ }
6726
6779
  // THE DELEGATION BOUND, on the grant as it will be minted: every channel and capability the
6727
6780
  // helper gets, from the persona, the raw overrides and the `callerAcl` default alike, and its own
6728
6781
  // event plane, so no door reaches the mint around it. Before any reserve or mint, so a refusal
@@ -7445,7 +7498,7 @@ export class Manager {
7445
7498
  return { ok: false, error: refused };
7446
7499
  }
7447
7500
  if (refused !== undefined) {
7448
- this.stopHandle(managed, false);
7501
+ this.stopHandle(managed, false, "carried-fork-refused");
7449
7502
  this.trackStoppedHandle(managed, true, "carried-fork-refused");
7450
7503
  await hooks?.onOutcome?.({ kind: "failed", data: { error: refused } });
7451
7504
  return { ok: false, error: refused };
@@ -7469,7 +7522,7 @@ export class Manager {
7469
7522
  }
7470
7523
  catch (error) {
7471
7524
  const detail = `${managed.name} joined, but its exact host session could not be bound for supervised recovery: ${rejectionText(error)}`;
7472
- this.stopHandle(managed, false);
7525
+ this.stopHandle(managed, false, "session-bind-failed");
7473
7526
  this.trackStoppedHandle(managed, true, "session-bind-failed");
7474
7527
  await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
7475
7528
  return { ok: false, error: detail };
@@ -7484,7 +7537,7 @@ export class Manager {
7484
7537
  }
7485
7538
  catch (error) {
7486
7539
  const detail = `${managed.name} joined, but supervise cannot cover a manager restart for it: ${rejectionText(error)}`;
7487
- this.stopHandle(managed, false);
7540
+ this.stopHandle(managed, false, "supervise-record-failed");
7488
7541
  this.trackStoppedHandle(managed, true, "supervise-record-failed");
7489
7542
  await hooks?.onOutcome?.({ kind: "failed", data: { error: detail } });
7490
7543
  return { ok: false, error: detail };
@@ -8246,7 +8299,7 @@ export class Manager {
8246
8299
  * would reap it: it is freed only once its exit is proved, and otherwise stays managed until it
8247
8300
  * exits or the manager stops it. */
8248
8301
  async stopFailedResume(managed, cause, detail) {
8249
- const refused = this.stopHandle(managed, false);
8302
+ const refused = this.stopHandle(managed, false, cause);
8250
8303
  const unproven = refused === undefined
8251
8304
  ? await this.awaitHandleExit(managed.handle).then(() => undefined, rejectionText)
8252
8305
  : `stop failed: ${refused}`;
@@ -8640,8 +8693,9 @@ export class Manager {
8640
8693
  return { ok: true, data: { name: a.name, stopped: true, graceful } };
8641
8694
  });
8642
8695
  }
8643
- this.stopHandle(a, graceful);
8644
- this.trackStoppedHandle(a, trackNonAdmin, { kind: "stopped-requested", requester: caller });
8696
+ const cause = { kind: "stopped-requested", requester: caller };
8697
+ this.stopHandle(a, graceful, cause);
8698
+ this.trackStoppedHandle(a, trackNonAdmin, cause);
8645
8699
  void this.cancelAgentGoal(a.name, graceful ? "graceful" : "terminate"); // Cancel a live spawn goal
8646
8700
  return { ok: true, data: { name: a.name, stopped: true, graceful } };
8647
8701
  }
@@ -8867,7 +8921,7 @@ export class Manager {
8867
8921
  terminalSessions: this.execution !== "none",
8868
8922
  agentCount: ownerFilter === undefined ? this.agents.size : [...this.agents.values()].filter((a) => a.userOwner === ownerFilter).length,
8869
8923
  uptimeMs: Date.now() - this.startedAtMs,
8870
- connectors: this.connectorStatuses.map((row) => ({ ...row, binaries: { ...row.binaries } })),
8924
+ connectors: this.servedConnectorStatuses(),
8871
8925
  classSpawn: this.classSpawnEnabled(),
8872
8926
  staticReconciliation: this.staticReconciliationStatus(),
8873
8927
  stopImpact: {
@@ -9250,7 +9304,7 @@ export class Manager {
9250
9304
  // grant (no new grant, no new writer); core refuses on anything but a gate provably
9251
9305
  // reopened past the slot's stamp.
9252
9306
  observeHolderGeneration: (holderInstanceId) => readEndpointGateGeneration(authKv, { endpoint: MANAGER_ENDPOINT, instanceId: holderInstanceId }),
9253
- status: { connectors: this.connectorStatuses.map((row) => ({ ...row, binaries: { ...row.binaries } })) },
9307
+ status: { connectors: this.servedConnectorStatuses() },
9254
9308
  });
9255
9309
  const fence = serveIssuanceGateKv(authKv, this.space, { endpoint: MANAGER_ENDPOINT, instanceId: iid });
9256
9310
  // Open mesh: NO mint - the §13.1 fence is issuance-only and nothing is ever issued, so the
@@ -11020,8 +11074,9 @@ export class Manager {
11020
11074
  * stop frees the slot first, so this stop reaps them itself. */
11021
11075
  stopOnceSeat(a, reason) {
11022
11076
  this.reapChildrenOf(this.managedPrincipal(a));
11023
- this.stopHandle(a, true);
11024
- this.trackStoppedHandle(a, false, { kind: "stopped-once", reason });
11077
+ const cause = { kind: "stopped-once", reason };
11078
+ this.stopHandle(a, true, cause);
11079
+ this.trackStoppedHandle(a, false, cause);
11025
11080
  void this.cancelAgentGoal(a.name, "graceful");
11026
11081
  }
11027
11082
  /** The once task's exit hook, on the handle the seat was launched with: whichever path ends the
@@ -11903,13 +11958,23 @@ export class Manager {
11903
11958
  // ceiling, which `confirm` verifies against the recorded evidence before the ledger append. A
11904
11959
  // changed ceiling is refused there: that is a fresh issuance on a new connection, never a renewal.
11905
11960
  const issued = a.issued;
11961
+ const endpoints = lowerPersonaEndpoints(a.launch.endpoints);
11962
+ const reads = this.managedStaticInstanceReads(a.launch.capabilities);
11963
+ if (reads.length) {
11964
+ // Resolve this incarnation's original issuance, not its current spawner or a reconstructed
11965
+ // run admission. Old seats and run helpers keep the exact ceiling they were minted with.
11966
+ const caller = { owner: DEV_OWNER, actor: a.id, uid: a.lifecycleUid, generation: issued.generation };
11967
+ const { evidence } = await withIssuerSession({ servers: this.servers ?? DEFAULT_SERVER, space: this.space, auth: this.auth, tls: false }, (s) => s.store.resolve({ space: this.space, ...caller }, s.sourceIsLive));
11968
+ if (!grantOverreach(this.space, caller, evidence.permissions, { endpoints: reads }).length)
11969
+ endpoints.push(...reads);
11970
+ }
11906
11971
  const creds = await this.withIssuer((i) => mintCreds(this.auth, { id: a.id, seed: a.seed }, "agent", {
11907
11972
  eventPayloads: this.eventPayloadsWithheld ? false : a.launch.eventPayloads,
11908
11973
  allowSubscribe: a.launch.allowSubscribe,
11909
11974
  allowPublish: a.launch.allowPublish,
11910
11975
  role: a.role,
11911
11976
  capabilities: a.launch.capabilities,
11912
- ...(a.launch.endpoints?.length ? { endpointCapabilities: lowerPersonaEndpoints(a.launch.endpoints) } : {}),
11977
+ ...(endpoints.length ? { endpointCapabilities: endpoints } : {}),
11913
11978
  lifecycleUid: a.lifecycleUid,
11914
11979
  expiresAt: exp,
11915
11980
  issued,