@clagentic/console 1.6.0-beta.2 → 1.6.0-beta.3

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.
@@ -0,0 +1,85 @@
1
+ // lr-9d4b: Shared keep-vs-clear decision for session.pendingPermissions /
2
+ // activeTaskToolIds / taskIdMap at turn-boundary cleanup sites.
3
+ //
4
+ // Two call sites reset this same state at the end of a turn:
5
+ // - sdk-message-processor.js: the 'result' message handler
6
+ // - sdk-bridge.js: processQueryStream's finally block (normal, non-
7
+ // superseded completion)
8
+ // Both used to unconditionally wipe session.pendingPermissions, which
9
+ // destroys a backgrounded sub-agent's still-open permission resolver if the
10
+ // sub-agent's own tool call (e.g. Bash) is still awaiting the operator's
11
+ // approval when the parent turn ends. The permission card stays on the UI,
12
+ // but the resolver is gone, so the sub-agent's canUseTool Promise (no
13
+ // timeout on the in-process path) hangs forever (lr-9d4b root cause).
14
+ //
15
+ // This module computes which entries are owned by a still-active
16
+ // backgrounded sub-agent (via session.subagentToolOwners, recorded in
17
+ // processSubagentMessage) so both cleanup sites can preserve them instead of
18
+ // wiping them, mirroring the existing _keepAskUser preservation pattern for
19
+ // session.pendingAskUser (mcp-mode entries survive the same cleanup sites).
20
+
21
+ /**
22
+ * Partition session.pendingPermissions into entries to keep (owned by a
23
+ * still-active backgrounded sub-agent) vs. the rest (top-level, or a
24
+ * sub-agent whose owning Task has already finished) — the latter are
25
+ * cleared exactly as before.
26
+ *
27
+ * @param {object} session - session object with pendingPermissions,
28
+ * subagentToolOwners, activeTaskToolIds.
29
+ * @returns {{keptPermissions: object, preservedTaskIds: object}}
30
+ * keptPermissions: requestId -> pending entry, to become the new
31
+ * session.pendingPermissions.
32
+ * preservedTaskIds: Task tool-use id -> true, for the caller to also keep
33
+ * the corresponding activeTaskToolIds/taskIdMap entries (the sub-agent's
34
+ * bookkeeping must survive alongside its pending permission).
35
+ */
36
+ function partitionSubagentOwnedPermissions(session) {
37
+ var keptPermissions = {};
38
+ var pendingPermissions = session.pendingPermissions || {};
39
+ var subagentToolOwners = session.subagentToolOwners || {};
40
+ var activeTaskToolIds = session.activeTaskToolIds || {};
41
+
42
+ var permissionIds = Object.keys(pendingPermissions);
43
+ for (var i = 0; i < permissionIds.length; i++) {
44
+ var pid = permissionIds[i];
45
+ var pentry = pendingPermissions[pid];
46
+ var owningTaskId = pentry && pentry.toolUseId ? subagentToolOwners[pentry.toolUseId] : null;
47
+ if (owningTaskId && activeTaskToolIds[owningTaskId]) {
48
+ keptPermissions[pid] = pentry;
49
+ }
50
+ }
51
+
52
+ var preservedTaskIds = {};
53
+ for (var kpid in keptPermissions) {
54
+ var kpTaskId = subagentToolOwners[keptPermissions[kpid].toolUseId];
55
+ preservedTaskIds[kpTaskId] = true;
56
+ }
57
+
58
+ return { keptPermissions: keptPermissions, preservedTaskIds: preservedTaskIds };
59
+ }
60
+
61
+ /**
62
+ * Apply the partition result to activeTaskToolIds/taskIdMap, keeping only
63
+ * entries for Task ids whose permission was just preserved.
64
+ *
65
+ * @param {object} session
66
+ * @param {object} preservedTaskIds - from partitionSubagentOwnedPermissions.
67
+ */
68
+ function retainPreservedTaskBookkeeping(session, preservedTaskIds) {
69
+ var nextActiveTaskToolIds = {};
70
+ for (var atk in (session.activeTaskToolIds || {})) {
71
+ if (preservedTaskIds[atk]) nextActiveTaskToolIds[atk] = session.activeTaskToolIds[atk];
72
+ }
73
+ session.activeTaskToolIds = nextActiveTaskToolIds;
74
+
75
+ var nextTaskIdMap = {};
76
+ for (var tik in (session.taskIdMap || {})) {
77
+ if (preservedTaskIds[tik]) nextTaskIdMap[tik] = session.taskIdMap[tik];
78
+ }
79
+ session.taskIdMap = nextTaskIdMap;
80
+ }
81
+
82
+ module.exports = {
83
+ partitionSubagentOwnedPermissions: partitionSubagentOwnedPermissions,
84
+ retainPreservedTaskBookkeeping: retainPreservedTaskBookkeeping,
85
+ };
package/lib/sessions.js CHANGED
@@ -4,6 +4,7 @@ var config = require("./config");
4
4
  var utils = require("./utils");
