@cotal-ai/manager 0.163.4 → 0.164.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.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
- import { drainAndClose, requestSafeReconnect } from "@cotal-ai/core";
2
+ import { checkEventStartup, EventStateConflictError, isPermissionDenied, chatStream, drainAndClose, requestSafeReconnect } from "@cotal-ai/core";
3
3
  import { hostname, homedir } from "node:os";
4
4
  import { listDirectory } from "./list-dir.js";
5
5
  import { credsAuthenticator, RequestError } from "@nats-io/transport-node";
@@ -422,6 +422,8 @@ function userMeshEndpointsRefusal(door) {
422
422
  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). ` +
423
423
  "Drop `endpoints` from the persona, and ask the operator to grant the helper with `cotal service-endpoint grant` once it runs.";
424
424
  }
425
+ class LegacyEventCountPermissionError extends Error {
426
+ }
425
427
  const TURN_PARTICIPATION_TTL_MS = 5 * 60_000;
426
428
  function participantKey(owner, actor, uid) {
427
429
  return `${owner}.${actor}.${uid}`;
@@ -557,6 +559,7 @@ export class Manager {
557
559
  name;
558
560
  workspaceRoot;
559
561
  eventsRequired;
562
+ eventPayloadsWithheld;
560
563
  /** The operator-set global live-session ceiling (see {@link ManagerOptions.maxSessions}). */
561
564
  maxSessions;
562
565
  /** The operator-set per-owner seat ceiling (see {@link ManagerOptions.seatCap}). */
@@ -953,6 +956,7 @@ export class Manager {
953
956
  this.workspaceRoot = opts.workspaceRoot ?? findCotalRoot();
954
957
  this.onServiceIdentity = opts.onServiceIdentity;
955
958
  this.eventsRequired = opts.eventsRequired === true;
959
+ this.eventPayloadsWithheld = opts.eventPayloadsWithheld === true;
956
960
  this.maxSessions = opts.maxSessions;
957
961
  this.seatCap = opts.seatCap ?? DEFAULT_SEAT_CAP;
958
962
  this.remoteAuthority = opts.remoteAuthority;
@@ -1171,10 +1175,10 @@ export class Manager {
1171
1175
  }
1172
1176
  /** The CHAT stream frontier at a preservation cut (issue #545), read through whichever local
1173
1177
  * authority this mesh mode holds: open mode's own endpoint already has `$JS.API.STREAM.INFO`
1174
- * on the CHAT stream ({@link supervisorPermissions} grants it there); static/user mode's own
1175
- * supervisor credential does NOT (it holds that grant only on the manager/presence/delivery
1176
- * buckets), so those modes borrow the same ephemeral `provisioner` profile the manager already
1177
- * mints per spawn, which DOES hold it under space auth. A remote-authority manager (`this.auth`
1178
+ * on the CHAT stream. Local and remote supervisor credentials also hold this metadata grant
1179
+ * for transcript startup checks, but this preservation path retains its existing local-authority
1180
+ * boundary. Static/user modes borrow the ephemeral `provisioner` profile the manager already
1181
+ * mints per spawn. A remote-authority manager (`this.auth`
1178
1182
  * undefined in static/user mode) has no local space authority to mint that provisioner with, so
1179
1183
  * it prints one line and returns no floor — the inventory then carries none and resumed seats
1180
1184
  * behave exactly as before this fix, not a silent partial degrade. */
@@ -1199,9 +1203,9 @@ export class Manager {
1199
1203
  `WHOLE row, and an omitted flag is refused, or with \`--full\` is the WIDE default (\`>\` read, \`>\` post, \`spawn,run,role:default\` ` +
1200
1204
  `scope).`);
1201
1205
  case "static":
