@clagentic/console 1.6.0 → 1.7.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/bin/cli.js +20 -102
  2. package/deploy/clagentic-console.service +10 -1
  3. package/lib/agents-favorites.js +0 -1
  4. package/lib/agents.js +0 -10
  5. package/lib/cli-sessions.js +0 -12
  6. package/lib/codex-defaults.js +4 -1
  7. package/lib/config.js +0 -8
  8. package/lib/daemon.js +88 -9
  9. package/lib/dm.js +0 -1
  10. package/lib/ipc.js +129 -59
  11. package/lib/loop-handoff.js +5 -1
  12. package/lib/memory-limits.js +214 -36
  13. package/lib/memory-shed.js +207 -0
  14. package/lib/notes.js +0 -20
  15. package/lib/os-users.js +0 -3
  16. package/lib/project-connection.js +31 -5
  17. package/lib/project-external-trigger.js +2 -1
  18. package/lib/project-filesystem.js +18 -11
  19. package/lib/project-knowledge.js +0 -8
  20. package/lib/project-loop.js +162 -9
  21. package/lib/project-sessions.js +87 -21
  22. package/lib/project-user-mention.js +2 -1
  23. package/lib/project-user-message.js +16 -5
  24. package/lib/project.js +14 -25
  25. package/lib/public/app.js +1 -2
  26. package/lib/public/css/channel-layout.css +25 -158
  27. package/lib/public/css/diagnostics.css +17 -1
  28. package/lib/public/css/icon-strip.css +1 -32
  29. package/lib/public/css/input.css +0 -56
  30. package/lib/public/css/loop.css +94 -0
  31. package/lib/public/css/messages.css +23 -4
  32. package/lib/public/css/mobile-nav.css +0 -124
  33. package/lib/public/index.html +11 -11
  34. package/lib/public/modules/app-connection.js +2 -1
  35. package/lib/public/modules/app-favicon.js +1 -1
  36. package/lib/public/modules/app-loop-ui.js +140 -4
  37. package/lib/public/modules/app-messages.js +17 -11
  38. package/lib/public/modules/app-projects.js +1 -1
  39. package/lib/public/modules/custom-icons.js +15 -1
  40. package/lib/public/modules/dom-refs.js +1 -2
  41. package/lib/public/modules/emoji-picker.js +6 -1
  42. package/lib/public/modules/filebrowser.js +33 -9
  43. package/lib/public/modules/input.js +39 -0
  44. package/lib/public/modules/scheduler.js +20 -6
  45. package/lib/public/modules/sidebar-mobile.js +0 -64
  46. package/lib/public/modules/sidebar-projects.js +90 -25
  47. package/lib/public/modules/sidebar-sessions.js +80 -13
  48. package/lib/public/modules/stt.js +2 -6
  49. package/lib/public/modules/tool-palette.js +0 -1
  50. package/lib/public/modules/tools.js +2 -6
  51. package/lib/public/style.css +0 -1
  52. package/lib/scheduler.js +0 -1
  53. package/lib/sdk-bridge.js +126 -194
  54. package/lib/sdk-message-processor.js +24 -9
  55. package/lib/sdk-permission-ownership.js +51 -0
  56. package/lib/server-auth.js +25 -18
  57. package/lib/server-dm.js +1 -1
  58. package/lib/server-skills.js +9 -1
  59. package/lib/server.js +18 -3
  60. package/lib/session-search.js +4 -299
  61. package/lib/sessions.js +467 -82
  62. package/lib/smtp.js +0 -15
  63. package/lib/user-presence.js +0 -12
  64. package/lib/users-preferences.js +2 -2
  65. package/lib/users.js +0 -5
  66. package/lib/utils.js +56 -0
  67. package/lib/ws-schema.js +3 -14
  68. package/lib/yoke/adapters/codex.js +96 -10
  69. package/lib/yoke/codex-local-image.js +79 -0
  70. package/package.json +1 -1
  71. package/scripts/postinstall.js +16 -11
  72. package/lib/ask-user-mcp-server.js +0 -121
  73. package/lib/project-memory.js +0 -39
  74. package/lib/public/console-icon.png +0 -0
  75. package/lib/public/css/debate.css +0 -1610
  76. package/lib/public/favicon-banded-32.png +0 -0
  77. package/lib/public/favicon-dark.svg +0 -32
  78. package/lib/public/favicon.svg +0 -32
  79. package/lib/public/icon-banded-96.png +0 -0
  80. package/lib/public/icons/email/gmail.svg +0 -7
  81. package/lib/public/icons/email/outlook.svg +0 -35
  82. package/lib/public/icons/email/yahoo.svg +0 -1
  83. package/lib/public/modules/events.js +0 -21
  84. package/lib/public/modules/state.js +0 -3
  85. package/lib/sdk-worker.js +0 -730