5
5
  var users = require("./users");
6
6
  var { CODEX_DEFAULTS } = require("./codex-defaults");
7
+ var { isVisibleHistoryEvent } = require("./history-visibility");
7
8
 
8
9
  function createSessionManager(opts) {
9
10
  var cwd = opts.cwd;
@@ -64,6 +65,13 @@ function createSessionManager(opts) {
64
65
  if (session.lastRewindUuid) metaObj.lastRewindUuid = session.lastRewindUuid;
65
66
  if (session.agentName) metaObj.agentName = session.agentName;
66
67
  if (session.loop) metaObj.loop = session.loop;
68
+ // Persist per-session "allow for session" tool grants (lr-8b2e) so they
69
+ // survive daemon restart / resume-by-cliSessionId rehydration instead of
70
+ // silently re-prompting. Only written when non-empty — grants that were
71
+ // never given must stay absent, not round-trip as {}.
72
+ if (session.allowedTools && Object.keys(session.allowedTools).length > 0) {
73
+ metaObj.allowedTools = session.allowedTools;
74
+ }
67
75
  var meta = JSON.stringify(metaObj);
68
76
  var lines = [meta];
69
77
  for (var i = 0; i < session.history.length; i++) {
@@ -285,6 +293,12 @@ function createSessionManager(opts) {
285
293
  sentToolResults: {},
286
294
  pendingPermissions: {},
287
295
  pendingAskUser: {},
296
+ // Hydrate previously-granted "allow for session" tool decisions from
297
+ // durable state (lr-8b2e); default to {} only when none was saved so
298
+ // grants that were never given remain empty, not re-prompted.
299
+ // Sanitized (lr-8b2e hardening) so a malformed/injected persisted
300
+ // record cannot silently auto-approve a tool.
301
+ allowedTools: utils.sanitizeAllowedTools(m.allowedTools),
288
302
  isProcessing: false,
289
303
  title: m.title || "",
290
304
  createdAt: m.createdAt || Date.now(),
@@ -462,6 +476,14 @@ function createSessionManager(opts) {
462
476
  // scroll-up via the existing pagination path.
463
477
  var HISTORY_PAGE_SIZE = 100;
464
478
 
479
+ // Hard cap on how many additional turn-boundary steps a page window may be
480
+ // extended backward by when searching for visible content (lr-c24b). Each
481
+ // step is itself bounded by HISTORY_PAGE_SIZE (see findTurnBoundary), so the
482
+ // total worst-case scan is MAX_VISIBILITY_EXTENSIONS * HISTORY_PAGE_SIZE —
483
+ // bounded, not unbounded (codex engrams 2026-05-27/29 flagged unbounded
484
+ // backward scans as a structural trap for this exact pagination path).
485
+ var MAX_VISIBILITY_EXTENSIONS = 5;
486
+
465
487
  // Scan backward from the END of history (hard-capped at HISTORY_PAGE_SIZE) to
466
488
  // find the most recent user_message. This ensures the initial replay window
467
489
  // always starts at a clean turn boundary rather than mid-stream, regardless of
@@ -490,6 +512,34 @@ function createSessionManager(opts) {
490
512
  return targetIndex;
491
513
  }
492
514
 
515
+ // Returns true when history[from..to) contains at least one event that
516
+ // app-messages.js will render as a new visible message (lr-c24b). A page
517
+ // window can otherwise land entirely on invisible-yield events (todo/task
518
+ // bookkeeping, hidden plan tools, state events, thinking deltas) and render
519
+ // zero bubbles even though it advanced historyFrom.
520
+ function sliceHasVisibleEvent(history, from, to) {
521
+ for (var i = from; i < to; i++) {
522
+ if (isVisibleHistoryEvent(history[i])) return true;
523
+ }
524
+ return false;
525
+ }
526
+
527
+ // Extend a turn-boundary-aligned page window backward, one turn boundary at
528
+ // a time, until the slice [from, to) contains at least one visibly-rendering
529
+ // event or from reaches 0 — capped at MAX_VISIBILITY_EXTENSIONS additional
530
+ // steps so the scan stays bounded even for pathological all-invisible runs.
531
+ // `to` never changes; only `from` moves backward.
532
+ function extendWindowForVisibility(history, from, to) {
533
+ var steps = 0;
534
+ while (from > 0 && !sliceHasVisibleEvent(history, from, to) && steps < MAX_VISIBILITY_EXTENSIONS) {
535
+ var next = findTurnBoundary(history, from - 1);
536
+ if (next >= from) break; // no further progress possible — avoid an infinite loop
537
+ from = next;
538
+ steps++;
539
+ }
540
+ return from;
541
+ }
542
+
493
543
  function replayHistory(session, fromIndex, targetWs, transform) {
494
544
  // Ensure history is in memory before replaying.
495
545
  loadSessionHistory(session);
@@ -506,6 +556,11 @@ function createSessionManager(opts) {
506
556
  var hardFloor = Math.max(0, total - HISTORY_PAGE_SIZE);
507
557
  var lastTurn = findLastTurnStart(session.history);
508
558
  fromIndex = Math.max(hardFloor, lastTurn);
559
+ // Same yield guarantee as load_more_history (lr-c24b): a turn
560
+ // dominated by invisible-yield events (todo/task bookkeeping, hidden
561
+ // plan tools, thinking deltas) can otherwise replay zero visible
562
+ // bubbles on initial resume.
563
+ fromIndex = extendWindowForVisibility(session.history, fromIndex, total);
509
564
  }
510
565
  }
511
566
 
@@ -826,7 +881,11 @@ function createSessionManager(opts) {
826
881
  sentToolResults: {},
827
882
  pendingPermissions: {},
828
883
  pendingAskUser: {},
829
- allowedTools: {},
884
+ // Hydrate previously-granted "allow for session" tool decisions from
885
+ // durable state (lr-8b2e); default to {} only when none was saved.
886
+ // Sanitized (lr-8b2e hardening) so a malformed/injected persisted
887
+ // record cannot silently auto-approve a tool.
888
+ allowedTools: utils.sanitizeAllowedTools(opts && opts.allowedTools),
830
889
  isProcessing: false,
831
890
  title: title,
832
891
  createdAt: Date.now(),
@@ -1093,6 +1152,7 @@ function createSessionManager(opts) {
1093
1152
  sendToSession: doSendToSession,
1094
1153
  findTurnBoundary: findTurnBoundary,
1095
1154
  findLastTurnStart: findLastTurnStart,
1155
+ extendWindowForVisibility: extendWindowForVisibility,
1096
1156
  replayHistory: replayHistory,
1097
1157
  searchSessions: searchSessions,
1098
1158
  searchSessionContent: searchSessionContent,
@@ -5,12 +5,19 @@
5
5
  // without relying on CLI stderr pattern matching.
6
6
  //
7
7
  // Public surface:
8
- // validateSettingsObject(obj, filePath) — pure: settings obj → diagnostic[]
9
- // runPreflight(opts) — IO: reads files, validates, returns diagnostic[]
10
- // VALID_HOOK_EVENTS — exported for tests
8
+ // validateSettingsObject(obj, filePath, scope) — pure: settings obj → diagnostic[]
9
+ // runPreflight(opts) — IO: reads files, validates, returns diagnostic[]
10
+ // VALID_HOOK_EVENTS — exported for tests
11
11
  //
12
12
  // Diagnostic shape (conforms to validateDiagnosticEvent from YOKE interface):
13
- // { type: 'diagnostic', severity, source: 'preflight', message }
13
+ // { type: 'diagnostic', severity, source: 'preflight', scope?: 'user'|'project', message }
14
+ //
15
+ // scope (lr-7e22) distinguishes which settings file a diagnostic came from —
16
+ // runPreflight checks both ~/.claude/settings.json (scope:'user') and
17
+ // <projectDir>/.claude/settings.json (scope:'project') independently, so a
18
+ // single unknown hook key can legitimately produce one diagnostic per file.
19
+ // The render layer (diagnostic-format.js) uses scope to keep those visually
20
+ // distinct instead of both showing an identical "Preflight" source label.
14
21
 
15
22
  "use strict";
16
23
 
@@ -21,20 +28,27 @@ var os = require("os");
21
28
  // ---------------------------------------------------------------------------
22
29
  // Hook event allowlist
23
30
  //
24
- // SOURCE: This list was derived from the Claude Code CLI documentation and SDK
25
- // source as of 2026-06-30 (claude@1.x). The hooks.AgentTeams case (the
31
+ // SOURCE: Verified live against the Claude Code hooks documentation
32
+ // (https://code.claude.com/docs/en/hooks, hook lifecycle table) as of
33
+ // 2026-07-01, cross-checked via web search. The hooks.AgentTeams case (the
26
34
  // motivating screenshot for this stage) is a real example of an unknown key
27
35
  // that surfaces as a silent no-op in the CLI but clutters the warnings stream.
36
+ // The 8 events added under lr-7e22 (PreCompact, PostCompact, SessionStart,
37
+ // UserPromptSubmit, PermissionRequest, TaskCreated, TeammateIdle,
38
+ // TaskCompleted) were confirmed present in that same table — they are not an
39
+ // exhaustive list of all documented events (the docs list ~30 total as of
40
+ // this sync), only the ones observed in the field that needed verification.
28
41
  //
29
42
  // IMPORTANT: This list is the ONLY place the valid hook events are defined in
30
43
  // the Console codebase. Do not duplicate it elsewhere — drift between copies
31
44
  // is exactly the parity bug we are fixing.
32
45
  //
33
46
  // TODO(lr-1a26): Sync this list whenever the Claude Code CLI releases new hook
34
- // event types. The authoritative upstream is the CLI's hook documentation or
35
- // source (search for "hook" + "event" in the @anthropic-ai/claude-code package).
36
- // Consider scripting a CI check against the installed CLI version's known events
37
- // if the CLI exposes a machine-readable list in a future release.
47
+ // event types. The authoritative upstream is the CLI's hook documentation
48
+ // (https://code.claude.com/docs/en/hooks) or source (search for "hook" +
49
+ // "event" in the @anthropic-ai/claude-code package). Consider scripting a CI
50
+ // check against the installed CLI version's known events if the CLI exposes
51
+ // a machine-readable list in a future release.
38
52
  // ---------------------------------------------------------------------------
39
53
  var VALID_HOOK_EVENTS = [
40
54
  "PreToolUse",
@@ -42,6 +56,15 @@ var VALID_HOOK_EVENTS = [
42
56
  "Notification",
43
57
  "Stop",
44
58
  "SubagentStop",
59
+ // lr-7e22: verified 2026-07-01 against code.claude.com/docs/en/hooks
60
+ "PreCompact",
61
+ "PostCompact",
62
+ "SessionStart",
63
+ "UserPromptSubmit",
64
+ "PermissionRequest",
65
+ "TaskCreated",
66
+ "TeammateIdle",
67
+ "TaskCompleted",
45
68
  ];
46
69
 
47
70
  // ---------------------------------------------------------------------------
@@ -55,9 +78,13 @@ var VALID_HOOK_EVENTS = [
55
78
  *
56
79
  * @param {object} obj - Parsed settings JSON (any shape; we check what we know)
57
80
  * @param {string} filePath - Path string used only in diagnostic messages
58
- * @returns {Array<{type,severity,source,message}>} Diagnostics (empty = no issues)
81
+ * @param {string} [scope] - 'user' | 'project', attached to each diagnostic so the
82
+ * render layer can distinguish which settings file a
83
+ * warning came from (lr-7e22). Omitted when the caller
84
+ * has no file-scope context (e.g. direct unit tests).
85
+ * @returns {Array<{type,severity,source,scope,message}>} Diagnostics (empty = no issues)
59
86
  */
60
- function validateSettingsObject(obj, filePath) {
87
+ function validateSettingsObject(obj, filePath, scope) {
61
88
  var diagnostics = [];
62
89
  var label = filePath || "settings.json";
63
90
 
@@ -75,6 +102,7 @@ function validateSettingsObject(obj, filePath) {
75
102
  type: "diagnostic",
76
103
  severity: "warning",
77
104
  source: "preflight",
105
+ scope: scope || undefined,
78
106
  message: label + ": 'hooks' field is not an object — expected { EventName: [...] }.",
79
107
  });
80
108
  } else {
@@ -86,6 +114,7 @@ function validateSettingsObject(obj, filePath) {
86
114
  type: "diagnostic",
87
115
  severity: "warning",
88
116
  source: "preflight",
117
+ scope: scope || undefined,
89
118
  message: label + ": unknown hook event '" + key + "'. Valid events: " + VALID_HOOK_EVENTS.join(", ") + ". This hook will be silently ignored by the CLI.",
90
119
  });
91
120
  }
@@ -112,9 +141,14 @@ function validateSettingsObject(obj, filePath) {
112
141
  * per the non-blocking preflight contract.
113
142
  *
114
143
  * @param {string} filePath - Absolute path to settings.json
144
+ * @param {string} [scope] - 'user' | 'project', attached to each diagnostic (lr-7e22)
145
+ * so multiple legitimate warnings across files render as
146
+ * visibly distinct entries instead of stacking as apparent
147
+ * duplicates. Optional — omitted when the caller has no
148
+ * file-scope context.
115
149
  * @returns {Array<object>} diagnostics
116
150
  */
117
- function validateSettingsFile(filePath) {
151
+ function validateSettingsFile(filePath, scope) {
118
152
  var diagnostics = [];
119
153
 
120
154
  // Missing file → nothing to validate. Not an error.
@@ -128,6 +162,7 @@ function validateSettingsFile(filePath) {
128
162
  type: "diagnostic",
129
163
  severity: "info",
130
164
  source: "preflight",
165
+ scope: scope || undefined,
131
166
  message: filePath + ": could not read settings file (" + e.code + " — " + (e.message || String(e)) + ").",
132
167
  });
133
168
  return diagnostics;
@@ -142,13 +177,14 @@ function validateSettingsFile(filePath) {
142
177
  type: "diagnostic",
143
178
  severity: "error",
144
179
  source: "preflight",
180
+ scope: scope || undefined,
145
181
  message: filePath + ": settings.json is not valid JSON — " + (e.message || String(e)) + ".",
146
182
  });
147
183
  return diagnostics;
148
184
  }
149
185
 
150
186
  // (b) Structural validation
151
- var structural = validateSettingsObject(obj, filePath);
187
+ var structural = validateSettingsObject(obj, filePath, scope);
152
188
  for (var i = 0; i < structural.length; i++) {
153
189
  diagnostics.push(structural[i]);
154
190
  }
@@ -186,7 +222,7 @@ function runPreflight(opts) {
186
222
 
187
223
  // User global: ~/.claude/settings.json
188
224
  var userSettingsPath = path.join(userHome, ".claude", "settings.json");
189
- var userDiags = validateSettingsFile(userSettingsPath);
225
+ var userDiags = validateSettingsFile(userSettingsPath, "user");
190
226
  for (var i = 0; i < userDiags.length; i++) {
191
227
  diagnostics.push(userDiags[i]);
192
228
  }
@@ -195,7 +231,7 @@ function runPreflight(opts) {
195
231
  var projectDir = opts.projectDir;
196
232
  if (projectDir && typeof projectDir === "string" && projectDir.length > 0) {
197
233
  var projectSettingsPath = path.join(projectDir, ".claude", "settings.json");
198
- var projectDiags = validateSettingsFile(projectSettingsPath);
234
+ var projectDiags = validateSettingsFile(projectSettingsPath, "project");
199
235
  for (var j = 0; j < projectDiags.length; j++) {
200
236
  diagnostics.push(projectDiags[j]);
201
237
  }
package/lib/utils.js CHANGED
@@ -57,8 +57,31 @@ function resolveEncodedFile(baseDir, cwd, ext) {
57
57
  });
58
58
  }
59
59
 
60
+ /**
61
+ * Sanitize a persisted `allowedTools` map before hydrating it into a live
62
+ * session (lr-8b2e). The value originates from a durable .jsonl meta record
63
+ * that shares its trust boundary with other session-file fields, but an
64
+ * un-validated shape would let a crafted record (e.g. {"Bash": "yes"} or a
65
+ * non-object) auto-approve a tool with no operator click at the
66
+ * handleCanUseTool check (lib/sdk-bridge.js:691).
67
+ *
68
+ * Keeps only entries whose key is a string and whose value is strictly
69
+ * boolean `true`; drops everything else. A non-object input (including
70
+ * null/undefined/arrays) yields {} rather than throwing.
71
+ */
72
+ function sanitizeAllowedTools(value) {
73
+ var out = {};
74
+ if (!value || typeof value !== "object" || Array.isArray(value)) return out;
75
+ for (var key in value) {
76
+ if (!Object.prototype.hasOwnProperty.call(value, key)) continue;
77
+ if (typeof key === "string" && value[key] === true) out[key] = true;
78
+ }
79
+ return out;
80
+ }
81
+
60
82
  module.exports = {
61
83
  encodeCwd: encodeCwd,
62
84
  resolveEncodedDir: resolveEncodedDir,
63
85
  resolveEncodedFile: resolveEncodedFile,
86
+ sanitizeAllowedTools: sanitizeAllowedTools,
64
87
  };
@@ -11,6 +11,18 @@
11
11
 
12
12
  var validateDiagnosticEvent = require("../interface").validateDiagnosticEvent;
13
13
 
14
+ // VALID_HOOK_EVENTS (lr-e901): the CLI's own "Unknown hook event: X" stderr
15
+ // line is matched generically below (source:'hook') without knowing whether
16
+ // the Console's allowlist actually considers X unknown. settings-preflight.js
17
+ // is the single source of truth for that allowlist (see its header comment —
18
+ // "the ONLY place the valid hook events are defined"). Reuse it here instead
19
+ // of re-deriving a second copy, so a hook event added to the allowlist stops
20
+ // producing a false "unknown hook" toast from BOTH emission paths at once.
21
+ var VALID_HOOK_EVENTS = require("../../settings-preflight").VALID_HOOK_EVENTS;
22
+
23
+ // Matches the hook event name out of a CLI "Unknown hook event: <Name>" line.
24
+ var UNKNOWN_HOOK_EVENT_RE = /^Unknown hook event:\s*(\S+)/;
25
+
14
26
  // ---------------------------------------------------------------------------
15
27
  // Pattern table
16
28
  // ---------------------------------------------------------------------------
@@ -91,6 +103,19 @@ function parseDiagnosticLine(rawLine) {
91
103
  for (var i = 0; i < PATTERNS.length; i++) {
92
104
  var pattern = PATTERNS[i];
93
105
  if (matches(line, pattern)) {
106
+ // lr-e901: reconcile the CLI-stderr "Unknown hook event" path against
107
+ // the Console's own VALID_HOOK_EVENTS allowlist (settings-preflight.js).
108
+ // The CLI's stderr message reflects the *installed CLI version's*
109
+ // knowledge of hook events, which can lag the allowlist verified here
110
+ // (see settings-preflight.js header, lr-7e22). When the named event IS
111
+ // in VALID_HOOK_EVENTS, treat this as a stale/false CLI warning and
112
+ // suppress it rather than surfacing a contradictory toast — do not
113
+ // widen the allowlist to "fix" this, the allowlist is already correct.
114
+ var hookMatch = pattern.source === "hook" && UNKNOWN_HOOK_EVENT_RE.exec(line);
115
+ if (hookMatch && VALID_HOOK_EVENTS.indexOf(hookMatch[1]) !== -1) {
116
+ return null;
117
+ }
118
+
94
119
  var event = {
95
120
  type: "diagnostic",
96
121
  severity: pattern.severity,
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.6.0-beta.2",
6
+ "version": "1.6.0-beta.3",
7
7
  "description": "Self-hosted console for Claude Code and Codex. Multi-user, browser-based, persistent AI sessions.",
8
8
  "bin": {
9
9
  "clagentic-console": "./bin/cli.js"