1202
- return (`\`cotal mint <reader> --profile agent --allow-subscribe ${channel} --provision\`, where there ` +
1206
+ return (`\`cotal auth mint <reader> --profile agent --allow-subscribe ${channel} --provision\`, where there ` +
1203
1207
  `is no actor ledger for \`actor grant\` to write to. The AGENT profile, not the observer ` +
1204
- `one: \`mint\` reads --allow-subscribe only for that profile, so an observer mint is ` +
1208
+ `one: \`auth mint\` reads --allow-subscribe only for that profile, so an observer mint is ` +
1205
1209
  `refused outright and writes no creds file.`);
1206
1210
  case "open":
1207
1211
  return (`there is nothing to grant on an open mesh: it has no credentials and no ACLs, so any peer ` +
@@ -2657,6 +2661,7 @@ export class Manager {
2657
2661
  capabilities: a.launch.capabilities,
2658
2662
  ...(a.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(a.launch.endpoints) } : {}),
2659
2663
  events: a.launch.events,
2664
+ eventPayloads: a.launch.eventPayloads,
2660
2665
  shareTools: a.launch.shareTools,
2661
2666
  forkSource: a.launch.forkSource,
2662
2667
  ...(this.forkProvenance(a) ? { resumed: this.forkProvenance(a) } : {}),
@@ -2870,6 +2875,7 @@ export class Manager {
2870
2875
  allowPublish: launch.allowPublish,
2871
2876
  capabilities: launch.capabilities,
2872
2877
  events: launch.events,
2878
+ eventPayloads: launch.eventPayloads,
2873
2879
  shareTools: launch.shareTools,
2874
2880
  forkSource: launch.forkSource,
2875
2881
  sessionId: launch.sessionId,
@@ -4330,6 +4336,7 @@ export class Manager {
4330
4336
  scope,
4331
4337
  allowSubscribe: opts.allowSubscribe,
4332
4338
  allowPublish: opts.allowPublish ?? [],
4339
+ ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
4333
4340
  role: opts.role,
4334
4341
  parent: spawnerPr ? opts.spawner : undefined,
4335
4342
  label: opts.label,
@@ -4422,6 +4429,7 @@ export class Manager {
4422
4429
  ...(opts.subscribe !== undefined ? { subscribe: opts.subscribe } : {}),
4423
4430
  allowSubscribe: opts.allowSubscribe,
4424
4431
  ...(opts.allowPublish !== undefined ? { allowPublish: opts.allowPublish } : {}),
4432
+ ...(opts.eventPayloads === false ? { eventPayloads: false } : {}),
4425
4433
  },
4426
4434
  ...(opts.spawnRequest !== undefined ? { spawn: opts.spawnRequest } : {}),
4427
4435
  };
@@ -5612,13 +5620,11 @@ export class Manager {
5612
5620
  * ({@link issuedNumberedNames}), even after its holder retired. The requested base is exempt
5613
5621
  * from that history: it is the persona's own name, which stays reusable even when it once came
5614
5622
  * out of another persona's numbering. */
5615
- uniqueName(base) {
5623
+ uniqueName(base, unavailable = new Set()) {
5616
5624
  const live = this.liveRosterNames();
5617
5625
  // The cap belongs to user mode alone: only there is the numbered name the actor. Static and open
5618
5626
  // mode key the actor on the minted nkey, so a numbered name there has no length to fit.
5619
- const name = firstFreeName(base, (n) => this.nameInUse(n, live) || (n !== base && this.issuedNumberedNames.has(n)), this.userMode ? { actorBound: true } : undefined);
5620
- if (name !== base)
5621
- this.issuedNumberedNames.add(name);
5627
+ const name = firstFreeName(base, (n) => unavailable.has(n) || this.nameInUse(n, live) || (n !== base && this.issuedNumberedNames.has(n)), this.userMode ? { actorBound: true } : undefined);
5622
5628
  return name;
5623
5629
  }
5624
5630
  /** Spawn a teammate by persona ref (`name` loads `.cotal/agents/<name>.md`; the peer presents
@@ -5666,6 +5672,8 @@ export class Manager {
5666
5672
  // !== false`, so omission ARMS the plane — a gate on the explicit bit alone is bypassed by
5667
5673
  // omitting it. The gate is on the DECISION, and it runs before connector resolution and
5668
5674
  // before `startAgent` (which mints credentials), so a refusal provisions nothing.
5675
+ if (args.eventPayloads !== undefined && typeof args.eventPayloads !== "boolean")
5676
+ return Promise.resolve({ ok: false, error: "eventPayloads must be a boolean" });
5669
5677
  const requestedEvents = typeof args.events === "boolean" ? args.events : undefined;
5670
5678
  let eventsNotice;
5671
5679
  let events = requestedEvents;
@@ -5711,6 +5719,7 @@ export class Manager {
5711
5719
  resumeClaim: args.resumeClaim,
5712
5720
  resumeAgent: args.resumeAgent,
5713
5721
  events,
5722
+ eventPayloads: args.eventPayloads,
5714
5723
  eventsNotice,
5715
5724
  cwd: args.cwd,
5716
5725
  prompt: args.prompt,
@@ -5894,6 +5903,7 @@ export class Manager {
5894
5903
  envAllow: spawnEnvAllow(cotalConfig),
5895
5904
  resolvedBinaries: harness.binaries,
5896
5905
  eventsRequired: this.eventsRequired,
5906
+ ...(this.eventPayloadsWithheld ? { eventPayloads: false } : {}),
5897
5907
  // So a connector that keeps per-agent local state can root it at the workspace, not the
5898
5908
  // (possibly per-agent) launch cwd.
5899
5909
  workspaceRoot: this.workspaceRoot,
@@ -6431,9 +6441,8 @@ export class Manager {
6431
6441
  // a refusal names the persona instead of a path.
6432
6442
  let configPath = persona.configPath;
6433
6443
  const where = configPath ?? `inline persona "${ref}"`;
6434
- // Materialize the requested connector up front — the ONE async step in the spawn path (a lazy
6435
- // `cotal ext` manifest import on the published binary). It runs BEFORE the capacity/reserve span
6436
- // below so that span stays fully SYNCHRONOUS and atomic. On the manifest binary this also honors a
6444
+ // Materialize the requested connector before the capacity/reserve span so its lazy import
6445
+ // cannot interleave that synchronous allocation. On the manifest binary this also honors a
6437
6446
  // live `cotal ext remove`: a removed connector is rejected here even if an earlier spawn already
6438
6447
  // imported it. A broken/missing connector fails loud here with a clear name + install hint.
6439
6448
  let connector;
@@ -6666,6 +6675,9 @@ export class Manager {
6666
6675
  // The AG-UI event plane is on unless the launch explicitly opted out. A connector that cannot
6667
6676
  // emit one is refused further down, before anything is minted.
6668
6677
  const events = this.eventsRequired || opts.events !== false;
6678
+ if (this.eventPayloadsWithheld && opts.eventPayloads === true)
6679
+ return { ok: false, error: "space policy withholds event payloads" };
6680
+ const eventPayloads = !this.eventPayloadsWithheld && (opts.eventPayloads ?? def?.eventPayloads) !== false;
6669
6681
  // THE DELEGATION BOUND, on the grant as it will be minted: every channel and capability the
6670
6682
  // helper gets, from the persona, the raw overrides and the `callerAcl` default alike, and its own
6671
6683
  // event plane, so no door reaches the mint around it. Before any reserve or mint, so a refusal
@@ -6813,27 +6825,65 @@ export class Manager {
6813
6825
  // base name (no pin) keeps uniqueName's collision numbering, so multi-peer `spawn reviewer` twice
6814
6826
  // still yields reviewer + reviewer_2. The alias-reuse gate above is orthogonal and already fired.
6815
6827
  const hardPinned = opts.identity !== undefined || opts.resolved !== undefined;
6828
+ const owner = this.launchOwner(opts, spawner);
6829
+ const unavailable = new Set();
6816
6830
  let name;
6817
- if (hardPinned) {
6818
- // The collision check consults THE SAME liveness source uniqueName uses ({@link nameInUse}:
6819
- // this manager's agents/reserved/retiring PLUS the roster-live set) - a hard-pinned name
6820
- // colliding with ANY live incarnation (managed, unmanaged foreground/connector, or another
6821
- // manager's agent) refuses cleanly at accept, rather than minting the collision and black-
6822
- // holing on the broker/auth refusal (a pinned name live under another manager MUST refuse).
6823
- if (this.nameInUse(identityName))
6824
- 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` };
6825
- name = identityName;
6826
- }
6827
- else {
6828
- // Numbering appends `_<n>` and stops at the actor bound, so a base whose every fitting
6829
- // candidate is taken throws rather than naming an actor the exchange refuses. That refusal
6830
- // lands here, before the reservation below, so the spawn starts nothing.
6831
- try {
6832
- name = this.uniqueName(identityName);
6831
+ for (;;) {
6832
+ if (hardPinned) {
6833
+ if (this.nameInUse(identityName))
6834
+ 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` };
6835
+ name = identityName;
6833
6836
  }
6834
- catch (e) {
6835
- return { ok: false, error: rejectionText(e) };
6837
+ else {
6838
+ try {
6839
+ name = this.uniqueName(identityName, unavailable);
6840
+ }
6841
+ catch (e) {
6842
+ return { ok: false, error: rejectionText(e) };
6843
+ }
6844
+ }
6845
+ // In user mode the name is the principal's actor. A fresh nkey in static/open mode
6846
+ // cannot collide with an earlier transcript. Use the connector's own startup proof.
6847
+ const eventOwner = opts.owner ?? (spawner === undefined ? undefined : parsePrincipalKey(spawner)?.owner);
6848
+ if (events && this.userMode && !runtime.spawnDelegated && eventOwner?.startsWith("u_")) {
6849
+ try {
6850
+ await checkEventStartup({
6851
+ workspaceRoot: this.workspaceRoot,
6852
+ space: this.space,
6853
+ principal: { owner: eventOwner, actor: name },
6854
+ retainedMessages: async () => {
6855
+ try {
6856
+ return (await this.ep.chatRetention()).senders;
6857
+ }
6858
+ catch (e) {
6859
+ // Older hosts do not issue this metadata grant. Do not infer that the name is
6860
+ // free or renumber it: preserve the requested candidate and let the launched
6861
+ // agent's existing startup check decide. Every other read failure stays loud.
6862
+ if (!isPermissionDenied(e))
6863
+ throw e;
6864
+ console.error(`! event startup name check: missing $JS.API.STREAM.INFO.${chatStream(this.space)} permission; launching "${name}" unchanged so the agent checks its transcript state`);
6865
+ throw new LegacyEventCountPermissionError();
6866
+ }
6867
+ },
6868
+ });
6869
+ }
6870
+ catch (e) {
6871
+ if (e instanceof EventStateConflictError && !hardPinned) {
6872
+ unavailable.add(name);
6873
+ continue;
6874
+ }
6875
+ if (!(e instanceof LegacyEventCountPermissionError))
6876
+ return { ok: false, code: "failed-precondition", error: `cannot check event startup for ${eventOwner}.${name}: ${rejectionText(e)}` };
6877
+ }
6878
+ // Another spawn may have reserved the candidate while the disk/broker proof awaited.
6879
+ // Recheck in the same synchronous window as the cap and reservation below.
6880
+ if (this.nameInUse(name) || (!hardPinned && name !== identityName && this.issuedNumberedNames.has(name))) {
6881
+ if (!hardPinned)
6882
+ continue;
6883
+ return { ok: false, code: "already-exists", error: `the hard-pinned name "${name}" became occupied while checking event startup; pick another name` };
6884
+ }
6836
6885
  }
6886
+ break;
6837
6887
  }
6838
6888
  // The `chat_` prefix belongs to static chat sessions, whose aliases only `chat-session-open`
6839
6889
  // draws. Checked once the name is fixed by either branch above, so a persona name, a numbered
@@ -6846,7 +6896,6 @@ export class Manager {
6846
6896
  // before any of the others reserved, and they all pass. Nothing between here and the reserve
6847
6897
  // awaits. It refuses BEFORE `onEffect`, so the launch states `not-executed` and leaves no
6848
6898
  // name, no mint and no footprint behind.
6849
- const owner = this.launchOwner(opts, spawner);
6850
6899
  const overCap = this.seatCapRefusal(owner);
6851
6900
  if (overCap)
6852
6901
  return { ok: false, code: overCap.code, error: overCap.message, ...(overCap.details ? { details: overCap.details } : {}) };
@@ -6869,6 +6918,8 @@ export class Manager {
6869
6918
  // Taken right before the try so its finally is the only release; a refusal belongs above the
6870
6919
  // allocation, where there is no name to give back.
6871
6920
  hooks?.onEffect?.();
6921
+ if (!hardPinned && name !== identityName)
6922
+ this.issuedNumberedNames.add(name);
6872
6923
  this.reserved.set(name, owner);
6873
6924
  try {
6874
6925
  // A stable nkey identity assigned at spawn: the public key is the agent's card.id (threaded via
@@ -6973,6 +7024,7 @@ export class Manager {
6973
7024
  let enrolled;
6974
7025
  if (this.userMode) {
6975
7026
  const prep = await this.provisionUserAgent(name, {
7027
+ eventPayloads,
6976
7028
  spawner,
6977
7029
  specOwner: opts.owner,
6978
7030
  subscribe,
@@ -7053,6 +7105,7 @@ export class Manager {
7053
7105
  issued = { generation: mintGeneration(now + STATIC_GENERATION_HORIZON_SEC), acceptedToken: mintAcceptedToken(), listing: true };
7054
7106
  const issuedAgent = { name, id: identity.id, lifecycleUid };
7055
7107
  const creds = await this.withIssuer((i) => this.withProvisioner((prov) => provisionAgent(prov, this.auth, identity, {
7108
+ eventPayloads,
7056
7109
  subscribe,
7057
7110
  allowSubscribe,
7058
7111
  allowPublish,
@@ -7138,6 +7191,7 @@ export class Manager {
7138
7191
  // file that may have changed since.
7139
7192
  endpoints: copyPersonaEndpoints(personaEndpoints) ?? [],
7140
7193
  events,
7194
+ eventPayloads,
7141
7195
  cwd,
7142
7196
  };
7143
7197
  // A delegated seat gets no local launch at all: no launch-material file, control token or
@@ -7149,7 +7203,7 @@ export class Manager {
7149
7203
  if (this.delegatedLaunched.has(lifecycleUid))
7150
7204
  throw new Error(`lifecycle ${lifecycleUid} was already handed to runtime "${runtime.kind}"; a lifecycle is handed off at most once`);
7151
7205
  this.delegatedLaunched.add(lifecycleUid);
7152
- handle = runtime.spawnDelegated({ agent, persona: readFileSync(configPath, "utf8"), managerInstanceId: this.managerInstanceId, role, model, variant, prompt, launchOptions: launchOptions, events }, handoff);
7206
+ handle = runtime.spawnDelegated({ agent, persona: readFileSync(configPath, "utf8"), managerInstanceId: this.managerInstanceId, role, model, variant, prompt, launchOptions: launchOptions, events, eventPayloads }, handoff);
7153
7207
  }
7154
7208
  else {
7155
7209
  if (carried) {
@@ -7214,6 +7268,7 @@ export class Manager {
7214
7268
  capabilities,
7215
7269
  ...(personaEndpoints?.length ? { endpoints: copyPersonaEndpoints(personaEndpoints) } : {}),
7216
7270
  events,
7271
+ eventPayloads,
7217
7272
  shareTools: opts.shareTools,
7218
7273
  forkSource: opts.resume,
7219
7274
  ...(opts.resume !== undefined && spec?.resumeRecordPath ? { resumeRecordPath: spec.resumeRecordPath } : {}),
@@ -7945,6 +8000,7 @@ export class Manager {
7945
8000
  capabilities: entry.launch.capabilities,
7946
8001
  endpoints: copyPersonaEndpoints(entry.launch.endpoints) ?? [],
7947
8002
  events: entry.launch.events,
8003
+ eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
7948
8004
  cwd: entry.launch.cwd,
7949
8005
  };
7950
8006
  const spec = connector.buildLaunch(launchOpts);
@@ -8030,6 +8086,7 @@ export class Manager {
8030
8086
  capabilities: entry.launch.capabilities,
8031
8087
  ...(entry.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(entry.launch.endpoints) } : {}),
8032
8088
  events: entry.launch.events,
8089
+ eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
8033
8090
  shareTools: entry.launch.shareTools,
8034
8091
  forkSource: entry.launch.forkSource,
8035
8092
  ...(entry.launch.resumed ? { resumed: entry.launch.resumed } : {}),
@@ -11343,6 +11400,7 @@ export class Manager {
11343
11400
  capabilities: entry.launch.capabilities,
11344
11401
  ...(entry.launch.endpoints?.length ? { endpoints: copyPersonaEndpoints(entry.launch.endpoints) } : {}),
11345
11402
  events: entry.launch.events,
11403
+ eventPayloads: this.eventPayloadsWithheld ? false : entry.launch.eventPayloads,
11346
11404
  shareTools: entry.launch.shareTools,
11347
11405
  forkSource: entry.launch.forkSource,
11348
11406
  ...(entry.launch.resumed ? { resumed: entry.launch.resumed } : {}),
@@ -11790,6 +11848,7 @@ export class Manager {
11790
11848
  // changed ceiling is refused there: that is a fresh issuance on a new connection, never a renewal.
11791
11849
  const issued = a.issued;
11792
11850
  const creds = await this.withIssuer((i) => mintCreds(this.auth, { id: a.id, seed: a.seed }, "agent", {
11851
+ eventPayloads: this.eventPayloadsWithheld ? false : a.launch.eventPayloads,
11793
11852
  allowSubscribe: a.launch.allowSubscribe,
11794
11853
  allowPublish: a.launch.allowPublish,
11795
11854
  role: a.role,