@clagentic/console 1.8.0 → 1.9.0-beta.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.
Files changed (35) hide show
  1. package/lib/build-sha.json +2 -2
  2. package/lib/generated/claude-model-catalog.json +180 -0
  3. package/lib/model-catalog.js +202 -0
  4. package/lib/model-context-windows.js +9 -0
  5. package/lib/model-families.js +243 -0
  6. package/lib/project-connection.js +16 -4
  7. package/lib/project-sessions.js +102 -18
  8. package/lib/project.js +4 -0
  9. package/lib/public/css/menus.css +67 -0
  10. package/lib/public/css/server-settings.css +72 -0
  11. package/lib/public/index.html +3 -0
  12. package/lib/public/modules/app-loop-ui.js +4 -0
  13. package/lib/public/modules/app-messages.js +29 -4
  14. package/lib/public/modules/app-panels.js +93 -24
  15. package/lib/public/modules/app-rate-limit.js +1 -1
  16. package/lib/public/modules/model-context-windows.js +9 -0
  17. package/lib/public/modules/model-families.js +230 -0
  18. package/lib/public/modules/project-settings.js +1 -0
  19. package/lib/public/modules/scheduler.js +5 -0
  20. package/lib/public/modules/server-settings.js +14 -12
  21. package/lib/public/modules/settings-defaults.js +151 -41
  22. package/lib/public/modules/tools.js +38 -0
  23. package/lib/sdk-bridge.js +88 -13
  24. package/lib/sdk-message-processor.js +128 -3
  25. package/lib/server.js +55 -0
  26. package/lib/session-activity.js +282 -0
  27. package/lib/sessions.js +58 -3
  28. package/lib/terminal-manager.js +40 -0
  29. package/lib/utils.js +44 -0
  30. package/lib/ws-schema.js +1 -0
  31. package/lib/yoke/adapters/claude-worker.js +6 -2
  32. package/lib/yoke/adapters/claude.js +377 -87
  33. package/lib/yoke/adapters/codex.js +20 -0
  34. package/package.json +1 -1
  35. package/scripts/generate-model-catalog.js +337 -0
@@ -2,6 +2,7 @@ var usersModule = require("./users");
2
2
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
3
3
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
4
4
  var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping, sweepClearedPermissionIndex } = require("./sdk-permission-ownership");
5
+ var sessionActivity = require("./session-activity");
5
6
 
