@clagentic/console 1.8.0 → 1.9.0-beta.2

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 (64) hide show
  1. package/bin/cli.js +12 -1
  2. package/lib/agents.js +13 -3
  3. package/lib/build-sha.json +2 -2
  4. package/lib/cli/ipc-subcommands.js +40 -4
  5. package/lib/daemon.js +25 -1
  6. package/lib/generated/claude-model-catalog.json +180 -0
  7. package/lib/model-catalog.js +202 -0
  8. package/lib/model-families.js +243 -0
  9. package/lib/project-connection.js +30 -5
  10. package/lib/project-loop.js +46 -2
  11. package/lib/project-sessions.js +133 -21
  12. package/lib/project-user-message.js +70 -3
  13. package/lib/project.js +11 -1
  14. package/lib/public/app.js +14 -4
  15. package/lib/public/css/base.css +14 -0
  16. package/lib/public/css/home-hub.css +28 -8
  17. package/lib/public/css/icon-strip.css +17 -0
  18. package/lib/public/css/menus.css +67 -0
  19. package/lib/public/css/messages.css +11 -0
  20. package/lib/public/css/mobile-nav.css +22 -0
  21. package/lib/public/css/server-settings.css +72 -0
  22. package/lib/public/css/sidebar.css +15 -0
  23. package/lib/public/css/title-bar.css +10 -1
  24. package/lib/public/index.html +4 -0
  25. package/lib/public/modules/activity-latch.js +159 -0
  26. package/lib/public/modules/activity-state.js +157 -0
  27. package/lib/public/modules/app-connection.js +10 -4
  28. package/lib/public/modules/app-favicon.js +88 -1
  29. package/lib/public/modules/app-home-hub.js +14 -11
  30. package/lib/public/modules/app-loop-ui.js +90 -2
  31. package/lib/public/modules/app-messages.js +117 -28
  32. package/lib/public/modules/app-panels.js +184 -56
  33. package/lib/public/modules/app-projects.js +28 -8
  34. package/lib/public/modules/app-rate-limit.js +14 -2
  35. package/lib/public/modules/model-families.js +230 -0
  36. package/lib/public/modules/project-settings.js +1 -0
  37. package/lib/public/modules/scheduler.js +5 -0
  38. package/lib/public/modules/server-settings.js +14 -12
  39. package/lib/public/modules/settings-defaults.js +151 -41
  40. package/lib/public/modules/sidebar-mobile.js +32 -22
  41. package/lib/public/modules/sidebar-projects.js +42 -14
  42. package/lib/public/modules/sidebar-sessions.js +168 -48
  43. package/lib/public/modules/tools.js +22 -12
  44. package/lib/sdk-bridge.js +389 -35
  45. package/lib/sdk-message-processor.js +215 -7
  46. package/lib/sdk-skill-discovery.js +46 -6
  47. package/lib/sdk-slash-enrichment.js +5 -2
  48. package/lib/server-hub-sessions.js +70 -0
  49. package/lib/server.js +79 -22
  50. package/lib/session-activity.js +289 -0
  51. package/lib/sessions.js +104 -3
  52. package/lib/smtp.js +10 -1
  53. package/lib/terminal-manager.js +40 -0
  54. package/lib/utils.js +44 -0
  55. package/lib/ws-schema.js +17 -0
  56. package/lib/yoke/adapters/claude-worker.js +6 -2
  57. package/lib/yoke/adapters/claude.js +384 -88
  58. package/lib/yoke/adapters/codex.js +239 -31
  59. package/package.json +2 -2
  60. package/scripts/check-test-count.js +397 -0
  61. package/scripts/generate-model-catalog.js +337 -0
  62. package/scripts/test-file-completion-reporter.js +43 -0
  63. package/lib/model-context-windows.js +0 -65
  64. package/lib/public/modules/model-context-windows.js +0 -62
package/lib/sdk-bridge.js CHANGED
@@ -11,9 +11,10 @@ var { attachMessageProcessor } = require("./sdk-message-processor");
11
11
  var { readAgentToolsFromFile, parseFrontmatter, slugifyAgentName, AGENTS_SOURCE_DIR } = require("./agents");
12
12
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
13
13
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
14
- var { KNOWN_CONTEXT_WINDOWS: _BACKEND_KNOWN_CONTEXT_WINDOWS, resolveModelContextWindow } = require("./model-context-windows");
15
14
  var { runPreflight } = require("./settings-preflight");
16
15
  var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping, sweepClearedPermissionIndex } = require("./sdk-permission-ownership");
16
+ var { permissionGrantKey } = require("./utils");
17
+ var sessionActivity = require("./session-activity");
17
18
 
18
19
  // --- lr-29f9: Global concurrent-session ceiling ---
19
20
  // Counts queries that are actively running (startQuery entered, processQueryStream
@@ -26,11 +27,148 @@ var MAX_CONCURRENT_SESSIONS = (function () {
26
27
  return (env > 0) ? env : 50;
27
28
  })();
28
29
 
