@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
@@ -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;
@@ -22,6 +23,9 @@ function attachMessageProcessor(ctx) {
22
23
  var mergeSkills = ctx.mergeSkills;
23
24
  var discoverSkillsWithMeta = ctx.discoverSkillsWithMeta;
24
25
  var mergeSkillsWithMeta = ctx.mergeSkillsWithMeta;
26
+ // lr-3ccc78 — resolves the session owner's home on a shared multi-user
27
+ // daemon; returns null (falls back to REAL_HOME) in single-user mode.
28
+ var resolveSessionHome = ctx.resolveSessionHome || function () { return null; };
25
29
  // Allows callers (and tests) to inject a mock; falls back to the real implementation.
26
30
  var discoverWorkflowsFn = ctx.discoverWorkflows || discoverWorkflows;
27
31
 
@@ -35,6 +39,78 @@ function attachMessageProcessor(ctx) {
35
39
  sm.sendToSession(session, obj);
36
40
  }
37
41
 
42
+ // lr-9bcd7b: server activity registry wiring. Acquire/release a token in
43
+ // lib/session-activity.js and broadcast the SESSION LIST only on a real
44
+ // 0->1 / 1->0 transition of the derived active boolean (the chattiness
45
+ // mitigation the spec makes mandatory — a Task tool starting/progressing
46
+ // while another source is already active must not trigger a broadcast).
47
+ //
48
+ // session.isProcessing itself is intentionally left as a legacy write in
49
+ // parallel (see the 'result' handler below) rather than fully retired in
50
+ // this pass — see this task's PR body for the explicit shadow-mode
51
+ // boundary and what's deferred to lr-66c118.
52
+ function acquireActivity(session, token, info) {
53
+ var result = sessionActivity.acquireToken(session, token, info);
54
+ if (result.changed) sm.broadcastSessionList();
55
+ return result;
56
+ }
57
+
58
+ function releaseActivity(session, token) {
59
+ var result = sessionActivity.releaseToken(session, token);
60
+ if (result.changed) sm.broadcastSessionList();
61
+ return result;
62
+ }
63
+
64
+ // lr-c56476: Codex parity wiring. Codex (lib/yoke/adapters/codex.js) has no
65
+ // subagent concept -- ordinary tool_start/thinking_start there are NOT a
66
+ // backgrounded Task the way Claude's Task tool is, so this does not (and
67
+ // must not) fabricate a Task lifecycle. What it DOES need: Codex's
68
+ // tool_start/thinking_start/tool_result/result already ride through this
69
+ // same shared processor, but unlike Claude, Codex has no equivalent of the
70
+ // turn-wide isProcessing=true covering ordinary tool activity implicitly --
71
+ // acquiring an explicit token here is how Codex activity becomes visible to
72
+ // the derived isProcessing/picker-dot path at all. Gated on
73
+ // session.vendor === "codex" so this stays independent of Claude's own
74
+ // widened acquisition below (lr-6e20f7, block_stop) -- the two vendors
75
+ // acquire tokens through different yokeType branches (tool_start here vs.
76
+ // block_stop for Claude) and neither path double-acquires the other's
77
+ // tokens.
78
+ //
79
+ // Release happens on tool_result (per-token, matching Claude's tool_result
80
+ // release) OR at the turn's result event, which releases EVERY still-live
81
+ // Codex-sourced token for this session at once -- a catch-all so a
82
+ // thinking block (which Codex ends via its own top-level thinking_stop
83
+ // event that this shared processor does not otherwise dispatch) is never
84
+ // left acquired past the end of its own turn. This mirrors Claude's
85
+ // task_notification acting as a second, idempotent drain path for a token
86
+ // that tool_result might not otherwise catch.
87
+ function releaseAllCodexActivity(session) {
88
+ var sources = sessionActivity.listActiveSources(session);
89
+ for (var i = 0; i < sources.length; i++) {
90
+ if (sources[i].source === "codex-tool" || sources[i].source === "codex-thinking") {
91
+ releaseActivity(session, sources[i].token);
92
+ }
93
+ }
94
+ }
95
+
96
+ // lr-9bcd7b / lr-255e residual #2: the SDK 'result' handler used to clear
97
+ // session.isProcessing UNCONDITIONALLY, with no check for a still-running
98
+ // backgrounded Task — the exact defect that made every session/project/
99
+ // recent picker's green dot go dark the instant a subagent started (picker
100
+ // dots read session.isProcessing directly — lib/sessions.js
101
+ // mapSessionForClient). Now: only clear isProcessing when the activity
102
+ // registry agrees nothing else is live for this session (e.g. no
103
+ // backgrounded Task still running). If the registry disagrees (something
104
+ // is still active), isProcessing stays true — this is the shadow-mode
105
+ // reconciliation called for in the PR body: the legacy field is kept in
106
+ // sync with the new derived source of truth at its known-wrong write site,
107
+ // rather than either fully retiring session.isProcessing (too large a diff
108
+ // for this pass) or leaving this specific site unconditionally wrong (the
109
+ // one residual this task exists to fix).
110
+ function setIsProcessingFromRegistry(session) {
111
+ session.isProcessing = sessionActivity.isSessionActive(session);
112
+ }
113
+
38
114
  function getModelsForVendor(vendor) {
39
115
  if (vendor && sm.modelsByVendor && sm.modelsByVendor[vendor]) return sm.modelsByVendor[vendor];
40
116
  return sm.availableModels || [];
@@ -182,13 +258,16 @@ function attachMessageProcessor(ctx) {
182
258
 
183
259
  // Cache slash_commands and model from CLI init message
184
260
  if (parsed.yokeType === "init") {
185
- var fsSkills = discoverSkillDirs();
261
+ // lr-3ccc78 — resolve THIS session's owner's home so skill discovery
262
+ // isn't the daemon's REAL_HOME for every user on a shared daemon.
263
+ var _initHome = resolveSessionHome(session);
264
+ var fsSkills = discoverSkillDirs(_initHome);
186
265
  sm.skillNames = mergeSkills(parsed.skills, fsSkills);
187
266
  sm.workflowMeta = discoverWorkflowsFn(cwd);
188
267
  // Enriched skill metadata (lr-7d8d) — stored alongside skillNames for consumers
189
268
  // that need description and type without breaking existing skillNames callers.
190
269
  if (typeof discoverSkillsWithMeta === "function" && typeof mergeSkillsWithMeta === "function") {
191
- var fsSkillsMeta = discoverSkillsWithMeta(cwd);
270
+ var fsSkillsMeta = discoverSkillsWithMeta(cwd, _initHome);
192
271
  sm.skillMeta = mergeSkillsWithMeta(parsed.skills, fsSkillsMeta);
193
272
  }
194
273
  if (parsed.slashCommands) {
@@ -198,6 +277,7 @@ function attachMessageProcessor(ctx) {
198
277
  discoverSkillsWithMeta: typeof discoverSkillsWithMeta === "function" ? discoverSkillsWithMeta : undefined,
199
278
  mergeSkillsWithMeta: typeof mergeSkillsWithMeta === "function" ? mergeSkillsWithMeta : undefined,
200
279
  discoverWorkflows: discoverWorkflowsFn,
280
+ homeOverride: _initHome,
201
281
  };
202
282
  var combined = buildEnrichedSlashCommands(parsed.slashCommands, cwd, _enrichFns);
203
283
  sm.slashCommands = combined;
@@ -231,9 +311,20 @@ function attachMessageProcessor(ctx) {
231
311
  if (parsed.yokeType === "tool_start") {
232
312
  session.blocks[idx] = { type: "tool_use", id: parsed.toolId, name: parsed.toolName, inputJson: "" };
233
313
  sendAndRecord(session, { type: "tool_start", id: parsed.toolId, name: parsed.toolName });
314
+ // lr-c56476: Codex parity -- see releaseAllCodexActivity above for why
315
+ // this is gated to vendor === "codex" and not applied to Claude.
316
+ if (session.vendor === "codex" && parsed.toolId) {
317
+ acquireActivity(session, parsed.toolId, { source: "codex-tool", label: parsed.toolName || "" });
318
+ }
234
319
  } else if (parsed.yokeType === "thinking_start") {
235
320
  session.blocks[idx] = { type: "thinking", thinkingText: "", startTime: Date.now() };
236
321
  sendAndRecord(session, { type: "thinking_start" });
322
+ // lr-c56476: Codex parity. Token id keyed on blockId (Codex's
323
+ // "blk_N" counter, see lib/yoke/adapters/codex.js flattenEvent) since
324
+ // a thinking_start event carries no separate tool-style id.
325
+ if (session.vendor === "codex") {
326
+ acquireActivity(session, "thinking_" + idx, { source: "codex-thinking", label: "" });
327
+ }
237
328
  } else if (parsed.yokeType === "text_start") {
238
329
  session.blocks[idx] = { type: "text" };
239
330
  }
@@ -288,6 +379,14 @@ function attachMessageProcessor(ctx) {
288
379
  is_error: !!parsed.isError,
289
380
  });
290
381
 
382
+ // lr-c56476: Codex parity -- release the token acquired at tool_start
383
+ // for this same toolId. releaseActivity is idempotent (see
384
+ // session-activity.js), so this is always safe even if the token was
385
+ // already released elsewhere (e.g. by the result-time catch-all below).
386
+ if (session.vendor === "codex" && parsed.toolId) {
387
+ releaseActivity(session, parsed.toolId);
388
+ }
389
+
291
390
  // TeamCreate result: extract team ID from result text and activate
292
391
  if (onTeamCreate && session._pendingTeamCreates && session._pendingTeamCreates[parsed.toolId]) {
293
392
  var pending = session._pendingTeamCreates[parsed.toolId];
@@ -348,6 +447,19 @@ function attachMessageProcessor(ctx) {
348
447
  try { input = JSON.parse(block.inputJson); } catch (e) {}
349
448
  sendAndRecord(session, { type: "tool_executing", id: block.id, name: block.name, input: input });
350
449
 
450
+ // lr-6e20f7: acquire an activity token for EVERY Claude tool_use
451
+ // block, not only Task. Claude has turn-wide isProcessing coverage
452
+ // for ordinary tools (see the module-header comment), which is
453
+ // sufficient for the LOCAL viewing client's own turn-in-flight
454
+ // signal (store.processing) but not for the SERVER-side registry
455
+ // that drives every OTHER client's picker/sidebar dot — that
456
+ // registry previously only saw a live token for a backgrounded
457
+ // Task, so a plain Bash/Read/Edit call was invisible to it. Released
458
+ // at the same block below (whichever tool ends up there) OR at the
459
+ // 'message' handler's tool_result content-array scan below
460
+ // (releaseActivity is idempotent either way).
461
+ acquireActivity(session, block.id, { source: "tool", label: input.description || block.name || "" });
462
+
351
463
  // Track active Task tools for sub-agent done detection
352
464
  if (block.name === "Task") {
353
465
  if (!session.activeTaskToolIds) session.activeTaskToolIds = {};
@@ -429,6 +541,24 @@ function attachMessageProcessor(ctx) {
429
541
  });
430
542
  delete session.activeTaskToolIds[block.tool_use_id];
431
543
  }
544
+ // lr-9bcd7b (widened lr-6e20f7): release the activity token
545
+ // acquired at block_stop for this tool id, unconditionally --
546
+ // NOT gated on activeTaskToolIds still containing the entry.
547
+ // This covers every tool now (lr-6e20f7 widened acquisition
548
+ // beyond Task), not only backgrounded Task tools -- the
549
+ // Task-specific bookkeeping above (activeTaskToolIds,
550
+ // subagent_done) is unrelated to this release and unaffected by
551
+ // the widening. The 'result' handler's pre-existing lr-9d4b
552
+ // cleanup (retainPreservedTaskBookkeeping) already trims
553
+ // activeTaskToolIds down to only Task ids with a preserved
554
+ // permission on EVERY result, so a Task with no pending permission
555
+ // of its own has its activeTaskToolIds entry deleted before this
556
+ // tool_result ever arrives -- gating the release on that same map
557
+ // would silently skip it and leak the token forever. releaseToken
558
+ // is idempotent (no-op if this id was never acquired, or already
559
+ // released by task_notification), so calling it unconditionally
560
+ // for every tool_result is always safe.
561
+ releaseActivity(session, block.tool_use_id);
432
562
  var resultText = "";
433
563
  var resultImages = [];
434
564
  if (typeof block.content === "string") {
@@ -464,6 +594,17 @@ function attachMessageProcessor(ctx) {
464
594
  } else if (parsed.yokeType === "result") {
465
595
  session.blocks = {};
466
596
  session.sentToolResults = {};
597
+ // lr-c56476: Codex parity catch-all -- release EVERY still-live
598
+ // Codex-sourced token for this session now, regardless of whether its
599
+ // own tool_result/thinking_stop already fired. This runs first, before
600
+ // the error_during_execution early return below, so a turn that ends
601
+ // in an SDK execution error still drains Codex's tokens (Codex has no
602
+ // task_notification-equivalent second drain path the way Claude does,
603
+ // so this is the ONLY backstop short of the next startQuery's
604
+ // generation bump -- see this task's PR body for why that generation
605
+ // bump already covers the harder case of abort/interrupt ending the
606
+ // stream before 'result' is ever reached at all).
607
+ if (session.vendor === "codex") releaseAllCodexActivity(session);
467
608
  // lr-9d4b: Preserve pendingPermissions entries owned by a backgrounded
468
609
  // sub-agent that is still running when the PARENT turn's 'result' arrives.
469
610
  // A Task tool launched an async sub-agent whose own Bash/etc permission
@@ -526,7 +667,7 @@ function attachMessageProcessor(ctx) {
526
667
  : "Unknown SDK error";
527
668
  if (parsed.terminalReason) execError += " (reason: " + parsed.terminalReason + ")";
528
669
  console.error("[sdk-bridge] Execution error for session " + session.localId + ": " + execError);
529
- session.isProcessing = false;
670
+ setIsProcessingFromRegistry(session);
530
671
  onProcessingChanged();
531
672
  sendAndRecord(session, { type: "error", text: "Claude error: " + execError });
532
673
  sendAndRecord(session, { type: "done", code: 1 });
@@ -534,7 +675,7 @@ function attachMessageProcessor(ctx) {
534
675
  return;
535
676
  }
536
677
 
537
- session.isProcessing = false;
678
+ setIsProcessingFromRegistry(session);
538
679
  onProcessingChanged();
539
680
  // Detect "Not logged in" scenario early for the check below
540
681
  var previewTrimmed = (session.responsePreview || "").trim();
@@ -641,8 +782,14 @@ function attachMessageProcessor(ctx) {
641
782
  session.streamedText = false;
642
783
  sm.broadcastSessionList();
643
784
 
644
- // Auto-generate title after N turns (skip if loop or already auto-generated)
645
- if (session.turnCount === AUTO_TITLE_TURN_THRESHOLD
785
+ // Auto-generate title after N turns (skip if loop or already auto-generated).
786
+ // lr-62157d: '===' -> '>=' so a session that skips past the exact
787
+ // threshold turn (early return, error path, non-result terminal event,
788
+ // or a turnCount that was never persisted before this fix) still gets
789
+ // titled on a later turn instead of being permanently disqualified.
790
+ // Idempotence comes from !session.titleAutoGenerated, which is now
791
+ // durable (see sessions.js buildMetaLine/loadSessions).
792
+ if (session.turnCount >= AUTO_TITLE_TURN_THRESHOLD
646
793
  && !session.titleAutoGenerated
647
794
  && !session.titleManuallySet
648
795
  && !session.loop
@@ -650,6 +797,46 @@ function attachMessageProcessor(ctx) {
650
797
  try { onAutoTitle(session); } catch (e) {
651
798
  console.error("[auto-title] onAutoTitle threw:", e.message || e);
652
799
  }
800
+ } else {
801
+ // lr-efdab6 (DRUMMER decision, comment #1): the taken branch above
802
+ // already logs on every path (sdk-bridge.js [auto-title] sites) — but
803
+ // logging existed on NOTHING that recorded the gate NOT firing, so
804
+ // silence read identically for "ran fine and logged nothing notable",
805
+ // "never invoked", and "invoked and died before the first log". That
806
+ // ambiguity is exactly what let lr-62157d's dead auto-title feature
807
+ // survive ~3 months / ~160 sessions undetected. This branch makes the
808
+ // negative case unambiguous: every turn where the gate evaluates
809
+ // false gets exactly one line naming why.
810
+ //
811
+ // already_auto_generated is the expected steady-state reason for the
812
+ // overwhelming majority of turns in a mature session (fires every
813
+ // turn after the session's title is set) and is logged at a lower
814
+ // level (console.debug) so a normal journald view isn't dominated by
815
+ // it; every other reason is diagnostic of a gate that should be
816
+ // firing but isn't, and stays at console.log so it is visible by
817
+ // default. Nothing here transmits session content — only flags/counts.
818
+ var _autoTitleReason;
819
+ if (!onAutoTitle) {
820
+ _autoTitleReason = "no_callback";
821
+ } else if (session.loop) {
822
+ _autoTitleReason = "loop_running";
823
+ } else if (session.titleManuallySet) {
824
+ _autoTitleReason = "manually_set";
825
+ } else if (session.titleAutoGenerated) {
826
+ _autoTitleReason = "already_auto_generated";
827
+ } else if (session.turnCount < AUTO_TITLE_TURN_THRESHOLD) {
828
+ _autoTitleReason = "turn_threshold_not_met";
829
+ } else {
830
+ _autoTitleReason = "unknown";
831
+ }
832
+ var _autoTitleLogFn = (_autoTitleReason === "already_auto_generated") ? console.debug : console.log;
833
+ _autoTitleLogFn(
834
+ "[auto-title] gate did not fire: reason=" + _autoTitleReason
835
+ + " turnCount=" + session.turnCount
836
+ + " titleAutoGenerated=" + !!session.titleAutoGenerated
837
+ + " titleManuallySet=" + !!session.titleManuallySet
838
+ + " loop=" + !!session.loop
839
+ );
653
840
  }
654
841
 
655
842
  if (onTurnDone) {
@@ -661,6 +848,20 @@ function attachMessageProcessor(ctx) {
661
848
  sendAndRecord(session, { type: "compacting", active: true });
662
849
  } else if (session.compacting) {
663
850
  sendAndRecord(session, { type: "compacting", active: false });
851
+ // lr-3af675: compaction just finished (session.compacting true ->
852
+ // this transition). Re-read vendor-reported usage now instead of
853
+ // leaving the context meter pinned at its pre-compact figure until
854
+ // the next turn's 'result' event — the provider has already
855
+ // self-corrected its own usage accounting at this point, we just
856
+ // never asked. Fire-and-forget, same pattern as the 'result' handler.
857
+ if (session.queryInstance && typeof session.queryInstance.getContextUsage === "function") {
858
+ session.queryInstance.getContextUsage().then(function(ctxUsage) {
859
+ session.lastContextUsage = ctxUsage;
860
+ sendToSession(session, { type: "context_usage", data: ctxUsage });
861
+ }).catch(function(e) {
862
+ console.error("[sdk-bridge] post-compaction getContextUsage failed (non-fatal):", e.message || e);
863
+ });
864
+ }
664
865
  }
665
866
  session.compacting = parsed.status === "compacting";
666
867
 
@@ -699,7 +900,7 @@ function attachMessageProcessor(ctx) {
699
900
 
700
901
  } else if (parsed.yokeType === "task_updated") {
701
902
  // Live task state patches (status, description, error, backgrounded)
702
- var taskId = parsed.task_id;
903
+ var taskId = parsed.taskId;
703
904
  var patch = parsed.patch || {};
704
905
  var parentId = null;
705
906
  if (session.taskIdMap) {
@@ -739,6 +940,13 @@ function attachMessageProcessor(ctx) {
739
940
  summary: parsed.summary || "",
740
941
  usage: parsed.usage || null,
741
942
  });
943
+ // lr-9bcd7b: release the activity token for this Task, in case the
944
+ // tool_result drain path above never fired for it (e.g. the SDK
945
+ // delivered task_notification without a corresponding tool_result
946
+ // block, or delivered it first). releaseActivity is idempotent —
947
+ // if tool_result already released this same token, this is a no-op.
948
+ if (session.activeTaskToolIds) delete session.activeTaskToolIds[parentId];
949
+ releaseActivity(session, parentId);
742
950
  }
743
951
  if (session.taskIdMap) {
744
952
  for (var k in session.taskIdMap) {
@@ -1,6 +1,29 @@
1
1
  var fs = require("fs");
2
2
  var path = require("path");
3
3
 
4
+ // Two-stage containment check mirroring project.js's safePath: a directory
5
+ // entry name from readdirSync can be a symlink, so a lexical path.resolve
6
+ // check alone (entry.name embedded in a path string that lexically stays
7
+ // under base) is NOT sufficient — the subsequent fs.accessSync/readFileSync
8
+ // on SKILL.md follows the symlink at read time, escaping base entirely.
9
+ // Stage 1 (lexical) rejects a literal ".." style escape before any syscall.
10
+ // Stage 2 (fs.realpathSync) resolves the symlink and re-checks containment
11
+ // against the REAL target, which is the check that actually defeats a
12
+ // symlinked directory entry pointing outside base. Returns the resolved
13
+ // real path on success, or null if entry escapes base or doesn't exist.
14
+ function resolveContainedSkillDir(base, entryName) {
15
+ var resolvedBase = path.resolve(base);
16
+ var lexical = path.resolve(resolvedBase, entryName);
17
+ if (lexical !== resolvedBase && lexical.indexOf(resolvedBase + path.sep) !== 0) return null;
18
+ try {
19
+ var real = fs.realpathSync(lexical);
20
+ if (real !== resolvedBase && real.indexOf(resolvedBase + path.sep) !== 0) return null;
21
+ return real;
22
+ } catch (e) {
23
+ return null;
24
+ }
25
+ }
26
+
4
27
  // Split shell command on operators (&&, ||, ;, |) while respecting quotes
5
28
  // and parentheses. Returns array of command segments.
6
29
  function splitShellSegments(cmd) {
@@ -197,9 +220,16 @@ function extractSkillDescription(skillDir) {
197
220
  // skill directories. Reads every SKILL.md to extract a description.
198
221
  // Project skills override global skills with the same name (global → project
199
222
  // discovery order, last-write wins).
200
- function discoverSkillsWithMeta(cwd) {
223
+ //
224
+ // homeOverride: optional. On a shared multi-user daemon, the caller resolves
225
+ // the SESSION OWNER's home (os-users.getLinuxUserHome(linuxUser)) and passes
226
+ // it here so the global skills dir is the invoking user's own ~/.claude/skills,
227
+ // not the daemon process's REAL_HOME (lr-3ccc78). Falls back to REAL_HOME when
228
+ // absent — the single-user / no-OS-isolation case, unchanged behavior.
229
+ function discoverSkillsWithMeta(cwd, homeOverride) {
230
+ var globalHome = homeOverride || require("./config").REAL_HOME;
201
231
  var dirs = [
202
- path.join(require("./config").REAL_HOME, ".claude", "skills"),
232
+ path.join(globalHome, ".claude", "skills"),
203
233
  path.join(cwd, ".claude", "skills"),
204
234
  ];
205
235
  // Ordered map so project skills override global skills
@@ -215,7 +245,8 @@ function discoverSkillsWithMeta(cwd) {
215
245
  for (var i = 0; i < entries.length; i++) {
216
246
  var entry = entries[i];
217
247
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
218
- var skillDir = path.join(base, entry.name);
248
+ var skillDir = resolveContainedSkillDir(base, entry.name);
249
+ if (!skillDir) continue;
219
250
  var skillMdPath = path.join(skillDir, "SKILL.md");
220
251
  try {
221
252
  fs.accessSync(skillMdPath, fs.constants.R_OK);
@@ -271,10 +302,14 @@ function mergeSkillsWithMeta(sdkSkillNames, fsSkillsWithMeta) {
271
302
  function attachSkillDiscovery(ctx) {
272
303
  var cwd = ctx.cwd;
273
304
 
274
- function discoverSkillDirs() {
305
+ // homeOverride: optional per-call override (see discoverSkillsWithMeta
306
+ // above) so a caller can resolve the session owner's home instead of the
307
+ // daemon's REAL_HOME on a shared multi-user daemon (lr-3ccc78).
308
+ function discoverSkillDirs(homeOverride) {
275
309
  var skills = {};
310
+ var globalHome = homeOverride || require("./config").REAL_HOME;
276
311
  var dirs = [
277
- path.join(require("./config").REAL_HOME, ".claude", "skills"),
312
+ path.join(globalHome, ".claude", "skills"),
278
313
  path.join(cwd, ".claude", "skills"),
279
314
  ];
280
315
  for (var d = 0; d < dirs.length; d++) {
@@ -288,7 +323,8 @@ function attachSkillDiscovery(ctx) {
288
323
  for (var i = 0; i < entries.length; i++) {
289
324
  var entry = entries[i];
290
325
  if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;
291
- var skillDir = path.join(base, entry.name);
326
+ var skillDir = resolveContainedSkillDir(base, entry.name);
327
+ if (!skillDir) continue;
292
328
  var skillMd = path.join(skillDir, "SKILL.md");
293
329
  try {
294
330
  fs.accessSync(skillMd, fs.constants.R_OK);
@@ -326,4 +362,8 @@ module.exports = {
326
362
  extractSkillDescription: extractSkillDescription,
327
363
  discoverSkillsWithMeta: discoverSkillsWithMeta,
328
364
  mergeSkillsWithMeta: mergeSkillsWithMeta,
365
+ // Exported so other skill-discovery consumers (yoke/adapters/codex.js)
366
+ // reuse the same two-stage (lexical + realpath) containment check instead
367
+ // of approximating it — see the function's own doc comment.
368
+ resolveContainedSkillDir: resolveContainedSkillDir,
329
369
  };
@@ -12,7 +12,9 @@ var _defaultDiscoverWorkflows = require('./sdk-workflow-discovery').discoverWork
12
12
  //
13
13
  // The optional third argument `fns` allows callers to inject alternative
14
14
  // discovery functions — used by sdk-message-processor.js to pass its
15
- // context-injected mocks so tests remain hermetic.
15
+ // context-injected mocks so tests remain hermetic. `fns.homeOverride`
16
+ // (lr-3ccc78) is forwarded to discoverSkillsWithMeta as the global skills
17
+ // home for a shared multi-user daemon — see that function's own doc comment.
16
18
  //
17
19
  // Both discovery calls are wrapped in try/catch so a missing .claude directory
18
20
  // on disk never prevents slash commands from reaching the frontend.
@@ -20,9 +22,10 @@ function buildEnrichedSlashCommands(cliSlashCommands, cwd, fns) {
20
22
  var discoverSkillsWithMeta = (fns && fns.discoverSkillsWithMeta) || _defaultDiscoverSkillsWithMeta;
21
23
  var mergeSkillsWithMeta = (fns && fns.mergeSkillsWithMeta) || _defaultMergeSkillsWithMeta;
22
24
  var discoverWorkflows = (fns && fns.discoverWorkflows) || _defaultDiscoverWorkflows;
25
+ var homeOverride = (fns && fns.homeOverride) || null;
23
26
 
24
27
  var fsSkillsMeta = [];
25
- try { fsSkillsMeta = discoverSkillsWithMeta(cwd); } catch (e) {}
28
+ try { fsSkillsMeta = discoverSkillsWithMeta(cwd, homeOverride); } catch (e) {}
26
29
  var skillMeta = [];
27
30
  try { skillMeta = mergeSkillsWithMeta([], fsSkillsMeta); } catch (e) {}
28
31
 
@@ -0,0 +1,70 @@
1
+ // Extracted from lib/server.js's addProject() closure (lr-c4da07 rework) so
2
+ // the Home Hub recent-sessions access filter is directly unit-testable
3
+ // against real code, not a test-file reimplementation of its loop shape.
4
+ // lib/server.js's getAllProjectSessions is now a thin call into
5
+ // computeAllProjectSessions below; both production and test code call this
6
+ // same function.
7
+
8
+ // Gathers every session across every project the given user may access,
9
+ // annotated with project metadata, for the Home Hub recent-sessions list.
10
+ //
11
+ // userId: REQUIRED to filter results to what the viewing user may actually
12
+ // see. Fails CLOSED: no userId (or no onGetProjectAccess) means no sessions
13
+ // are returned. There is no legitimate no-auth caller of this function --
14
+ // the WS upgrade handler in lib/server.js rejects any connection without an
15
+ // authenticated user with 401 before ws._clayUser can ever be set, including
16
+ // in single-user/PIN mode (still a real authenticated user, just one
17
+ // account) -- so failing closed here never breaks a real deployment mode.
18
+ //
19
+ // deps:
20
+ // projects Map<slug, projectCtx> (or anything with .forEach(fn(ctx, slug)))
21
+ // users the users module (canAccessProject / canAccessSession)
22
+ // onGetProjectAccess function(slug) -> access object | {error} | falsy
23
+ // callerSlug the connecting project's own slug (for includeSelf skip)
24
+ // includeSelf when true, callerSlug's own sessions are included too
25
+ // userId the viewing user's id, or null/undefined to fail closed
26
+ function computeAllProjectSessions(deps) {
27
+ var projects = deps.projects;
28
+ var users = deps.users;
29
+ var onGetProjectAccess = deps.onGetProjectAccess;
30
+ var callerSlug = deps.callerSlug;
31
+ var includeSelf = deps.includeSelf;
32
+ var userId = deps.userId;
33
+
34
+ var allSessions = [];
35
+ if (!userId || !onGetProjectAccess) return allSessions;
36
+
37
+ projects.forEach(function (pCtx, pSlug) {
38
+ if (!includeSelf && pSlug === callerSlug) return; // skip self unless asked
39
+ var status = pCtx.getStatus();
40
+ if (status.isWorktree) return;
41
+ var pSm = pCtx.getSessionManager();
42
+ if (!pSm) return;
43
+ // Resolve per-project access ONCE per project (hoisted out of the
44
+ // per-session inner loop below, not re-resolved per session) and skip
45
+ // the whole project up front if the user cannot access it at all --
46
+ // avoids an O(projects * sessions) repeated-resolution pattern for a
47
+ // value that does not vary per session.
48
+ var access = onGetProjectAccess(pSlug);
49
+ if (!access || access.error) return;
50
+ if (!users.canAccessProject(userId, access)) return;
51
+ var projectTitle = status.title || status.project || pSlug;
52
+ var projectIcon = status.icon || null;
53
+ pSm.sessions.forEach(function (s) {
54
+ if (!s.hidden && users.canAccessSession(userId, s, access)) {
55
+ // Push a shallow copy annotated with project metadata rather than
56
+ // mutating the live session object with transient UI fields.
57
+ allSessions.push(Object.assign({}, s, {
58
+ _projectTitle: projectTitle,
59
+ _projectSlug: pSlug,
60
+ _projectIcon: projectIcon,
61
+ }));
62
+ }
63
+ });
64
+ });
65
+ return allSessions;
66
+ }
67
+
68
+ module.exports = {
69
+ computeAllProjectSessions: computeAllProjectSessions,
70
+ };