6
7
  function attachMessageProcessor(ctx) {
7
8
  var sm = ctx.sm;
@@ -35,6 +36,76 @@ function attachMessageProcessor(ctx) {
35
36
  sm.sendToSession(session, obj);
36
37
  }
37
38
 
39
+ // lr-9bcd7b: server activity registry wiring. Acquire/release a token in
40
+ // lib/session-activity.js and broadcast the SESSION LIST only on a real
41
+ // 0->1 / 1->0 transition of the derived active boolean (the chattiness
42
+ // mitigation the spec makes mandatory — a Task tool starting/progressing
43
+ // while another source is already active must not trigger a broadcast).
44
+ //
45
+ // session.isProcessing itself is intentionally left as a legacy write in
46
+ // parallel (see the 'result' handler below) rather than fully retired in
47
+ // this pass — see this task's PR body for the explicit shadow-mode
48
+ // boundary and what's deferred to lr-66c118.
49
+ function acquireActivity(session, token, info) {
50
+ var result = sessionActivity.acquireToken(session, token, info);
51
+ if (result.changed) sm.broadcastSessionList();
52
+ return result;
53
+ }
54
+
55
+ function releaseActivity(session, token) {
56
+ var result = sessionActivity.releaseToken(session, token);
57
+ if (result.changed) sm.broadcastSessionList();
58
+ return result;
59
+ }
60
+
61
+ // lr-c56476: Codex parity wiring. Codex (lib/yoke/adapters/codex.js) has no
62
+ // subagent concept -- ordinary tool_start/thinking_start there are NOT a
63
+ // backgrounded Task the way Claude's Task tool is, so this does not (and
64
+ // must not) fabricate a Task lifecycle. What it DOES need: Codex's
65
+ // tool_start/thinking_start/tool_result/result already ride through this
66
+ // same shared processor, but unlike Claude, Codex has no equivalent of the
67
+ // turn-wide isProcessing=true covering ordinary tool activity implicitly --
68
+ // acquiring an explicit token here is how Codex activity becomes visible to
69
+ // the derived isProcessing/picker-dot path at all. Gated on
70
+ // session.vendor === "codex" so Claude's existing behavior (which already
71
+ // has turn-wide isProcessing coverage for ordinary tools, and only acquires
72
+ // a token for backgrounded Task tools) is completely unchanged by this.
73
+ //
74
+ // Release happens on tool_result (per-token, matching Claude's tool_result
75
+ // release) OR at the turn's result event, which releases EVERY still-live
76
+ // Codex-sourced token for this session at once -- a catch-all so a
77
+ // thinking block (which Codex ends via its own top-level thinking_stop
78
+ // event that this shared processor does not otherwise dispatch) is never
79
+ // left acquired past the end of its own turn. This mirrors Claude's
80
+ // task_notification acting as a second, idempotent drain path for a token
81
+ // that tool_result might not otherwise catch.
82
+ function releaseAllCodexActivity(session) {
83
+ var sources = sessionActivity.listActiveSources(session);
84
+ for (var i = 0; i < sources.length; i++) {
85
+ if (sources[i].source === "codex-tool" || sources[i].source === "codex-thinking") {
86
+ releaseActivity(session, sources[i].token);
87
+ }
88
+ }
89
+ }
90
+
91
+ // lr-9bcd7b / lr-255e residual #2: the SDK 'result' handler used to clear
92
+ // session.isProcessing UNCONDITIONALLY, with no check for a still-running
93
+ // backgrounded Task — the exact defect that made every session/project/
94
+ // recent picker's green dot go dark the instant a subagent started (picker
95
+ // dots read session.isProcessing directly — lib/sessions.js
96
+ // mapSessionForClient). Now: only clear isProcessing when the activity
97
+ // registry agrees nothing else is live for this session (e.g. no
98
+ // backgrounded Task still running). If the registry disagrees (something
99
+ // is still active), isProcessing stays true — this is the shadow-mode
100
+ // reconciliation called for in the PR body: the legacy field is kept in
101
+ // sync with the new derived source of truth at its known-wrong write site,
102
+ // rather than either fully retiring session.isProcessing (too large a diff
103
+ // for this pass) or leaving this specific site unconditionally wrong (the
104
+ // one residual this task exists to fix).
105
+ function setIsProcessingFromRegistry(session) {
106
+ session.isProcessing = sessionActivity.isSessionActive(session);
107
+ }
108
+
38
109
  function getModelsForVendor(vendor) {
39
110
  if (vendor && sm.modelsByVendor && sm.modelsByVendor[vendor]) return sm.modelsByVendor[vendor];
40
111
  return sm.availableModels || [];
@@ -231,9 +302,20 @@ function attachMessageProcessor(ctx) {
231
302
  if (parsed.yokeType === "tool_start") {
232
303
  session.blocks[idx] = { type: "tool_use", id: parsed.toolId, name: parsed.toolName, inputJson: "" };
233
304
  sendAndRecord(session, { type: "tool_start", id: parsed.toolId, name: parsed.toolName });
305
+ // lr-c56476: Codex parity -- see releaseAllCodexActivity above for why
306
+ // this is gated to vendor === "codex" and not applied to Claude.
307
+ if (session.vendor === "codex" && parsed.toolId) {
308
+ acquireActivity(session, parsed.toolId, { source: "codex-tool", label: parsed.toolName || "" });
309
+ }
234
310
  } else if (parsed.yokeType === "thinking_start") {
235
311
  session.blocks[idx] = { type: "thinking", thinkingText: "", startTime: Date.now() };
236
312
  sendAndRecord(session, { type: "thinking_start" });
313
+ // lr-c56476: Codex parity. Token id keyed on blockId (Codex's
314
+ // "blk_N" counter, see lib/yoke/adapters/codex.js flattenEvent) since
315
+ // a thinking_start event carries no separate tool-style id.
316
+ if (session.vendor === "codex") {
317
+ acquireActivity(session, "thinking_" + idx, { source: "codex-thinking", label: "" });
318
+ }
237
319
  } else if (parsed.yokeType === "text_start") {
238
320
  session.blocks[idx] = { type: "text" };
239
321
  }
@@ -288,6 +370,14 @@ function attachMessageProcessor(ctx) {
288
370
  is_error: !!parsed.isError,
289
371
  });
290
372
 
373
+ // lr-c56476: Codex parity -- release the token acquired at tool_start
374
+ // for this same toolId. releaseActivity is idempotent (see
375
+ // session-activity.js), so this is always safe even if the token was
376
+ // already released elsewhere (e.g. by the result-time catch-all below).
377
+ if (session.vendor === "codex" && parsed.toolId) {
378
+ releaseActivity(session, parsed.toolId);
379
+ }
380
+
291
381
  // TeamCreate result: extract team ID from result text and activate
292
382
  if (onTeamCreate && session._pendingTeamCreates && session._pendingTeamCreates[parsed.toolId]) {
293
383
  var pending = session._pendingTeamCreates[parsed.toolId];
@@ -352,6 +442,10 @@ function attachMessageProcessor(ctx) {
352
442
  if (block.name === "Task") {
353
443
  if (!session.activeTaskToolIds) session.activeTaskToolIds = {};
354
444
  session.activeTaskToolIds[block.id] = true;
445
+ // lr-9bcd7b: acquire an activity token for the lifetime of this
446
+ // backgrounded Task — released at the tool_result / task_notification
447
+ // drain paths below (whichever fires first for this same block.id).
448
+ acquireActivity(session, block.id, { source: "task", label: input.description || "" });
355
449
  }
356
450
 
357
451
  if (pushModule && block.name === "AskUserQuestion" && input.questions) {
@@ -429,6 +523,19 @@ function attachMessageProcessor(ctx) {
429
523
  });
430
524
  delete session.activeTaskToolIds[block.tool_use_id];
431
525
  }
526
+ // lr-9bcd7b: release the activity token acquired at block_stop for
527
+ // this tool id, unconditionally -- NOT gated on activeTaskToolIds
528
+ // still containing the entry. The 'result' handler's pre-existing
529
+ // lr-9d4b cleanup (retainPreservedTaskBookkeeping) already trims
530
+ // activeTaskToolIds down to only Task ids with a preserved
531
+ // permission on EVERY result, so a Task with no pending permission
532
+ // of its own has its activeTaskToolIds entry deleted before this
533
+ // tool_result ever arrives -- gating the release on that same map
534
+ // would silently skip it and leak the token forever. releaseToken
535
+ // is idempotent (no-op if this id was never acquired, or already
536
+ // released by task_notification), so calling it unconditionally
537
+ // for every tool_result is always safe.
538
+ releaseActivity(session, block.tool_use_id);
432
539
  var resultText = "";
433
540
  var resultImages = [];
434
541
  if (typeof block.content === "string") {
@@ -464,6 +571,17 @@ function attachMessageProcessor(ctx) {
464
571
  } else if (parsed.yokeType === "result") {
465
572
  session.blocks = {};
466
573
  session.sentToolResults = {};
574
+ // lr-c56476: Codex parity catch-all -- release EVERY still-live
575
+ // Codex-sourced token for this session now, regardless of whether its
576
+ // own tool_result/thinking_stop already fired. This runs first, before
577
+ // the error_during_execution early return below, so a turn that ends
578
+ // in an SDK execution error still drains Codex's tokens (Codex has no
579
+ // task_notification-equivalent second drain path the way Claude does,
580
+ // so this is the ONLY backstop short of the next startQuery's
581
+ // generation bump -- see this task's PR body for why that generation
582
+ // bump already covers the harder case of abort/interrupt ending the
583
+ // stream before 'result' is ever reached at all).
584
+ if (session.vendor === "codex") releaseAllCodexActivity(session);
467
585
  // lr-9d4b: Preserve pendingPermissions entries owned by a backgrounded
468
586
  // sub-agent that is still running when the PARENT turn's 'result' arrives.
469
587
  // A Task tool launched an async sub-agent whose own Bash/etc permission
@@ -526,7 +644,7 @@ function attachMessageProcessor(ctx) {
526
644
  : "Unknown SDK error";
527
645
  if (parsed.terminalReason) execError += " (reason: " + parsed.terminalReason + ")";
528
646
  console.error("[sdk-bridge] Execution error for session " + session.localId + ": " + execError);
529
- session.isProcessing = false;
647
+ setIsProcessingFromRegistry(session);
530
648
  onProcessingChanged();
531
649
  sendAndRecord(session, { type: "error", text: "Claude error: " + execError });
532
650
  sendAndRecord(session, { type: "done", code: 1 });
@@ -534,7 +652,7 @@ function attachMessageProcessor(ctx) {
534
652
  return;
535
653
  }
536
654
 
537
- session.isProcessing = false;
655
+ setIsProcessingFromRegistry(session);
538
656
  onProcessingChanged();
539
657
  // Detect "Not logged in" scenario early for the check below
540
658
  var previewTrimmed = (session.responsePreview || "").trim();
@@ -699,7 +817,7 @@ function attachMessageProcessor(ctx) {
699
817
 
700
818
  } else if (parsed.yokeType === "task_updated") {
701
819
  // Live task state patches (status, description, error, backgrounded)
702
- var taskId = parsed.task_id;
820
+ var taskId = parsed.taskId;
703
821
  var patch = parsed.patch || {};
704
822
  var parentId = null;
705
823
  if (session.taskIdMap) {
@@ -739,6 +857,13 @@ function attachMessageProcessor(ctx) {
739
857
  summary: parsed.summary || "",
740
858
  usage: parsed.usage || null,
741
859
  });
860
+ // lr-9bcd7b: release the activity token for this Task, in case the
861
+ // tool_result drain path above never fired for it (e.g. the SDK
862
+ // delivered task_notification without a corresponding tool_result
863
+ // block, or delivered it first). releaseActivity is idempotent —
864
+ // if tool_result already released this same token, this is a no-op.
865
+ if (session.activeTaskToolIds) delete session.activeTaskToolIds[parentId];
866
+ releaseActivity(session, parentId);
742
867
  }
743
868
  if (session.taskIdMap) {
744
869
  for (var k in session.taskIdMap) {
package/lib/server.js CHANGED
@@ -1148,6 +1148,52 @@ function createServer(opts) {
1148
1148
  broadcastProcessingChange();
1149
1149
  }
1150
1150
 
1151
+ // lr-13c047 (Badge A prune-on-delete): a deleted session's crossProjectUnread
1152
+ // entry previously had no clear path at all — onSessionDone is increment-only
1153
+ // and the only clears were on full project-switch reconnect (below) or the
1154
+ // same-project ws._clayUnread zeroing in switchSession. If the session that
1155
+ // accrued the unread count is deleted before any client ever reconnects to
1156
+ // its project, that count is now permanently unreachable (its key can never
1157
+ // be zeroed by the connect-time prefix clear, since the session no longer
1158
+ // exists to switch to) — a phantom that inflates the Projects-tab badge
1159
+ // forever. Delete the key for every client of every project so the rollup
1160
+ // (getCrossProjectUnreadForSlug) stops counting it on the next broadcast.
1161
+ function onSessionDeleted(sourceSlug, sourceLocalId) {
1162
+ var key = crossUnreadKey(sourceSlug, sourceLocalId);
1163
+ var sawEntry = false;
1164
+ projects.forEach(function (ctx) {
1165
+ ctx.forEachClient(function (ws) {
1166
+ var map = getCrossProjectUnread(ws);
1167
+ if (key in map) {
1168
+ sawEntry = true;
1169
+ delete map[key];
1170
+ }
1171
+ });
1172
+ });
1173
+ if (sawEntry) broadcastProcessingChange();
1174
+ }
1175
+
1176
+ // lr-13c047 (Badge A non-switch clear path): zero every crossProjectUnread
1177
+ // entry for a given project slug, for one client, without requiring that
1178
+ // client to actually connect to (switch into) that project. Wired to a
1179
+ // client-initiated "mark_cross_project_read" WS message (lib/project-sessions.js)
1180
+ // so a user can dismiss the Projects-tab badge for a project they don't want
1181
+ // to open right now — previously the only clear path was the connect-time
1182
+ // prefix zero at :1069-1077 below, which requires a full navigation.
1183
+ function markCrossProjectRead(ws, projSlug) {
1184
+ var map = getCrossProjectUnread(ws);
1185
+ var prefix = projSlug + "::";
1186
+ var keys = Object.keys(map);
1187
+ var cleared = false;
1188
+ for (var i = 0; i < keys.length; i++) {
1189
+ if (keys[i].indexOf(prefix) === 0 && map[keys[i]]) {
1190
+ map[keys[i]] = 0;
1191
+ cleared = true;
1192
+ }
1193
+ }
1194
+ if (cleared) broadcastProcessingChange();
1195
+ }
1196
+
1151
1197
  // --- Debounced broadcast for processing status changes ---
1152
1198
  var processingUpdateTimer = null;
1153
1199
  function broadcastProcessingChange() {
@@ -1329,6 +1375,15 @@ function createServer(opts) {
1329
1375
  onPresenceChange: broadcastPresenceChange,
1330
1376
  onProcessingChanged: broadcastProcessingChange,
1331
1377
  onSessionDone: function (localId) { onSessionDone(slug, localId); },
1378
+ // lr-13c047: prune crossProjectUnread['slug::localId'] for every client
1379
+ // when a session in this project is deleted — see onSessionDeleted's
1380
+ // header above.
1381
+ onSessionDeleted: function (localId) { onSessionDeleted(slug, localId); },
1382
+ // lr-13c047: expose the non-switch "mark read" clear path (see
1383
+ // markCrossProjectRead's header above) so lib/project-sessions.js can
1384
+ // wire a client-initiated mark_cross_project_read WS message without
1385
+ // reaching into server.js internals directly.
1386
+ markCrossProjectRead: function (ws, projSlug) { markCrossProjectRead(ws, projSlug); },
1332
1387
  // lr-0aa7b6: per-session unread lookup for the Home Hub Recent
1333
1388
  // Sessions data path — see getSessionUnread's header above for why
1334
1389
  // this must distinguish "own project" (ws._clayUnread) from
@@ -0,0 +1,282 @@
1
+ // lr-9bcd7b: Server-authoritative activity registry.
2
+ //
3
+ // Problem this replaces: session.isProcessing is written directly at ~26
4
+ // scattered call sites across roughly 8 files (sdk-message-processor.js,
5
+ // sdk-bridge.js, project-sessions.js, and others). One of those sites --
6
+ // the SDK 'result' handler -- clears it unconditionally with no check for
7
+ // a still-running backgrounded Task subagent (lr-255e close comment #8,
8
+ // residual #2). session_list ships isProcessing per session
9
+ // (lib/sessions.js mapSessionForClient) and every session/project/recent
10
+ // picker renders it, so every picker's green dot goes dark the instant a
11
+ // subagent starts, on top of the equivalent in-conversation dots bug.
12
+ //
13
+ // Design: reference-counted token registry, one per session, stored as
14
+ // plain data. isProcessing becomes DERIVED (token count > 0) instead of an
15
+ // independently written boolean. Any subsystem that starts genuine session
16
+ // activity acquires a token; it releases the SAME token on every terminal
17
+ // path (success, error, abort). The derived boolean cannot go stale because
18
+ // of a single missed clear site the way the old boolean could -- as long as
19
+ // acquire/release are balanced, and leak resistance (below) covers the case
20
+ // where they are not.
21
+ //
22
+ // Leak resistance -- four layers, PRIMARY listed first, weakest listed last.
23
+ // A design that trades "dots missing" for "dots stuck on forever" is not an
24
+ // improvement (a stuck dot destroys trust in the signal permanently), so
25
+ // the layers are ordered by how proactively they prevent that outcome:
26
+ //
27
+ // 1. PRIMARY -- generation counter. Each token is stamped with the
28
+ // session's activity generation at acquire time. bumpGeneration(session)
29
+ // (called by the caller on every genuine new-query/turn boundary) makes
30
+ // every token from a prior generation invisible to isSessionActive/
31
+ // getActiveCount immediately, with no timer and no explicit release
32
+ // required. This is the same ownership-guard shape already proved in
33
+ // this codebase for query/session ownership (sdk-bridge.js's
34
+ // `session.queryInstance === myQueryInstance` checks around the
35
+ // processQueryStream finally block) -- a stale reference from an
36
+ // earlier generation is simply outvoted, not manually hunted down.
37
+ // 2. Explicit release on every known terminal path (tool_result,
38
+ // task_notification, turn-boundary block_stop cleanup) -- ordinary,
39
+ // expected cleanup, exercised directly by this module's tests and by
40
+ // the sdk-message-processor wiring.
41
+ // 3. BACKSTOP ONLY -- staleness sweep. sweepStaleTokens(session, maxAgeMs)
42
+ // drops any token older than maxAgeMs regardless of generation. This
43
+ // exists purely to bound the worst case (a token whose owning
44
+ // subsystem died without ever calling release AND without a
45
+ // generation bump happening in between -- e.g. a session that idles
46
+ // forever mid-turn). It is not the primary defense and must never be
47
+ // the ONLY thing keeping the registry honest; layers 1 and 2 are
48
+ // expected to handle the overwhelming majority of releases.
49
+ // 4. Wholesale replacement on reconnect, never merge. hydrateSnapshot()
50
+ // always REPLACES a session's registry outright rather than merging
51
+ // entries -- a reconnecting client must never see a union of stale
52
+ // pre-disconnect tokens and fresh post-reconnect ones.
53
+ //
54
+ // Chattiness mitigation -- mandatory, not optional (see lr-9bcd7b spec).
55
+ // isProcessing changed ~2x/turn under the old boolean; a token registry
56
+ // changes on every tool start/stop and every subagent progress tick, which
57
+ // would be an O(sessions x clients) JSON-serialization broadcast per tool
58
+ // call if naively wired to broadcastSessionList(). The registry itself
59
+ // does NOT broadcast anything -- it is plain data. The caller (sdk-bridge.js/
60
+ // sdk-message-processor.js) is responsible for calling acquireToken/
61
+ // releaseToken and reacting ONLY to the returned `changed` flag, which is
62
+ // true exactly on a 0->1 or 1->0 transition of the derived boolean.
63
+ // Acquiring a second token while the session is already active (count >=1
64
+ // before the call) returns changed:false -- the derived boolean does not
65
+ // move, so the caller must not broadcast. This collapses volume back to
66
+ // roughly the old ~2x/turn rate (only the first acquire and the last
67
+ // release of any turn actually flip the boolean), independent of how many
68
+ // tools/subagents are concurrently active.
69
+
70
+ /**
71
+ * Create a fresh, empty activity registry for a session.
72
+ * @returns {{tokens: object, generation: number}}
73
+ */
74
+ function createRegistry() {
75
+ return {
76
+ tokens: {}, // token -> { source, label, startedAt, generation }
77
+ generation: 0,
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Ensure session.activity exists, creating it if this is the first call for
83
+ * this session. Callers should prefer this over reading session.activity
84
+ * directly so a session created before this module existed (or a bare test
85
+ * double) degrades to an empty registry instead of throwing.
86
+ * @param {object} session
87
+ * @returns {{tokens: object, generation: number}}
88
+ */
89
+ function ensureRegistry(session) {
90
+ if (!session.activity) session.activity = createRegistry();
91
+ return session.activity;
92
+ }
93
+
94
+ /**
95
+ * True if the session has at least one live (current-generation) token.
96
+ * This is the DERIVED value that replaces session.isProcessing as a
97
+ * server-side write target -- see the module header for why write sites
98
+ * are being retired in favor of reading this.
99
+ * @param {object} session
100
+ * @returns {boolean}
101
+ */
102
+ function isSessionActive(session) {
103
+ return getActiveCount(session) > 0;
104
+ }
105
+
106
+ /**
107
+ * Count of live (current-generation) tokens. Stale-generation tokens that
108
+ * have not yet been physically swept still don't count -- generation is
109
+ * checked at read time, not just at sweep time, so a generation bump takes
110
+ * effect immediately even before sweepStaleTokens or the next acquire/
111
+ * release physically deletes the entries.
112
+ * @param {object} session
113
+ * @returns {number}
114
+ */
115
+ function getActiveCount(session) {
116
+ var registry = ensureRegistry(session);
117
+ var count = 0;
118
+ for (var token in registry.tokens) {
119
+ if (registry.tokens[token].generation === registry.generation) count++;
120
+ }
121
+ return count;
122
+ }
123
+
124
+ /**
125
+ * Acquire a new activity token for `source` (e.g. "task", "tool",
126
+ * "subagent"). Stamps the token with the session's CURRENT generation, so a
127
+ * token acquired just before a generation bump is immediately treated as
128
+ * stale by every reader without needing its own release call.
129
+ *
130
+ * @param {object} session
131
+ * @param {string} token - caller-chosen unique id (e.g. a tool_use id).
132
+ * Acquiring the same token twice is idempotent (see double-acquire note
133
+ * below) -- the second call refreshes label/startedAt but does not
134
+ * double-count or change `changed`.
135
+ * @param {object} [info] - { source, label }
136
+ * @returns {{changed: boolean, activeCount: number}}
137
+ * changed is true only on a 0->1 transition of isSessionActive -- the
138
+ * mandatory chattiness invariant. Acquiring a second (or further) token
139
+ * while the session is already active returns changed:false.
140
+ */
141
+ function acquireToken(session, token, info) {
142
+ var registry = ensureRegistry(session);
143
+ var wasActive = isSessionActive(session);
144
+ var existed = Object.prototype.hasOwnProperty.call(registry.tokens, token)
145
+ && registry.tokens[token].generation === registry.generation;
146
+ registry.tokens[token] = {
147
+ source: (info && info.source) || "unknown",
148
+ label: (info && info.label) || "",
149
+ startedAt: existed ? registry.tokens[token].startedAt : Date.now(),
150
+ generation: registry.generation,
151
+ };
152
+ var nowActive = true; // acquiring always leaves at least one live token
153
+ return { changed: !wasActive && nowActive, activeCount: getActiveCount(session) };
154
+ }
155
+
156
+ /**
157
+ * Release a token. Idempotent -- releasing an already-released or
158
+ * never-acquired token is a no-op (returns changed:false), never an error.
159
+ * This matters because multiple terminal paths can race to release the
160
+ * same logical unit of work (e.g. tool_result AND a later task_notification
161
+ * for the same Task tool id) -- see sdk-message-processor.js's existing
162
+ * lr-9d4b ownership-cleanup pattern, which this mirrors.
163
+ *
164
+ * @param {object} session
165
+ * @param {string} token
166
+ * @returns {{changed: boolean, activeCount: number}}
167
+ * changed is true only on a 1->0 transition of isSessionActive.
168
+ */
169
+ function releaseToken(session, token) {
170
+ var registry = ensureRegistry(session);
171
+ var wasActive = isSessionActive(session);
172
+ delete registry.tokens[token];
173
+ var nowActive = isSessionActive(session);
174
+ return { changed: wasActive && !nowActive, activeCount: getActiveCount(session) };
175
+ }
176
+
177
+ /**
178
+ * PRIMARY leak-resistance layer. Bump the session's activity generation --
179
+ * every token acquired before this call becomes invisible to
180
+ * isSessionActive/getActiveCount immediately, with no explicit release
181
+ * needed. Callers should invoke this at genuine new-query/turn-start
182
+ * boundaries (the same boundary sdk-bridge.js already treats as
183
+ * "isNewQuery" / resets activeTaskToolIds for) so a subagent or tool that
184
+ * died silently mid-turn cannot hold the indicator on forever into an
185
+ * unrelated later turn.
186
+ *
187
+ * This reuses the ownership-guard SHAPE already proved in this codebase at
188
+ * sdk-bridge.js's `session.queryInstance === myQueryInstance` checks (a
189
+ * stale reference is outvoted by identity/generation comparison, not
190
+ * tracked down and manually cleared) -- see lr-8355.
191
+ *
192
+ * @param {object} session
193
+ * @returns {{changed: boolean, activeCount: number}}
194
+ * changed is true if this bump caused a transition from active to
195
+ * inactive (i.e. every live token was stale-generation and got dropped).
196
+ */
197
+ function bumpGeneration(session) {
198
+ var registry = ensureRegistry(session);
199
+ var wasActive = isSessionActive(session);
200
+ registry.generation++;
201
+ // Physically drop stale entries now rather than waiting for the next
202
+ // sweep -- keeps registry.tokens from growing unboundedly across a very
203
+ // long-lived session with many turns.
204
+ for (var token in registry.tokens) {
205
+ if (registry.tokens[token].generation !== registry.generation) {
206
+ delete registry.tokens[token];
207
+ }
208
+ }
209
+ var nowActive = isSessionActive(session);
210
+ return { changed: wasActive && !nowActive, activeCount: getActiveCount(session) };
211
+ }
212
+
213
+ /**
214
+ * BACKSTOP ONLY leak-resistance layer -- see module header. Drops any token
215
+ * older than maxAgeMs regardless of generation. Never call this as the
216
+ * primary mechanism for clearing activity; it exists solely to bound the
217
+ * worst case where a subsystem died without releasing AND no generation
218
+ * bump has happened since (e.g. a session idling forever mid-turn with no
219
+ * new query started).
220
+ *
221
+ * @param {object} session
222
+ * @param {number} maxAgeMs
223
+ * @returns {{changed: boolean, activeCount: number, swept: number}}
224
+ */
225
+ function sweepStaleTokens(session, maxAgeMs) {
226
+ var registry = ensureRegistry(session);
227
+ var wasActive = isSessionActive(session);
228
+ var now = Date.now();
229
+ var swept = 0;
230
+ for (var token in registry.tokens) {
231
+ if (now - registry.tokens[token].startedAt > maxAgeMs) {
232
+ delete registry.tokens[token];
233
+ swept++;
234
+ }
235
+ }
236
+ var nowActive = isSessionActive(session);
237
+ return { changed: wasActive && !nowActive, activeCount: getActiveCount(session), swept: swept };
238
+ }
239
+
240
+ /**
241
+ * Wholesale-replace a session's registry (used on reconnect hydration) --
242
+ * NEVER merge with whatever the client last saw. See module header layer 4.
243
+ * @param {object} session
244
+ * @param {{tokens: object, generation: number}} [snapshot] - defaults to a
245
+ * fresh empty registry when omitted, matching "reconnect clears activity
246
+ * unless the caller has a live snapshot to restore".
247
+ */
248
+ function replaceRegistry(session, snapshot) {
249
+ session.activity = snapshot || createRegistry();
250
+ }
251
+
252
+ /**
253
+ * Detailed per-source breakdown of currently-live tokens, for scoping to
254
+ * the viewing client only (ws._clayActiveSession-style filtering) rather
255
+ * than broadcasting to every connected client -- see lr-9bcd7b spec's
256
+ * chattiness mitigation #3.
257
+ * @param {object} session
258
+ * @returns {Array<{token: string, source: string, label: string, startedAt: number}>}
259
+ */
260
+ function listActiveSources(session) {
261
+ var registry = ensureRegistry(session);
262
+ var out = [];
263
+ for (var token in registry.tokens) {
264
+ var entry = registry.tokens[token];
265
+ if (entry.generation !== registry.generation) continue;
266
+ out.push({ token: token, source: entry.source, label: entry.label, startedAt: entry.startedAt });
267
+ }
268
+ return out;
269
+ }
270
+
271
+ module.exports = {
272
+ createRegistry: createRegistry,
273
+ ensureRegistry: ensureRegistry,
274
+ isSessionActive: isSessionActive,
275
+ getActiveCount: getActiveCount,
276
+ acquireToken: acquireToken,
277
+ releaseToken: releaseToken,
278
+ bumpGeneration: bumpGeneration,
279
+ sweepStaleTokens: sweepStaleTokens,
280
+ replaceRegistry: replaceRegistry,
281
+ listActiveSources: listActiveSources,
282
+ };