30
+ // --- lr-58c813: activity-source divergence probe (instrumentation only) ---
31
+ // Baseline measurement for the lr-5edd64 redesign: session.isProcessing (the
32
+ // plain mutable boolean, ~14 raw writers) is DERIVED at exactly one site
33
+ // (sdk-bridge.js's "lr-9bcd7b" comment above) from
34
+ // sessionActivity.isSessionActive(session) (the token registry). This counts
35
+ // how often the two disagree at runtime -- READ ONLY, never corrects or
36
+ // mutates either value, never gates a renderer, never changes what a client
37
+ // sees. Sizes the redesign; does not implement it.
38
+ //
39
+ // Genuinely read-only means never triggering session.activity's own lazy
40
+ // initialization either (session-activity.js's ensureRegistry assigns
41
+ // session.activity on first call, and lib/sessions.js's constructors never
42
+ // set it) -- see _peekIsSessionActive below, which this probe uses instead
43
+ // of sessionActivity.isSessionActive for exactly that reason.
44
+ //
45
+ // Bounded by construction: sampled once per session per idle-reaper tick
46
+ // (IDLE_CHECK_INTERVAL_MS = 60s below), not per tool call/message -- the
47
+ // reaper's own setInterval is the sampling clock, so this adds zero new
48
+ // per-event hot-path cost. A ring buffer caps the retained detail so a
49
+ // daemon that runs for weeks cannot grow this unboundedly; the total count
50
+ // is exact (increments forever), only the per-event detail is capped.
51
+ var _activityDivergenceCount = 0;
52
+ var _activityDivergenceSamples = []; // ring buffer, most-recent-first
53
+ var ACTIVITY_DIVERGENCE_SAMPLE_CAP = 20;
54
+
55
+ /**
56
+ * Non-mutating read of "does this session have at least one live activity
57
+ * token", WITHOUT going through sessionActivity.isSessionActive/
58
+ * getActiveCount -- both of those call ensureRegistry(session), which
59
+ * lazily creates and ASSIGNS session.activity on first call
60
+ * (lib/session-activity.js). Session objects from lib/sessions.js's two
61
+ * constructors never initialize session.activity, so calling the mutating
62
+ * path here would create it on every session's first idle-reaper tick --
63
+ * a real write this probe must never cause (PEACHES lr-58c813 finding).
64
+ *
65
+ * A session with no session.activity has, by construction, acquired zero
66
+ * tokens, so "absent" and "present but empty/stale-generation" both mean
67
+ * not-active -- this mirrors isSessionActive's own semantics exactly, it
68
+ * just never creates the registry to get there. Does not read/write
69
+ * anything in lib/session-activity.js, which is out of scope and proven
70
+ * correct twice already; this adapts the caller to the existing API
71
+ * instead of changing it.
72
+ */
73
+ function _peekIsSessionActive(session) {
74
+ var registry = session.activity;
75
+ if (!registry) return false;
76
+ for (var token in registry.tokens) {
77
+ if (registry.tokens[token].generation === registry.generation) return true;
78
+ }
79
+ return false;
80
+ }
81
+
82
+ /**
83
+ * Read-only comparison of the two activity sources for one session. Does not
84
+ * write session.isProcessing, does not call onProcessingChanged, does not
85
+ * touch the registry -- including never triggering the registry's own lazy
86
+ * initialization (see _peekIsSessionActive above). Call site (idle reaper,
87
+ * see startIdleReaper) observes BEFORE any reaper-driven correction runs in
88
+ * the same tick, so a divergence caused by a leaked token that the reaper is
89
+ * about to sweep is still counted -- the point is measuring how often
90
+ * production state actually disagrees, not how often it disagrees net of
91
+ * self-healing.
92
+ */
93
+ function _recordActivityDivergenceIfAny(session) {
94
+ var rawIsProcessing = !!session.isProcessing;
95
+ var derivedIsActive = _peekIsSessionActive(session);
96
+ if (rawIsProcessing === derivedIsActive) return;
97
+ _activityDivergenceCount++;
98
+ // lr-58c813 (BOBBIE finding): no sessionId here. process_stats (the
99
+ // handler that folds these samples into its response, see
100
+ // project-sessions.js) has no admin/role gate -- any authenticated
101
+ // client on a shared project could otherwise read another user's
102
+ // session ids through this counter. The measurement goal (how often the
103
+ // two sources disagree, and roughly under what conditions) survives
104
+ // without a per-session identifier, so the identifier is dropped rather
105
+ // than gating process_stats (which would widen this PR's scope into a
106
+ // pre-existing, unrelated auth gap -- see PR body).
107
+ var sample = {
108
+ ts: Date.now(),
109
+ rawIsProcessing: rawIsProcessing,
110
+ derivedIsActive: derivedIsActive,
111
+ hasQueryInstance: !!session.queryInstance,
112
+ };
113
+ _activityDivergenceSamples.unshift(sample);
114
+ if (_activityDivergenceSamples.length > ACTIVITY_DIVERGENCE_SAMPLE_CAP) {
115
+ _activityDivergenceSamples.length = ACTIVITY_DIVERGENCE_SAMPLE_CAP;
116
+ }
117
+ // lr-58c813 (PEACHES nit): no console.warn here. MILLER's diagnosis
118
+ // predicts divergence may be common, and this fires once per diverging
119
+ // session per idle-reaper tick (60s) forever -- an unbounded, unrated
120
+ // log volume risk on the operator's own machine for a value that isn't
121
+ // actionable as a log line anyway. The counter + bounded sample ring
122
+ // (both above) are the actual deliverable; dropping the warn and
123
+ // relying on getActivityDivergenceStats()/process_stats for visibility
124
+ // avoids the flood risk entirely rather than trying to rate-limit it.
125
+ }
126
+
127
+ // Module-scope accessor so tests and other bridge instances (this counter is
128
+ // intentionally shared across ALL project bridge instances, same as
129
+ // _activeLiveCount above) can read the current totals without reaching into
130
+ // closure state.
131
+ function getActivityDivergenceStats() {
132
+ return {
133
+ count: _activityDivergenceCount,
134
+ recentSamples: _activityDivergenceSamples.slice(),
135
+ };
136
+ }
137
+
138
+ // lr-8b476f: shared response builder for the agent-readable retrieval path
139
+ // (daemon.js's "get_activity_diagnostics" IPC command, over the existing
140
+ // daemon.sock Unix socket). Pulled out here — rather than inlined in
141
+ // daemon.js, which has no module.exports and cannot be safely required by a
142
+ // test without binding real sockets/HTTP servers — so this is unit-testable
143
+ // the same way getActivityDivergenceStats()/getActiveLiveCount() already
144
+ // are. Read-only: calls only the two existing module-level accessors above,
145
+ // writes nothing.
146
+ function buildActivityDiagnosticsResponse() {
147
+ var divergence = getActivityDivergenceStats();
148
+ return {
149
+ ok: true,
150
+ activeLiveCount: getActiveLiveCount(),
151
+ activityDivergenceCount: divergence.count,
152
+ activityDivergenceRecentSamples: divergence.recentSamples,
153
+ };
154
+ }
155
+
29
156
  // --- lr-2d91: MemAvailable gate ---