package/lib/sdk-bridge.js CHANGED
@@ -13,7 +13,7 @@ var { discoverWorkflows } = require("./sdk-workflow-discovery");
13
13
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
14
14
  var { KNOWN_CONTEXT_WINDOWS: _BACKEND_KNOWN_CONTEXT_WINDOWS, resolveModelContextWindow } = require("./model-context-windows");
15
15
  var { runPreflight } = require("./settings-preflight");
16
- var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping } = require("./sdk-permission-ownership");
16
+ var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping, sweepClearedPermissionIndex } = require("./sdk-permission-ownership");
17
17
 
18
18
  // --- lr-29f9: Global concurrent-session ceiling ---
19
19
  // Counts queries that are actively running (startQuery entered, processQueryStream
@@ -375,19 +375,41 @@ function createSDKBridge(opts) {
375
375
  // --- Message processing (extracted to sdk-message-processor.js) ---
376
376
  // Auto-generate a session title via YOKE adapter.generateTitle().
377
377
  // Triggered by sdk-message-processor after AUTO_TITLE_TURN_THRESHOLD turns.
378
+ //
379
+ // lr-2ea2a7: this fires early (AUTO_TITLE_TURN_THRESHOLD=2 turns), so the
380
+ // heap tail normally holds all 5 target user messages — scanning from
381
+ // index 0 forward is a scan over the heap array (which starts at absolute
382
+ // index session._historyBaseIndex, NOT 0, once any trim has happened).
383
+ // If the session's heap has already been trimmed (_historyBaseIndex > 0
384
+ // — a title-generation retry on a long-lived session, or an unusually
385
+ // small HISTORY_INMEM_MAX override) and the heap scan alone doesn't find 5
386
+ // user messages, fall back to a disk-backed full scan via
387
+ // loadFullSessionHistory + retrimHistory rather than silently under-titling
388
+ // with whatever partial set the trimmed heap happened to retain. The full
389
+ // load is never left resident — retrimHistory() re-applies the cap
390
+ // immediately after this function reads what it needs.
378
391
  function autoGenerateTitle(session) {
379
392
  var sessionAdapter = getAdapterForSession(session);
380
393
  if (typeof sessionAdapter.generateTitle !== "function") {
381
394
  console.log("[auto-title] adapter.generateTitle not available for vendor=" + sessionAdapter.vendor);
382
395
  return;
383
396
  }
384
- var userMessages = [];
385
- for (var i = 0; i < session.history.length; i++) {
386
- var entry = session.history[i];
387
- if (entry.type === "user_message" && entry.text) {
388
- userMessages.push(entry.text.substring(0, 200));
389
- if (userMessages.length >= 5) break;
397
+ function collectUserMessages(history) {
398
+ var out = [];
399
+ for (var i = 0; i < history.length; i++) {
400
+ var entry = history[i];
401
+ if (entry.type === "user_message" && entry.text) {
402
+ out.push(entry.text.substring(0, 200));
403
+ if (out.length >= 5) break;
404
+ }
390
405
  }
406
+ return out;
407
+ }
408
+ var userMessages = collectUserMessages(session.history);
409
+ if (userMessages.length < 5 && (session._historyBaseIndex || 0) > 0) {
410
+ sm.loadFullSessionHistory(session);
411
+ userMessages = collectUserMessages(session.history);
412
+ sm.retrimHistory(session);
391
413
  }
392
414
  if (userMessages.length === 0) {
393
415
  console.log("[auto-title] No user messages found in session " + session.localId);
@@ -580,6 +602,17 @@ function createSDKBridge(opts) {
580
602
  // These are purely read-only commands that cannot modify files, install
581
603
  // packages, or change system state. Functionally equivalent to the
582
604
  // Read/Glob/Grep built-in tools which are already auto-approved.
605
+ //
606
+ // lr-74c8: this whitelist previously included multi-purpose tools
607
+ // (interpreters, package managers, git, sed/awk, xargs, tee, find,
608
+ // curl/wget/http) with only a first-word check, so e.g.
609
+ // `python3 -c "..."`, `git push --force`, `xargs rm -rf`, and
610
+ // `sed -i ... file` were silently auto-allowed. Those entries are
611
+ // removed outright (they have no read-only-only form worth trusting to
612
+ // a first-word check). `git` is retained but restricted to an
613
+ // argument-validated read-only subcommand allowlist. A leading `sudo`
614
+ // is NEVER stripped before this check — a sudo-prefixed command must
615
+ // fall through to the normal user permission prompt.
583
616
  if (toolName === "Bash" && input && input.command) {
584
617
  var cmd = input.command.trim();
585
618
  var safeBashCommands = {
@@ -587,27 +620,28 @@ function createSDKBridge(opts) {
587
620
  cd: true, pushd: true, popd: true,
588
621
  // File/dir inspection
589
622
  ls: true, cat: true, head: true, tail: true, wc: true, file: true,
590
- stat: true, find: true, tree: true, du: true, df: true,
623
+ stat: true, tree: true, du: true, df: true,
591
624
  readlink: true, realpath: true, basename: true, dirname: true,
592
625
  // Search
593
626
  grep: true, rg: true, ag: true, ack: true, fgrep: true, egrep: true,
594
627
  // Lookup
595
- which: true, type: true, whereis: true, command: true, hash: true,
628
+ which: true, type: true, whereis: true, hash: true,
596
629
  // Environment/system info
597
- echo: true, printf: true, env: true, printenv: true, pwd: true,
630
+ // lr-74c8 (BOBBIE follow-up): `env` and `command` are execution
631
+ // primitives, not read-only inspection — `env rm -rf /` and
632
+ // `command rm -rf /` launder an arbitrary tail command past a
633
+ // first-word-only check with no argument validator. Removed
634
+ // outright rather than gated: neither has a read-only-only form
635
+ // worth trusting to a first-word check (contrast `printenv`,
636
+ // which genuinely can only print).
637
+ echo: true, printf: true, printenv: true, pwd: true,
598
638
  whoami: true, id: true, groups: true,
599
639
  date: true, uname: true, hostname: true, uptime: true, arch: true,
600
640
  nproc: true, free: true, lsb_release: true, sw_vers: true,
601
641
  locale: true, timedatectl: true,
602
- // Version checks (--version only, but first-word check is sufficient
603
- // since these never take destructive subcommands as first arg)
604
- git: true, node: true, npm: true, npx: true, python: true, python3: true, pip: true,
605
- dotnet: true, ruby: true, java: true, javac: true,
606
- rustc: true, cargo: true, gcc: true, clang: true, cmake: true,
607
- go: true, deno: true, bun: true,
608
642
  // Text processing (pure stdin/stdout, no side effects)
609
643
  jq: true, yq: true, sort: true, uniq: true, cut: true, tr: true,
610
- awk: true, sed: true, paste: true, column: true, fold: true,
644
+ paste: true, column: true, fold: true,
611
645
  rev: true, tac: true, nl: true, expand: true, unexpand: true,
612
646
  fmt: true, pr: true, csplit: true, comm: true, join: true,
613
647
  // Comparison/hashing
@@ -616,27 +650,79 @@ function createSDKBridge(opts) {
616
650
  xxd: true, od: true, hexdump: true,
617
651
  // Misc read-only
618
652
  test: true, true: true, false: true, seq: true, yes: true,
619
- sleep: true, tee: true, xargs: true, time: true,
653
+ sleep: true, time: true,
620
654
  man: true, help: true, info: true, apropos: true,
621
655
  cal: true, bc: true, expr: true, factor: true,
622
656
  lsof: true, ps: true, top: true, htop: true, pgrep: true,
623
657
  netstat: true, ss: true, ifconfig: true, ip: true, dig: true,
624
658
  nslookup: true, host: true, ping: true, traceroute: true,
625
- curl: true, wget: true, http: true,
659
+ };
660
+ // Multi-purpose tools retained in the whitelist but restricted to a
661
+ // read-only subcommand/flag allowlist (lr-74c8). Each validator
662
+ // receives the segment's argv (excluding the command word itself)
663
+ // and returns true only for forms that cannot mutate state.
664
+ var validatedCommands = {
665
+ // Only the explicitly read-only git subcommands from the lr-74c8
666
+ // spec are allowed. Deliberately narrow: no `remote`, `tag`,
667
+ // `branch`, etc. — those have mutating forms (`branch -D`,
668
+ // `remote add`, `tag <name>`) that a subcommand-only check cannot
669
+ // safely distinguish from their read-only forms.
670
+ git: function (args) {
671
+ if (args.length === 0) return false;
672
+ var readOnlySubcommands = {
673
+ status: true, log: true, diff: true, show: true, "--version": true,
674
+ };
675
+ if (!readOnlySubcommands[args[0]]) return false;
676
+ // lr-74c8 (BOBBIE follow-up): the subcommand allowlist above only
677
+ // checked args[0] and ignored everything after it. `git show
678
+ // --output=<path>` / `git log --output=<path>` (and the `-o`
679
+ // short form) inherit diff/log's file-write flag, turning a
680
+ // "read-only" subcommand into an unprompted arbitrary file write.
681
+ // `-c <config>` can inject a pager/external-diff/exec config
682
+ // (core.pager, diff.external) that runs an arbitrary command;
683
+ // `--exec`, `--ext-diff`, `--textconv`, `-O`/`--output-indicator-*`
684
+ // extend the same file-write/exec surface. Any of these flags on
685
+ // an otherwise-allowed subcommand falls through to the prompt.
686
+ var dangerousFlagRe = /^(-o|--output(=.*)?|-O|--output-indicator.*|-c|--exec(=.*)?|--ext-diff|--textconv|--upload-pack(=.*)?|--receive-pack(=.*)?)$/;
687
+ for (var gi = 1; gi < args.length; gi++) {
688
+ if (dangerousFlagRe.test(args[gi])) return false;
689
+ }
690
+ return true;
691
+ },
626
692
  };
627
693
  // Split compound commands on operators (&&, ||, ;, |) while respecting
628
694
  // quoted strings and subshells so that e.g. grep -E "(a|b)" is not split
629
695
  var segments = splitShellSegments(cmd);
696
+ // lr-74c8 (BOBBIE follow-up): splitShellSegments treats unquoted
697
+ // $(...) and backtick command substitution as opaque inline text —
698
+ // it never splits them out or inspects what's inside. That let
699
+ // e.g. `echo $(rm -rf /)` / `echo \`rm -rf /\`` auto-approve on
700
+ // firstWord `echo` alone, with the embedded command never
701
+ // independently validated. splitShellSegments has exactly one
702
+ // caller (here) plus a loose backward-compat test, so it is safe to
703
+ // change, but changing its segmentation semantics for every caller
704
+ // is riskier than gating at this single call site: any segment that
705
+ // still contains an unquoted `$(`, backtick, or bare `` $`` marker
706
+ // is treated as unwhitelistable outright and falls through to the
707
+ // normal permission prompt, regardless of firstWord.
708
+ var COMMAND_SUBSTITUTION_RE = /\$\(|`/;
630
709
  var allSafe = true;
631
710
  for (var si = 0; si < segments.length; si++) {
632
711
  var seg = segments[si].trim();
633
712
  if (!seg) continue;
634
- // Strip leading env assignments (FOO=bar cmd) and sudo
635
- var firstWord = seg.replace(/^(?:\w+=\S*\s+)*/, "").split(/\s/)[0];
636
- if (firstWord === "sudo") {
637
- firstWord = seg.replace(/^(?:\w+=\S*\s+)*sudo\s+(?:-\S+\s+)*/, "").split(/\s/)[0];
713
+ if (COMMAND_SUBSTITUTION_RE.test(seg)) {
714
+ allSafe = false;
715
+ break;
638
716
  }
639
- if (!safeBashCommands[firstWord]) { allSafe = false; break; }
717
+ // Strip leading env assignments (FOO=bar cmd) only. A leading sudo
718
+ // is intentionally NOT stripped — `sudo <anything>` always falls
719
+ // through to the normal permission prompt (lr-74c8).
720
+ var segTokens = seg.replace(/^(?:\w+=\S*\s+)*/, "").split(/\s+/).filter(Boolean);
721
+ var firstWord = segTokens[0];
722
+ if (safeBashCommands[firstWord]) continue;
723
+ if (validatedCommands[firstWord] && validatedCommands[firstWord](segTokens.slice(1))) continue;
724
+ allSafe = false;
725
+ break;
640
726
  }
641
727
  if (allSafe) {
642
728
  return { behavior: "allow", updatedInput: input };
@@ -1054,6 +1140,12 @@ function createSDKBridge(opts) {
1054
1140
  // same shared keep-decision as that handler (see
1055
1141
  // lib/sdk-permission-ownership.js) rather than duplicating it.
1056
1142
  var _perm9d4b = partitionSubagentOwnedPermissions(session);
1143
+ // lr-f940 (N3): sweep sm.permissionRequestIndex for every entry this
1144
+ // pass is about to drop (everything not in keptPermissions) — this is
1145
+ // the ONLY cleanup that runs for the worker path, whose fake abort
1146
+ // signal (yoke/adapters/claude.js) never fires the normal
1147
+ // abort-listener deletion. Must run against the PRE-reassignment map.
1148
+ sweepClearedPermissionIndex(sm, session.pendingPermissions, _perm9d4b.keptPermissions);
1057
1149
  session.pendingPermissions = _perm9d4b.keptPermissions;
1058
1150
  // Preserve MCP-mode AskUserQuestion entries across turn boundaries.
1059
1151
  // The MCP path is intentionally stateless: ask_user returns immediately
@@ -1649,11 +1741,16 @@ function createSDKBridge(opts) {
1649
1741
  adapterOptions: {
1650
1742
  CLAUDE: claudeOpts,
1651
1743
  CODEX: {
1652
- // Always use "never" (auto-approve) because Clagentic: Console handles tool
1653
- // permissions via its own UI (checkToolWhitelist + handleCanUseTool).
1654
- // Codex's native approval prompts are terminal-based and cannot be
1655
- // relayed through the web UI, causing MCP tool calls to hang.
1656
- approvalPolicy: "never",
1744
+ // lr-f7a4 — honor the user-configured approval policy instead of
1745
+ // hardwiring "never". approvalPolicy only controls Codex's own
1746
+ // terminal-native approval UI; every requestApproval /
1747
+ // requestUserInput notification the app-server sends is already
1748
+ // routed through canUseTool -> handleCanUseTool -> the same
1749
+ // WebSocket permission_request prompt Claude sessions use (see
1750
+ // handleServerEvent in lib/yoke/adapters/codex.js). So honoring
1751
+ // the configured policy here does not reintroduce the
1752
+ // terminal-prompt hang this code previously guarded against.
1753
+ approvalPolicy: codexConfig.approval,
1657
1754
  sandboxMode: codexConfig.sandbox,
1658
1755
  webSearchMode: codexConfig.webSearch,
1659
1756
  },
@@ -2012,170 +2109,6 @@ function createSDKBridge(opts) {
2012
2109
  }
2013
2110
  }
2014
2111
 
2015
- // --- @Mention: persistent read-only session for a mentioned Mate ---
2016
- // Creates a mention session that can be reused across multiple mentions
2017
- // within a conversation flow (session continuity).
2018
- async function createMentionSession(opts) {
2019
- // opts: { vendor, claudeMd, initialContext, initialMessage, onDelta, onDone, onError, onActivity }
2020
- var abortController = new AbortController();
2021
-
2022
- // Current response callbacks (swapped on each pushMessage)
2023
- var currentOnDelta = opts.onDelta;
2024
- var currentOnDone = opts.onDone;
2025
- var currentOnError = opts.onError;
2026
- var currentOnActivity = opts.onActivity || null;
2027
- var responseFullText = "";
2028
- var responseStreamedText = false;
2029
- var mentionBlocks = {};
2030
- var alive = true;
2031
-
2032
- // Use the mate's vendor adapter if specified, otherwise default
2033
- var mentionAdapter = (opts.vendor && adapters[opts.vendor]) || adapter;
2034
-
2035
- var handle;
2036
- try {
2037
- handle = await mentionAdapter.createQuery({
2038
- cwd: cwd,
2039
- systemPrompt: opts.claudeMd,
2040
- model: opts.model || undefined,
2041
- toolServers: opts.includeMcpServers ? (mergeMcpServers(getMcpServers(), getRemoteMcpServers) || undefined) : undefined,
2042
- abortController: abortController,
2043
- canUseTool: opts.canUseTool || function (toolName, input) {
2044
- var whitelisted = checkToolWhitelist(toolName, input);
2045
- if (whitelisted) {
2046
- return Promise.resolve(whitelisted);
2047
- }
2048
- return Promise.resolve({
2049
- behavior: "deny",
2050
- message: "Read-only access. You cannot make changes via @mention.",
2051
- });
2052
- },
2053
- adapterOptions: {
2054
- CLAUDE: {
2055
- settingSources: ["user"],
2056
- includePartialMessages: true,
2057
- },
2058
- },
2059
- });
2060
- } catch (e) {
2061
- opts.onError("Failed to create mention query: " + (e.message || e));
2062
- return null;
2063
- }
2064
- var query = handle;
2065
-
2066
- // Push the initial message (context + question, with optional images)
2067
- var initialPrompt = opts.initialContext + "\n\n" + opts.initialMessage;
2068
- handle.pushMessage(initialPrompt, opts.initialImages || null);
2069
-
2070
- // Background stream processing loop (consumes flattened yokeType events)
2071
- (async function () {
2072
- try {
2073
- for await (var msg of query) {
2074
- // Track content blocks for activity reporting
2075
- if (msg.yokeType === "thinking_start") {
2076
- mentionBlocks[msg.blockId] = { type: "thinking" };
2077
- if (currentOnActivity) currentOnActivity("thinking");
2078
- } else if (msg.yokeType === "tool_start") {
2079
- mentionBlocks[msg.blockId] = { type: "tool_use", name: msg.toolName, inputJson: "" };
2080
- var toolLabel = msg.toolName;
2081
- if (toolLabel === "Read") toolLabel = "Reading file...";
2082
- else if (toolLabel === "Grep") toolLabel = "Searching code...";
2083
- else if (toolLabel === "Glob") toolLabel = "Finding files...";
2084
- if (currentOnActivity) currentOnActivity(toolLabel);
2085
- } else if (msg.yokeType === "text_start") {
2086
- mentionBlocks[msg.blockId] = { type: "text" };
2087
-
2088
- } else if (msg.yokeType === "text_delta" && typeof msg.text === "string") {
2089
- responseStreamedText = true;
2090
- responseFullText += msg.text;
2091
- if (currentOnActivity) currentOnActivity(null);
2092
- if (currentOnDelta) currentOnDelta(msg.text);
2093
- } else if (msg.yokeType === "tool_input_delta" && mentionBlocks[msg.blockId]) {
2094
- mentionBlocks[msg.blockId].inputJson += msg.partialJson;
2095
-
2096
- } else if (msg.yokeType === "block_stop") {
2097
- var blk = mentionBlocks[msg.blockId];
2098
- if (blk && blk.type === "tool_use") {
2099
- var toolInput = {};
2100
- try { toolInput = JSON.parse(blk.inputJson); } catch (e) {}
2101
- if (blk.name === "Read" && toolInput.file_path) {
2102
- var fname = toolInput.file_path.split(/[/\\]/).pop();
2103
- if (currentOnActivity) currentOnActivity("Reading " + fname + "...");
2104
- } else if (blk.name === "Grep" && toolInput.pattern) {
2105
- if (currentOnActivity) currentOnActivity("Searching: " + toolInput.pattern.substring(0, 30) + "...");
2106
- } else if (blk.name === "Glob" && toolInput.pattern) {
2107
- if (currentOnActivity) currentOnActivity("Finding: " + toolInput.pattern.substring(0, 30) + "...");
2108
- }
2109
- }
2110
- delete mentionBlocks[msg.blockId];
2111
-
2112
- } else if (msg.yokeType === "message" && msg.messageRole === "assistant" && !responseStreamedText && msg.content) {
2113
- // Fallback: if text was not streamed via deltas, extract from assistant message
2114
- var content = msg.content;
2115
- if (Array.isArray(content)) {
2116
- for (var ci = 0; ci < content.length; ci++) {
2117
- if (content[ci].type === "text" && content[ci].text) {
2118
- responseFullText += content[ci].text;
2119
- if (currentOnDelta) currentOnDelta(content[ci].text);
2120
- }
2121
- }
2122
- }
2123
-
2124
- } else if (msg.yokeType === "result") {
2125
- // One response complete. Signal done and reset for next message.
2126
- if (currentOnActivity) currentOnActivity(null);
2127
- var doneRef = currentOnDone;
2128
- if (doneRef) {
2129
- doneRef(responseFullText);
2130
- }
2131
- // Only reset if pushMessage was not called during onDone
2132
- // (pushMessage swaps callbacks and resets state itself)
2133
- if (currentOnDone === doneRef) {
2134
- currentOnDelta = null;
2135
- currentOnDone = null;
2136
- currentOnError = null;
2137
- currentOnActivity = null;
2138
- mentionBlocks = {};
2139
- responseFullText = "";
2140
- responseStreamedText = false;
2141
- }
2142
- }
2143
- }
2144
- } catch (err) {
2145
- if (currentOnError) {
2146
- if (err.name === "AbortError" || (abortController && abortController.signal.aborted)) {
2147
- currentOnError("Mention query was cancelled.");
2148
- } else {
2149
- currentOnError(err.message || String(err));
2150
- }
2151
- }
2152
- }
2153
- alive = false;
2154
- })();
2155
-
2156
- return {
2157
- // Push a follow-up message to the existing mention session
2158
- pushMessage: function (text, callbacks, images) {
2159
- currentOnDelta = callbacks.onDelta;
2160
- currentOnDone = callbacks.onDone;
2161
- currentOnError = callbacks.onError;
2162
- currentOnActivity = callbacks.onActivity || null;
2163
- mentionBlocks = {};
2164
- responseFullText = "";
2165
- responseStreamedText = false;
2166
- handle.pushMessage(text, images || null);
2167
- },
2168
- abort: function () {
2169
- try { abortController.abort(); } catch (e) {}
2170
- },
2171
- close: function () {
2172
- alive = false;
2173
- try { handle.close(); } catch (e) {}
2174
- },
2175
- isAlive: function () { return alive; },
2176
- };
2177
- }
2178
-
2179
2112
  // lr-2d91: Expose live concurrency stats for process_stats WS response.
2180
2113
  // Called by project-sessions.js when building the process_stats payload.
2181
2114
  function getMemoryStats() {
@@ -2207,7 +2140,6 @@ function createSDKBridge(opts) {
2207
2140
  permissionPushBody: permissionPushBody,
2208
2141
  warmup: warmup,
2209
2142
  stopTask: stopTask,
2210
- createMentionSession: createMentionSession,
2211
2143
  startIdleReaper: startIdleReaper,
2212
2144
  stopIdleReaper: stopIdleReaper,
2213
2145
  getMemoryStats: getMemoryStats,
@@ -1,7 +1,7 @@
1
1
  var usersModule = require("./users");
2
2
  var { discoverWorkflows } = require("./sdk-workflow-discovery");
3
3
  var { buildEnrichedSlashCommands } = require("./sdk-slash-enrichment");
4
- var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping } = require("./sdk-permission-ownership");
4
+ var { partitionSubagentOwnedPermissions, retainPreservedTaskBookkeeping, sweepClearedPermissionIndex } = require("./sdk-permission-ownership");
5
5
 
6
6
  function attachMessageProcessor(ctx) {
7
7
  var sm = ctx.sm;
@@ -136,22 +136,33 @@ function attachMessageProcessor(ctx) {
136
136
  }
137
137
  }
138
138
 
139
- // Extract session_id from any message that carries it
140
- if (parsed.sessionId && !session.cliSessionId) {
139
+ // Extract session_id from any message that carries it. Persist the meta
140
+ // record whenever cliSessionId actually changes (not only when it was
141
+ // previously null) -- otherwise a changed id starts appending history
142
+ // lines to a file whose first line is never a meta record, and the
143
+ // session is silently dropped by loadSessions/loadSessionHistory on
144
+ // restart (lr-1bdb item B).
145
+ if (parsed.sessionId && parsed.sessionId !== session.cliSessionId) {
146
+ var _isNewSessionId = !session.cliSessionId;
141
147
  session.cliSessionId = parsed.sessionId;
142
148
  sm.saveSessionFile(session);
143
- sendAndRecord(session, { type: "session_id", cliSessionId: session.cliSessionId });
144
- } else if (parsed.sessionId) {
145
- session.cliSessionId = parsed.sessionId;
149
+ if (_isNewSessionId) {
150
+ sendAndRecord(session, { type: "session_id", cliSessionId: session.cliSessionId });
151
+ }
146
152
  }
147
153
 
148
- // Capture message UUIDs for rewind support
154
+ // Capture message UUIDs for rewind support.
155
+ // lr-2ea2a7: historyIndex must be ABSOLUTE (session._historyBaseIndex +
156
+ // heap length), not the raw heap length — messageUUIDs[].historyIndex is
157
+ // part of the wire/rewind contract and must stay valid once the heap
158
+ // array can be trimmed out from under a long-running session.
149
159
  if (parsed.uuid) {
160
+ var _absHistoryIndex = (session._historyBaseIndex || 0) + session.history.length;
150
161
  if (parsed.messageType === "user" && !parsed.parentToolUseId) {
151
- session.messageUUIDs.push({ uuid: parsed.uuid, type: "user", historyIndex: session.history.length });
162
+ session.messageUUIDs.push({ uuid: parsed.uuid, type: "user", historyIndex: _absHistoryIndex });
152
163
  sendAndRecord(session, { type: "message_uuid", uuid: parsed.uuid, messageType: "user" });
153
164
  } else if (parsed.messageType === "assistant") {
154
- session.messageUUIDs.push({ uuid: parsed.uuid, type: "assistant", historyIndex: session.history.length });
165
+ session.messageUUIDs.push({ uuid: parsed.uuid, type: "assistant", historyIndex: _absHistoryIndex });
155
166
  sendAndRecord(session, { type: "message_uuid", uuid: parsed.uuid, messageType: "assistant" });
156
167
  }
157
168
  }
@@ -456,6 +467,10 @@ function attachMessageProcessor(ctx) {
456
467
  // that is the ownership information this decision depends on. Mirrors the
457
468
  // _keepAskUser preservation pattern for pendingAskUser directly below.
458
469
  var _perm9d4b = partitionSubagentOwnedPermissions(session);
470
+ // lr-f940 (N3): sweep sm.permissionRequestIndex for every entry this
471
+ // pass is about to drop — see sdk-permission-ownership.js for why this
472
+ // mirrors the same sweep in sdk-bridge.js's processQueryStream finally.
473
+ sweepClearedPermissionIndex(sm, session.pendingPermissions, _perm9d4b.keptPermissions);
459
474
  session.pendingPermissions = _perm9d4b.keptPermissions;
460
475
  session.pendingElicitations = {};
461
476
  // Record ask_user_answered for any leftover pending questions so replay pairs correctly.
@@ -58,6 +58,56 @@ function partitionSubagentOwnedPermissions(session) {
58
58
  return { keptPermissions: keptPermissions, preservedTaskIds: preservedTaskIds };
59
59
  }
60
60
 
61
+ // lr-f940 (N3, top-3): sm.permissionRequestIndex[requestId] -> session.localId
62
+ // is written once per permission request (sdk-bridge.js handleCanUseTool) and
63
+ // is normally deleted in exactly two places: the user-driven permission_response
64
+ // handler (project-sessions.js) and the opts.signal "abort" listener
65
+ // (sdk-bridge.js). Both turn-boundary cleanup sites that call
66
+ // partitionSubagentOwnedPermissions() (the 'result' message handler in
67
+ // sdk-message-processor.js, and processQueryStream's finally block in
68
+ // sdk-bridge.js) drop entries from session.pendingPermissions wholesale
69
+ // (everything not in keptPermissions) without ever touching
70
+ // sm.permissionRequestIndex, so the dropped requestIds' index entries persist
71
+ // for the life of the daemon. On the WORKER path this is the ONLY cleanup that
72
+ // ever runs for those entries: the worker's canUseTool bridge (yoke/adapters/
73
+ // claude.js) passes a fake `signal: { addEventListener: function() {} }` to
74
+ // the in-process canUseTool, so the abort-listener deletion path is a no-op —
75
+ // the index entry is orphaned unconditionally once the turn ends.
76
+ //
77
+ // Call this immediately after reassigning session.pendingPermissions to
78
+ // keptPermissions, passing the PRE-reassignment map, so every entry that was
79
+ // dropped (i.e. not preserved for a still-active backgrounded sub-agent) is
80
+ // swept from sm.permissionRequestIndex and its orphaned resolver is settled
81
+ // with a deny — an SDK canUseTool Promise left unresolved forever is itself a
82
+ // (smaller) leak on top of the index leak.
83
+ //
84
+ // @param {object} sm - the session manager (owns permissionRequestIndex).
85
+ // @param {object} prevPendingPermissions - session.pendingPermissions as it
86
+ // was BEFORE this cleanup pass reassigned it to keptPermissions.
87
+ // @param {object} keptPermissions - the entries being preserved (from
88
+ // partitionSubagentOwnedPermissions's return value).
89
+ function sweepClearedPermissionIndex(sm, prevPendingPermissions, keptPermissions) {
90
+ // Production sm always carries permissionRequestIndex (lib/sessions.js
91
+ // initializes it unconditionally) — this guard exists only so a caller
92
+ // without one (e.g. a minimal test double predating this sweep) is a
93
+ // no-op, matching its pre-existing behavior exactly rather than gaining a
94
+ // new side effect it never asked for.
95
+ if (!sm || !sm.permissionRequestIndex) return;
96
+ var prevIds = Object.keys(prevPendingPermissions || {});
97
+ for (var i = 0; i < prevIds.length; i++) {
98
+ var pid = prevIds[i];
99
+ if (keptPermissions && keptPermissions[pid]) continue; // still owned, not dropped
100
+ delete sm.permissionRequestIndex[pid];
101
+ // Settle the orphaned resolver too — an abandoned canUseTool Promise is
102
+ // itself a (smaller) leak on top of the index leak (lr-f940).
103
+ var droppedEntry = prevPendingPermissions[pid];
104
+ if (droppedEntry && typeof droppedEntry.resolve === "function") {
105
+ try { droppedEntry.resolve({ behavior: "deny", message: "Session turn ended" }); }
106
+ catch (e) { /* resolver already settled or threw — nothing further to do */ }
107
+ }
108
+ }
109
+ }
110
+
61
111
  /**
62
112
  * Apply the partition result to activeTaskToolIds/taskIdMap, keeping only
63
113
  * entries for Task ids whose permission was just preserved.
@@ -82,4 +132,5 @@ function retainPreservedTaskBookkeeping(session, preservedTaskIds) {
82
132
  module.exports = {
83
133
  partitionSubagentOwnedPermissions: partitionSubagentOwnedPermissions,
84
134
  retainPreservedTaskBookkeeping: retainPreservedTaskBookkeeping,
135
+ sweepClearedPermissionIndex: sweepClearedPermissionIndex,
85
136
  };