30
157
  // Default minimum available memory threshold in MB. Referenced by sdk-bridge
31
158
  // and daemon.js — changing this constant is the single place to adjust the default.
32
159
  var DEFAULT_MEM_AVAILABLE_MIN_MB = 1024;
33
160
 
161
+ // --- lr-5450ef: pendingMessages bound ---
162
+ // session.pendingMessages (pushMessage's between-turns buffer, lr-b61b) was
163
+ // unbounded — a session stuck with isProcessing pinned true (e.g. by a
164
+ // leaked activity token) would accept every subsequent message into this
165
+ // array forever with no UI signal. Bounding it turns an unbounded silent
166
+ // leak into a bounded, OBSERVABLE one: once full, the oldest buffered
167
+ // message is dropped to make room, and a diagnostic is emitted either way
168
+ // (see pushMessage) so the user sees SOMETHING went sideways instead of
169
+ // nothing.
170
+ var MAX_PENDING_MESSAGES = 20;
171
+
34
172
  // --- lr-2d91: cgroup context token guard ---
35
173
  // Empirical calibration: claude-opus-4 at 1M context peaks at ~15 GB RSS,
36
174
  // yielding approximately 67 tokens per MB of headroom consumed.
@@ -45,12 +183,6 @@ var DEFAULT_TOKENS_PER_MB_HEADROOM = 67;
45
183
  var DEFAULT_CGROUP_WARN_FRACTION = 0.8;
46
184
  var DEFAULT_CONTEXT_WINDOW_WARN_FRACTION = 0.8;
47
185
 
48
- // Known context windows for models the backend may encounter (lr-1f7e, lr-336f).
49
- // Imported from lib/model-context-windows.js — shared source of truth with the frontend.
50
- // The alias preserves backward compatibility for any callers that reference this name.
51
- var BACKEND_KNOWN_CONTEXT_WINDOWS = _BACKEND_KNOWN_CONTEXT_WINDOWS;
52
- // resolveModelContextWindow imported from lib/model-context-windows.js above.
53
-
54
186
  // Read Linux MemAvailable from /proc/meminfo synchronously.
55
187
  // Returns available memory in MB, or null on non-Linux or read failure.
56
188
  // Sub-millisecond on Linux; the synchronous read is correct here — this is a
@@ -99,6 +231,22 @@ function readCgroupHeadroomMB() {
99
231
  }
100
232
  }
101
233
 
234
+ // lr-3ccc78 — resolve the effective global skills/agents home for a query.
235
+ // On a shared multi-user daemon (linuxUser set), skill/agent discovery must
236
+ // read the SESSION OWNER's own ~/.claude/, not the daemon process's
237
+ // REAL_HOME (lib/config.js's REAL_HOME is a module-level constant computed
238
+ // once at process load and is never per-user). Falls back to REAL_HOME when
239
+ // linuxUser is absent — the single-user / no-OS-isolation case is unchanged.
240
+ function resolveEffectiveHome(linuxUser) {
241
+ if (!linuxUser) return null;
242
+ try {
243
+ var home = require("./os-users").getLinuxUserHome(linuxUser);
244
+ return home || null;
245
+ } catch (e) {
246
+ return null;
247
+ }
248
+ }
249
+
102
250
  // Extract serializable tool descriptors from MCP server instances.
103
251
  // Used for IPC to worker processes (McpSdkServerConfigWithInstance is not serializable).
104
252
  function extractMcpDescriptors(mcpServers) {
@@ -314,6 +462,28 @@ function createSDKBridge(opts) {
314
462
  installedVendors: sm.installedVendors || [],
315
463
  });
316
464
  }
465
+
466
+ // lr-041af8: session-scoped counterpart to sendModelInfoForVendor above.
467
+ // A single session's model choice (setModel, or the worker-driven
468
+ // model_changed event) must only update the chip for clients CURRENTLY
469
+ // VIEWING that session — sendModelInfoForVendor's broadcast (send()) was
470
+ // overwriting every other open session's model_info with whatever session
471
+ // last called setModel. Falls back to the broadcast helper when no session
472
+ // is available yet (mirrors setModel's own no-session-vendor-bound branch).
473
+ function sendModelInfoToSession(session, vendor, model) {
474
+ if (!session) {
475
+ sendModelInfoForVendor(vendor, model);
476
+ return;
477
+ }
478
+ sendToSession(session, {
479
+ type: "model_info",
480
+ model: model || "",
481
+ models: getModelsForVendor(vendor),
482
+ vendor: vendor || (adapter && adapter.vendor) || "claude",
483
+ availableVendors: sm.availableVendors || [],
484
+ installedVendors: sm.installedVendors || [],
485
+ });
486
+ }
317
487
  var onTurnDone = opts.onTurnDone || null;
318
488
 
319
489
  // --- Idle session reaper ---
@@ -348,6 +518,14 @@ function createSDKBridge(opts) {
348
518
  // liveChildReclaims handling).
349
519
  var IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
350
520
  var IDLE_CHECK_INTERVAL_MS = 60 * 1000; // check every 60 seconds
521
+ // lr-5450ef: BACKSTOP staleness window for the activity registry's leak
522
+ // resistance (see lib/session-activity.js header, layer 3). Deliberately
523
+ // shorter than IDLE_TIMEOUT_MS — this is recovering a session pinned by a
524
+ // leaked token (no live query, no way for the user to self-heal by typing
525
+ // again, since every message they send just buffers), not reaping a
526
+ // genuinely-idle-but-live session, so it should not make an operator wait
527
+ // a full 30 minutes to get their session back.
528
+ var ACTIVITY_STALE_MS = 5 * 60 * 1000; // 5 minutes
351
529
  var _idleReaperTimer = null;
352
530
 
353
531
  function startIdleReaper() {
@@ -355,12 +533,44 @@ function createSDKBridge(opts) {
355
533
  _idleReaperTimer = setInterval(function () {
356
534
  var now = Date.now();
357
535
  sm.sessions.forEach(function (session) {
536
+ if (session.destroying) return;
537
+
538
+ // lr-58c813: divergence probe, READ ONLY — observe the raw/derived
539
+ // activity values exactly as production has them right now, before
540
+ // any reaper-driven correction below runs this tick. See the
541
+ // _recordActivityDivergenceIfAny doc comment for why "before" matters.
542
+ _recordActivityDivergenceIfAny(session);
543
+
544
+ // lr-5450ef: sweepStaleTokens BACKSTOP — recover a session pinned by
545
+ // a leaked activity token (isProcessing derives true from the
546
+ // registry, but there is no live queryInstance left to ever call
547
+ // startQuery/bumpGeneration again). This is the "sweepStaleTokens
548
+ // has ZERO production call sites" gap: the registry's own PRIMARY
549
+ // layer (bumpGeneration) only runs from inside startQuery, which a
550
+ // pinned isProcessing prevents from ever being reached — nothing
551
+ // upstream of this reaper can self-heal that state. Runs BEFORE the
552
+ // "skip if isProcessing" idle-query check below on purpose, since a
553
+ // session with a leaked token and no queryInstance would otherwise
554
+ // never reach any reaper logic at all (lr-5450ef diagnosis: "the
555
+ // trap is self-sealing").
556
+ if (session.isProcessing && !session.queryInstance) {
557
+ var sweepResult = sessionActivity.sweepStaleTokens(session, ACTIVITY_STALE_MS);
558
+ if (sweepResult.changed) {
559
+ console.log("[sdk-bridge] Idle reaper: swept " + sweepResult.swept +
560
+ " stale activity token(s) for session " + session.localId +
561
+ ", recovering isProcessing=false" +
562
+ (session.title ? " title=" + JSON.stringify(session.title) : ""));
563
+ session.isProcessing = false;
564
+ onProcessingChanged();
565
+ sm.broadcastSessionList();
566
+ }
567
+ }
568
+
358
569
  // Skip sessions that are actively processing, have no query,
359
570
  // or are single-turn (Ralph Loop — managed by onQueryComplete).
360
571
  if (session.isProcessing) return;
361
572
  if (!session.queryInstance) return;
362
573
  if (session.singleTurn) return;
363
- if (session.destroying) return;
364
574
 
365
575
  var lastActivity = session.lastActivityAt || 0;
366
576
  if (now - lastActivity > IDLE_TIMEOUT_MS) {
@@ -439,12 +649,26 @@ function createSDKBridge(opts) {
439
649
  }
440
650
  console.log("[auto-title] Calling adapter.generateTitle with " + userMessages.length + " messages for session " + session.localId);
441
651
 
442
- sessionAdapter.generateTitle(userMessages, { cwd: cwd }).then(function(title) {
652
+ // lr-62157d: returns the promise chain (previously fire-and-forget) so
653
+ // this is directly awaitable in tests via _test_autoGenerateTitle; the
654
+ // real onAutoTitle callers (sdk-message-processor.js) call this
655
+ // fire-and-forget already and are unaffected by a function now
656
+ // returning a value they don't use.
657
+ return sessionAdapter.generateTitle(userMessages, { cwd: cwd }).then(function(title) {
443
658
  if (!title || title.length < 2) return;
444
659
  title = title.substring(0, 100);
445
- if (!session.titleManuallySet) {
660
+ // lr-62157d: overwrite whenever the current title is provisional (the
661
+ // raw first-message truncation from project-user-message.js, or no
662
+ // title at all) and the user hasn't manually renamed the session.
663
+ // Before titleProvisional existed, the first-message fallback looked
664
+ // exactly like a real title, so this guard had nothing that let it
665
+ // tell "already properly titled" apart from "still carrying the raw
666
+ // 50-char truncation" — this is what actually lets a real LLM title
667
+ // replace that truncation.
668
+ if ((session.titleProvisional || !session.title) && !session.titleManuallySet) {
446
669
  session.title = title;
447
670
  session.titleAutoGenerated = true;
671
+ session.titleProvisional = false;
448
672
  sm.saveSessionFile(session);
449
673
  sm.broadcastSessionList();
450
674
  if (session.cliSessionId && typeof adapter.renameSession === "function") {
@@ -473,8 +697,18 @@ function createSDKBridge(opts) {
473
697
  opts: opts,
474
698
  discoverSkillDirs: discoverSkillDirs,
475
699
  mergeSkills: mergeSkills,
476
- discoverSkillsWithMeta: function(cwdArg) { return discoverSkillsWithMeta(cwdArg); },
700
+ discoverSkillsWithMeta: function(cwdArg, homeOverride) { return discoverSkillsWithMeta(cwdArg, homeOverride); },
477
701
  mergeSkillsWithMeta: mergeSkillsWithMeta,
702
+ // lr-3ccc78 — session-owner home resolution for skill/agent discovery on
703
+ // a shared multi-user daemon. usersModule.findUserById(session.ownerId)
704
+ // is the same pattern already used elsewhere in this file (getFreshAuthState).
705
+ resolveSessionHome: function(session) {
706
+ var ownerId = session && session.ownerId;
707
+ if (!ownerId) return null;
708
+ var owner = usersModule.findUserById(ownerId);
709
+ var ownerLinuxUser = owner && owner.linuxUser ? owner.linuxUser : null;
710
+ return resolveEffectiveHome(ownerLinuxUser);
711
+ },
478
712
  });
479
713
  var processSDKMessage = msgProcessor.processSDKMessage;
480
714
  var sendAndRecord = msgProcessor.sendAndRecord;
@@ -796,8 +1030,10 @@ function createSDKBridge(opts) {
796
1030
  });
797
1031
  }
798
1032
 
799
- // Auto-approve if tool was previously allowed for session
800
- if (session.allowedTools && session.allowedTools[toolName]) {
1033
+ // Auto-approve if tool was previously allowed for session (lr-f969dc:
1034
+ // keyed on toolName + input discriminator, not bare toolName — see
1035
+ // permissionGrantKey doc comment for why the Skill tool needs this).
1036
+ if (session.allowedTools && session.allowedTools[permissionGrantKey(toolName, input)]) {
801
1037
  return Promise.resolve({ behavior: "allow", updatedInput: input });
802
1038
  }
803
1039
 
@@ -957,9 +1193,18 @@ function createSDKBridge(opts) {
957
1193
  sendToSession(session, { type: "context_usage", data: metaData.data });
958
1194
  break;
959
1195
  case "model_changed":
960
- sm.currentModel = metaData.model;
961
- sendModelInfoForVendor(session.vendor || (adapter && adapter.vendor) || "claude", metaData.model);
962
- send({ type: "config_state", model: sm.currentModel, mode: sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [] });
1196
+ // lr-041af8: this event is scoped to ONE session's worker
1197
+ // (the CLI itself changed model mid-stream, e.g. via a /model
1198
+ // slash command) — writing it into the shared sm.currentModel
1199
+ // was the same class of leak lr-db0437 fixed for setModel()
1200
+ // (see that function's header comment), just in the reverse
1201
+ // direction and left unfixed. Session-only write; targeted
1202
+ // sends via sendToSession so only clients viewing THIS session
1203
+ // see the change, matching every other per-session config_state
1204
+ // reply (project-sessions.js's set_model/switch_session).
1205
+ session.model = metaData.model;
1206
+ sendModelInfoToSession(session, session.vendor || (adapter && adapter.vendor) || "claude", metaData.model);
1207
+ sendToSession(session, { type: "config_state", model: metaData.model, mode: sm.currentPermissionMode || "default", effort: sm.currentEffort || "medium", betas: sm.currentBetas || [] });
963
1208
  break;
964
1209
  case "effort_changed":
965
1210
  sm.currentEffort = metaData.effort;
@@ -984,6 +1229,19 @@ function createSDKBridge(opts) {
984
1229
  if (session.isProcessing && session.taskStopRequested) {
985
1230
  session.isProcessing = false;
986
1231
  onProcessingChanged();
1232
+ // lr-5450ef: an interrupted turn can leave an activity token
1233
+ // acquired (block_stop, sdk-message-processor.js \u2014 Task originally,
1234
+ // widened to every tool_use block by lr-6e20f7) with no later
1235
+ // tool_result/task_notification ever arriving to release it \u2014 the
1236
+ // stream that would have delivered those events just ended here.
1237
+ // Bump the generation so that leaked token (and any other from this
1238
+ // turn) is immediately invisible to isSessionActive, same as the
1239
+ // PRIMARY leak-resistance layer already does at startQuery. Without
1240
+ // this, the finally block below re-derives isProcessing=true from
1241
+ // the leaked token and every later user message is silently
1242
+ // buffered (pushMessage) into a queue only startQuery ever drains \u2014
1243
+ // and startQuery is precisely what a pinned isProcessing prevents.
1244
+ sessionActivity.bumpGeneration(session);
987
1245
  send({ type: "status", processing: false });
988
1246
  sendAndRecord(session, { type: "thinking_stop" });
989
1247
  var interruptMsg = (session.vendor === "codex")
@@ -997,6 +1255,11 @@ function createSDKBridge(opts) {
997
1255
  if (session.isProcessing) {
998
1256
  session.isProcessing = false;
999
1257
  onProcessingChanged();
1258
+ // lr-5450ef: same leak-resistance bump as the taskStopRequested
1259
+ // branch above \u2014 an aborted/errored stream can also leave an
1260
+ // activity token acquired (any tool_use block since lr-6e20f7, not
1261
+ // only Task) with no terminal event left to release it.
1262
+ sessionActivity.bumpGeneration(session);
1000
1263
  if (err.name === "AbortError" || (myAbortController && myAbortController.signal.aborted) || session.taskStopRequested) {
1001
1264
  if (!session.destroying) {
1002
1265
  sendAndRecord(session, { type: "thinking_stop" });
@@ -1191,7 +1454,15 @@ function createSDKBridge(opts) {
1191
1454
  // Auto-continue on rate limit (scheduler sessions, or user setting)
1192
1455
  // Mark session as done processing so the late rate_limit_event handler
1193
1456
  // can detect the race condition and schedule auto-continue itself.
1194
- session.isProcessing = false;
1457
+ //
1458
+ // lr-9bcd7b: mirrors the same reconciliation as the 'result' handler's
1459
+ // setIsProcessingFromRegistry (sdk-message-processor.js) — only clear
1460
+ // isProcessing when the activity registry agrees nothing else (e.g. a
1461
+ // still-active backgrounded Task) is live for this session. This is
1462
+ // the SAME finally block that lr-9d4b already teaches must not
1463
+ // unconditionally wipe subagent-owned bookkeeping; this is the
1464
+ // isProcessing counterpart of that lesson.
1465
+ session.isProcessing = sessionActivity.isSessionActive(session);
1195
1466
  }
1196
1467
 
1197
1468
  var didScheduleAutoContinue = false;
@@ -1489,11 +1760,13 @@ function createSDKBridge(opts) {
1489
1760
 
1490
1761
  // lr-1f7e: proactive model context-window warn.
1491
1762
  // Fires before the cgroup hard gate so the user gets an early signal.
1492
- // Degrades cleanly when the model window is unknown (resolveModelContextWindow returns 0)
1493
- // or when ctxWinWarnFraction is 0 (disabled via config).
1494
- // Pass sm.currentBetas so context-1m beta is respected (mirrors app-panels.js logic).
1495
- var _sessionModel = session.model || sm.currentModel || null;
1496
- var _modelWindow = resolveModelContextWindow(_sessionModel, sm.currentBetas || []);
1763
+ // lr-3af675: vendor-first — the hardcoded model->window table is gone.
1764
+ // The only window figure trusted here is the vendor's own last-reported
1765
+ // value (session.lastContextUsage.maxTokens, set from getContextUsage()
1766
+ // at the end of the previous turn — see sdk-message-processor.js). When
1767
+ // no such value is available yet (no prior turn, or the vendor never
1768
+ // reported one), the warn simply degrades to skipped rather than guessing.
1769
+ var _modelWindow = (session.lastContextUsage && session.lastContextUsage.maxTokens) || 0;
1497
1770
  if (_modelWindow > 0 && ctxWinWarnFraction > 0) {
1498
1771
  var _winWarnTokens = Math.floor(_modelWindow * ctxWinWarnFraction);
1499
1772
  if (contextTokens >= _winWarnTokens) {
@@ -1574,6 +1847,14 @@ function createSDKBridge(opts) {
1574
1847
  session.activeTaskToolIds = {};
1575
1848
  session.pendingElicitations = {};
1576
1849
  session.streamedText = false;
1850
+ // lr-9bcd7b: PRIMARY leak-resistance layer — bump the activity
1851
+ // generation at every startQuery call (turn boundary), same spot
1852
+ // activeTaskToolIds is reset above. Any token from a prior generation
1853
+ // (e.g. a subagent that died silently mid-turn without ever releasing)
1854
+ // becomes invisible to isSessionActive immediately, with no explicit
1855
+ // release or timer needed — see lib/session-activity.js header.
1856
+ var _bumpResult = sessionActivity.bumpGeneration(session);
1857
+ if (_bumpResult.changed) sm.broadcastSessionList();
1577
1858
  session.responsePreview = "";
1578
1859
 
1579
1860
  // For in-process path, create AbortController. For worker path, the adapter
@@ -1614,7 +1895,15 @@ function createSDKBridge(opts) {
1614
1895
 
1615
1896
  if (session.agentName && sessionAdapter.vendor !== 'codex') {
1616
1897
  claudeOpts.agent = session.agentName;
1617
- var agentTools = readAgentToolsFromFile(session.agentName);
1898
+
1899
+ // lr-3ccc78 — on a shared multi-user daemon (linuxUser set), read the
1900
+ // session owner's own ~/.claude/agents, not the daemon process's
1901
+ // REAL_HOME (AGENTS_SOURCE_DIR is a module-level constant computed
1902
+ // once at process load — same defect class as skill discovery).
1903
+ var effectiveHome = resolveEffectiveHome(linuxUser);
1904
+ var effectiveAgentsDir = effectiveHome ? path.join(effectiveHome, ".claude", "agents") : AGENTS_SOURCE_DIR;
1905
+
1906
+ var agentTools = readAgentToolsFromFile(session.agentName, effectiveAgentsDir);
1618
1907
  if (agentTools) {
1619
1908
  claudeOpts.tools = agentTools;
1620
1909
  console.log("[sdk-bridge] agent tools enforced for " + session.agentName + ": " + agentTools.join(", "));
@@ -1627,7 +1916,7 @@ function createSDKBridge(opts) {
1627
1916
  // and ensures the model receives the agent persona directly.
1628
1917
  // We keep claudeOpts.agent set — it still applies tool restrictions via settingSources.
1629
1918
  var agentSlug = slugifyAgentName(session.agentName);
1630
- var agentFilePath = path.join(AGENTS_SOURCE_DIR, agentSlug + ".md");
1919
+ var agentFilePath = path.join(effectiveAgentsDir, agentSlug + ".md");
1631
1920
  var agentRaw;
1632
1921
  try {
1633
1922
  agentRaw = fs.readFileSync(agentFilePath, "utf8");
@@ -1775,6 +2064,12 @@ function createSDKBridge(opts) {
1775
2064
  approvalPolicy: codexConfig.approval,
1776
2065
  sandboxMode: codexConfig.sandbox,
1777
2066
  webSearchMode: codexConfig.webSearch,
2067
+ // lr-3ccc78 — mirrors CLAUDE.linuxUser above. The Codex adapter
2068
+ // resolves this into the session owner's own home for skill
2069
+ // discovery (discoverClaudeSkills); it does not (yet) route the
2070
+ // app-server process itself through OS-level uid/gid isolation —
2071
+ // see the PR body for why that's deliberately out of scope here.
2072
+ linuxUser: linuxUser || undefined,
1778
2073
  },
1779
2074
  },
1780
2075
  };
@@ -1879,8 +2174,26 @@ function createSDKBridge(opts) {
1879
2174
  // startQuery has not been called yet). Buffer the message so it is not
1880
2175
  // silently dropped; startQuery will flush it after the handle is created.
1881
2176
  if (!session.pendingMessages) session.pendingMessages = [];
2177
+ // lr-5450ef: bound the buffer and make buffering itself OBSERVABLE.
2178
+ // Before this fix, a session wedged with isProcessing pinned true (no
2179
+ // way to reach the only drain, startQuery) accepted every message a
2180
+ // user typed into this array with nothing but a server-log line —
2181
+ // the message looked "sent" in the UI and was never delivered, with
2182
+ // no error surfaced. Silence-to-UI, not just this specific pinning
2183
+ // mechanism, is the deeper defect: emit a diagnostic on every buffer
2184
+ // so any candidate cause that lands a message here is visible.
2185
+ var wasFull = session.pendingMessages.length >= MAX_PENDING_MESSAGES;
2186
+ if (wasFull) session.pendingMessages.shift();
1882
2187
  session.pendingMessages.push({ text: text, images: images });
1883
2188
  console.log("[sdk-bridge] pushMessage: queryInstance null, buffered message for session " + session.localId + " (pending=" + session.pendingMessages.length + ")");
2189
+ sendAndRecord(session, {
2190
+ type: "diagnostic",
2191
+ severity: "warning",
2192
+ source: "message-buffer",
2193
+ message: wasFull
2194
+ ? "Clagentic: Console couldn't start a new turn for this message — it replaced the oldest buffered message and is still waiting. Try reloading this session."
2195
+ : "Clagentic: Console couldn't start a new turn for this message yet — it's buffered and waiting. If this persists, try reloading this session.",
2196
+ });
1884
2197
  }
1885
2198
  }
1886
2199
 
@@ -1983,17 +2296,21 @@ function createSDKBridge(opts) {
1983
2296
  slug: slug,
1984
2297
  });
1985
2298
 
1986
- var fsSkills = discoverSkillDirs();
2299
+ // lr-3ccc78 — resolve the session owner's own home on a shared
2300
+ // multi-user daemon so global skill discovery isn't the daemon's
2301
+ // REAL_HOME for every user.
2302
+ var _warmupHome = resolveEffectiveHome(linuxUser);
2303
+ var fsSkills = discoverSkillDirs(_warmupHome);
1987
2304
  sm.skillNames = mergeSkills(result.skills, fsSkills);
1988
2305
  sm.workflowMeta = discoverWorkflows(cwd);
1989
2306
  // Enriched skill metadata (lr-7d8d)
1990
- var fsSkillsMeta = discoverSkillsWithMeta(cwd);
2307
+ var fsSkillsMeta = discoverSkillsWithMeta(cwd, _warmupHome);
1991
2308
  sm.skillMeta = mergeSkillsWithMeta(result.skills, fsSkillsMeta);
1992
2309
  if (result.slashCommands) {
1993
2310
  // Build enriched {name,desc,type}[] using the shared helper (lr-cf84).
1994
2311
  // Applies skill/workflow priority chain at warmup time, matching the
1995
2312
  // live-query init path so the UI receives enriched objects on connect.
1996
- var combined = buildEnrichedSlashCommands(result.slashCommands, cwd);
2313
+ var combined = buildEnrichedSlashCommands(result.slashCommands, cwd, { homeOverride: _warmupHome });
1997
2314
  sm.slashCommands = combined;
1998
2315
  sm.setSlashCommandsForVendor(defaultVendor, combined);
1999
2316
  send({ type: "slash_commands", commands: combined, vendor: defaultVendor });
@@ -2052,30 +2369,54 @@ function createSDKBridge(opts) {
2052
2369
  });
2053
2370
  }
2054
2371
 
2372
+ // lr-db0437: session-only write, mirroring setPermissionMode's pattern
2373
+ // (:2096-2111 below). A per-session model choice must never leak into
2374
+ // sm.currentModel — that field is the project/global DEFAULT, consulted by
2375
+ // new_session when seeding a fresh session (project-sessions.js) and by
2376
+ // startQuery's precedence chain (agent-declared > loop settings >
2377
+ // session.model > sm.currentModel) as the last-resort fallback. Writing it
2378
+ // here made every session's model choice silently become the de-facto
2379
+ // default for every subsequently created session — the root cause this
2380
+ // task fixes. Callers that need to change the actual default (server/
2381
+ // project settings pages) go through onSetServerDefaultModel /
2382
+ // onSetProjectDefaultModel (project-sessions.js) instead, which update
2383
+ // sm.currentModel directly without touching any session.
2384
+ // lr-f22787: returns { ok: true } or { ok: false, error: <message> } so the
2385
+ // caller (project-sessions.js) can tell whether the switch actually
2386
+ // succeeded and reply to the REQUESTING client specifically, instead of
2387
+ // always sending a success-shaped config_state reply regardless of outcome.
2388
+ // A broadcast error is still sent here too (existing behavior other
2389
+ // surfaces may depend on), but it is not a substitute for a targeted reply.
2055
2390
  async function setModel(session, model) {
2056
2391
  // Normalize to string id in case a { value, displayName } object slips in
2057
2392
  if (model && typeof model !== "string") {
2058
2393
  model = modelEntryValue(model);
2059
2394
  }
2060
2395
  if (!session.queryInstance) {
2061
- // No active query — store on session and shared state for next startQuery
2396
+ // No active query — store on session only (not sm — that's for project
2397
+ // defaults, see header comment above).
2062
2398
  session.model = model;
2063
- sm.currentModel = model;
2064
2399
  // Don't send vendor here: session vendor not yet bound, let client keep its selection
2065
- sendModelInfoForVendor(null, model);
2400
+ // lr-041af8: targeted to this session's own clients — sendModelInfoForVendor
2401
+ // (broadcast) was overwriting every other open session's model_info with
2402
+ // this one's choice on every setModel call.
2403
+ sendModelInfoToSession(session, null, model);
2066
2404
  // config_state is sent targeted by the caller (project-sessions.js) to
2067
2405
  // avoid broadcasting this session's model to all other open sessions.
2068
- return;
2406
+ return { ok: true };
2069
2407
  }
2070
2408
  try {
2071
2409
  await session.queryInstance.setModel(model);
2072
2410
  session.model = model;
2073
- sm.currentModel = model;
2074
2411
  var sessionVendor = session.vendor || (adapter && adapter.vendor) || "claude";
2075
- sendModelInfoForVendor(sessionVendor, model);
2412
+ // lr-041af8: targeted — see comment in the no-active-query branch above.
2413
+ sendModelInfoToSession(session, sessionVendor, model);
2076
2414
  // config_state sent targeted by caller — no broadcast here.
2415
+ return { ok: true };
2077
2416
  } catch (e) {
2078
- send({ type: "error", text: "Failed to switch model: " + (e.message || e) });
2417
+ var errMsg = e.message || String(e);
2418
+ send({ type: "error", text: "Failed to switch model: " + errMsg });
2419
+ return { ok: false, error: errMsg };
2079
2420
  }
2080
2421
  }
2081
2422
 
@@ -2133,10 +2474,17 @@ function createSDKBridge(opts) {
2133
2474
 
2134
2475
  // lr-2d91: Expose live concurrency stats for process_stats WS response.
2135
2476
  // Called by project-sessions.js when building the process_stats payload.
2477
+ // lr-58c813: also folds in the activity-source divergence probe totals —
2478
+ // same "instance function reads module-shared counter" shape as
2479
+ // activeLiveCount above, so process_stats gets both without a second round
2480
+ // trip. See getActivityDivergenceStats() module-scope doc comment.
2136
2481
  function getMemoryStats() {
2482
+ var divergence = getActivityDivergenceStats();
2137
2483
  return {
2138
2484
  activeLiveCount: _activeLiveCount,
2139
2485
  maxConcurrentSessions: MAX_CONCURRENT_SESSIONS,
2486
+ activityDivergenceCount: divergence.count,
2487
+ activityDivergenceRecentSamples: divergence.recentSamples,
2140
2488
  };
2141
2489
  }
2142
2490
 
@@ -2165,6 +2513,12 @@ function createSDKBridge(opts) {
2165
2513
  startIdleReaper: startIdleReaper,
2166
2514
  stopIdleReaper: stopIdleReaper,
2167
2515
  getMemoryStats: getMemoryStats,
2516
+ // lr-62157d: exposed for direct unit testing of the provisional-title
2517
+ // overwrite guard, following the _test_-prefixed exposure convention
2518
+ // already used by lib/yoke/adapters/codex.js's resolveTitleModel. Not
2519
+ // part of the bridge's real call surface (project.js never calls it by
2520
+ // this name) — it is the same closure onAutoTitle wraps internally.
2521
+ _test_autoGenerateTitle: autoGenerateTitle,
2168
2522
  };
2169
2523
  }
2170
2524
 
@@ -2174,5 +2528,5 @@ function getActiveLiveCount() {
2174
2528
  return _activeLiveCount;
2175
2529
  }
2176
2530
 
2177
- module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, readCgroupHeadroomMB, resolveModelContextWindow, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount };
2531
+ module.exports = { createSDKBridge, createMessageQueue, readMemAvailableMB, readCgroupHeadroomMB, DEFAULT_MEM_AVAILABLE_MIN_MB, DEFAULT_TOKENS_PER_MB_HEADROOM, getActiveLiveCount, getActivityDivergenceStats, buildActivityDiagnosticsResponse };
2178
2532