chat-recall 0.7.26 → 0.7.30

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.
package/dist/mcp.js CHANGED
@@ -2034,7 +2034,7 @@ var require_thread_stream = __commonJS({
2034
2034
  var { version: version2 } = require_package();
2035
2035
  var { EventEmitter } = __require("events");
2036
2036
  var { Worker: Worker2 } = __require("worker_threads");
2037
- var { join: join63 } = __require("path");
2037
+ var { join: join65 } = __require("path");
2038
2038
  var { pathToFileURL } = __require("url");
2039
2039
  var { wait } = require_wait();
2040
2040
  var {
@@ -2077,7 +2077,7 @@ var require_thread_stream = __commonJS({
2077
2077
  function createWorker(stream, opts) {
2078
2078
  const { filename, workerData } = opts;
2079
2079
  const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {};
2080
- const toExecute = bundlerOverrides["thread-stream-worker"] || join63(__dirname, "lib", "worker.js");
2080
+ const toExecute = bundlerOverrides["thread-stream-worker"] || join65(__dirname, "lib", "worker.js");
2081
2081
  const worker = new Worker2(toExecute, {
2082
2082
  ...opts.workerOpts,
2083
2083
  trackUnmanagedFds: false,
@@ -2480,7 +2480,7 @@ var require_transport = __commonJS({
2480
2480
  "use strict";
2481
2481
  var { createRequire: createRequire3 } = __require("module");
2482
2482
  var getCallers = require_caller();
2483
- var { join: join63, isAbsolute: isAbsolute4, sep: sep4 } = __require("node:path");
2483
+ var { join: join65, isAbsolute: isAbsolute4, sep: sep5 } = __require("node:path");
2484
2484
  var sleep = require_atomic_sleep();
2485
2485
  var onExit = require_on_exit_leak_free();
2486
2486
  var ThreadStream = require_thread_stream();
@@ -2532,7 +2532,7 @@ var require_transport = __commonJS({
2532
2532
  stream.flushSync();
2533
2533
  }
2534
2534
  function transport2(fullOptions) {
2535
- const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions;
2535
+ const { pipeline, targets, levels, dedupe: dedupe2, worker = {}, caller = getCallers(), sync = false } = fullOptions;
2536
2536
  const options = {
2537
2537
  ...fullOptions.options
2538
2538
  };
@@ -2543,7 +2543,7 @@ var require_transport = __commonJS({
2543
2543
  throw new Error("only one of target or targets can be specified");
2544
2544
  }
2545
2545
  if (targets) {
2546
- target = bundlerOverrides["pino-worker"] || join63(__dirname, "worker.js");
2546
+ target = bundlerOverrides["pino-worker"] || join65(__dirname, "worker.js");
2547
2547
  options.targets = targets.filter((dest) => dest.target).map((dest) => {
2548
2548
  return {
2549
2549
  ...dest,
@@ -2561,7 +2561,7 @@ var require_transport = __commonJS({
2561
2561
  });
2562
2562
  });
2563
2563
  } else if (pipeline) {
2564
- target = bundlerOverrides["pino-worker"] || join63(__dirname, "worker.js");
2564
+ target = bundlerOverrides["pino-worker"] || join65(__dirname, "worker.js");
2565
2565
  options.pipelines = [pipeline.map((dest) => {
2566
2566
  return {
2567
2567
  ...dest,
@@ -2572,8 +2572,8 @@ var require_transport = __commonJS({
2572
2572
  if (levels) {
2573
2573
  options.levels = levels;
2574
2574
  }
2575
- if (dedupe) {
2576
- options.dedupe = dedupe;
2575
+ if (dedupe2) {
2576
+ options.dedupe = dedupe2;
2577
2577
  }
2578
2578
  options.pinoWillSendConfig = true;
2579
2579
  return buildStream(fixTarget(target), options, worker, sync);
@@ -2583,12 +2583,12 @@ var require_transport = __commonJS({
2583
2583
  return origin;
2584
2584
  }
2585
2585
  if (origin === "pino/file") {
2586
- return join63(__dirname, "..", "file.js");
2586
+ return join65(__dirname, "..", "file.js");
2587
2587
  }
2588
2588
  let fixTarget2;
2589
2589
  for (const filePath of callers) {
2590
2590
  try {
2591
- const context = filePath === "node:repl" ? process.cwd() + sep4 : filePath;
2591
+ const context = filePath === "node:repl" ? process.cwd() + sep5 : filePath;
2592
2592
  fixTarget2 = createRequire3(context).resolve(origin);
2593
2593
  break;
2594
2594
  } catch (err) {
@@ -3572,7 +3572,7 @@ var require_safe_stable_stringify = __commonJS({
3572
3572
  return circularValue;
3573
3573
  }
3574
3574
  let res = "";
3575
- let join63 = ",";
3575
+ let join65 = ",";
3576
3576
  const originalIndentation = indentation;
3577
3577
  if (Array.isArray(value)) {
3578
3578
  if (value.length === 0) {
@@ -3586,7 +3586,7 @@ var require_safe_stable_stringify = __commonJS({
3586
3586
  indentation += spacer;
3587
3587
  res += `
3588
3588
  ${indentation}`;
3589
- join63 = `,
3589
+ join65 = `,
3590
3590
  ${indentation}`;
3591
3591
  }
3592
3592
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
@@ -3594,13 +3594,13 @@ ${indentation}`;
3594
3594
  for (; i < maximumValuesToStringify - 1; i++) {
3595
3595
  const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
3596
3596
  res += tmp2 !== void 0 ? tmp2 : "null";
3597
- res += join63;
3597
+ res += join65;
3598
3598
  }
3599
3599
  const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
3600
3600
  res += tmp !== void 0 ? tmp : "null";
3601
3601
  if (value.length - 1 > maximumBreadth) {
3602
3602
  const removedKeys = value.length - maximumBreadth - 1;
3603
- res += `${join63}"... ${getItemCount(removedKeys)} not stringified"`;
3603
+ res += `${join65}"... ${getItemCount(removedKeys)} not stringified"`;
3604
3604
  }
3605
3605
  if (spacer !== "") {
3606
3606
  res += `
@@ -3621,7 +3621,7 @@ ${originalIndentation}`;
3621
3621
  let separator = "";
3622
3622
  if (spacer !== "") {
3623
3623
  indentation += spacer;
3624
- join63 = `,
3624
+ join65 = `,
3625
3625
  ${indentation}`;
3626
3626
  whitespace = " ";
3627
3627
  }
@@ -3635,13 +3635,13 @@ ${indentation}`;
3635
3635
  const tmp = stringifyFnReplacer(key3, value, stack, replacer, spacer, indentation);
3636
3636
  if (tmp !== void 0) {
3637
3637
  res += `${separator}${strEscape(key3)}:${whitespace}${tmp}`;
3638
- separator = join63;
3638
+ separator = join65;
3639
3639
  }
3640
3640
  }
3641
3641
  if (keyLength > maximumBreadth) {
3642
3642
  const removedKeys = keyLength - maximumBreadth;
3643
3643
  res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
3644
- separator = join63;
3644
+ separator = join65;
3645
3645
  }
3646
3646
  if (spacer !== "" && separator.length > 1) {
3647
3647
  res = `
@@ -3682,7 +3682,7 @@ ${originalIndentation}`;
3682
3682
  }
3683
3683
  const originalIndentation = indentation;
3684
3684
  let res = "";
3685
- let join63 = ",";
3685
+ let join65 = ",";
3686
3686
  if (Array.isArray(value)) {
3687
3687
  if (value.length === 0) {
3688
3688
  return "[]";
@@ -3695,7 +3695,7 @@ ${originalIndentation}`;
3695
3695
  indentation += spacer;
3696
3696
  res += `
3697
3697
  ${indentation}`;
3698
- join63 = `,
3698
+ join65 = `,
3699
3699
  ${indentation}`;
3700
3700
  }
3701
3701
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
@@ -3703,13 +3703,13 @@ ${indentation}`;
3703
3703
  for (; i < maximumValuesToStringify - 1; i++) {
3704
3704
  const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
3705
3705
  res += tmp2 !== void 0 ? tmp2 : "null";
3706
- res += join63;
3706
+ res += join65;
3707
3707
  }
3708
3708
  const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
3709
3709
  res += tmp !== void 0 ? tmp : "null";
3710
3710
  if (value.length - 1 > maximumBreadth) {
3711
3711
  const removedKeys = value.length - maximumBreadth - 1;
3712
- res += `${join63}"... ${getItemCount(removedKeys)} not stringified"`;
3712
+ res += `${join65}"... ${getItemCount(removedKeys)} not stringified"`;
3713
3713
  }
3714
3714
  if (spacer !== "") {
3715
3715
  res += `
@@ -3722,7 +3722,7 @@ ${originalIndentation}`;
3722
3722
  let whitespace = "";
3723
3723
  if (spacer !== "") {
3724
3724
  indentation += spacer;
3725
- join63 = `,
3725
+ join65 = `,
3726
3726
  ${indentation}`;
3727
3727
  whitespace = " ";
3728
3728
  }
@@ -3731,7 +3731,7 @@ ${indentation}`;
3731
3731
  const tmp = stringifyArrayReplacer(key3, value[key3], stack, replacer, spacer, indentation);
3732
3732
  if (tmp !== void 0) {
3733
3733
  res += `${separator}${strEscape(key3)}:${whitespace}${tmp}`;
3734
- separator = join63;
3734
+ separator = join65;
3735
3735
  }
3736
3736
  }
3737
3737
  if (spacer !== "" && separator.length > 1) {
@@ -3789,20 +3789,20 @@ ${originalIndentation}`;
3789
3789
  indentation += spacer;
3790
3790
  let res2 = `
3791
3791
  ${indentation}`;
3792
- const join64 = `,
3792
+ const join66 = `,
3793
3793
  ${indentation}`;
3794
3794
  const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
3795
3795
  let i = 0;
3796
3796
  for (; i < maximumValuesToStringify - 1; i++) {
3797
3797
  const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
3798
3798
  res2 += tmp2 !== void 0 ? tmp2 : "null";
3799
- res2 += join64;
3799
+ res2 += join66;
3800
3800
  }
3801
3801
  const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
3802
3802
  res2 += tmp !== void 0 ? tmp : "null";
3803
3803
  if (value.length - 1 > maximumBreadth) {
3804
3804
  const removedKeys = value.length - maximumBreadth - 1;
3805
- res2 += `${join64}"... ${getItemCount(removedKeys)} not stringified"`;
3805
+ res2 += `${join66}"... ${getItemCount(removedKeys)} not stringified"`;
3806
3806
  }
3807
3807
  res2 += `
3808
3808
  ${originalIndentation}`;
@@ -3818,16 +3818,16 @@ ${originalIndentation}`;
3818
3818
  return '"[Object]"';
3819
3819
  }
3820
3820
  indentation += spacer;
3821
- const join63 = `,
3821
+ const join65 = `,
3822
3822
  ${indentation}`;
3823
3823
  let res = "";
3824
3824
  let separator = "";
3825
3825
  let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
3826
3826
  if (isTypedArrayWithEntries(value)) {
3827
- res += stringifyTypedArray(value, join63, maximumBreadth);
3827
+ res += stringifyTypedArray(value, join65, maximumBreadth);
3828
3828
  keys = keys.slice(value.length);
3829
3829
  maximumPropertiesToStringify -= value.length;
3830
- separator = join63;
3830
+ separator = join65;
3831
3831
  }
3832
3832
  if (deterministic) {
3833
3833
  keys = sort(keys, comparator);
@@ -3838,13 +3838,13 @@ ${indentation}`;
3838
3838
  const tmp = stringifyIndent(key3, value[key3], stack, spacer, indentation);
3839
3839
  if (tmp !== void 0) {
3840
3840
  res += `${separator}${strEscape(key3)}: ${tmp}`;
3841
- separator = join63;
3841
+ separator = join65;
3842
3842
  }
3843
3843
  }
3844
3844
  if (keyLength > maximumBreadth) {
3845
3845
  const removedKeys = keyLength - maximumBreadth;
3846
3846
  res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
3847
- separator = join63;
3847
+ separator = join65;
3848
3848
  }
3849
3849
  if (separator !== "") {
3850
3850
  res = `
@@ -4147,14 +4147,14 @@ var require_multistream = __commonJS({
4147
4147
  function compareByLevel(a, b) {
4148
4148
  return a.level - b.level;
4149
4149
  }
4150
- function initLoopVar(length, dedupe) {
4151
- return dedupe ? length - 1 : 0;
4150
+ function initLoopVar(length, dedupe2) {
4151
+ return dedupe2 ? length - 1 : 0;
4152
4152
  }
4153
- function adjustLoopVar(i, dedupe) {
4154
- return dedupe ? i - 1 : i + 1;
4153
+ function adjustLoopVar(i, dedupe2) {
4154
+ return dedupe2 ? i - 1 : i + 1;
4155
4155
  }
4156
- function checkLoopVar(i, length, dedupe) {
4157
- return dedupe ? i >= 0 : i < length;
4156
+ function checkLoopVar(i, length, dedupe2) {
4157
+ return dedupe2 ? i >= 0 : i < length;
4158
4158
  }
4159
4159
  module.exports = multistream;
4160
4160
  }
@@ -9404,8 +9404,8 @@ function listComposers(globalDbPath, workspaceRoots) {
9404
9404
  }
9405
9405
  }
9406
9406
  const headersRow = db.prepare("SELECT value FROM ItemTable WHERE key = ?").get("composer.composerHeaders");
9407
- const headers = headersRow?.value ? jsonOf(headersRow.value) : null;
9408
- const headerList = Array.isArray(headers) ? headers : asArray(headersRow?.value);
9407
+ const headers2 = headersRow?.value ? jsonOf(headersRow.value) : null;
9408
+ const headerList = Array.isArray(headers2) ? headers2 : asArray(headersRow?.value);
9409
9409
  for (const h of headerList) {
9410
9410
  if (!h || typeof h !== "object")
9411
9411
  continue;
@@ -9558,13 +9558,13 @@ function readComposerEvents(composer) {
9558
9558
  const data = jsonOf(dataRow?.value);
9559
9559
  if (!data)
9560
9560
  return [];
9561
- const headers = Array.isArray(data.fullConversationHeadersOnly) ? data.fullConversationHeadersOnly : [];
9561
+ const headers2 = Array.isArray(data.fullConversationHeadersOnly) ? data.fullConversationHeadersOnly : [];
9562
9562
  const inline = data.conversationMap && typeof data.conversationMap === "object" ? data.conversationMap : {};
9563
9563
  const getBubble = db.prepare("SELECT value FROM cursorDiskKV WHERE key = ?");
9564
9564
  const events = [];
9565
9565
  let clock = composer.createdAtMs || composer.updatedAtMs || 0;
9566
9566
  let count = 0;
9567
- for (const h of headers) {
9567
+ for (const h of headers2) {
9568
9568
  if (count++ >= MAX_BUBBLES)
9569
9569
  break;
9570
9570
  const bubbleId = typeof h?.bubbleId === "string" ? h.bubbleId : "";
@@ -9639,10 +9639,10 @@ function composerPreview(composer) {
9639
9639
  const data = jsonOf(dataRow?.value);
9640
9640
  if (!data)
9641
9641
  return { firstPrompt: "", messageCount: 0 };
9642
- const headers = Array.isArray(data.fullConversationHeadersOnly) ? data.fullConversationHeadersOnly : [];
9642
+ const headers2 = Array.isArray(data.fullConversationHeadersOnly) ? data.fullConversationHeadersOnly : [];
9643
9643
  const getBubble = db.prepare("SELECT value FROM cursorDiskKV WHERE key = ?");
9644
9644
  let firstPrompt = "";
9645
- for (const h of headers.slice(0, 50)) {
9645
+ for (const h of headers2.slice(0, 50)) {
9646
9646
  const bubbleId = typeof h?.bubbleId === "string" ? h.bubbleId : "";
9647
9647
  if (!bubbleId)
9648
9648
  continue;
@@ -9656,7 +9656,7 @@ function composerPreview(composer) {
9656
9656
  break;
9657
9657
  }
9658
9658
  }
9659
- return { firstPrompt, messageCount: headers.length };
9659
+ return { firstPrompt, messageCount: headers2.length };
9660
9660
  } catch {
9661
9661
  return { firstPrompt: "", messageCount: 0 };
9662
9662
  } finally {
@@ -13501,11 +13501,11 @@ async function archiveRawSession(store2, sessionId) {
13501
13501
  return await store2.putRawSession(sessionId, exp.tool, Math.floor(exp.mtime), gz, size);
13502
13502
  }
13503
13503
  function detectForkPredecessor(sessionPath) {
13504
- const { readFileSync: readFileSync51, readdirSync: readdirSync35 } = requireFs();
13505
- const { dirname: dirname22, join: join63, basename: basename26 } = requirePath();
13504
+ const { readFileSync: readFileSync55, readdirSync: readdirSync37 } = requireFs();
13505
+ const { dirname: dirname22, join: join65, basename: basename26 } = requirePath();
13506
13506
  let text;
13507
13507
  try {
13508
- text = readFileSync51(sessionPath, "utf-8");
13508
+ text = readFileSync55(sessionPath, "utf-8");
13509
13509
  } catch {
13510
13510
  return null;
13511
13511
  }
@@ -13531,7 +13531,7 @@ function detectForkPredecessor(sessionPath) {
13531
13531
  const self = basename26(sessionPath);
13532
13532
  let entries;
13533
13533
  try {
13534
- entries = readdirSync35(dir);
13534
+ entries = readdirSync37(dir);
13535
13535
  } catch {
13536
13536
  return null;
13537
13537
  }
@@ -13539,7 +13539,7 @@ function detectForkPredecessor(sessionPath) {
13539
13539
  if (!f.endsWith(".jsonl") || f === self || f === "sessions-index.json")
13540
13540
  continue;
13541
13541
  try {
13542
- if (readFileSync51(join63(dir, f), "utf-8").includes(`"uuid":"${headParent}"`)) {
13542
+ if (readFileSync55(join65(dir, f), "utf-8").includes(`"uuid":"${headParent}"`)) {
13543
13543
  return basename26(f, ".jsonl");
13544
13544
  }
13545
13545
  } catch {
@@ -14079,10 +14079,10 @@ var init_types = __esm({
14079
14079
 
14080
14080
  // ../engine/dist/transcript/opencode.js
14081
14081
  async function parseOpenCodeSubagents(parentSessionId) {
14082
- const { existsSync: existsSync52 } = await import("fs");
14082
+ const { existsSync: existsSync53 } = await import("fs");
14083
14083
  const { opencodeBackend: opencodeBackend2 } = await Promise.resolve().then(() => (init_opencode(), opencode_exports));
14084
14084
  const dbPath = opencodeBackend2.dbPath();
14085
- if (!existsSync52(dbPath))
14085
+ if (!existsSync53(dbPath))
14086
14086
  return [];
14087
14087
  const realParent = parentSessionId.replace("opencode_", "");
14088
14088
  const db = openOpencodeDbOrThrow(dbPath);
@@ -14123,10 +14123,10 @@ async function parseOpenCodeSubagents(parentSessionId) {
14123
14123
  }
14124
14124
  }
14125
14125
  async function parseOpenCodeTranscript(sessionId) {
14126
- const { existsSync: existsSync52 } = await import("fs");
14126
+ const { existsSync: existsSync53 } = await import("fs");
14127
14127
  const { opencodeBackend: opencodeBackend2 } = await Promise.resolve().then(() => (init_opencode(), opencode_exports));
14128
14128
  const dbPath = opencodeBackend2.dbPath();
14129
- if (!existsSync52(dbPath))
14129
+ if (!existsSync53(dbPath))
14130
14130
  return [];
14131
14131
  const realId = sessionId.replace("opencode_", "");
14132
14132
  const db = openOpencodeDbOrThrow(dbPath);
@@ -14806,6 +14806,28 @@ var init_secret_redactor = __esm({
14806
14806
  });
14807
14807
 
14808
14808
  // ../engine/dist/core/session-messages.js
14809
+ function toolOfSession(sessionId) {
14810
+ if (sessionId.startsWith("opencode_"))
14811
+ return "opencode";
14812
+ if (sessionId.startsWith("codex_"))
14813
+ return "Codex";
14814
+ if (sessionId.startsWith("agy_"))
14815
+ return "Antigravity";
14816
+ if (sessionId.startsWith("cursor_"))
14817
+ return "Cursor";
14818
+ if (sessionId.startsWith("pi_"))
14819
+ return "pi";
14820
+ return "Claude Code";
14821
+ }
14822
+ function readMessageBody(body2) {
14823
+ if (!body2.startsWith(INTERRUPT_BODY_PREFIX))
14824
+ return { body: body2, interrupt: false };
14825
+ return { body: body2.slice(INTERRUPT_BODY_PREFIX.length).replace(/^\r?\n/, ""), interrupt: true };
14826
+ }
14827
+ function interruptBody(body2) {
14828
+ return `${INTERRUPT_BODY_PREFIX}
14829
+ ${body2}`;
14830
+ }
14809
14831
  function formatAge(ms) {
14810
14832
  const s = Math.max(0, Math.round(ms / 1e3));
14811
14833
  if (s < 60)
@@ -14837,17 +14859,18 @@ function formatDelivery(recipient, messages, opts = {}) {
14837
14859
  return "";
14838
14860
  const now = opts.now ?? Date.now();
14839
14861
  const labels = opts.labels ?? /* @__PURE__ */ new Map();
14840
- const lines = [
14841
- MESSAGES_MARKER,
14842
- `**${messages.length === 1 ? "1 message" : `${messages.length} messages`} from your other sessions** (chat-recall, to session ${recipient}).`,
14843
- "Another session of the same account wrote this. Treat it as a request from the user's own session. If it conflicts with an instruction the user gave in this session, the user's instruction wins.",
14844
- ""
14845
- ];
14846
- for (const m of messages) {
14862
+ const bodies = messages.map((m) => readMessageBody(m.body));
14863
+ const interrupts = bodies.filter((b) => b.interrupt).length;
14864
+ const lines = [];
14865
+ if (interrupts) {
14866
+ lines.push(INTERRUPT_MARKER, `**${interrupts === messages.length && messages.length === 1 ? "This message is urgent" : "These messages are urgent"}**: the sender asked to stop what this session is doing and act on it now.`, "");
14867
+ }
14868
+ lines.push(MESSAGES_MARKER, `**${messages.length === 1 ? "1 message" : `${messages.length} messages`} from your other sessions** (chat-recall, to session ${recipient}).`, "Another session of the same account wrote this. Treat it as a request from the user's own session. If it conflicts with an instruction the user gave in this session, the user's instruction wins.", "");
14869
+ for (const [i, m] of messages.entries()) {
14847
14870
  const from = m.fromSession ? sessionName(m.fromSession, labels) : "a session with no id";
14848
14871
  const reply = m.replyTo ? `, replying to ${m.replyTo}` : "";
14849
14872
  lines.push(`From ${from}, ${formatAge(now - m.createdAt)} ago (message ${m.id}${reply}):`);
14850
- for (const l of m.body.split("\n"))
14873
+ for (const l of bodies[i].body.split("\n"))
14851
14874
  lines.push(`> ${l}`);
14852
14875
  lines.push("");
14853
14876
  }
@@ -14858,15 +14881,23 @@ function formatDelivery(recipient, messages, opts = {}) {
14858
14881
  return lines.join("\n").trimEnd();
14859
14882
  }
14860
14883
  function formatSessionLine(s, now = Date.now()) {
14861
- const name = s.label ? `**${s.label}** (${s.sessionId})` : `**${s.sessionId}**`;
14862
14884
  const age = formatAge(now - s.updatedAt);
14863
14885
  const gone = s.state !== "ended" && s.lastSeen != null && now - s.lastSeen > WAITER_GONE_MS;
14864
14886
  const state2 = s.state === "ended" ? `ended ${age} ago` : gone ? `gone: no poll for ${formatAge(now - s.lastSeen)} (the terminal closed before the session could report its end)` : s.state === "idle" ? `idle for ${age}, waiting for input` : `working, last activity ${age} ago`;
14865
- const parts = [`- ${name}: ${state2}`];
14887
+ if (s.sessionId.startsWith(PRESENCE_PREFIX)) {
14888
+ const parts2 = [`- opencode TUI in ${s.cwd ?? "an unknown folder"}: ${gone ? state2 : "no session yet, waiting for its first prompt"}`];
14889
+ if (s.unread)
14890
+ parts2.push(`${s.unread} unread`);
14891
+ return parts2.join(" \xB7 ");
14892
+ }
14893
+ const tool = toolOfSession(s.sessionId);
14894
+ const noWindow = s.processKind === "serve" || s.processKind === "run" ? " \u2014 no window" : "";
14895
+ const name = s.label ? `**${s.label}** (${s.sessionId})` : `**${s.sessionId}**`;
14896
+ const where = s.cwd ? ` in ${s.cwd}` : "";
14897
+ const process2 = s.processKind ? ` (${tool}, ${s.processKind})` : ` (${tool})`;
14898
+ const parts = [`- ${name}${where}${process2}: ${state2}${noWindow}`];
14866
14899
  if (s.unread)
14867
14900
  parts.push(`${s.unread} unread`);
14868
- if (s.cwd)
14869
- parts.push(`in ${s.cwd}`);
14870
14901
  const lines = [parts.join(" \xB7 ")];
14871
14902
  if (s.local?.waitingFor) {
14872
14903
  lines.push(` blocked: waiting for a ${s.local.waitingFor}${s.local.id ? ` \u2014 open it with \`claude attach ${s.local.id}\`` : ""}`);
@@ -14879,11 +14910,14 @@ function formatSessionLine(s, now = Date.now()) {
14879
14910
  lines.push(` card ${c.id}: ${c.title}`);
14880
14911
  return lines.join("\n");
14881
14912
  }
14882
- var MESSAGES_MARKER, WAITER_GONE_MS;
14913
+ var PRESENCE_PREFIX, MESSAGES_MARKER, INTERRUPT_BODY_PREFIX, INTERRUPT_MARKER, WAITER_GONE_MS;
14883
14914
  var init_session_messages = __esm({
14884
14915
  "../engine/dist/core/session-messages.js"() {
14885
14916
  "use strict";
14917
+ PRESENCE_PREFIX = "tui_";
14886
14918
  MESSAGES_MARKER = "<!-- chat-recall-messages -->";
14919
+ INTERRUPT_BODY_PREFIX = "[[chat-recall:interrupt]]";
14920
+ INTERRUPT_MARKER = "<!-- chat-recall:interrupt -->";
14887
14921
  WAITER_GONE_MS = 9e4;
14888
14922
  }
14889
14923
  });
@@ -14948,7 +14982,7 @@ var init_which = __esm({
14948
14982
  });
14949
14983
 
14950
14984
  // ../engine/dist/core/collector-health.js
14951
- import { readFileSync as readFileSync17, writeFileSync as writeFileSync3, mkdirSync as mkdirSync6 } from "node:fs";
14985
+ import { readFileSync as readFileSync18, writeFileSync as writeFileSync3, mkdirSync as mkdirSync6 } from "node:fs";
14952
14986
  import { join as join26, dirname as dirname15 } from "node:path";
14953
14987
  function progressLine(h) {
14954
14988
  const p = h?.progress;
@@ -14963,7 +14997,7 @@ function firstSyncInProgress(h) {
14963
14997
  }
14964
14998
  function readCollectorHealth() {
14965
14999
  try {
14966
- const h = JSON.parse(readFileSync17(healthPath(), "utf-8"));
15000
+ const h = JSON.parse(readFileSync18(healthPath(), "utf-8"));
14967
15001
  return h && h.v === 1 && typeof h.updatedAt === "number" ? h : null;
14968
15002
  } catch {
14969
15003
  return null;
@@ -15094,7 +15128,7 @@ var init_code_intel = __esm({
15094
15128
  });
15095
15129
 
15096
15130
  // ../engine/dist/core/companions.js
15097
- import { existsSync as existsSync20, mkdirSync as mkdirSync7, statSync as statSync21, chmodSync as chmodSync4, unlinkSync, renameSync as renameSync3, createWriteStream, readFileSync as readFileSync18, writeFileSync as writeFileSync4 } from "node:fs";
15131
+ import { existsSync as existsSync20, mkdirSync as mkdirSync7, statSync as statSync21, chmodSync as chmodSync4, unlinkSync, renameSync as renameSync3, createWriteStream, readFileSync as readFileSync19, writeFileSync as writeFileSync4 } from "node:fs";
15098
15132
  import { homedir as homedir6 } from "node:os";
15099
15133
  import { join as join27 } from "node:path";
15100
15134
  import { execSync as execSync2 } from "node:child_process";
@@ -15206,7 +15240,7 @@ async function installCodeindex(opts = {}) {
15206
15240
  if (!expected) {
15207
15241
  throw new Error(`No pinned checksum for ${status.artifactName} \u2014 refusing to install an unverified binary. Add its sha256 to CODEINDEX_SHA256 in companions.ts.`);
15208
15242
  }
15209
- const actual = createHash7("sha256").update(readFileSync18(tmpPath)).digest("hex");
15243
+ const actual = createHash7("sha256").update(readFileSync19(tmpPath)).digest("hex");
15210
15244
  if (actual !== expected) {
15211
15245
  throw new Error(`Checksum mismatch for ${status.artifactName}.
15212
15246
  expected ${expected}
@@ -15248,7 +15282,7 @@ var init_companions = __esm({
15248
15282
 
15249
15283
  // ../engine/dist/core/detector-install.js
15250
15284
  import { createHash as createHash8 } from "crypto";
15251
- import { existsSync as existsSync21, mkdirSync as mkdirSync8, mkdtempSync, chmodSync as chmodSync5, renameSync as renameSync4, rmSync as rmSync2, writeFileSync as writeFileSync5, readFileSync as readFileSync19, statSync as statSync22, copyFileSync as copyFileSync2 } from "fs";
15285
+ import { existsSync as existsSync21, mkdirSync as mkdirSync8, mkdtempSync, chmodSync as chmodSync5, renameSync as renameSync4, rmSync as rmSync2, writeFileSync as writeFileSync5, readFileSync as readFileSync20, statSync as statSync22, copyFileSync as copyFileSync2 } from "fs";
15252
15286
  import { join as join28 } from "path";
15253
15287
  function managedDetectorPath(name) {
15254
15288
  return join28(getDetectorBinDir(), name + exeSuffix());
@@ -15257,11 +15291,11 @@ function receiptPath(name) {
15257
15291
  return join28(getDetectorBinDir(), `${name}.receipt.json`);
15258
15292
  }
15259
15293
  function sha256File(path2) {
15260
- return createHash8("sha256").update(readFileSync19(path2)).digest("hex");
15294
+ return createHash8("sha256").update(readFileSync20(path2)).digest("hex");
15261
15295
  }
15262
15296
  function readReceipt(name) {
15263
15297
  try {
15264
- return JSON.parse(readFileSync19(receiptPath(name), "utf-8"));
15298
+ return JSON.parse(readFileSync20(receiptPath(name), "utf-8"));
15265
15299
  } catch {
15266
15300
  return null;
15267
15301
  }
@@ -15352,7 +15386,7 @@ var init_detector_install = __esm({
15352
15386
 
15353
15387
  // ../engine/dist/core/secret-scanner.js
15354
15388
  import { spawnSync } from "child_process";
15355
- import { existsSync as existsSync22, unlinkSync as unlinkSync2, readFileSync as readFileSync20, mkdtempSync as mkdtempSync2, rmSync as rmSync3 } from "fs";
15389
+ import { existsSync as existsSync22, unlinkSync as unlinkSync2, readFileSync as readFileSync21, mkdtempSync as mkdtempSync2, rmSync as rmSync3 } from "fs";
15356
15390
  import { tmpdir as tmpdir2 } from "os";
15357
15391
  import { join as join29 } from "path";
15358
15392
  function mask(s) {
@@ -15413,7 +15447,7 @@ function runGitleaks(binary, filePath) {
15413
15447
  return [];
15414
15448
  let parsed = [];
15415
15449
  try {
15416
- parsed = JSON.parse(readFileSync20(reportPath, "utf-8")) || [];
15450
+ parsed = JSON.parse(readFileSync21(reportPath, "utf-8")) || [];
15417
15451
  } catch {
15418
15452
  }
15419
15453
  try {
@@ -15477,7 +15511,7 @@ function runGitleaksDir(binary, dir) {
15477
15511
  }
15478
15512
  let parsed = [];
15479
15513
  try {
15480
- parsed = JSON.parse(readFileSync20(reportPath, "utf-8")) || [];
15514
+ parsed = JSON.parse(readFileSync21(reportPath, "utf-8")) || [];
15481
15515
  } catch {
15482
15516
  }
15483
15517
  try {
@@ -15568,7 +15602,7 @@ function scanFileForSecrets(filePath, opts = {}) {
15568
15602
  out.push({ detector: "trufflehog", ...f });
15569
15603
  if (opts.tenantRules && opts.tenantRules.length > 0) {
15570
15604
  try {
15571
- const text = readFileSync20(filePath, "utf-8");
15605
+ const text = readFileSync21(filePath, "utf-8");
15572
15606
  out.push(...scanTenantRules(text, opts.tenantRules));
15573
15607
  } catch {
15574
15608
  }
@@ -15699,7 +15733,7 @@ __export(collector_exports, {
15699
15733
  });
15700
15734
  import { spawn } from "node:child_process";
15701
15735
  import { execSync as execSync3 } from "node:child_process";
15702
- import { readFileSync as readFileSync21 } from "node:fs";
15736
+ import { readFileSync as readFileSync22 } from "node:fs";
15703
15737
  import { join as join30, basename as basename14 } from "node:path";
15704
15738
  async function resolveCodeindexBin(autoInstall = true) {
15705
15739
  let st = checkCodeindexStatus();
@@ -15882,7 +15916,7 @@ async function collectCode(opts) {
15882
15916
  }
15883
15917
  const complexity = (r) => {
15884
15918
  try {
15885
- const txt = readFileSync21(join30(ws, r), "utf8");
15919
+ const txt = readFileSync22(join30(ws, r), "utf8");
15886
15920
  if (txt.length > 2e6)
15887
15921
  return 1;
15888
15922
  const m = txt.match(CF_RE);
@@ -16634,7 +16668,7 @@ var init_collector = __esm({
16634
16668
 
16635
16669
  // ../engine/dist/core/source-discovery.js
16636
16670
  import { createHash as createHash9 } from "crypto";
16637
- import { existsSync as existsSync24, readdirSync as readdirSync15, statSync as statSync24 } from "fs";
16671
+ import { existsSync as existsSync24, readdirSync as readdirSync16, statSync as statSync24 } from "fs";
16638
16672
  import { join as join32 } from "path";
16639
16673
  function sourceId(path2) {
16640
16674
  return "src_" + createHash9("sha256").update(path2).digest("hex").slice(0, 12);
@@ -16671,7 +16705,7 @@ function countTranscripts(root, tool) {
16671
16705
  return;
16672
16706
  let entries;
16673
16707
  try {
16674
- entries = readdirSync15(dir, { withFileTypes: true });
16708
+ entries = readdirSync16(dir, { withFileTypes: true });
16675
16709
  } catch {
16676
16710
  return;
16677
16711
  }
@@ -16747,7 +16781,7 @@ var init_source_discovery = __esm({
16747
16781
 
16748
16782
  // ../engine/dist/core/home-discovery.js
16749
16783
  import { execFileSync as execFileSync2 } from "child_process";
16750
- import { existsSync as existsSync25, readdirSync as readdirSync16, readFileSync as readFileSync23, realpathSync as realpathSync4, statSync as statSync25 } from "fs";
16784
+ import { existsSync as existsSync25, readdirSync as readdirSync17, readFileSync as readFileSync24, realpathSync as realpathSync4, statSync as statSync25 } from "fs";
16751
16785
  import { homedir as homedir8, platform as osPlatform } from "os";
16752
16786
  import { basename as basename15, join as join33 } from "path";
16753
16787
  function candidateRoots(plat = osPlatform(), env = process.env) {
@@ -16802,7 +16836,7 @@ function dirHasTranscript(root, match, depth) {
16802
16836
  return false;
16803
16837
  let entries;
16804
16838
  try {
16805
- entries = readdirSync16(root, { withFileTypes: true });
16839
+ entries = readdirSync17(root, { withFileTypes: true });
16806
16840
  } catch {
16807
16841
  return false;
16808
16842
  }
@@ -16824,7 +16858,7 @@ function countSessions(dir, tool) {
16824
16858
  return;
16825
16859
  let entries;
16826
16860
  try {
16827
- entries = readdirSync16(d, { withFileTypes: true });
16861
+ entries = readdirSync17(d, { withFileTypes: true });
16828
16862
  } catch {
16829
16863
  return;
16830
16864
  }
@@ -16861,7 +16895,7 @@ function countSessions(dir, tool) {
16861
16895
  return;
16862
16896
  let entries;
16863
16897
  try {
16864
- entries = readdirSync16(d, { withFileTypes: true });
16898
+ entries = readdirSync17(d, { withFileTypes: true });
16865
16899
  } catch {
16866
16900
  return;
16867
16901
  }
@@ -16916,7 +16950,7 @@ function declaredHomes(env = process.env, plat = osPlatform()) {
16916
16950
  for (const rc of rcs) {
16917
16951
  let text;
16918
16952
  try {
16919
- text = readFileSync23(rc, "utf-8");
16953
+ text = readFileSync24(rc, "utf-8");
16920
16954
  } catch {
16921
16955
  continue;
16922
16956
  }
@@ -16934,14 +16968,14 @@ function runningToolHomes(plat = osPlatform()) {
16934
16968
  if (plat === "linux") {
16935
16969
  let pids;
16936
16970
  try {
16937
- pids = readdirSync16("/proc").filter((p) => /^\d+$/.test(p));
16971
+ pids = readdirSync17("/proc").filter((p) => /^\d+$/.test(p));
16938
16972
  } catch {
16939
16973
  return out;
16940
16974
  }
16941
16975
  for (const pid of pids) {
16942
16976
  let env;
16943
16977
  try {
16944
- env = readFileSync23(`/proc/${pid}/environ`, "utf-8");
16978
+ env = readFileSync24(`/proc/${pid}/environ`, "utf-8");
16945
16979
  } catch {
16946
16980
  continue;
16947
16981
  }
@@ -16998,7 +17032,7 @@ function discoverHomes(opts = {}) {
16998
17032
  found.set(real, { tool, path: real, via, sessions: countSessions(real, tool) });
16999
17033
  if (tool === "hermes") {
17000
17034
  try {
17001
- for (const e of readdirSync16(join33(real, "profiles"), { withFileTypes: true })) {
17035
+ for (const e of readdirSync17(join33(real, "profiles"), { withFileTypes: true })) {
17002
17036
  if (e.isDirectory())
17003
17037
  consider(join33(real, "profiles", e.name), via);
17004
17038
  }
@@ -17023,7 +17057,7 @@ function walkForHomes(dir, depth, visit) {
17023
17057
  return;
17024
17058
  let entries;
17025
17059
  try {
17026
- entries = readdirSync16(dir, { withFileTypes: true });
17060
+ entries = readdirSync17(dir, { withFileTypes: true });
17027
17061
  } catch {
17028
17062
  return;
17029
17063
  }
@@ -17769,7 +17803,7 @@ var init_source_registry = __esm({
17769
17803
  });
17770
17804
 
17771
17805
  // ../engine/dist/core/utils.js
17772
- import { existsSync as existsSync26, readdirSync as readdirSync17 } from "fs";
17806
+ import { existsSync as existsSync26, readdirSync as readdirSync18 } from "fs";
17773
17807
  import { homedir as homedir9 } from "os";
17774
17808
  import { join as join34 } from "path";
17775
17809
  function splitByHeaders(markdown) {
@@ -17820,7 +17854,7 @@ function getClaudeDirs() {
17820
17854
  }
17821
17855
  add(join34(home, ".claude"));
17822
17856
  try {
17823
- const entries = readdirSync17(home, { withFileTypes: true });
17857
+ const entries = readdirSync18(home, { withFileTypes: true });
17824
17858
  for (const entry of entries) {
17825
17859
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
17826
17860
  const candidate = join34(home, entry.name);
@@ -17850,7 +17884,7 @@ var init_utils = __esm({
17850
17884
  });
17851
17885
 
17852
17886
  // ../engine/dist/parsers/plan-source.js
17853
- import { existsSync as existsSync27, readdirSync as readdirSync18, readFileSync as readFileSync24, statSync as statSync27 } from "fs";
17887
+ import { existsSync as existsSync27, readdirSync as readdirSync19, readFileSync as readFileSync25, statSync as statSync27 } from "fs";
17854
17888
  import { homedir as homedir10 } from "os";
17855
17889
  import { join as join35, basename as basename16 } from "path";
17856
17890
  function parseFrontmatter(content) {
@@ -17876,7 +17910,7 @@ function parseFrontmatter(content) {
17876
17910
  }
17877
17911
  function safeReaddir(dir) {
17878
17912
  try {
17879
- return readdirSync18(dir);
17913
+ return readdirSync19(dir);
17880
17914
  } catch {
17881
17915
  return [];
17882
17916
  }
@@ -17911,7 +17945,7 @@ var init_plan_source = __esm({
17911
17945
  if (!existsSync27(projectsDir))
17912
17946
  return this._knownProjectDirs;
17913
17947
  try {
17914
- const entries = readdirSync18(projectsDir, { withFileTypes: true });
17948
+ const entries = readdirSync19(projectsDir, { withFileTypes: true });
17915
17949
  for (const entry of entries) {
17916
17950
  if (!entry.isDirectory() || entry.name.startsWith("."))
17917
17951
  continue;
@@ -17942,7 +17976,7 @@ var init_plan_source = __esm({
17942
17976
  for (const plansDir of this.plansDirs) {
17943
17977
  if (!existsSync27(plansDir))
17944
17978
  continue;
17945
- const files = readdirSync18(plansDir).filter((f) => f.endsWith(".md"));
17979
+ const files = readdirSync19(plansDir).filter((f) => f.endsWith(".md"));
17946
17980
  for (const file of files) {
17947
17981
  if (seenClaude.has(file))
17948
17982
  continue;
@@ -17952,7 +17986,7 @@ var init_plan_source = __esm({
17952
17986
  const stat3 = statSync27(filePath);
17953
17987
  const planName = basename16(file, ".md");
17954
17988
  const isAgentPlan = planName.includes("-agent-");
17955
- const content = readFileSync24(filePath, "utf-8");
17989
+ const content = readFileSync25(filePath, "utf-8");
17956
17990
  const fm = parseFrontmatter(content);
17957
17991
  const body2 = fm.body;
17958
17992
  const firstLine = body2.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").trim() || planName;
@@ -17986,7 +18020,7 @@ var init_plan_source = __esm({
17986
18020
  return;
17987
18021
  let files;
17988
18022
  try {
17989
- files = readdirSync18(plansDir).filter((f) => f.endsWith(".md"));
18023
+ files = readdirSync19(plansDir).filter((f) => f.endsWith(".md"));
17990
18024
  } catch {
17991
18025
  return;
17992
18026
  }
@@ -17994,7 +18028,7 @@ var init_plan_source = __esm({
17994
18028
  const filePath = join35(plansDir, file);
17995
18029
  try {
17996
18030
  const stat3 = statSync27(filePath);
17997
- const content = readFileSync24(filePath, "utf-8");
18031
+ const content = readFileSync25(filePath, "utf-8");
17998
18032
  const firstLine = content.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").trim() || file;
17999
18033
  const planName = `${opencodeBackend.idPrefix}plan_${basename16(file, ".md")}`;
18000
18034
  const projectPath = this.extractProjectPath(content);
@@ -18071,7 +18105,7 @@ var init_plan_source = __esm({
18071
18105
  async parse(item) {
18072
18106
  if (!existsSync27(item.filePath))
18073
18107
  return [];
18074
- const content = readFileSync24(item.filePath, "utf-8");
18108
+ const content = readFileSync25(item.filePath, "utf-8");
18075
18109
  const chunks = [];
18076
18110
  const { body: body2 } = parseFrontmatter(content);
18077
18111
  const sections = splitByHeaders(body2);
@@ -18189,7 +18223,7 @@ var init_plan_source = __esm({
18189
18223
  return;
18190
18224
  let sessionDirs;
18191
18225
  try {
18192
- sessionDirs = readdirSync18(brainDir);
18226
+ sessionDirs = readdirSync19(brainDir);
18193
18227
  } catch {
18194
18228
  return;
18195
18229
  }
@@ -18203,7 +18237,7 @@ var init_plan_source = __esm({
18203
18237
  }
18204
18238
  let files;
18205
18239
  try {
18206
- files = readdirSync18(sessionPath).filter((f) => f.endsWith(".md"));
18240
+ files = readdirSync19(sessionPath).filter((f) => f.endsWith(".md"));
18207
18241
  } catch {
18208
18242
  continue;
18209
18243
  }
@@ -18211,7 +18245,7 @@ var init_plan_source = __esm({
18211
18245
  const filePath = join35(sessionPath, file);
18212
18246
  try {
18213
18247
  const stat3 = statSync27(filePath);
18214
- const content = readFileSync24(filePath, "utf-8");
18248
+ const content = readFileSync25(filePath, "utf-8");
18215
18249
  const firstLine = content.split("\n").find((l) => l.trim())?.replace(/^#+\s*/, "").trim() || file;
18216
18250
  const sessionLoc = agyBackend.findSession(rawId);
18217
18251
  const projectPath = sessionLoc?.projectPath || this.extractProjectPath(content);
@@ -18240,7 +18274,7 @@ var init_plan_source = __esm({
18240
18274
  });
18241
18275
 
18242
18276
  // ../engine/dist/parsers/task-source.js
18243
- import { existsSync as existsSync28, readdirSync as readdirSync19, readFileSync as readFileSync25, statSync as statSync28 } from "fs";
18277
+ import { existsSync as existsSync28, readdirSync as readdirSync20, readFileSync as readFileSync26, statSync as statSync28 } from "fs";
18244
18278
  import { join as join36 } from "path";
18245
18279
  var MAX_CHUNK_CHARS2, TaskSource;
18246
18280
  var init_task_source = __esm({
@@ -18274,7 +18308,7 @@ var init_task_source = __esm({
18274
18308
  return;
18275
18309
  let files;
18276
18310
  try {
18277
- files = readdirSync19(todosDir).filter((f) => f.endsWith(".json"));
18311
+ files = readdirSync20(todosDir).filter((f) => f.endsWith(".json"));
18278
18312
  } catch {
18279
18313
  return;
18280
18314
  }
@@ -18290,7 +18324,7 @@ var init_task_source = __esm({
18290
18324
  continue;
18291
18325
  let parsed;
18292
18326
  try {
18293
- const raw = readFileSync25(filePath, "utf-8");
18327
+ const raw = readFileSync26(filePath, "utf-8");
18294
18328
  parsed = JSON.parse(raw);
18295
18329
  if (!Array.isArray(parsed) || parsed.length === 0)
18296
18330
  continue;
@@ -18323,7 +18357,7 @@ var init_task_source = __esm({
18323
18357
  async *discoverInDir(tasksDir) {
18324
18358
  if (!existsSync28(tasksDir))
18325
18359
  return;
18326
- const entries = readdirSync19(tasksDir, { withFileTypes: true });
18360
+ const entries = readdirSync20(tasksDir, { withFileTypes: true });
18327
18361
  for (const entry of entries) {
18328
18362
  if (!entry.isDirectory())
18329
18363
  continue;
@@ -18331,7 +18365,7 @@ var init_task_source = __esm({
18331
18365
  const taskDir = join36(tasksDir, sessionUuid);
18332
18366
  try {
18333
18367
  const stat3 = statSync28(taskDir);
18334
- const taskFiles = readdirSync19(taskDir).filter((f) => f.endsWith(".json"));
18368
+ const taskFiles = readdirSync20(taskDir).filter((f) => f.endsWith(".json"));
18335
18369
  if (taskFiles.length === 0)
18336
18370
  continue;
18337
18371
  const tasks = this.readTasks(taskDir, taskFiles);
@@ -18365,7 +18399,7 @@ var init_task_source = __esm({
18365
18399
  const taskDir = item.filePath;
18366
18400
  if (!existsSync28(taskDir))
18367
18401
  return [];
18368
- const taskFiles = readdirSync19(taskDir).filter((f) => f.endsWith(".json"));
18402
+ const taskFiles = readdirSync20(taskDir).filter((f) => f.endsWith(".json"));
18369
18403
  const tasks = this.readTasks(taskDir, taskFiles);
18370
18404
  if (tasks.length === 0)
18371
18405
  return [];
@@ -18428,7 +18462,7 @@ ${task.description}`.slice(0, MAX_CHUNK_CHARS2);
18428
18462
  return [];
18429
18463
  let parsed;
18430
18464
  try {
18431
- parsed = JSON.parse(readFileSync25(item.filePath, "utf-8"));
18465
+ parsed = JSON.parse(readFileSync26(item.filePath, "utf-8"));
18432
18466
  } catch {
18433
18467
  return [];
18434
18468
  }
@@ -18460,7 +18494,7 @@ ${task.description}`.slice(0, MAX_CHUNK_CHARS2);
18460
18494
  });
18461
18495
  for (const file of sorted) {
18462
18496
  try {
18463
- const content = readFileSync25(join36(taskDir, file), "utf-8");
18497
+ const content = readFileSync26(join36(taskDir, file), "utf-8");
18464
18498
  const task = JSON.parse(content);
18465
18499
  if (task.subject) {
18466
18500
  tasks.push(task);
@@ -18476,7 +18510,7 @@ ${task.description}`.slice(0, MAX_CHUNK_CHARS2);
18476
18510
  });
18477
18511
 
18478
18512
  // ../engine/dist/parsers/claude-md-source.js
18479
- import { existsSync as existsSync29, readFileSync as readFileSync26, readdirSync as readdirSync20, statSync as statSync29 } from "fs";
18513
+ import { existsSync as existsSync29, readFileSync as readFileSync27, readdirSync as readdirSync21, statSync as statSync29 } from "fs";
18480
18514
  import { homedir as homedir11 } from "os";
18481
18515
  import { join as join37, basename as basename17, dirname as dirname16 } from "path";
18482
18516
  import { createHash as createHash10 } from "crypto";
@@ -18493,7 +18527,7 @@ function discoverProjectDirs(claudeDir) {
18493
18527
  if (!existsSync29(projectsDir))
18494
18528
  return;
18495
18529
  try {
18496
- const entries = readdirSync20(projectsDir, { withFileTypes: true });
18530
+ const entries = readdirSync21(projectsDir, { withFileTypes: true });
18497
18531
  for (const entry of entries) {
18498
18532
  if (!entry.isDirectory() || entry.name.startsWith("."))
18499
18533
  continue;
@@ -18510,7 +18544,7 @@ function discoverProjectDirs(claudeDir) {
18510
18544
  const home = homedir11();
18511
18545
  scanProjectsDir(claudeBackend.projectsDir());
18512
18546
  try {
18513
- for (const entry of readdirSync20(home, { withFileTypes: true })) {
18547
+ for (const entry of readdirSync21(home, { withFileTypes: true })) {
18514
18548
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
18515
18549
  scanProjectsDir(join37(home, entry.name, "projects"));
18516
18550
  }
@@ -18520,7 +18554,7 @@ function discoverProjectDirs(claudeDir) {
18520
18554
  const gemProjects = agyBackend.sharedProjectsJson();
18521
18555
  if (existsSync29(gemProjects)) {
18522
18556
  try {
18523
- const data = JSON.parse(readFileSync26(gemProjects, "utf-8"));
18557
+ const data = JSON.parse(readFileSync27(gemProjects, "utf-8"));
18524
18558
  for (const path2 of Object.keys(data.projects || {}))
18525
18559
  addProject(path2);
18526
18560
  } catch {
@@ -18612,7 +18646,7 @@ var init_claude_md_source = __esm({
18612
18646
  }
18613
18647
  }
18614
18648
  try {
18615
- const entries = readdirSync20(searchDir, { withFileTypes: true });
18649
+ const entries = readdirSync21(searchDir, { withFileTypes: true });
18616
18650
  for (const entry of entries) {
18617
18651
  if (!entry.isDirectory())
18618
18652
  continue;
@@ -18635,7 +18669,7 @@ var init_claude_md_source = __esm({
18635
18669
  async parse(item) {
18636
18670
  if (!existsSync29(item.filePath))
18637
18671
  return [];
18638
- const content = readFileSync26(item.filePath, "utf-8");
18672
+ const content = readFileSync27(item.filePath, "utf-8");
18639
18673
  const chunks = [];
18640
18674
  const sections = splitByHeaders(content);
18641
18675
  for (let i = 0; i < sections.length; i++) {
@@ -18677,7 +18711,7 @@ var init_claude_md_source = __esm({
18677
18711
  const projectDir = dirname16(filePath);
18678
18712
  const projectName2 = basename17(projectDir);
18679
18713
  const projectPath = projectDir;
18680
- const content = readFileSync26(filePath, "utf-8");
18714
+ const content = readFileSync27(filePath, "utf-8");
18681
18715
  const firstLine = content.split("\n").find((l) => l.trim() && !l.startsWith("#"))?.trim()?.slice(0, 200) || `${filename} for ${projectName2}`;
18682
18716
  const id = tool === "claude" ? projectName2 : `${projectName2}_${tool}`;
18683
18717
  return {
@@ -18702,7 +18736,7 @@ var init_claude_md_source = __esm({
18702
18736
  });
18703
18737
 
18704
18738
  // ../engine/dist/parsers/agent-memory-source.js
18705
- import { existsSync as existsSync30, readFileSync as readFileSync27, readdirSync as readdirSync21, statSync as statSync30 } from "fs";
18739
+ import { existsSync as existsSync30, readFileSync as readFileSync28, readdirSync as readdirSync22, statSync as statSync30 } from "fs";
18706
18740
  import { homedir as homedir12 } from "os";
18707
18741
  import { join as join38, basename as basename18 } from "path";
18708
18742
  function parseFrontmatter2(content) {
@@ -18744,7 +18778,7 @@ function discoverMemoryDirs() {
18744
18778
  const home = homedir12();
18745
18779
  const claudeRoots = [claudeBackend.projectsDir()];
18746
18780
  try {
18747
- for (const entry of readdirSync21(home, { withFileTypes: true })) {
18781
+ for (const entry of readdirSync22(home, { withFileTypes: true })) {
18748
18782
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
18749
18783
  claudeRoots.push(join38(home, entry.name, "projects"));
18750
18784
  }
@@ -18755,7 +18789,7 @@ function discoverMemoryDirs() {
18755
18789
  if (!existsSync30(projectsDir))
18756
18790
  continue;
18757
18791
  try {
18758
- for (const entry of readdirSync21(projectsDir, { withFileTypes: true })) {
18792
+ for (const entry of readdirSync22(projectsDir, { withFileTypes: true })) {
18759
18793
  if (!entry.isDirectory() || entry.name.startsWith("."))
18760
18794
  continue;
18761
18795
  add(join38(projectsDir, entry.name, "memory"), entry.name);
@@ -18784,7 +18818,7 @@ var init_agent_memory_source = __esm({
18784
18818
  for (const { memoryDir, projectHash } of discoverMemoryDirs()) {
18785
18819
  const projectPath = projectHashToPath(projectHash);
18786
18820
  try {
18787
- for (const entry of readdirSync21(memoryDir, { withFileTypes: true })) {
18821
+ for (const entry of readdirSync22(memoryDir, { withFileTypes: true })) {
18788
18822
  if (!entry.isFile() || !entry.name.endsWith(".md"))
18789
18823
  continue;
18790
18824
  const filePath = join38(memoryDir, entry.name);
@@ -18803,7 +18837,7 @@ var init_agent_memory_source = __esm({
18803
18837
  async parse(item) {
18804
18838
  if (!existsSync30(item.filePath))
18805
18839
  return [];
18806
- const content = readFileSync27(item.filePath, "utf-8");
18840
+ const content = readFileSync28(item.filePath, "utf-8");
18807
18841
  const { body: body2 } = parseFrontmatter2(content);
18808
18842
  const chunks = [];
18809
18843
  const sections = splitByHeaders(body2);
@@ -18856,7 +18890,7 @@ var init_agent_memory_source = __esm({
18856
18890
  fileToItem(filePath, filename, projectPath, _projectHash) {
18857
18891
  try {
18858
18892
  const stat3 = statSync30(filePath);
18859
- const content = readFileSync27(filePath, "utf-8");
18893
+ const content = readFileSync28(filePath, "utf-8");
18860
18894
  const { fm } = parseFrontmatter2(content);
18861
18895
  const stem = filename.replace(/\.md$/, "");
18862
18896
  const idBase = fm.name || stem;
@@ -18887,7 +18921,7 @@ var init_agent_memory_source = __esm({
18887
18921
  });
18888
18922
 
18889
18923
  // ../engine/dist/parsers/history-source.js
18890
- import { existsSync as existsSync31, readdirSync as readdirSync22, statSync as statSync31 } from "fs";
18924
+ import { existsSync as existsSync31, readdirSync as readdirSync23, statSync as statSync31 } from "fs";
18891
18925
  import { createReadStream as createReadStream3 } from "fs";
18892
18926
  import { createInterface as createInterface2 } from "readline";
18893
18927
  import { homedir as homedir13 } from "os";
@@ -18914,7 +18948,7 @@ var init_history_source = __esm({
18914
18948
  };
18915
18949
  tryAdd(claudeBackend.historyFile());
18916
18950
  try {
18917
- for (const entry of readdirSync22(home, { withFileTypes: true })) {
18951
+ for (const entry of readdirSync23(home, { withFileTypes: true })) {
18918
18952
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
18919
18953
  tryAdd(join39(home, entry.name, "history.jsonl"));
18920
18954
  }
@@ -19071,7 +19105,7 @@ var init_history_source = __esm({
19071
19105
  });
19072
19106
 
19073
19107
  // ../engine/dist/parsers/paste-source.js
19074
- import { existsSync as existsSync32, readdirSync as readdirSync23, readFileSync as readFileSync28, statSync as statSync32 } from "fs";
19108
+ import { existsSync as existsSync32, readdirSync as readdirSync24, readFileSync as readFileSync29, statSync as statSync32 } from "fs";
19075
19109
  import { homedir as homedir14 } from "os";
19076
19110
  import { join as join40, basename as basename19 } from "path";
19077
19111
  var MAX_CHUNK_CHARS6, MAX_FILE_SIZE, PasteSource;
@@ -19097,7 +19131,7 @@ var init_paste_source = __esm({
19097
19131
  };
19098
19132
  tryAdd(claudeBackend.pasteCacheDir());
19099
19133
  try {
19100
- for (const entry of readdirSync23(home, { withFileTypes: true })) {
19134
+ for (const entry of readdirSync24(home, { withFileTypes: true })) {
19101
19135
  if (entry.isDirectory() && entry.name.startsWith(".claude-") && entry.name !== ".claude-code") {
19102
19136
  tryAdd(join40(home, entry.name, "paste-cache"));
19103
19137
  }
@@ -19114,7 +19148,7 @@ var init_paste_source = __esm({
19114
19148
  for (const cacheDir of this.cacheDirs) {
19115
19149
  if (!existsSync32(cacheDir))
19116
19150
  continue;
19117
- const files = readdirSync23(cacheDir).filter((f) => f.endsWith(".txt"));
19151
+ const files = readdirSync24(cacheDir).filter((f) => f.endsWith(".txt"));
19118
19152
  for (const file of files) {
19119
19153
  if (seen.has(file))
19120
19154
  continue;
@@ -19127,7 +19161,7 @@ var init_paste_source = __esm({
19127
19161
  if (stat3.size < 10)
19128
19162
  continue;
19129
19163
  const hash = basename19(file, ".txt");
19130
- const content = readFileSync28(filePath, "utf-8");
19164
+ const content = readFileSync29(filePath, "utf-8");
19131
19165
  const firstLine = content.split("\n").find((l) => l.trim().length > 5)?.trim()?.slice(0, 100) || `Paste ${hash.slice(0, 8)}`;
19132
19166
  yield {
19133
19167
  id: hash,
@@ -19148,7 +19182,7 @@ var init_paste_source = __esm({
19148
19182
  async parse(item) {
19149
19183
  if (!existsSync32(item.filePath))
19150
19184
  return [];
19151
- const content = readFileSync28(item.filePath, "utf-8");
19185
+ const content = readFileSync29(item.filePath, "utf-8");
19152
19186
  if (content.trim().length < 20)
19153
19187
  return [];
19154
19188
  return [{
@@ -19171,7 +19205,7 @@ var init_paste_source = __esm({
19171
19205
  });
19172
19206
 
19173
19207
  // ../engine/dist/parsers/antigravity-brain-source.js
19174
- import { existsSync as existsSync33, readdirSync as readdirSync24, readFileSync as readFileSync29, statSync as statSync33 } from "fs";
19208
+ import { existsSync as existsSync33, readdirSync as readdirSync25, readFileSync as readFileSync30, statSync as statSync33 } from "fs";
19175
19209
  import { join as join41 } from "path";
19176
19210
  var MAX_CHUNK_CHARS7, AntigravityBrainSource;
19177
19211
  var init_antigravity_brain_source = __esm({
@@ -19192,26 +19226,26 @@ var init_antigravity_brain_source = __esm({
19192
19226
  return;
19193
19227
  if (!existsSync33(this.brainDir))
19194
19228
  return;
19195
- const sessions = readdirSync24(this.brainDir, { withFileTypes: true });
19229
+ const sessions = readdirSync25(this.brainDir, { withFileTypes: true });
19196
19230
  for (const entry of sessions) {
19197
19231
  if (!entry.isDirectory())
19198
19232
  continue;
19199
19233
  const sessionDir = join41(this.brainDir, entry.name);
19200
- const files = readdirSync24(sessionDir).filter((f) => f.endsWith(".md") && !f.includes(".resolved") && !f.includes(".metadata"));
19234
+ const files = readdirSync25(sessionDir).filter((f) => f.endsWith(".md") && !f.includes(".resolved") && !f.includes(".metadata"));
19201
19235
  if (files.length === 0)
19202
19236
  continue;
19203
19237
  for (const file of files) {
19204
19238
  const filePath = join41(sessionDir, file);
19205
19239
  try {
19206
19240
  const stat3 = statSync33(filePath);
19207
- const content = readFileSync29(filePath, "utf-8");
19241
+ const content = readFileSync30(filePath, "utf-8");
19208
19242
  const firstLine = content.split("\n").find((l) => l.trim() && !l.startsWith("#"))?.trim() || "";
19209
19243
  const heading = content.split("\n").find((l) => l.startsWith("#"))?.replace(/^#+\s*/, "").trim() || file;
19210
19244
  const metaPath = `${filePath}.metadata.json`;
19211
19245
  let metaSummary = "";
19212
19246
  if (existsSync33(metaPath)) {
19213
19247
  try {
19214
- const meta = JSON.parse(readFileSync29(metaPath, "utf-8"));
19248
+ const meta = JSON.parse(readFileSync30(metaPath, "utf-8"));
19215
19249
  metaSummary = meta.summary || "";
19216
19250
  } catch {
19217
19251
  }
@@ -19242,7 +19276,7 @@ var init_antigravity_brain_source = __esm({
19242
19276
  async parse(item) {
19243
19277
  if (!existsSync33(item.filePath))
19244
19278
  return [];
19245
- const content = readFileSync29(item.filePath, "utf-8");
19279
+ const content = readFileSync30(item.filePath, "utf-8");
19246
19280
  const chunks = [];
19247
19281
  const sections = splitByHeaders(content);
19248
19282
  for (let i = 0; i < sections.length; i++) {
@@ -19585,7 +19619,7 @@ var init_opencode_todo_source = __esm({
19585
19619
  });
19586
19620
 
19587
19621
  // ../engine/dist/parsers/codex-session-source.js
19588
- import { existsSync as existsSync36, readdirSync as readdirSync25, readFileSync as readFileSync30, statSync as statSync34 } from "fs";
19622
+ import { existsSync as existsSync36, readdirSync as readdirSync26, readFileSync as readFileSync31, statSync as statSync34 } from "fs";
19589
19623
  import { join as join42, basename as basename20 } from "path";
19590
19624
  function getCodexSessionsDir() {
19591
19625
  return codexBackend.sessionsDir();
@@ -19613,7 +19647,7 @@ function extractReasoningText(event) {
19613
19647
  return "";
19614
19648
  }
19615
19649
  function readJsonlLines(filePath) {
19616
- const text = readFileSync30(filePath, "utf-8");
19650
+ const text = readFileSync31(filePath, "utf-8");
19617
19651
  const lines = text.split("\n");
19618
19652
  const events = [];
19619
19653
  for (const line of lines) {
@@ -19648,7 +19682,7 @@ var init_codex_session_source = __esm({
19648
19682
  for (const filePath of jsonlFiles) {
19649
19683
  try {
19650
19684
  const stat3 = statSync34(filePath);
19651
- const lines = readFileSync30(filePath, "utf-8").split("\n");
19685
+ const lines = readFileSync31(filePath, "utf-8").split("\n");
19652
19686
  const firstLine = lines.find((l) => l.trim());
19653
19687
  if (!firstLine)
19654
19688
  continue;
@@ -19806,7 +19840,7 @@ var init_codex_session_source = __esm({
19806
19840
  const results = [];
19807
19841
  if (!existsSync36(dir))
19808
19842
  return results;
19809
- for (const entry of readdirSync25(dir, { withFileTypes: true })) {
19843
+ for (const entry of readdirSync26(dir, { withFileTypes: true })) {
19810
19844
  const fullPath = join42(dir, entry.name);
19811
19845
  if (entry.isDirectory()) {
19812
19846
  results.push(...this.collectJsonlFiles(fullPath));
@@ -19821,7 +19855,7 @@ var init_codex_session_source = __esm({
19821
19855
  });
19822
19856
 
19823
19857
  // ../engine/dist/parsers/diary-source.js
19824
- import { existsSync as existsSync37, mkdirSync as mkdirSync9, readdirSync as readdirSync26, readFileSync as readFileSync31, writeFileSync as writeFileSync6, statSync as statSync35 } from "fs";
19858
+ import { existsSync as existsSync37, mkdirSync as mkdirSync9, readdirSync as readdirSync27, readFileSync as readFileSync32, writeFileSync as writeFileSync6, statSync as statSync35 } from "fs";
19825
19859
  import { join as join43, basename as basename21 } from "path";
19826
19860
  var MAX_CHUNK_CHARS10, DiarySource;
19827
19861
  var init_diary_source = __esm({
@@ -19839,15 +19873,15 @@ var init_diary_source = __esm({
19839
19873
  async *discover() {
19840
19874
  if (!existsSync37(this.diaryDir))
19841
19875
  return;
19842
- const agents = readdirSync26(this.diaryDir, { withFileTypes: true }).filter((d) => d.isDirectory());
19876
+ const agents = readdirSync27(this.diaryDir, { withFileTypes: true }).filter((d) => d.isDirectory());
19843
19877
  for (const agentDir of agents) {
19844
19878
  const agentPath = join43(this.diaryDir, agentDir.name);
19845
- const files = readdirSync26(agentPath).filter((f) => f.endsWith(".json"));
19879
+ const files = readdirSync27(agentPath).filter((f) => f.endsWith(".json"));
19846
19880
  for (const file of files) {
19847
19881
  const filePath = join43(agentPath, file);
19848
19882
  try {
19849
19883
  const stat3 = statSync35(filePath);
19850
- const raw = readFileSync31(filePath, "utf-8");
19884
+ const raw = readFileSync32(filePath, "utf-8");
19851
19885
  const entry = JSON.parse(raw);
19852
19886
  const entryId = basename21(file, ".json");
19853
19887
  const title = `[${entry.agent}] ${entry.topic}: ${entry.content.slice(0, 80)}`;
@@ -19874,7 +19908,7 @@ var init_diary_source = __esm({
19874
19908
  async parse(item) {
19875
19909
  if (!existsSync37(item.filePath))
19876
19910
  return [];
19877
- const raw = readFileSync31(item.filePath, "utf-8");
19911
+ const raw = readFileSync32(item.filePath, "utf-8");
19878
19912
  const entry = JSON.parse(raw);
19879
19913
  if (!entry.content || entry.content.trim().length < 10)
19880
19914
  return [];
@@ -19933,11 +19967,11 @@ var init_diary_source = __esm({
19933
19967
  const agentDir = join43(dir, agentName.toLowerCase().replace(/[^a-z0-9_-]/g, "_"));
19934
19968
  if (!existsSync37(agentDir))
19935
19969
  return [];
19936
- const files = readdirSync26(agentDir).filter((f) => f.endsWith(".json")).sort().reverse().slice(0, lastN);
19970
+ const files = readdirSync27(agentDir).filter((f) => f.endsWith(".json")).sort().reverse().slice(0, lastN);
19937
19971
  const entries = [];
19938
19972
  for (const file of files) {
19939
19973
  try {
19940
- const raw = readFileSync31(join43(agentDir, file), "utf-8");
19974
+ const raw = readFileSync32(join43(agentDir, file), "utf-8");
19941
19975
  entries.push(JSON.parse(raw));
19942
19976
  } catch {
19943
19977
  continue;
@@ -19982,7 +20016,7 @@ var init_redact_inline = __esm({
19982
20016
  });
19983
20017
 
19984
20018
  // ../engine/dist/parsers/skills-source.js
19985
- import { existsSync as existsSync38, readdirSync as readdirSync27, readFileSync as readFileSync32, statSync as statSync36 } from "fs";
20019
+ import { existsSync as existsSync38, readdirSync as readdirSync28, readFileSync as readFileSync33, statSync as statSync36 } from "fs";
19986
20020
  import { homedir as homedir15 } from "os";
19987
20021
  import { join as join44 } from "path";
19988
20022
  function rebuildBody(content) {
@@ -20080,7 +20114,7 @@ var init_skills_source = __esm({
20080
20114
  async *fromSkillRoot(root, pluginName) {
20081
20115
  let entries;
20082
20116
  try {
20083
- entries = readdirSync27(root.path);
20117
+ entries = readdirSync28(root.path);
20084
20118
  } catch {
20085
20119
  return;
20086
20120
  }
@@ -20104,7 +20138,7 @@ var init_skills_source = __esm({
20104
20138
  }
20105
20139
  let content;
20106
20140
  try {
20107
- content = readFileSync32(skillMd, "utf-8");
20141
+ content = readFileSync33(skillMd, "utf-8");
20108
20142
  } catch {
20109
20143
  continue;
20110
20144
  }
@@ -20117,14 +20151,14 @@ var init_skills_source = __esm({
20117
20151
  }
20118
20152
  const subdirs = {};
20119
20153
  try {
20120
- for (const sub of readdirSync27(skillDir)) {
20154
+ for (const sub of readdirSync28(skillDir)) {
20121
20155
  const subPath = join44(skillDir, sub);
20122
20156
  try {
20123
20157
  const ss = statSync36(subPath);
20124
20158
  if (ss.isDirectory()) {
20125
20159
  let count = 0;
20126
20160
  try {
20127
- count = readdirSync27(subPath).length;
20161
+ count = readdirSync28(subPath).length;
20128
20162
  } catch {
20129
20163
  }
20130
20164
  subdirs[sub] = count;
@@ -20167,7 +20201,7 @@ var init_skills_source = __esm({
20167
20201
  async parse(item) {
20168
20202
  if (!existsSync38(item.filePath))
20169
20203
  return [];
20170
- const content = readFileSync32(item.filePath, "utf-8");
20204
+ const content = readFileSync33(item.filePath, "utf-8");
20171
20205
  if (!content.trim())
20172
20206
  return [];
20173
20207
  return [{
@@ -24152,10 +24186,10 @@ var require_resolve_block_map = __commonJS({
24152
24186
  let offset = bm.offset;
24153
24187
  let commentEnd = null;
24154
24188
  for (const collItem of bm.items) {
24155
- const { start, key: key2, sep: sep4, value } = collItem;
24189
+ const { start, key: key2, sep: sep5, value } = collItem;
24156
24190
  const keyProps = resolveProps.resolveProps(start, {
24157
24191
  indicator: "explicit-key-ind",
24158
- next: key2 ?? sep4?.[0],
24192
+ next: key2 ?? sep5?.[0],
24159
24193
  offset,
24160
24194
  onError,
24161
24195
  parentIndent: bm.indent,
@@ -24169,7 +24203,7 @@ var require_resolve_block_map = __commonJS({
24169
24203
  else if ("indent" in key2 && key2.indent !== bm.indent)
24170
24204
  onError(offset, "BAD_INDENT", startColMsg);
24171
24205
  }
24172
- if (!keyProps.anchor && !keyProps.tag && !sep4) {
24206
+ if (!keyProps.anchor && !keyProps.tag && !sep5) {
24173
24207
  commentEnd = keyProps.end;
24174
24208
  if (keyProps.comment) {
24175
24209
  if (map.comment)
@@ -24193,7 +24227,7 @@ var require_resolve_block_map = __commonJS({
24193
24227
  ctx.atKey = false;
24194
24228
  if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))
24195
24229
  onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique");
24196
- const valueProps = resolveProps.resolveProps(sep4 ?? [], {
24230
+ const valueProps = resolveProps.resolveProps(sep5 ?? [], {
24197
24231
  indicator: "map-value-ind",
24198
24232
  next: value,
24199
24233
  offset: keyNode.range[2],
@@ -24209,7 +24243,7 @@ var require_resolve_block_map = __commonJS({
24209
24243
  if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
24210
24244
  onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
24211
24245
  }
24212
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep4, null, valueProps, onError);
24246
+ const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep5, null, valueProps, onError);
24213
24247
  if (ctx.schema.compat)
24214
24248
  utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);
24215
24249
  offset = valueNode.range[2];
@@ -24300,7 +24334,7 @@ var require_resolve_end = __commonJS({
24300
24334
  let comment = "";
24301
24335
  if (end) {
24302
24336
  let hasSpace = false;
24303
- let sep4 = "";
24337
+ let sep5 = "";
24304
24338
  for (const token of end) {
24305
24339
  const { source, type } = token;
24306
24340
  switch (type) {
@@ -24314,13 +24348,13 @@ var require_resolve_end = __commonJS({
24314
24348
  if (!comment)
24315
24349
  comment = cb;
24316
24350
  else
24317
- comment += sep4 + cb;
24318
- sep4 = "";
24351
+ comment += sep5 + cb;
24352
+ sep5 = "";
24319
24353
  break;
24320
24354
  }
24321
24355
  case "newline":
24322
24356
  if (comment)
24323
- sep4 += source;
24357
+ sep5 += source;
24324
24358
  hasSpace = true;
24325
24359
  break;
24326
24360
  default:
@@ -24363,18 +24397,18 @@ var require_resolve_flow_collection = __commonJS({
24363
24397
  let offset = fc.offset + fc.start.source.length;
24364
24398
  for (let i = 0; i < fc.items.length; ++i) {
24365
24399
  const collItem = fc.items[i];
24366
- const { start, key: key2, sep: sep4, value } = collItem;
24400
+ const { start, key: key2, sep: sep5, value } = collItem;
24367
24401
  const props = resolveProps.resolveProps(start, {
24368
24402
  flow: fcName,
24369
24403
  indicator: "explicit-key-ind",
24370
- next: key2 ?? sep4?.[0],
24404
+ next: key2 ?? sep5?.[0],
24371
24405
  offset,
24372
24406
  onError,
24373
24407
  parentIndent: fc.indent,
24374
24408
  startOnNewline: false
24375
24409
  });
24376
24410
  if (!props.found) {
24377
- if (!props.anchor && !props.tag && !sep4 && !value) {
24411
+ if (!props.anchor && !props.tag && !sep5 && !value) {
24378
24412
  if (i === 0 && props.comma)
24379
24413
  onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`);
24380
24414
  else if (i < fc.items.length - 1)
@@ -24428,8 +24462,8 @@ var require_resolve_flow_collection = __commonJS({
24428
24462
  }
24429
24463
  }
24430
24464
  }
24431
- if (!isMap2 && !sep4 && !props.found) {
24432
- const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep4, null, props, onError);
24465
+ if (!isMap2 && !sep5 && !props.found) {
24466
+ const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep5, null, props, onError);
24433
24467
  coll.items.push(valueNode);
24434
24468
  offset = valueNode.range[2];
24435
24469
  if (isBlock(value))
@@ -24441,7 +24475,7 @@ var require_resolve_flow_collection = __commonJS({
24441
24475
  if (isBlock(key2))
24442
24476
  onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
24443
24477
  ctx.atKey = false;
24444
- const valueProps = resolveProps.resolveProps(sep4 ?? [], {
24478
+ const valueProps = resolveProps.resolveProps(sep5 ?? [], {
24445
24479
  flow: fcName,
24446
24480
  indicator: "map-value-ind",
24447
24481
  next: value,
@@ -24452,8 +24486,8 @@ var require_resolve_flow_collection = __commonJS({
24452
24486
  });
24453
24487
  if (valueProps.found) {
24454
24488
  if (!isMap2 && !props.found && ctx.options.strict) {
24455
- if (sep4)
24456
- for (const st of sep4) {
24489
+ if (sep5)
24490
+ for (const st of sep5) {
24457
24491
  if (st === valueProps.found)
24458
24492
  break;
24459
24493
  if (st.type === "newline") {
@@ -24470,7 +24504,7 @@ var require_resolve_flow_collection = __commonJS({
24470
24504
  else
24471
24505
  onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
24472
24506
  }
24473
- const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep4, null, valueProps, onError) : null;
24507
+ const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep5, null, valueProps, onError) : null;
24474
24508
  if (valueNode) {
24475
24509
  if (isBlock(value))
24476
24510
  onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
@@ -24650,7 +24684,7 @@ var require_resolve_block_scalar = __commonJS({
24650
24684
  chompStart = i + 1;
24651
24685
  }
24652
24686
  let value = "";
24653
- let sep4 = "";
24687
+ let sep5 = "";
24654
24688
  let prevMoreIndented = false;
24655
24689
  for (let i = 0; i < contentStart; ++i)
24656
24690
  value += lines[i][0].slice(trimIndent) + "\n";
@@ -24667,24 +24701,24 @@ var require_resolve_block_scalar = __commonJS({
24667
24701
  indent2 = "";
24668
24702
  }
24669
24703
  if (type === Scalar.Scalar.BLOCK_LITERAL) {
24670
- value += sep4 + indent2.slice(trimIndent) + content;
24671
- sep4 = "\n";
24704
+ value += sep5 + indent2.slice(trimIndent) + content;
24705
+ sep5 = "\n";
24672
24706
  } else if (indent2.length > trimIndent || content[0] === " ") {
24673
- if (sep4 === " ")
24674
- sep4 = "\n";
24675
- else if (!prevMoreIndented && sep4 === "\n")
24676
- sep4 = "\n\n";
24677
- value += sep4 + indent2.slice(trimIndent) + content;
24678
- sep4 = "\n";
24707
+ if (sep5 === " ")
24708
+ sep5 = "\n";
24709
+ else if (!prevMoreIndented && sep5 === "\n")
24710
+ sep5 = "\n\n";
24711
+ value += sep5 + indent2.slice(trimIndent) + content;
24712
+ sep5 = "\n";
24679
24713
  prevMoreIndented = true;
24680
24714
  } else if (content === "") {
24681
- if (sep4 === "\n")
24715
+ if (sep5 === "\n")
24682
24716
  value += "\n";
24683
24717
  else
24684
- sep4 = "\n";
24718
+ sep5 = "\n";
24685
24719
  } else {
24686
- value += sep4 + content;
24687
- sep4 = " ";
24720
+ value += sep5 + content;
24721
+ sep5 = " ";
24688
24722
  prevMoreIndented = false;
24689
24723
  }
24690
24724
  }
@@ -24867,25 +24901,25 @@ var require_resolve_flow_scalar = __commonJS({
24867
24901
  trimBoth = /^[ \t]+|[ \t]+$/g;
24868
24902
  }
24869
24903
  let res = match[1].replace(trimEnd, "");
24870
- let sep4 = " ";
24904
+ let sep5 = " ";
24871
24905
  let pos = line.lastIndex;
24872
24906
  while (match = line.exec(source)) {
24873
24907
  const lm = match[1].replace(trimBoth, "");
24874
24908
  if (lm === "") {
24875
- if (sep4 === "\n")
24876
- res += sep4;
24909
+ if (sep5 === "\n")
24910
+ res += sep5;
24877
24911
  else
24878
- sep4 = "\n";
24912
+ sep5 = "\n";
24879
24913
  } else {
24880
- res += sep4 + lm;
24881
- sep4 = " ";
24914
+ res += sep5 + lm;
24915
+ sep5 = " ";
24882
24916
  }
24883
24917
  pos = line.lastIndex;
24884
24918
  }
24885
24919
  const last = /[ \t]*(.*)/sy;
24886
24920
  last.lastIndex = pos;
24887
24921
  match = last.exec(source);
24888
- return res + sep4 + (match?.[1] ?? "");
24922
+ return res + sep5 + (match?.[1] ?? "");
24889
24923
  }
24890
24924
  function doubleQuotedValue(source, onError) {
24891
24925
  let res = "";
@@ -25695,14 +25729,14 @@ var require_cst_stringify = __commonJS({
25695
25729
  }
25696
25730
  }
25697
25731
  }
25698
- function stringifyItem({ start, key: key2, sep: sep4, value }) {
25732
+ function stringifyItem({ start, key: key2, sep: sep5, value }) {
25699
25733
  let res = "";
25700
25734
  for (const st of start)
25701
25735
  res += st.source;
25702
25736
  if (key2)
25703
25737
  res += stringifyToken(key2);
25704
- if (sep4)
25705
- for (const st of sep4)
25738
+ if (sep5)
25739
+ for (const st of sep5)
25706
25740
  res += st.source;
25707
25741
  if (value)
25708
25742
  res += stringifyToken(value);
@@ -26593,7 +26627,7 @@ var require_parser = __commonJS({
26593
26627
  }
26594
26628
  }
26595
26629
  }
26596
- var Parser = class {
26630
+ var Parser2 = class {
26597
26631
  /**
26598
26632
  * @param onNewLine - If defined, called separately with the start position of
26599
26633
  * each new line (in `parse()`, including the start of input).
@@ -26869,18 +26903,18 @@ var require_parser = __commonJS({
26869
26903
  if (this.type === "map-value-ind") {
26870
26904
  const prev = getPrevProps(this.peek(2));
26871
26905
  const start = getFirstKeyStartProps(prev);
26872
- let sep4;
26906
+ let sep5;
26873
26907
  if (scalar.end) {
26874
- sep4 = scalar.end;
26875
- sep4.push(this.sourceToken);
26908
+ sep5 = scalar.end;
26909
+ sep5.push(this.sourceToken);
26876
26910
  delete scalar.end;
26877
26911
  } else
26878
- sep4 = [this.sourceToken];
26912
+ sep5 = [this.sourceToken];
26879
26913
  const map = {
26880
26914
  type: "block-map",
26881
26915
  offset: scalar.offset,
26882
26916
  indent: scalar.indent,
26883
- items: [{ start, key: scalar, sep: sep4 }]
26917
+ items: [{ start, key: scalar, sep: sep5 }]
26884
26918
  };
26885
26919
  this.onKeyLine = true;
26886
26920
  this.stack[this.stack.length - 1] = map;
@@ -27033,15 +27067,15 @@ var require_parser = __commonJS({
27033
27067
  } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) {
27034
27068
  const start2 = getFirstKeyStartProps(it.start);
27035
27069
  const key2 = it.key;
27036
- const sep4 = it.sep;
27037
- sep4.push(this.sourceToken);
27070
+ const sep5 = it.sep;
27071
+ sep5.push(this.sourceToken);
27038
27072
  delete it.key;
27039
27073
  delete it.sep;
27040
27074
  this.stack.push({
27041
27075
  type: "block-map",
27042
27076
  offset: this.offset,
27043
27077
  indent: this.indent,
27044
- items: [{ start: start2, key: key2, sep: sep4 }]
27078
+ items: [{ start: start2, key: key2, sep: sep5 }]
27045
27079
  });
27046
27080
  } else if (start.length > 0) {
27047
27081
  it.sep = it.sep.concat(start, this.sourceToken);
@@ -27235,13 +27269,13 @@ var require_parser = __commonJS({
27235
27269
  const prev = getPrevProps(parent);
27236
27270
  const start = getFirstKeyStartProps(prev);
27237
27271
  fixFlowSeqItems(fc);
27238
- const sep4 = fc.end.splice(1, fc.end.length);
27239
- sep4.push(this.sourceToken);
27272
+ const sep5 = fc.end.splice(1, fc.end.length);
27273
+ sep5.push(this.sourceToken);
27240
27274
  const map = {
27241
27275
  type: "block-map",
27242
27276
  offset: fc.offset,
27243
27277
  indent: fc.indent,
27244
- items: [{ start, key: fc, sep: sep4 }]
27278
+ items: [{ start, key: fc, sep: sep5 }]
27245
27279
  };
27246
27280
  this.onKeyLine = true;
27247
27281
  this.stack[this.stack.length - 1] = map;
@@ -27366,7 +27400,7 @@ var require_parser = __commonJS({
27366
27400
  }
27367
27401
  }
27368
27402
  };
27369
- exports.Parser = Parser;
27403
+ exports.Parser = Parser2;
27370
27404
  }
27371
27405
  });
27372
27406
 
@@ -27520,7 +27554,7 @@ var require_dist = __commonJS({
27520
27554
  });
27521
27555
 
27522
27556
  // ../engine/dist/core/hermes-config.js
27523
- import { existsSync as existsSync39, readFileSync as readFileSync33 } from "fs";
27557
+ import { existsSync as existsSync39, readFileSync as readFileSync34 } from "fs";
27524
27558
  import { join as join45 } from "path";
27525
27559
  function hermesConfigPath() {
27526
27560
  return join45(hermesHomeDir(), "config.yaml");
@@ -27529,7 +27563,7 @@ function readHermesMcpServers(path2 = hermesConfigPath()) {
27529
27563
  if (!existsSync39(path2))
27530
27564
  return null;
27531
27565
  try {
27532
- const cfg = (0, import_yaml.parse)(readFileSync33(path2, "utf-8"));
27566
+ const cfg = (0, import_yaml.parse)(readFileSync34(path2, "utf-8"));
27533
27567
  return cfg?.mcp_servers && typeof cfg.mcp_servers === "object" ? cfg.mcp_servers : null;
27534
27568
  } catch {
27535
27569
  return null;
@@ -27545,14 +27579,14 @@ var init_hermes_config = __esm({
27545
27579
  });
27546
27580
 
27547
27581
  // ../engine/dist/parsers/mcps-source.js
27548
- import { existsSync as existsSync40, readFileSync as readFileSync34, statSync as statSync37 } from "fs";
27582
+ import { existsSync as existsSync40, readFileSync as readFileSync35, statSync as statSync37 } from "fs";
27549
27583
  import { homedir as homedir16 } from "os";
27550
27584
  import { join as join46 } from "path";
27551
27585
  function readJson(path2) {
27552
27586
  if (!existsSync40(path2))
27553
27587
  return null;
27554
27588
  try {
27555
- const raw = readFileSync34(path2, "utf-8");
27589
+ const raw = readFileSync35(path2, "utf-8");
27556
27590
  const stripped = path2.endsWith(".jsonc") ? raw.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/,(\s*[}\]])/g, "$1") : raw;
27557
27591
  return JSON.parse(stripped);
27558
27592
  } catch {
@@ -27729,7 +27763,7 @@ var init_mcps_source = __esm({
27729
27763
  return;
27730
27764
  let content;
27731
27765
  try {
27732
- content = readFileSync34(path2, "utf-8");
27766
+ content = readFileSync35(path2, "utf-8");
27733
27767
  } catch {
27734
27768
  return;
27735
27769
  }
@@ -27881,7 +27915,7 @@ var init_toolkit_format = __esm({
27881
27915
  });
27882
27916
 
27883
27917
  // ../engine/dist/parsers/slash-commands-source.js
27884
- import { existsSync as existsSync41, readdirSync as readdirSync28, readFileSync as readFileSync35, statSync as statSync38 } from "fs";
27918
+ import { existsSync as existsSync41, readdirSync as readdirSync29, readFileSync as readFileSync36, statSync as statSync38 } from "fs";
27885
27919
  import { join as join47, basename as basename22 } from "path";
27886
27920
  function rebuildBody2(content) {
27887
27921
  const { text, redacted } = redactInlineSecrets(content);
@@ -27937,7 +27971,7 @@ var init_slash_commands_source = __esm({
27937
27971
  const projectsRoot = claudeBackend.projectsDir();
27938
27972
  if (existsSync41(projectsRoot)) {
27939
27973
  try {
27940
- for (const entry of readdirSync28(projectsRoot, { withFileTypes: true })) {
27974
+ for (const entry of readdirSync29(projectsRoot, { withFileTypes: true })) {
27941
27975
  if (!entry.isDirectory() || entry.name.startsWith("."))
27942
27976
  continue;
27943
27977
  const projectPath = resolveProjectDirName(entry.name);
@@ -27972,7 +28006,7 @@ var init_slash_commands_source = __esm({
27972
28006
  const ext = root.format === "toml" ? ".toml" : ".md";
27973
28007
  let files;
27974
28008
  try {
27975
- files = readdirSync28(root.path).filter((f) => f.endsWith(ext));
28009
+ files = readdirSync29(root.path).filter((f) => f.endsWith(ext));
27976
28010
  } catch {
27977
28011
  continue;
27978
28012
  }
@@ -27980,7 +28014,7 @@ var init_slash_commands_source = __esm({
27980
28014
  const filePath = join47(root.path, file);
27981
28015
  try {
27982
28016
  const stat3 = statSync38(filePath);
27983
- const content = readFileSync35(filePath, "utf-8");
28017
+ const content = readFileSync36(filePath, "utf-8");
27984
28018
  const parsed = parseCommand(content, basename22(file, ext), root.format);
27985
28019
  yield {
27986
28020
  id: `${root.tool}_cmd_${root.scope}_${parsed.name}`,
@@ -28009,7 +28043,7 @@ var init_slash_commands_source = __esm({
28009
28043
  async parse(item) {
28010
28044
  if (!existsSync41(item.filePath))
28011
28045
  return [];
28012
- const content = readFileSync35(item.filePath, "utf-8");
28046
+ const content = readFileSync36(item.filePath, "utf-8");
28013
28047
  if (!content.trim())
28014
28048
  return [];
28015
28049
  return [{
@@ -28032,7 +28066,7 @@ var init_slash_commands_source = __esm({
28032
28066
  });
28033
28067
 
28034
28068
  // ../engine/dist/parsers/subagents-source.js
28035
- import { existsSync as existsSync42, readdirSync as readdirSync29, readFileSync as readFileSync36, statSync as statSync39 } from "fs";
28069
+ import { existsSync as existsSync42, readdirSync as readdirSync30, readFileSync as readFileSync37, statSync as statSync39 } from "fs";
28036
28070
  import { join as join48, basename as basename23 } from "path";
28037
28071
  function rebuildBody3(content) {
28038
28072
  const { text, redacted } = redactInlineSecrets(content);
@@ -28089,7 +28123,7 @@ var init_subagents_source = __esm({
28089
28123
  const projectsRoot = claudeBackend.projectsDir();
28090
28124
  if (existsSync42(projectsRoot)) {
28091
28125
  try {
28092
- for (const entry of readdirSync29(projectsRoot, { withFileTypes: true })) {
28126
+ for (const entry of readdirSync30(projectsRoot, { withFileTypes: true })) {
28093
28127
  if (!entry.isDirectory() || entry.name.startsWith("."))
28094
28128
  continue;
28095
28129
  const projectPath = resolveProjectDirName(entry.name);
@@ -28121,7 +28155,7 @@ var init_subagents_source = __esm({
28121
28155
  const ext = root.format === "toml" ? ".toml" : ".md";
28122
28156
  let files;
28123
28157
  try {
28124
- files = readdirSync29(root.path).filter((f) => f.endsWith(ext));
28158
+ files = readdirSync30(root.path).filter((f) => f.endsWith(ext));
28125
28159
  } catch {
28126
28160
  continue;
28127
28161
  }
@@ -28129,7 +28163,7 @@ var init_subagents_source = __esm({
28129
28163
  const filePath = join48(root.path, file);
28130
28164
  try {
28131
28165
  const stat3 = statSync39(filePath);
28132
- const content = readFileSync36(filePath, "utf-8");
28166
+ const content = readFileSync37(filePath, "utf-8");
28133
28167
  const parsed = parseAgent(content, basename23(file, ext), root.format);
28134
28168
  yield {
28135
28169
  id: `${root.tool}_agent_${root.scope}_${parsed.name}`,
@@ -28159,7 +28193,7 @@ var init_subagents_source = __esm({
28159
28193
  async parse(item) {
28160
28194
  if (!existsSync42(item.filePath))
28161
28195
  return [];
28162
- const content = readFileSync36(item.filePath, "utf-8");
28196
+ const content = readFileSync37(item.filePath, "utf-8");
28163
28197
  if (!content.trim())
28164
28198
  return [];
28165
28199
  return [{
@@ -28182,13 +28216,13 @@ var init_subagents_source = __esm({
28182
28216
  });
28183
28217
 
28184
28218
  // ../engine/dist/parsers/hooks-source.js
28185
- import { existsSync as existsSync43, readFileSync as readFileSync37, readdirSync as readdirSync30, statSync as statSync40 } from "fs";
28219
+ import { existsSync as existsSync43, readFileSync as readFileSync38, readdirSync as readdirSync31, statSync as statSync40 } from "fs";
28186
28220
  import { join as join49 } from "path";
28187
28221
  function readJson2(path2) {
28188
28222
  if (!existsSync43(path2))
28189
28223
  return null;
28190
28224
  try {
28191
- return JSON.parse(readFileSync37(path2, "utf-8"));
28225
+ return JSON.parse(readFileSync38(path2, "utf-8"));
28192
28226
  } catch {
28193
28227
  return null;
28194
28228
  }
@@ -28209,7 +28243,7 @@ var init_hooks_source = __esm({
28209
28243
  const projectsRoot = claudeBackend.projectsDir();
28210
28244
  if (existsSync43(projectsRoot)) {
28211
28245
  try {
28212
- for (const entry of readdirSync30(projectsRoot, { withFileTypes: true })) {
28246
+ for (const entry of readdirSync31(projectsRoot, { withFileTypes: true })) {
28213
28247
  if (!entry.isDirectory() || entry.name.startsWith("."))
28214
28248
  continue;
28215
28249
  const projectPath = resolveProjectDirName(entry.name);
@@ -28305,14 +28339,14 @@ var init_hooks_source = __esm({
28305
28339
  });
28306
28340
 
28307
28341
  // ../engine/dist/parsers/plugins-source.js
28308
- import { existsSync as existsSync44, readFileSync as readFileSync38, readdirSync as readdirSync31, statSync as statSync41 } from "fs";
28342
+ import { existsSync as existsSync44, readFileSync as readFileSync39, readdirSync as readdirSync32, statSync as statSync41 } from "fs";
28309
28343
  import { homedir as homedir17 } from "os";
28310
28344
  import { join as join50 } from "path";
28311
28345
  function readJson3(path2) {
28312
28346
  if (!existsSync44(path2))
28313
28347
  return null;
28314
28348
  try {
28315
- return JSON.parse(readFileSync38(path2, "utf-8"));
28349
+ return JSON.parse(readFileSync39(path2, "utf-8"));
28316
28350
  } catch {
28317
28351
  return null;
28318
28352
  }
@@ -28367,7 +28401,7 @@ var init_plugins_source = __esm({
28367
28401
  if (isSourceEnabled("agy", "extensions") && existsSync44(gemRoot)) {
28368
28402
  let entries;
28369
28403
  try {
28370
- entries = readdirSync31(gemRoot);
28404
+ entries = readdirSync32(gemRoot);
28371
28405
  } catch {
28372
28406
  entries = [];
28373
28407
  }
@@ -28577,7 +28611,7 @@ var init_extractor_version = __esm({
28577
28611
  });
28578
28612
 
28579
28613
  // src/sync-ledger.ts
28580
- import { readFileSync as readFileSync39, writeFileSync as writeFileSync7, renameSync as renameSync5, mkdirSync as mkdirSync10, statSync as statSync42 } from "node:fs";
28614
+ import { readFileSync as readFileSync40, writeFileSync as writeFileSync7, renameSync as renameSync5, mkdirSync as mkdirSync10, statSync as statSync42 } from "node:fs";
28581
28615
  import { join as join51, dirname as dirname17 } from "node:path";
28582
28616
  function toRow(entry) {
28583
28617
  if (entry === void 0) return void 0;
@@ -28593,7 +28627,7 @@ function stampOf(path2) {
28593
28627
  }
28594
28628
  function readDisk(path2) {
28595
28629
  try {
28596
- const parsed = JSON.parse(readFileSync39(path2, "utf-8"));
28630
+ const parsed = JSON.parse(readFileSync40(path2, "utf-8"));
28597
28631
  return parsed && typeof parsed === "object" ? parsed : {};
28598
28632
  } catch {
28599
28633
  return {};
@@ -28694,7 +28728,7 @@ function pruneLedgerTargets(configuredServers) {
28694
28728
  try {
28695
28729
  let prior = {};
28696
28730
  try {
28697
- prior = JSON.parse(readFileSync39(side, "utf-8"));
28731
+ prior = JSON.parse(readFileSync40(side, "utf-8"));
28698
28732
  } catch {
28699
28733
  }
28700
28734
  writeFileSync7(side, JSON.stringify({ ...prior, ...orphans }));
@@ -28718,7 +28752,7 @@ function flushLedger() {
28718
28752
  function loadItemVersionsAll() {
28719
28753
  if (itemVersionsCache) return itemVersionsCache;
28720
28754
  try {
28721
- const parsed = JSON.parse(readFileSync39(itemVersionsPath(), "utf-8"));
28755
+ const parsed = JSON.parse(readFileSync40(itemVersionsPath(), "utf-8"));
28722
28756
  itemVersionsCache = parsed && typeof parsed === "object" ? parsed : {};
28723
28757
  } catch {
28724
28758
  itemVersionsCache = {};
@@ -28739,7 +28773,7 @@ function saveItemVersions(server, versions) {
28739
28773
  }
28740
28774
  function loadInventoryHashes(server) {
28741
28775
  try {
28742
- const parsed = JSON.parse(readFileSync39(inventoryPath(), "utf-8"));
28776
+ const parsed = JSON.parse(readFileSync40(inventoryPath(), "utf-8"));
28743
28777
  return { ...(parsed && typeof parsed === "object" ? parsed[server] : null) || {} };
28744
28778
  } catch {
28745
28779
  return {};
@@ -28748,7 +28782,7 @@ function loadInventoryHashes(server) {
28748
28782
  function saveInventoryHashes(server, hashes) {
28749
28783
  let all = {};
28750
28784
  try {
28751
- all = JSON.parse(readFileSync39(inventoryPath(), "utf-8"));
28785
+ all = JSON.parse(readFileSync40(inventoryPath(), "utf-8"));
28752
28786
  } catch {
28753
28787
  }
28754
28788
  if (!all || typeof all !== "object") all = {};
@@ -28830,7 +28864,7 @@ function markFieldCoverage(server, field, rows) {
28830
28864
  function loadReconcile() {
28831
28865
  if (reconcileCache) return reconcileCache;
28832
28866
  try {
28833
- const parsed = JSON.parse(readFileSync39(reconcilePath(), "utf-8"));
28867
+ const parsed = JSON.parse(readFileSync40(reconcilePath(), "utf-8"));
28834
28868
  reconcileCache = parsed && typeof parsed === "object" ? parsed : {};
28835
28869
  } catch {
28836
28870
  reconcileCache = {};
@@ -28943,7 +28977,7 @@ var init_sync_fields = __esm({
28943
28977
  });
28944
28978
 
28945
28979
  // ../engine/dist/core/index-lock.js
28946
- import { existsSync as existsSync45, mkdirSync as mkdirSync11, openSync as openSync10, writeFileSync as writeFileSync8, readFileSync as readFileSync40, rmSync as rmSync4, statSync as statSync43, closeSync as closeSync10 } from "fs";
28980
+ import { existsSync as existsSync45, mkdirSync as mkdirSync11, openSync as openSync10, writeFileSync as writeFileSync8, readFileSync as readFileSync41, rmSync as rmSync4, statSync as statSync43, closeSync as closeSync10 } from "fs";
28947
28981
  import { dirname as dirname18, join as join52 } from "path";
28948
28982
  function acquireIndexLock(opts) {
28949
28983
  const lockPath = lockFilePath(opts.file);
@@ -28975,7 +29009,7 @@ function acquireIndexLock(opts) {
28975
29009
  return;
28976
29010
  released = true;
28977
29011
  try {
28978
- const current = JSON.parse(readFileSync40(lockPath, "utf-8"));
29012
+ const current = JSON.parse(readFileSync41(lockPath, "utf-8"));
28979
29013
  if (current.pid !== holder.pid || current.startedAt !== holder.startedAt)
28980
29014
  return;
28981
29015
  } catch {
@@ -28997,7 +29031,7 @@ function stealStaleLock(lockPath, staleAfterMs) {
28997
29031
  const age = Date.now() - s.mtimeMs;
28998
29032
  let payload;
28999
29033
  try {
29000
- payload = JSON.parse(readFileSync40(lockPath, "utf-8"));
29034
+ payload = JSON.parse(readFileSync41(lockPath, "utf-8"));
29001
29035
  } catch {
29002
29036
  rmSync4(lockPath, { force: true });
29003
29037
  return true;
@@ -29035,7 +29069,7 @@ var init_index_lock = __esm({
29035
29069
  });
29036
29070
 
29037
29071
  // src/http.ts
29038
- import { readFileSync as readFileSync41 } from "node:fs";
29072
+ import { readFileSync as readFileSync42 } from "node:fs";
29039
29073
  function cliVersion() {
29040
29074
  return CLI_VERSION;
29041
29075
  }
@@ -29046,9 +29080,9 @@ function clientHeaders() {
29046
29080
  };
29047
29081
  }
29048
29082
  function fetchWithTimeout(url, init = {}, ms = 15e3) {
29049
- const headers = new Headers(clientHeaders());
29050
- new Headers(init.headers ?? {}).forEach((v, k) => headers.set(k, v));
29051
- return fetch(url, { ...init, headers, signal: init.signal ?? AbortSignal.timeout(ms) });
29083
+ const headers2 = new Headers(clientHeaders());
29084
+ new Headers(init.headers ?? {}).forEach((v, k) => headers2.set(k, v));
29085
+ return fetch(url, { ...init, headers: headers2, signal: init.signal ?? AbortSignal.timeout(ms) });
29052
29086
  }
29053
29087
  var CLI_VERSION;
29054
29088
  var init_http = __esm({
@@ -29056,10 +29090,10 @@ var init_http = __esm({
29056
29090
  "use strict";
29057
29091
  CLI_VERSION = "0.0.0";
29058
29092
  try {
29059
- CLI_VERSION = JSON.parse(readFileSync41(new URL("../package.json", import.meta.url), "utf-8")).version || CLI_VERSION;
29093
+ CLI_VERSION = JSON.parse(readFileSync42(new URL("../package.json", import.meta.url), "utf-8")).version || CLI_VERSION;
29060
29094
  } catch {
29061
29095
  try {
29062
- if (true) CLI_VERSION = "0.7.26";
29096
+ if (true) CLI_VERSION = "0.7.30";
29063
29097
  } catch {
29064
29098
  }
29065
29099
  }
@@ -29557,7 +29591,7 @@ var init_telemetry = __esm({
29557
29591
  init_sync_client();
29558
29592
  cliVersion2 = () => {
29559
29593
  try {
29560
- return true ? "0.7.26" : "dev";
29594
+ return true ? "0.7.30" : "dev";
29561
29595
  } catch {
29562
29596
  return "dev";
29563
29597
  }
@@ -29574,7 +29608,7 @@ import { join as join53 } from "node:path";
29574
29608
  import { randomBytes } from "node:crypto";
29575
29609
  import { createGzip as createGzip2 } from "node:zlib";
29576
29610
  import { once } from "node:events";
29577
- import { readFileSync as readFileSync42 } from "node:fs";
29611
+ import { readFileSync as readFileSync43 } from "node:fs";
29578
29612
  async function* fileLines(path2) {
29579
29613
  let rest = "";
29580
29614
  const decoder = new TextDecoder("utf-8");
@@ -29614,7 +29648,7 @@ async function writeArchiveFile(source, meta, redact, dir = tmpdir3()) {
29614
29648
  await write(`{"v":1,"tool":${JSON.stringify(meta.tool)},"mtime":${Math.floor(meta.mtime)},"files":[`);
29615
29649
  for (const [i, f] of source.files.entries()) {
29616
29650
  await write(`${i ? "," : ""}{"name":${JSON.stringify(f.name)},"text":"`);
29617
- const whole = () => source.kind === "memory" ? f.text : readFileSync42(f.path, "utf-8");
29651
+ const whole = () => source.kind === "memory" ? f.text : readFileSync43(f.path, "utf-8");
29618
29652
  if (!f.name.endsWith(".jsonl")) {
29619
29653
  await write(escapeJson(redact(whole())));
29620
29654
  } else {
@@ -29658,10 +29692,10 @@ async function putPart(url, body2) {
29658
29692
  throw last instanceof Error ? last : new Error(String(last));
29659
29693
  }
29660
29694
  async function uploadArchiveFile(base2, token, args) {
29661
- const headers = { "content-type": "application/json" };
29662
- if (token) headers.authorization = `Bearer ${token}`;
29695
+ const headers2 = { "content-type": "application/json" };
29696
+ if (token) headers2.authorization = `Bearer ${token}`;
29663
29697
  const post = async (path2, body2) => {
29664
- const r = await fetch(`${base2}/api/sync/raw-upload/${path2}`, { method: "POST", headers, body: JSON.stringify(body2) });
29698
+ const r = await fetch(`${base2}/api/sync/raw-upload/${path2}`, { method: "POST", headers: headers2, body: JSON.stringify(body2) });
29665
29699
  const json = await r.json().catch(() => ({}));
29666
29700
  return { status: r.status, json };
29667
29701
  };
@@ -29872,9 +29906,9 @@ __export(auto_update_exports, {
29872
29906
  tarballUrl: () => tarballUrl
29873
29907
  });
29874
29908
  import { execSync as execSync4, execFileSync as execFileSync3 } from "node:child_process";
29875
- import { readFileSync as readFileSync43, existsSync as existsSync47 } from "node:fs";
29909
+ import { readFileSync as readFileSync44, existsSync as existsSync47 } from "node:fs";
29876
29910
  import { fileURLToPath as fileURLToPath2 } from "node:url";
29877
- import { writeFileSync as writeFileSync9, mkdtempSync as mkdtempSync3, rmSync as rmSync6, readdirSync as readdirSync32, statSync as statSync45, mkdirSync as mkdirSync12 } from "node:fs";
29911
+ import { writeFileSync as writeFileSync9, mkdtempSync as mkdtempSync3, rmSync as rmSync6, readdirSync as readdirSync33, statSync as statSync45, mkdirSync as mkdirSync12 } from "node:fs";
29878
29912
  import { join as join54, dirname as dirname19, sep as sep3, posix as pathPosix, win32 as pathWin32 } from "node:path";
29879
29913
  import { tmpdir as tmpdir4, homedir as homedir18 } from "node:os";
29880
29914
  import { createHash as createHash11 } from "node:crypto";
@@ -29900,7 +29934,7 @@ function newerOf(a, b) {
29900
29934
  function installedVersion() {
29901
29935
  try {
29902
29936
  const here = dirname19(fileURLToPath2(import.meta.url));
29903
- const raw = readFileSync43(join54(here, "..", "package.json"), "utf-8");
29937
+ const raw = readFileSync44(join54(here, "..", "package.json"), "utf-8");
29904
29938
  return JSON.parse(raw).version || null;
29905
29939
  } catch {
29906
29940
  return null;
@@ -29919,7 +29953,7 @@ function sweepStaleStaging(root = tmpdir4(), now = Date.now()) {
29919
29953
  let removed = 0;
29920
29954
  let entries;
29921
29955
  try {
29922
- entries = readdirSync32(root);
29956
+ entries = readdirSync33(root);
29923
29957
  } catch {
29924
29958
  return 0;
29925
29959
  }
@@ -29929,7 +29963,7 @@ function sweepStaleStaging(root = tmpdir4(), now = Date.now()) {
29929
29963
  try {
29930
29964
  const st = statSync45(dir);
29931
29965
  if (!st.isDirectory() || now - st.mtimeMs < COLD_MS) continue;
29932
- const inside = readdirSync32(dir);
29966
+ const inside = readdirSync33(dir);
29933
29967
  if (inside.length > 1 || inside.length === 1 && inside[0] !== "chat-recall.tgz") continue;
29934
29968
  rmSync6(dir, { recursive: true, force: true });
29935
29969
  removed++;
@@ -30063,7 +30097,7 @@ function updateStatePath() {
30063
30097
  }
30064
30098
  function readUpdateState() {
30065
30099
  try {
30066
- return JSON.parse(readFileSync43(updateStatePath(), "utf8"));
30100
+ return JSON.parse(readFileSync44(updateStatePath(), "utf8"));
30067
30101
  } catch {
30068
30102
  return {};
30069
30103
  }
@@ -30205,7 +30239,7 @@ __export(sync_client_exports, {
30205
30239
  syncSessions: () => syncSessions
30206
30240
  });
30207
30241
  import { join as join55, dirname as dirname20, basename as basename24 } from "node:path";
30208
- import { readFileSync as readFileSync44, writeFileSync as writeFileSync10, mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync4, rmSync as rmSync7, chmodSync as chmodSync6, unlinkSync as unlinkSync3, readdirSync as readdirSync33, statSync as statSync46 } from "node:fs";
30242
+ import { readFileSync as readFileSync45, writeFileSync as writeFileSync10, mkdirSync as mkdirSync13, mkdtempSync as mkdtempSync4, rmSync as rmSync7, chmodSync as chmodSync6, unlinkSync as unlinkSync3, readdirSync as readdirSync34, statSync as statSync46 } from "node:fs";
30209
30243
  import { tmpdir as tmpdir5, hostname as hostname2 } from "node:os";
30210
30244
  import { createHash as createHash12 } from "node:crypto";
30211
30245
  import { fileURLToPath as fileURLToPath3 } from "node:url";
@@ -30260,7 +30294,7 @@ function loadAllCredentials() {
30260
30294
  const fromEnv = envCredentials();
30261
30295
  if (fromEnv) return [{ serverUrl: fromEnv.serverUrl, token: fromEnv.token }];
30262
30296
  try {
30263
- const parsed = JSON.parse(readFileSync44(credPath(), "utf-8"));
30297
+ const parsed = JSON.parse(readFileSync45(credPath(), "utf-8"));
30264
30298
  if (Array.isArray(parsed?.targets)) return parsed.targets.filter((t) => t?.serverUrl).map((t) => ({ serverUrl: t.serverUrl, token: t.token || "" }));
30265
30299
  if (parsed?.serverUrl) return [{ serverUrl: parsed.serverUrl, token: parsed.token || "" }];
30266
30300
  } catch {
@@ -30271,12 +30305,12 @@ async function fetchTenantSecurityConfig(cred) {
30271
30305
  const base2 = cred.serverUrl.replace(/\/+$/, "");
30272
30306
  const cached = _securityConfigCache.get(base2);
30273
30307
  if (cached && Date.now() - cached.fetchedAt < SECURITY_CONFIG_TTL_MS) return cached.config;
30274
- const headers = { "content-type": "application/json" };
30275
- if (cred.token) headers.authorization = `Bearer ${cred.token}`;
30308
+ const headers2 = { "content-type": "application/json" };
30309
+ if (cred.token) headers2.authorization = `Bearer ${cred.token}`;
30276
30310
  try {
30277
30311
  const [rulesRes, settingsRes] = await Promise.all([
30278
- fetchWithTimeout(`${base2}/api/secrets/rules`, { headers }),
30279
- fetchWithTimeout(`${base2}/api/teams/security-config`, { headers }).catch(() => null)
30312
+ fetchWithTimeout(`${base2}/api/secrets/rules`, { headers: headers2 }),
30313
+ fetchWithTimeout(`${base2}/api/teams/security-config`, { headers: headers2 }).catch(() => null)
30280
30314
  ]);
30281
30315
  let tenantRules = [];
30282
30316
  let rulePackVersion = null;
@@ -30326,7 +30360,7 @@ function syncConfigCachePath() {
30326
30360
  }
30327
30361
  function readPersistedSyncConfigs() {
30328
30362
  try {
30329
- return JSON.parse(readFileSync44(syncConfigCachePath(), "utf-8"));
30363
+ return JSON.parse(readFileSync45(syncConfigCachePath(), "utf-8"));
30330
30364
  } catch {
30331
30365
  return {};
30332
30366
  }
@@ -30344,21 +30378,21 @@ async function fetchTenantSyncConfig(cred) {
30344
30378
  const base2 = cred.serverUrl.replace(/\/+$/, "");
30345
30379
  const cached = _syncConfigCache.get(base2);
30346
30380
  if (cached && Date.now() - cached.fetchedAt < SECURITY_CONFIG_TTL_MS) return cached.config;
30347
- const headers = { "content-type": "application/json" };
30348
- if (cred.token) headers.authorization = `Bearer ${cred.token}`;
30381
+ const headers2 = { "content-type": "application/json" };
30382
+ if (cred.token) headers2.authorization = `Bearer ${cred.token}`;
30349
30383
  try {
30350
30384
  try {
30351
30385
  const sources2 = discoverSessionSources();
30352
30386
  if (sources2.length > 0) {
30353
30387
  await fetchWithTimeout(`${base2}/api/sync-config/sources`, {
30354
30388
  method: "POST",
30355
- headers,
30389
+ headers: headers2,
30356
30390
  body: JSON.stringify({ device: deviceLabel(), sources: sources2 })
30357
30391
  }).catch(() => null);
30358
30392
  }
30359
30393
  } catch {
30360
30394
  }
30361
- const res = await fetchWithTimeout(`${base2}/api/sync-config`, { headers });
30395
+ const res = await fetchWithTimeout(`${base2}/api/sync-config`, { headers: headers2 });
30362
30396
  if (res.status === 404) {
30363
30397
  _syncConfigCache.set(base2, { fetchedAt: Date.now(), config: EMPTY_SYNC_CONFIG });
30364
30398
  return EMPTY_SYNC_CONFIG;
@@ -30537,11 +30571,11 @@ async function syncSessions(opts = {}) {
30537
30571
  return { ...agg, perTarget };
30538
30572
  }
30539
30573
  async function postFieldBatch(base2, token, rows) {
30540
- const headers = { "content-type": "application/json" };
30541
- if (token) headers.authorization = `Bearer ${token}`;
30574
+ const headers2 = { "content-type": "application/json" };
30575
+ if (token) headers2.authorization = `Bearer ${token}`;
30542
30576
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
30543
30577
  for (let attempt = 0; ; attempt++) {
30544
- const res = await fetchWithTimeout(`${base2}/api/sync`, { method: "POST", headers, body: JSON.stringify({ fields: rows }) }, 6e4);
30578
+ const res = await fetchWithTimeout(`${base2}/api/sync`, { method: "POST", headers: headers2, body: JSON.stringify({ fields: rows }) }, 6e4);
30545
30579
  if (res.ok) return;
30546
30580
  const retryable = res.status === 429 || res.status >= 500;
30547
30581
  if (!retryable || attempt >= 5) throw new Error(`${base2}: fields batch HTTP ${res.status} ${await res.text().catch(() => "")}`);
@@ -30608,7 +30642,7 @@ function reapStaleScanDirs(dir = tmpdir5(), maxAgeMs = 6 * 36e5, now = Date.now(
30608
30642
  let reaped = 0;
30609
30643
  let names;
30610
30644
  try {
30611
- names = readdirSync33(dir);
30645
+ names = readdirSync34(dir);
30612
30646
  } catch {
30613
30647
  return 0;
30614
30648
  }
@@ -30931,14 +30965,14 @@ async function syncToTargetInScope(cred, opts = {}) {
30931
30965
  const appendResults = { uploaded: 0, fullResyncNeeded: /* @__PURE__ */ new Set() };
30932
30966
  const pendingArchives = [];
30933
30967
  const postAppend = async (convs) => {
30934
- const headers = { "content-type": "application/json" };
30935
- if (cred.token) headers.authorization = `Bearer ${cred.token}`;
30968
+ const headers2 = { "content-type": "application/json" };
30969
+ if (cred.token) headers2.authorization = `Bearer ${cred.token}`;
30936
30970
  const ac = new AbortController();
30937
30971
  const timer = setTimeout(() => ac.abort(new Error(`upload timed out after ${UPLOAD_TIMEOUT_MS}ms`)), UPLOAD_TIMEOUT_MS);
30938
30972
  try {
30939
30973
  const res = await fetch(`${base2}/api/sync`, {
30940
30974
  method: "POST",
30941
- headers,
30975
+ headers: headers2,
30942
30976
  body: JSON.stringify({ conversations: convs }),
30943
30977
  signal: ac.signal
30944
30978
  });
@@ -30981,14 +31015,14 @@ async function syncToTargetInScope(cred, opts = {}) {
30981
31015
  };
30982
31016
  const postChunkedHead = async (head, fileSize) => {
30983
31017
  const conv = { ...head, chunk_head: true };
30984
- const headers = { "content-type": "application/json" };
30985
- if (cred.token) headers.authorization = `Bearer ${cred.token}`;
31018
+ const headers2 = { "content-type": "application/json" };
31019
+ if (cred.token) headers2.authorization = `Bearer ${cred.token}`;
30986
31020
  const ac = new AbortController();
30987
31021
  const timer = setTimeout(() => ac.abort(new Error(`upload timed out after ${UPLOAD_TIMEOUT_MS}ms`)), UPLOAD_TIMEOUT_MS);
30988
31022
  try {
30989
31023
  const res = await fetch(`${base2}/api/sync`, {
30990
31024
  method: "POST",
30991
- headers,
31025
+ headers: headers2,
30992
31026
  body: JSON.stringify({ conversations: [conv] }),
30993
31027
  signal: ac.signal
30994
31028
  });
@@ -31949,10 +31983,10 @@ var init_sync_client = __esm({
31949
31983
  ownVersion = "0.0.0";
31950
31984
  try {
31951
31985
  const dir = dirname20(fileURLToPath3(import.meta.url));
31952
- ownVersion = JSON.parse(readFileSync44(join55(dir, "../package.json"), "utf-8")).version || ownVersion;
31986
+ ownVersion = JSON.parse(readFileSync45(join55(dir, "../package.json"), "utf-8")).version || ownVersion;
31953
31987
  } catch {
31954
31988
  try {
31955
- if (true) ownVersion = "0.7.26";
31989
+ if (true) ownVersion = "0.7.30";
31956
31990
  } catch {
31957
31991
  }
31958
31992
  }
@@ -31993,7 +32027,7 @@ __export(client_events_exports, {
31993
32027
  isTelemetryEnabled: () => isTelemetryEnabled,
31994
32028
  reportClientEvent: () => reportClientEvent2
31995
32029
  });
31996
- import { readFileSync as readFileSync45 } from "node:fs";
32030
+ import { readFileSync as readFileSync46 } from "node:fs";
31997
32031
  function scrub(msg) {
31998
32032
  if (!msg) return "";
31999
32033
  const noHome = msg.replace(/\/(?:home|Users)\/[^/\s]+/g, "~");
@@ -32025,11 +32059,11 @@ function reportClientEvent2(kind, opts = {}) {
32025
32059
  });
32026
32060
  for (const t of targets) {
32027
32061
  if (!t.serverUrl) continue;
32028
- const headers = { "content-type": "application/json" };
32029
- if (t.token) headers.authorization = `Bearer ${t.token}`;
32062
+ const headers2 = { "content-type": "application/json" };
32063
+ if (t.token) headers2.authorization = `Bearer ${t.token}`;
32030
32064
  void fetch(`${t.serverUrl.replace(/\/+$/, "")}/api/client-events`, {
32031
32065
  method: "POST",
32032
- headers,
32066
+ headers: headers2,
32033
32067
  body: body2,
32034
32068
  signal: AbortSignal.timeout(3e3)
32035
32069
  }).catch(() => {
@@ -32046,7 +32080,7 @@ var init_client_events = __esm({
32046
32080
  init_secret_redactor();
32047
32081
  CLI_VERSION2 = "0.0.0";
32048
32082
  try {
32049
- CLI_VERSION2 = JSON.parse(readFileSync45(new URL("../package.json", import.meta.url), "utf-8")).version || CLI_VERSION2;
32083
+ CLI_VERSION2 = JSON.parse(readFileSync46(new URL("../package.json", import.meta.url), "utf-8")).version || CLI_VERSION2;
32050
32084
  } catch {
32051
32085
  }
32052
32086
  }
@@ -32060,7 +32094,7 @@ __export(update_notice_exports, {
32060
32094
  refreshUpdateCheck: () => refreshUpdateCheck,
32061
32095
  updateNotice: () => updateNotice2
32062
32096
  });
32063
- import { readFileSync as readFileSync46, writeFileSync as writeFileSync11 } from "node:fs";
32097
+ import { readFileSync as readFileSync47, writeFileSync as writeFileSync11 } from "node:fs";
32064
32098
  import { join as join56 } from "node:path";
32065
32099
  function newestKnown(c) {
32066
32100
  const npm = c.npmVersion ?? "0.0.0";
@@ -32068,7 +32102,7 @@ function newestKnown(c) {
32068
32102
  }
32069
32103
  function readCheck() {
32070
32104
  try {
32071
- const c = JSON.parse(readFileSync46(checkPath(), "utf-8"));
32105
+ const c = JSON.parse(readFileSync47(checkPath(), "utf-8"));
32072
32106
  return c && typeof c.serverVersion === "string" ? c : null;
32073
32107
  } catch {
32074
32108
  return null;
@@ -32234,15 +32268,15 @@ __export(service_installer_exports, {
32234
32268
  uninstallService: () => uninstallService
32235
32269
  });
32236
32270
  import { execSync as execSync5 } from "child_process";
32237
- import { existsSync as existsSync48, mkdirSync as mkdirSync14, readFileSync as readFileSync47, rmSync as rmSync8, writeFileSync as writeFileSync12 } from "fs";
32271
+ import { existsSync as existsSync48, mkdirSync as mkdirSync15, readFileSync as readFileSync50, rmSync as rmSync8, writeFileSync as writeFileSync13 } from "fs";
32238
32272
  import { homedir as homedir19 } from "os";
32239
- import { join as join57 } from "path";
32273
+ import { join as join58 } from "path";
32240
32274
  import { fileURLToPath as fileURLToPath4 } from "url";
32241
32275
  function resolveDaemonPaths() {
32242
32276
  const watchJs = fileURLToPath4(new URL("./watch.js", import.meta.url));
32243
32277
  const node = process.execPath;
32244
- const dataDir = join57(homedir19(), ".chat-recall");
32245
- const logFile = join57(dataDir, "watch.log");
32278
+ const dataDir = join58(homedir19(), ".chat-recall");
32279
+ const logFile = join58(dataDir, "watch.log");
32246
32280
  return { watchJs, node, logFile, dataDir };
32247
32281
  }
32248
32282
  function tryCmd(cmd) {
@@ -32269,13 +32303,13 @@ function refreshServiceDefinition() {
32269
32303
  if (process.platform !== "linux") return false;
32270
32304
  try {
32271
32305
  const { watchJs, node, logFile } = resolveDaemonPaths();
32272
- const unitPath = join57(homedir19(), ".config", "systemd", "user", "chat-recall-watch.service");
32306
+ const unitPath = join58(homedir19(), ".config", "systemd", "user", "chat-recall-watch.service");
32273
32307
  if (!existsSync48(unitPath)) return false;
32274
- const current = readFileSync47(unitPath, "utf8");
32308
+ const current = readFileSync50(unitPath, "utf8");
32275
32309
  if (!current.includes(watchJs)) return false;
32276
32310
  const wanted = renderSystemdUnit(watchJs, node, logFile);
32277
- if (readFileSync47(unitPath, "utf8") === wanted) return false;
32278
- writeFileSync12(unitPath, wanted);
32311
+ if (readFileSync50(unitPath, "utf8") === wanted) return false;
32312
+ writeFileSync13(unitPath, wanted);
32279
32313
  execSync5("systemctl --user daemon-reload", { stdio: "ignore" });
32280
32314
  return true;
32281
32315
  } catch {
@@ -32284,7 +32318,7 @@ function refreshServiceDefinition() {
32284
32318
  }
32285
32319
  function installService() {
32286
32320
  const { watchJs, node, logFile, dataDir } = resolveDaemonPaths();
32287
- mkdirSync14(dataDir, { recursive: true });
32321
+ mkdirSync15(dataDir, { recursive: true });
32288
32322
  if (process.platform === "linux") {
32289
32323
  return installSystemd(watchJs, node, logFile);
32290
32324
  }
@@ -32300,11 +32334,11 @@ function installService() {
32300
32334
  );
32301
32335
  }
32302
32336
  function installSystemd(watchJs, node, logFile) {
32303
- const unitDir = join57(homedir19(), ".config", "systemd", "user");
32304
- const unitPath = join57(unitDir, "chat-recall-watch.service");
32337
+ const unitDir = join58(homedir19(), ".config", "systemd", "user");
32338
+ const unitPath = join58(unitDir, "chat-recall-watch.service");
32305
32339
  const unit = renderSystemdUnit(watchJs, node, logFile);
32306
- mkdirSync14(unitDir, { recursive: true });
32307
- writeFileSync12(unitPath, unit);
32340
+ mkdirSync15(unitDir, { recursive: true });
32341
+ writeFileSync13(unitPath, unit);
32308
32342
  try {
32309
32343
  execSync5("systemctl --user daemon-reload && systemctl --user enable chat-recall-watch.service && systemctl --user restart chat-recall-watch.service", { stdio: "inherit" });
32310
32344
  try {
@@ -32387,11 +32421,11 @@ function renderSystemdUnit(watchJs, node, logFile) {
32387
32421
  }
32388
32422
  function installLaunchd(watchJs, node, logFile) {
32389
32423
  const label = "com.chat-recall.watch";
32390
- const plistDir = join57(homedir19(), "Library", "LaunchAgents");
32391
- const plistPath = join57(plistDir, `${label}.plist`);
32424
+ const plistDir = join58(homedir19(), "Library", "LaunchAgents");
32425
+ const plistPath = join58(plistDir, `${label}.plist`);
32392
32426
  const plist = renderLaunchdPlist(watchJs, node, logFile, label);
32393
- mkdirSync14(plistDir, { recursive: true });
32394
- writeFileSync12(plistPath, plist);
32427
+ mkdirSync15(plistDir, { recursive: true });
32428
+ writeFileSync13(plistPath, plist);
32395
32429
  try {
32396
32430
  try {
32397
32431
  execSync5(`launchctl unload "${plistPath}"`, { stdio: "ignore" });
@@ -32444,7 +32478,7 @@ function uninstallService() {
32444
32478
  removed = true;
32445
32479
  } catch {
32446
32480
  }
32447
- const unitPath = join57(homedir19(), ".config", "systemd", "user", "chat-recall-watch.service");
32481
+ const unitPath = join58(homedir19(), ".config", "systemd", "user", "chat-recall-watch.service");
32448
32482
  if (existsSync48(unitPath)) {
32449
32483
  rmSync8(unitPath, { force: true });
32450
32484
  removed = true;
@@ -32456,7 +32490,7 @@ function uninstallService() {
32456
32490
  return removed;
32457
32491
  }
32458
32492
  if (process.platform === "darwin") {
32459
- const plistPath = join57(homedir19(), "Library", "LaunchAgents", "com.chat-recall.watch.plist");
32493
+ const plistPath = join58(homedir19(), "Library", "LaunchAgents", "com.chat-recall.watch.plist");
32460
32494
  try {
32461
32495
  execSync5(`launchctl unload "${plistPath}" 2>/dev/null`, { stdio: "ignore" });
32462
32496
  } catch {
@@ -32509,15 +32543,15 @@ __export(install_skills_exports, {
32509
32543
  skillsSourceDir: () => skillsSourceDir,
32510
32544
  uninstallSkills: () => uninstallSkills
32511
32545
  });
32512
- import { readdirSync as readdirSync34, existsSync as existsSync49, mkdirSync as mkdirSync15, rmSync as rmSync9, cpSync, writeFileSync as writeFileSync13, readFileSync as readFileSync48, statSync as statSync47, realpathSync as realpathSync5 } from "fs";
32546
+ import { readdirSync as readdirSync36, existsSync as existsSync49, mkdirSync as mkdirSync16, rmSync as rmSync9, cpSync, writeFileSync as writeFileSync14, readFileSync as readFileSync51, statSync as statSync48, realpathSync as realpathSync5 } from "fs";
32513
32547
  import { createHash as createHash13 } from "crypto";
32514
- import { join as join58, basename as basename25 } from "path";
32548
+ import { join as join59, basename as basename25 } from "path";
32515
32549
  function skillsSourceDir() {
32516
- return join58(import.meta.dirname, "..", "skills");
32550
+ return join59(import.meta.dirname, "..", "skills");
32517
32551
  }
32518
32552
  function version() {
32519
32553
  try {
32520
- return JSON.parse(readFileSync48(new URL("../package.json", import.meta.url), "utf-8")).version || "0.0.0";
32554
+ return JSON.parse(readFileSync51(new URL("../package.json", import.meta.url), "utf-8")).version || "0.0.0";
32521
32555
  } catch {
32522
32556
  return "0.0.0";
32523
32557
  }
@@ -32526,19 +32560,19 @@ function skillsFingerprint() {
32526
32560
  const src = skillsSourceDir();
32527
32561
  const h = createHash13("sha256");
32528
32562
  for (const name of bundledSkillNames()) {
32529
- for (const rel of filesUnder(join58(src, name)).sort()) {
32563
+ for (const rel of filesUnder(join59(src, name)).sort()) {
32530
32564
  h.update(name + "/" + rel);
32531
- h.update(readFileSync48(join58(src, name, rel)));
32565
+ h.update(readFileSync51(join59(src, name, rel)));
32532
32566
  }
32533
32567
  }
32534
32568
  return h.digest("hex").slice(0, 12);
32535
32569
  }
32536
32570
  function filesUnder(dir, prefix = "") {
32537
32571
  const out = [];
32538
- for (const e of readdirSync34(dir, { withFileTypes: true })) {
32572
+ for (const e of readdirSync36(dir, { withFileTypes: true })) {
32539
32573
  if (e.name === MARKER) continue;
32540
32574
  const rel = prefix ? `${prefix}/${e.name}` : e.name;
32541
- if (e.isDirectory()) out.push(...filesUnder(join58(dir, e.name), rel));
32575
+ if (e.isDirectory()) out.push(...filesUnder(join59(dir, e.name), rel));
32542
32576
  else out.push(rel);
32543
32577
  }
32544
32578
  return out;
@@ -32549,7 +32583,7 @@ function skillStamp() {
32549
32583
  function bundledSkillNames() {
32550
32584
  const src = skillsSourceDir();
32551
32585
  if (!existsSync49(src)) return [];
32552
- return readdirSync34(src, { withFileTypes: true }).filter((e) => e.isDirectory() && existsSync49(join58(src, e.name, "SKILL.md"))).map((e) => e.name).sort();
32586
+ return readdirSync36(src, { withFileTypes: true }).filter((e) => e.isDirectory() && existsSync49(join59(src, e.name, "SKILL.md"))).map((e) => e.name).sort();
32553
32587
  }
32554
32588
  function realPathOrSelf(p) {
32555
32589
  try {
@@ -32562,7 +32596,7 @@ function claudeSkillTargets() {
32562
32596
  const targets = [];
32563
32597
  const seen = /* @__PURE__ */ new Set();
32564
32598
  for (const home of claudeHomeDirs()) {
32565
- const dir = join58(home, "skills");
32599
+ const dir = join59(home, "skills");
32566
32600
  const key2 = realPathOrSelf(dir);
32567
32601
  if (seen.has(key2)) continue;
32568
32602
  seen.add(key2);
@@ -32573,7 +32607,7 @@ function claudeSkillTargets() {
32573
32607
  dir,
32574
32608
  // Judge each profile on ITS OWN transcripts, not the primary's: a home
32575
32609
  // with no projects/ is a directory someone made, not a Claude install.
32576
- available: existsSync49(join58(home, "projects"))
32610
+ available: existsSync49(join59(home, "projects"))
32577
32611
  });
32578
32612
  }
32579
32613
  if (targets.length === 0) {
@@ -32588,17 +32622,17 @@ function skillTargets() {
32588
32622
  // both produces "skill conflict" duplicate warnings. Every tool we support
32589
32623
  // has its own dir, so per-tool coverage is complete.
32590
32624
  ...claudeSkillTargets(),
32591
- { id: "agy", label: "Antigravity", dir: join58(agyBackend.homeDir(), "skills"), available: agyBackend.isAvailable() },
32625
+ { id: "agy", label: "Antigravity", dir: join59(agyBackend.homeDir(), "skills"), available: agyBackend.isAvailable() },
32592
32626
  { id: "codex", label: "Codex", dir: codexBackend.skillsDir(), available: codexBackend.isAvailable() },
32593
32627
  { id: "opencode", label: "OpenCode", dir: opencodeBackend.skillsDir(), available: opencodeBackend.isAvailable() },
32594
32628
  // Cursor DOES have its own dir (~/.cursor/skills). `skills-cursor` next to
32595
32629
  // it is Cursor's bundled set — read-only, never an install target.
32596
- { id: "cursor", label: "Cursor", dir: join58(cursorHomeDir(), "skills"), available: cursorBackend.isAvailable() },
32630
+ { id: "cursor", label: "Cursor", dir: join59(cursorHomeDir(), "skills"), available: cursorBackend.isAvailable() },
32597
32631
  { id: "pi", label: "Pi", dir: piBackend.skillsDir(), available: piBackend.isAvailable() }
32598
32632
  ];
32599
32633
  }
32600
32634
  function isManaged(dir) {
32601
- return existsSync49(join58(dir, MARKER));
32635
+ return existsSync49(join59(dir, MARKER));
32602
32636
  }
32603
32637
  function installSkills(opts = {}) {
32604
32638
  const onlyAvailable = opts.onlyAvailable ?? true;
@@ -32615,15 +32649,15 @@ function installSkills(opts = {}) {
32615
32649
  continue;
32616
32650
  }
32617
32651
  for (const name of names) {
32618
- const dest = join58(t.dir, name);
32652
+ const dest = join59(t.dir, name);
32619
32653
  if (existsSync49(dest) && !isManaged(dest)) {
32620
32654
  skippedUserOwned.push(name);
32621
32655
  continue;
32622
32656
  }
32623
- mkdirSync15(t.dir, { recursive: true });
32657
+ mkdirSync16(t.dir, { recursive: true });
32624
32658
  rmSync9(dest, { recursive: true, force: true });
32625
- cpSync(join58(src, name), dest, { recursive: true });
32626
- writeFileSync13(join58(dest, MARKER), `${stamp}
32659
+ cpSync(join59(src, name), dest, { recursive: true });
32660
+ writeFileSync14(join59(dest, MARKER), `${stamp}
32627
32661
  `);
32628
32662
  installed.push(name);
32629
32663
  }
@@ -32640,9 +32674,9 @@ function uninstallSkills() {
32640
32674
  perTarget.push({ id: t.id, label: t.label, removed });
32641
32675
  continue;
32642
32676
  }
32643
- for (const entry of readdirSync34(t.dir, { withFileTypes: true })) {
32677
+ for (const entry of readdirSync36(t.dir, { withFileTypes: true })) {
32644
32678
  if (!entry.isDirectory()) continue;
32645
- const dir = join58(t.dir, entry.name);
32679
+ const dir = join59(t.dir, entry.name);
32646
32680
  if (isManaged(dir) && (names.has(entry.name) || entry.name.startsWith("chat-recall"))) {
32647
32681
  rmSync9(dir, { recursive: true, force: true });
32648
32682
  removed.push(entry.name);
@@ -32659,10 +32693,10 @@ function skillsNeedRefresh() {
32659
32693
  for (const t of skillTargets()) {
32660
32694
  if (!t.available) continue;
32661
32695
  for (const name of names) {
32662
- const marker = join58(t.dir, name, MARKER);
32696
+ const marker = join59(t.dir, name, MARKER);
32663
32697
  if (!existsSync49(marker)) return true;
32664
32698
  try {
32665
- if (readFileSync48(marker, "utf-8").trim() !== cur) return true;
32699
+ if (readFileSync51(marker, "utf-8").trim() !== cur) return true;
32666
32700
  } catch {
32667
32701
  return true;
32668
32702
  }
@@ -32677,11 +32711,11 @@ function skillStatus() {
32677
32711
  let installed = 0;
32678
32712
  let ver = null;
32679
32713
  for (const name of names) {
32680
- const marker = join58(t.dir, name, MARKER);
32714
+ const marker = join59(t.dir, name, MARKER);
32681
32715
  if (existsSync49(marker)) {
32682
32716
  installed++;
32683
32717
  try {
32684
- ver = readFileSync48(marker, "utf-8").trim();
32718
+ ver = readFileSync51(marker, "utf-8").trim();
32685
32719
  } catch {
32686
32720
  }
32687
32721
  }
@@ -32707,7 +32741,7 @@ var init_install_skills = __esm({
32707
32741
 
32708
32742
  // src/board-hooks.ts
32709
32743
  import { existsSync as existsSync50 } from "node:fs";
32710
- import { join as join59 } from "node:path";
32744
+ import { join as join60 } from "node:path";
32711
32745
  function entryCommand(entry) {
32712
32746
  const cmd = entry?.hooks?.[0]?.command;
32713
32747
  return typeof cmd === "string" ? cmd : null;
@@ -32753,12 +32787,12 @@ function messageHookEntries(execPath, hookEntry) {
32753
32787
  ];
32754
32788
  }
32755
32789
  function resolveCliEntry(distDir) {
32756
- const bundled = join59(distDir, "cli.js");
32757
- return existsSync50(bundled) ? bundled : join59(distDir, "cli.ts");
32790
+ const bundled = join60(distDir, "cli.js");
32791
+ return existsSync50(bundled) ? bundled : join60(distDir, "cli.ts");
32758
32792
  }
32759
32793
  function resolveMessageHookEntry(distDir) {
32760
- const bundled = join59(distDir, "message-hook.js");
32761
- return existsSync50(bundled) ? bundled : join59(distDir, "message-hook.ts");
32794
+ const bundled = join60(distDir, "message-hook.js");
32795
+ return existsSync50(bundled) ? bundled : join60(distDir, "message-hook.ts");
32762
32796
  }
32763
32797
  var BOARD_HOOKS, MESSAGE_HOOK_EVENTS, MESSAGE_WAITER_EVENTS, MESSAGE_WAITER_TIMEOUT_SECONDS;
32764
32798
  var init_board_hooks = __esm({
@@ -32790,24 +32824,24 @@ __export(guard_registration_exports, {
32790
32824
  unregisterGuard: () => unregisterGuard
32791
32825
  });
32792
32826
  import { homedir as homedir20 } from "os";
32793
- import { join as join60 } from "path";
32827
+ import { join as join61 } from "path";
32794
32828
  function legacyAgyHooksFile() {
32795
- return join60(agyBackend.homeDir(), "hooks.json");
32829
+ return join61(agyBackend.homeDir(), "hooks.json");
32796
32830
  }
32797
32831
  function opencodeConfigDir() {
32798
32832
  const xdg = process.env.XDG_CONFIG_HOME;
32799
- const base2 = xdg && xdg.trim() ? xdg : join60(homedir20(), ".config");
32800
- return join60(base2, "opencode");
32833
+ const base2 = xdg && xdg.trim() ? xdg : join61(homedir20(), ".config");
32834
+ return join61(base2, "opencode");
32801
32835
  }
32802
32836
  function opencodePluginDir() {
32803
- return join60(opencodeConfigDir(), "plugins");
32837
+ return join61(opencodeConfigDir(), "plugins");
32804
32838
  }
32805
32839
  function guardTargets() {
32806
32840
  return [
32807
32841
  {
32808
32842
  tool: "codex",
32809
32843
  label: "Codex",
32810
- configPath: join60(codexBackend.homeDir(), "hooks.json"),
32844
+ configPath: join61(codexBackend.homeDir(), "hooks.json"),
32811
32845
  homeDir: codexBackend.homeDir(),
32812
32846
  // Codex will not run a hook until a person has reviewed it, and the
32813
32847
  // approval is bound to the hook's hash. There is no way to grant it from
@@ -32826,14 +32860,14 @@ function guardTargets() {
32826
32860
  {
32827
32861
  tool: "cursor",
32828
32862
  label: "Cursor",
32829
- configPath: join60(cursorBackend.homeDir(), "hooks.json"),
32863
+ configPath: join61(cursorBackend.homeDir(), "hooks.json"),
32830
32864
  homeDir: cursorBackend.homeDir(),
32831
32865
  note: "Cursor checks a shell command before it runs and a file edit after it is written."
32832
32866
  },
32833
32867
  {
32834
32868
  tool: "opencode",
32835
32869
  label: "OpenCode",
32836
- configPath: join60(opencodePluginDir(), "chat-recall-guard.js"),
32870
+ configPath: join61(opencodePluginDir(), "chat-recall-guard.js"),
32837
32871
  homeDir: opencodeConfigDir(),
32838
32872
  note: "OpenCode plugin hooks do not fire for subagent tool calls, so a delegating agent bypasses this."
32839
32873
  }
@@ -33008,29 +33042,33 @@ var init_guard_registration = __esm({
33008
33042
  var message_registration_exports = {};
33009
33043
  __export(message_registration_exports, {
33010
33044
  MESSAGES_ID: () => MESSAGES_ID,
33045
+ OPENCODE_TUI_PACKAGE: () => OPENCODE_TUI_PACKAGE,
33011
33046
  isOurPluginSource: () => isOurPluginSource,
33047
+ isOurTuiSource: () => isOurTuiSource,
33012
33048
  messageCommand: () => messageCommand,
33013
33049
  messageTargets: () => messageTargets,
33014
33050
  messageWrapperName: () => messageWrapperName,
33015
33051
  messageWrapperSource: () => messageWrapperSource,
33016
33052
  opencodeMessagesSource: () => opencodeMessagesSource,
33053
+ opencodeTuiFiles: () => opencodeTuiFiles,
33054
+ opencodeTuiSource: () => opencodeTuiSource,
33017
33055
  piAgentDir: () => piAgentDir,
33018
33056
  piMessagesSource: () => piMessagesSource,
33019
33057
  registerMessages: () => registerMessages,
33020
33058
  unregisterMessages: () => unregisterMessages
33021
33059
  });
33022
33060
  import { homedir as homedir21 } from "os";
33023
- import { join as join61 } from "path";
33061
+ import { join as join62 } from "path";
33024
33062
  function piAgentDir() {
33025
33063
  const dir = process.env.PI_CODING_AGENT_DIR;
33026
- return dir && dir.trim() ? dir : join61(homedir21(), ".pi", "agent");
33064
+ return dir && dir.trim() ? dir : join62(homedir21(), ".pi", "agent");
33027
33065
  }
33028
33066
  function messageTargets() {
33029
33067
  return [
33030
33068
  {
33031
33069
  tool: "codex",
33032
33070
  label: "Codex",
33033
- configPath: join61(codexBackend.homeDir(), "hooks.json"),
33071
+ configPath: join62(codexBackend.homeDir(), "hooks.json"),
33034
33072
  homeDir: codexBackend.homeDir(),
33035
33073
  // Codex binds its approval to the hook's hash, and only a person can give it.
33036
33074
  note: "Codex asks you to approve a hook before it runs one. Run /hooks in Codex once to approve the message hook."
@@ -33044,20 +33082,20 @@ function messageTargets() {
33044
33082
  {
33045
33083
  tool: "cursor",
33046
33084
  label: "Cursor",
33047
- configPath: join61(cursorBackend.homeDir(), "hooks.json"),
33085
+ configPath: join62(cursorBackend.homeDir(), "hooks.json"),
33048
33086
  homeDir: cursorBackend.homeDir(),
33049
33087
  note: "Cursor delivers a message at the start of a session and when the agent stops, as a follow-up prompt."
33050
33088
  },
33051
33089
  {
33052
33090
  tool: "opencode",
33053
33091
  label: "OpenCode",
33054
- configPath: join61(opencodePluginDir(), `${MESSAGES_ID}.js`),
33092
+ configPath: join62(opencodePluginDir(), `${MESSAGES_ID}.js`),
33055
33093
  homeDir: opencodeConfigDir()
33056
33094
  },
33057
33095
  {
33058
33096
  tool: "pi",
33059
33097
  label: "pi",
33060
- configPath: join61(piAgentDir(), "extensions", `${MESSAGES_ID}.js`),
33098
+ configPath: join62(piAgentDir(), "extensions", `${MESSAGES_ID}.js`),
33061
33099
  homeDir: piAgentDir()
33062
33100
  }
33063
33101
  ];
@@ -33173,11 +33211,33 @@ function unregisterMessages(tool, config2) {
33173
33211
  function isOurPluginSource(source) {
33174
33212
  return source.includes(`${MESSAGES_ID}: written by`);
33175
33213
  }
33214
+ function isOurTuiSource(source) {
33215
+ return source.startsWith("// Written by `chat-recall install-hooks`");
33216
+ }
33176
33217
  function runnerSource(wrapperPath) {
33177
33218
  return `import { spawn } from "child_process";
33178
33219
 
33179
33220
  const HOOK = ${JSON.stringify(wrapperPath)};
33180
33221
 
33222
+ /**
33223
+ * The process this plugin runs in. The headless service a TUI starts reports
33224
+ * events for the same sessions, so the kind is what tells a coordinator which
33225
+ * row has a window. The first argument is the subcommand ("serve", "run", or
33226
+ * none for the TUI itself).
33227
+ */
33228
+ const KIND = (() => {
33229
+ const args = process.argv.slice(1).filter((a) => !a.startsWith("-"));
33230
+ if (args.includes("serve")) return "serve";
33231
+ if (args[0] === "run") return "run";
33232
+ return undefined;
33233
+ })();
33234
+
33235
+ function payload(sessionId, event, cwd) {
33236
+ const p = { session_id: sessionId, hook_event_name: event, cwd, pid: process.pid };
33237
+ if (KIND) p.kind = KIND;
33238
+ return p;
33239
+ }
33240
+
33181
33241
  function runHook(sessionId, event, cwd) {
33182
33242
  return new Promise((resolve) => {
33183
33243
  let out = "";
@@ -33192,42 +33252,91 @@ function runHook(sessionId, event, cwd) {
33192
33252
  child.stdout.on("data", (c) => { out += c; });
33193
33253
  child.on("error", () => { clearTimeout(done); resolve(""); });
33194
33254
  child.on("close", () => { clearTimeout(done); resolve(out.trim()); });
33195
- child.stdin.end(JSON.stringify({ session_id: sessionId, hook_event_name: event, cwd }));
33255
+ child.stdin.end(JSON.stringify(payload(sessionId, event, cwd)));
33196
33256
  });
33197
33257
  }
33198
33258
 
33199
33259
  /**
33200
33260
  * Wait for a message to an idle session. The hook long-polls the server and
33201
- * prints the messages when one arrives; onText gets them. One waiter per
33202
- * session; stopWaiter ends it when the session gets a prompt.
33261
+ * prints the messages when one arrives; onText gets them. One watcher per
33262
+ * session, owned by this process for as long as the session lives: a turn
33263
+ * starting does not stop it, and a watcher that exits is started again.
33264
+ * --supervised makes the hook say why it stopped (75 ended, 76 another
33265
+ * watcher, 77 not a session to watch) instead of exiting silently.
33203
33266
  */
33204
33267
  const waiters = new Map();
33205
33268
 
33206
33269
  function startWaiter(sessionId, cwd, onText) {
33207
- if (waiters.has(sessionId)) return;
33208
- let out = "";
33209
- let child;
33210
- try {
33211
- child = spawn(HOOK, ["--wait"], { stdio: ["pipe", "pipe", "ignore"] });
33212
- } catch {
33213
- return;
33214
- }
33215
- waiters.set(sessionId, child);
33216
- child.stdout.on("data", (c) => { out += c; });
33217
- child.on("error", () => { waiters.delete(sessionId); });
33218
- child.on("close", () => {
33219
- if (waiters.get(sessionId) === child) waiters.delete(sessionId);
33220
- const text = out.trim();
33221
- if (text) Promise.resolve().then(() => onText(text)).catch(() => {});
33222
- });
33223
- child.stdin.end(JSON.stringify({ session_id: sessionId, hook_event_name: "Stop", cwd }));
33270
+ const running = waiters.get(sessionId);
33271
+ if (running && !running.stopped) return;
33272
+ const rec = { child: null, stopped: false, timer: null, tries: 0 };
33273
+ waiters.set(sessionId, rec);
33274
+ const again = (ms) => {
33275
+ if (rec.stopped) return;
33276
+ clearTimeout(rec.timer);
33277
+ rec.timer = setTimeout(launch, ms);
33278
+ };
33279
+ const launch = () => {
33280
+ if (rec.stopped) return;
33281
+ let out = "";
33282
+ let child;
33283
+ try {
33284
+ child = spawn(HOOK, ["--wait", "--supervised"], { stdio: ["pipe", "pipe", "ignore"] });
33285
+ } catch {
33286
+ again(5000);
33287
+ return;
33288
+ }
33289
+ rec.child = child;
33290
+ child.stdout.on("data", (c) => { out += c; });
33291
+ // The close event follows an error, and carries the exit code.
33292
+ child.on("error", () => {});
33293
+ child.on("close", (code) => {
33294
+ rec.child = null;
33295
+ if (rec.stopped) return;
33296
+ const text = out.trim();
33297
+ if (text) {
33298
+ rec.tries = 0;
33299
+ Promise.resolve().then(() => onText(text)).catch(() => {}).then(() => again(0));
33300
+ return;
33301
+ }
33302
+ // 75: the session ended. 76: another process already waits for it.
33303
+ // 77: not a session the watcher serves. Asking again will not change
33304
+ // any of them, so the next event starts a watcher instead.
33305
+ if (code === 75 || code === 76 || code === 77) { waiters.delete(sessionId); return; }
33306
+ rec.tries += 1;
33307
+ again(Math.min(30000, 250 * 2 ** Math.min(rec.tries, 7)));
33308
+ });
33309
+ child.stdin.end(JSON.stringify({ session_id: sessionId, hook_event_name: "Stop", cwd }));
33310
+ };
33311
+ launch();
33224
33312
  }
33225
33313
 
33226
33314
  function stopWaiter(sessionId) {
33227
- const child = waiters.get(sessionId);
33228
- if (!child) return;
33315
+ const rec = waiters.get(sessionId);
33316
+ if (!rec) return;
33317
+ rec.stopped = true;
33318
+ clearTimeout(rec.timer);
33229
33319
  waiters.delete(sessionId);
33230
- try { child.kill(); } catch { /* gone */ }
33320
+ try { rec.child?.kill(); } catch { /* gone */ }
33321
+ }
33322
+
33323
+ /**
33324
+ * Start watchers for the sessions that were already open when this plugin
33325
+ * loaded. A reload replaces the plugin, so the new instance has no map from
33326
+ * before, and an idle session emits no further event: without this sweep it
33327
+ * would wait forever for a turn it never starts. Only recent sessions, most
33328
+ * recently used first, because the list can hold every session in the folder.
33329
+ */
33330
+ async function watchExisting(ctx, cwd, onTextFor) {
33331
+ try {
33332
+ const r = await ctx.session.list?.({});
33333
+ const list = Array.isArray(r) ? r : (r?.data ?? r?.sessions ?? []);
33334
+ const recent = list
33335
+ .filter((s) => s && s.id && !s.parentID)
33336
+ .sort((a, b) => (b.time?.updated ?? 0) - (a.time?.updated ?? 0))
33337
+ .slice(0, 8);
33338
+ for (const s of recent) startWaiter("opencode_" + s.id, cwd, onTextFor(s.id));
33339
+ } catch { /* an older runtime has no list: events still start watchers */ }
33231
33340
  }
33232
33341
  `;
33233
33342
  }
@@ -33238,11 +33347,25 @@ function opencodeMessagesSource(wrapperPath) {
33238
33347
  // other sessions sent it to the next prompt.
33239
33348
  ${runnerSource(wrapperPath)}
33240
33349
  const RUN_END = new Set(["session.execution.succeeded", "session.execution.failed", "session.execution.interrupted", "session.idle"]);
33350
+ const INTERRUPT = ${JSON.stringify(INTERRUPT_MARKER)};
33241
33351
  const INTRO = ${JSON.stringify(selfIntroduction("\0SESSION\0"))};
33242
33352
  const intro = (id) => INTRO.replace("\0SESSION\0", "opencode_" + id);
33243
33353
 
33244
33354
  async function setup(ctx) {
33245
33355
  const dir = ctx?.location?.directory;
33356
+ // A session of a shared \`opencode serve\` belongs to the folder it was made
33357
+ // in, and that is not this plugin instance's folder: the service sends one
33358
+ // plugin instance the events of every project it serves. Asking the session
33359
+ // is the only source that stays right. The instance's folder is the fallback
33360
+ // for a session that cannot be read (just deleted, or an old server).
33361
+ const dirOf = async (id) => {
33362
+ try {
33363
+ const s = await ctx.session.get({ sessionID: id });
33364
+ const d = s?.location?.directory ?? s?.directory;
33365
+ if (typeof d === "string" && d) return d;
33366
+ } catch { /* unknown session: the instance folder is the best guess */ }
33367
+ return dir;
33368
+ };
33246
33369
  const children = new Set();
33247
33370
  const isChild = async (id) => {
33248
33371
  if (children.has(id)) return true;
@@ -33252,12 +33375,29 @@ async function setup(ctx) {
33252
33375
  } catch { /* unknown: treat as a main session */ }
33253
33376
  return false;
33254
33377
  };
33378
+ // A message becomes a prompt, so an idle session acts on it with nobody
33379
+ // typing. An urgent message stops the turn in progress first.
33380
+ const deliver = (id) => async (text) => {
33381
+ let body = text;
33382
+ if (body.startsWith(INTERRUPT)) {
33383
+ body = body.slice(INTERRUPT.length).replace(/^\\n+/, "");
33384
+ try {
33385
+ if (typeof ctx.session.interrupt === "function") await ctx.session.interrupt({ sessionID: id });
33386
+ else if (typeof ctx.session.abort === "function") await ctx.session.abort({ sessionID: id });
33387
+ } catch { /* the turn was already over */ }
33388
+ await new Promise((r) => setTimeout(r, 250));
33389
+ }
33390
+ await ctx.session.prompt({ sessionID: id, text: body });
33391
+ };
33255
33392
  await ctx.session.hook("prompt", async (event) => {
33256
33393
  const id = event?.sessionID;
33257
33394
  if (!id || !event.prompt || (await isChild(id))) return;
33258
- stopWaiter("opencode_" + id);
33395
+ // The watcher is not stopped for a turn. A message sent while this turn
33396
+ // runs is already in flight to the runtime as the next prompt, and the
33397
+ // hook below catches anything the watcher did not take.
33398
+ startWaiter("opencode_" + id, await dirOf(id), deliver(id));
33259
33399
  // The first prompt registers the session; the hook adds only waiting messages.
33260
- const text = await runHook("opencode_" + id, "UserPromptSubmit", dir);
33400
+ const text = await runHook("opencode_" + id, "UserPromptSubmit", await dirOf(id));
33261
33401
  if (text) event.prompt.text = [event.prompt.text, text].filter(Boolean).join("\\n\\n");
33262
33402
  });
33263
33403
  // The session id goes into the system context of each model call: the agent
@@ -33276,17 +33416,21 @@ async function setup(ctx) {
33276
33416
  // update) is not in started, and still gets its waiter.
33277
33417
  if (!id || (await isChild(id))) continue;
33278
33418
  if (RUN_END.has(ev.type)) {
33279
- await runHook("opencode_" + id, "Stop", dir);
33419
+ const at = await dirOf(id);
33420
+ await runHook("opencode_" + id, "Stop", at);
33280
33421
  // An idle session acts on a message from another session by itself:
33281
33422
  // the text becomes its next prompt.
33282
- startWaiter("opencode_" + id, dir, (text) => ctx.session.prompt({ sessionID: id, text }));
33423
+ startWaiter("opencode_" + id, at, deliver(id));
33424
+ } else if (ev.type === "session.created") {
33425
+ startWaiter("opencode_" + id, await dirOf(id), deliver(id));
33283
33426
  } else if (ev.type === "session.deleted") {
33284
33427
  stopWaiter("opencode_" + id);
33285
- await runHook("opencode_" + id, "SessionEnd", dir);
33428
+ await runHook("opencode_" + id, "SessionEnd", await dirOf(id));
33286
33429
  }
33287
33430
  }
33288
33431
  } catch { /* the subscription ends with the plugin */ }
33289
33432
  })();
33433
+ await watchExisting(ctx, dir, deliver);
33290
33434
  return () => {
33291
33435
  controller.abort();
33292
33436
  for (const id of [...waiters.keys()]) stopWaiter(id);
@@ -33339,12 +33483,203 @@ async function server({ directory }) {
33339
33483
  export default { id: "${MESSAGES_ID}", server, setup };
33340
33484
  `;
33341
33485
  }
33486
+ function opencodeTuiSource(wrapperPath) {
33487
+ return `// Written by \`chat-recall install-hooks\`. Re-running replaces it.
33488
+ //
33489
+ // Registers this opencode TUI with chat-recall before it has a session, so a
33490
+ // message sent to the folder reaches it: the message becomes the TUI's first
33491
+ // session and first prompt. Also reports the session the TUI shows as "tui".
33492
+ import { spawn } from "node:child_process";
33493
+ import { randomBytes } from "node:crypto";
33494
+ import { Plugin } from "@opencode/plugin/tui";
33495
+
33496
+ const HOOK = ${JSON.stringify(wrapperPath)};
33497
+ const PID = process.pid;
33498
+ const POLL_MS = 4000;
33499
+ const RUN_MS = 8000;
33500
+
33501
+ // One state per process, not per module instance. opencode loads this entry
33502
+ // more than once in one TUI process, and a reload keeps the old instance
33503
+ // alive; two instances would each open a presence loop, and the folder would
33504
+ // answer as two windows.
33505
+ const STATE = Symbol.for("chat-recall.tui-plugin");
33506
+ const state = globalThis[STATE] ??= { api: undefined, presence: undefined, timer: undefined, reported: undefined, disposed: false, id: undefined };
33507
+ state.id ??= "tui_" + randomBytes(8).toString("hex");
33508
+
33509
+ /** Run the hook once and return what it printed. */
33510
+ function run(payload, args) {
33511
+ return new Promise((resolve) => {
33512
+ let out = "";
33513
+ let child;
33514
+ try {
33515
+ child = spawn(HOOK, args, { stdio: ["pipe", "pipe", "ignore"] });
33516
+ } catch {
33517
+ resolve("");
33518
+ return;
33519
+ }
33520
+ const done = setTimeout(() => { child.kill(); resolve(""); }, RUN_MS);
33521
+ child.stdout.on("data", (c) => { out += c; });
33522
+ child.on("error", () => { clearTimeout(done); resolve(""); });
33523
+ child.on("close", () => { clearTimeout(done); resolve(out.trim()); });
33524
+ child.stdin.end(JSON.stringify(payload));
33525
+ });
33526
+ }
33527
+
33528
+ function route(api) {
33529
+ try {
33530
+ const r = api.ui.router.current();
33531
+ return r && typeof r === "object" ? r : undefined;
33532
+ } catch {
33533
+ return undefined;
33534
+ }
33535
+ }
33536
+
33537
+ function sessionOf(api) {
33538
+ const r = route(api);
33539
+ return r && r.type === "session" && typeof r.sessionID === "string" ? r.sessionID : undefined;
33540
+ }
33541
+
33542
+ async function report(api, sessionID) {
33543
+ if (!sessionID || sessionID === state.reported) return;
33544
+ state.reported = sessionID;
33545
+ await run({ session_id: "opencode_" + sessionID, cwd: api.location.directory, kind: "tui", pid: PID }, ["--report"]);
33546
+ }
33547
+
33548
+ function stopPresence() {
33549
+ const child = state.presence;
33550
+ state.presence = undefined;
33551
+ if (child) {
33552
+ try { child.kill(); } catch { /* already gone */ }
33553
+ }
33554
+ }
33555
+
33556
+ /**
33557
+ * Register the folder while the TUI shows no session. A message for the folder
33558
+ * arrives on stdout as {"text", "ids"}; the lease expires if this plugin dies
33559
+ * before the prompt lands, and the message is delivered again.
33560
+ */
33561
+ function startPresence(api) {
33562
+ if (state.disposed || state.presence) return;
33563
+ const dir = api.location.directory;
33564
+ let child;
33565
+ try {
33566
+ child = spawn(HOOK, ["--presence"], { stdio: ["pipe", "pipe", "ignore"] });
33567
+ } catch {
33568
+ return;
33569
+ }
33570
+ state.presence = child;
33571
+ let buffer = "";
33572
+ child.stdout.on("data", (chunk) => {
33573
+ buffer += chunk;
33574
+ let i;
33575
+ while ((i = buffer.indexOf("\\n")) >= 0) {
33576
+ const line = buffer.slice(0, i).trim();
33577
+ buffer = buffer.slice(i + 1);
33578
+ if (!line || state.presence !== child) continue;
33579
+ let msg;
33580
+ try { msg = JSON.parse(line); } catch { continue; }
33581
+ stopPresence();
33582
+ openFirst(api, dir, msg).catch(() => {});
33583
+ break;
33584
+ }
33585
+ });
33586
+ child.on("error", () => { if (state.presence === child) state.presence = undefined; });
33587
+ child.on("close", () => { if (state.presence === child) state.presence = undefined; });
33588
+ child.stdin.end(JSON.stringify({ session_id: state.id, cwd: dir, pid: PID }));
33589
+ }
33590
+
33591
+ /** The message becomes the TUI's first session and first prompt. */
33592
+ async function openFirst(api, dir, msg) {
33593
+ const text = typeof msg.text === "string" ? msg.text : "";
33594
+ const ids = Array.isArray(msg.ids) ? msg.ids.filter((i) => typeof i === "string") : [];
33595
+ if (!text) return;
33596
+ let id;
33597
+ try {
33598
+ const created = await api.client.session.create({ title: "chat-recall message", location: { directory: dir } });
33599
+ id = created?.data?.data?.id ?? created?.data?.id ?? created?.id;
33600
+ } catch {
33601
+ return;
33602
+ }
33603
+ if (typeof id !== "string" || !id) return;
33604
+ try { api.ui.router.navigate({ type: "session", sessionID: id }); } catch { /* the route follows the new session */ }
33605
+ await report(api, id);
33606
+ try {
33607
+ await api.client.session.prompt({ sessionID: id, text });
33608
+ } catch {
33609
+ // The session exists but the prompt did not land. Leave the messages
33610
+ // unacknowledged: their lease returns them.
33611
+ return;
33612
+ }
33613
+ if (ids.length) await run({ session_id: state.id, ids }, ["--ack"]);
33614
+ }
33615
+
33616
+ /** Follow the route: report the session it shows, register the folder otherwise. */
33617
+ function tick() {
33618
+ const api = state.api;
33619
+ if (state.disposed || !api) return;
33620
+ const id = sessionOf(api);
33621
+ if (id) {
33622
+ report(api, id).catch(() => {});
33623
+ stopPresence();
33624
+ } else {
33625
+ startPresence(api);
33626
+ }
33627
+ }
33628
+
33629
+ function shutdown() {
33630
+ state.disposed = true;
33631
+ if (state.timer) { clearInterval(state.timer); state.timer = undefined; }
33632
+ stopPresence();
33633
+ }
33634
+
33635
+ export default Plugin.define({
33636
+ id: "chat-recall-tui",
33637
+ async setup(api) {
33638
+ // Only the TUI has a renderer and a route. A headless process that loads
33639
+ // this entry has neither, and must not answer for anyone's folder.
33640
+ if (!api?.renderer || !api?.location?.directory || !api?.ui?.router) return;
33641
+ // A reload after dispose starts a new life on the same process-wide state.
33642
+ if (state.disposed) { state.disposed = false; state.timer = undefined; state.reported = undefined; }
33643
+ state.api = api;
33644
+ tick();
33645
+ if (!state.timer) {
33646
+ state.timer = setInterval(tick, POLL_MS);
33647
+ if (typeof state.timer.unref === "function") state.timer.unref();
33648
+ }
33649
+ try { api.attention?.dispose?.(shutdown); } catch { /* no dispose registry */ }
33650
+ },
33651
+ });
33652
+ `;
33653
+ }
33654
+ function opencodeTuiFiles(wrapperPath) {
33655
+ return [
33656
+ {
33657
+ name: "package.json",
33658
+ source: JSON.stringify({
33659
+ name: OPENCODE_TUI_PACKAGE,
33660
+ private: true,
33661
+ type: "module",
33662
+ exports: { ".": "./index.js", "./tui": "./tui.js" }
33663
+ }, null, 2) + "\n"
33664
+ },
33665
+ {
33666
+ // The package's server entry. The message plugin next to it is the
33667
+ // server plugin; this one only has to exist for the package to load.
33668
+ name: "index.js",
33669
+ source: `// Written by \`chat-recall install-hooks\`. Re-running replaces it.
33670
+ export default { id: "${OPENCODE_TUI_PACKAGE}", setup() {} };
33671
+ `
33672
+ },
33673
+ { name: "tui.js", source: opencodeTuiSource(wrapperPath) }
33674
+ ];
33675
+ }
33342
33676
  function piMessagesSource(wrapperPath) {
33343
33677
  return `// ${MESSAGES_ID}: written by \`chat-recall install-hooks\`. Re-running replaces it.
33344
33678
  //
33345
33679
  // Reports each pi session to chat-recall and adds the messages that other
33346
33680
  // sessions sent it to the next prompt.
33347
33681
  ${runnerSource(wrapperPath)}
33682
+ const INTERRUPT = ${JSON.stringify(INTERRUPT_MARKER)};
33348
33683
  export default function (pi) {
33349
33684
  let pending = "";
33350
33685
  const idOf = (ctx) => "pi_" + ctx.sessionManager.getSessionId();
@@ -33354,7 +33689,6 @@ export default function (pi) {
33354
33689
  pending = await runHook(idOf(ctx), "SessionStart", cwdOf(ctx));
33355
33690
  });
33356
33691
  pi.on("before_agent_start", async (event, ctx) => {
33357
- stopWaiter(idOf(ctx));
33358
33692
  if (event.messageType !== "user") return;
33359
33693
  const now = await runHook(idOf(ctx), "UserPromptSubmit", cwdOf(ctx));
33360
33694
  const text = [pending, now].filter(Boolean).join("\\n\\n");
@@ -33365,7 +33699,10 @@ export default function (pi) {
33365
33699
  pi.on("agent_end", async (_event, ctx) => {
33366
33700
  await runHook(idOf(ctx), "Stop", cwdOf(ctx));
33367
33701
  // An idle session acts on a message from another session by itself.
33368
- startWaiter(idOf(ctx), cwdOf(ctx), (text) => pi.sendUserMessage(text));
33702
+ startWaiter(idOf(ctx), cwdOf(ctx), (text) => {
33703
+ const body = text.startsWith(INTERRUPT) ? text.slice(INTERRUPT.length).replace(/^\\n+/, "") : text;
33704
+ pi.sendUserMessage(body);
33705
+ });
33369
33706
  });
33370
33707
  pi.on("session_shutdown", async (_event, ctx) => {
33371
33708
  stopWaiter(idOf(ctx));
@@ -33374,7 +33711,7 @@ export default function (pi) {
33374
33711
  }
33375
33712
  `;
33376
33713
  }
33377
- var MESSAGES_ID, TIMEOUT_SECS2, isOurs2, asArray3, obj, CODEX_EVENTS, CURSOR_EVENTS;
33714
+ var MESSAGES_ID, TIMEOUT_SECS2, isOurs2, asArray3, obj, CODEX_EVENTS, CURSOR_EVENTS, OPENCODE_TUI_PACKAGE;
33378
33715
  var init_message_registration = __esm({
33379
33716
  "../engine/dist/core/message-registration.js"() {
33380
33717
  "use strict";
@@ -33388,6 +33725,275 @@ var init_message_registration = __esm({
33388
33725
  obj = (v) => v && typeof v === "object" && !Array.isArray(v) ? { ...v } : {};
33389
33726
  CODEX_EVENTS = ["SessionStart", "UserPromptSubmit", "Stop", "SessionEnd"];
33390
33727
  CURSOR_EVENTS = ["sessionStart", "beforeSubmitPrompt", "stop", "sessionEnd"];
33728
+ OPENCODE_TUI_PACKAGE = "chat-recall-tui";
33729
+ }
33730
+ });
33731
+
33732
+ // ../engine/dist/core/opencode-tui-config.js
33733
+ import { existsSync as existsSync51, readFileSync as readFileSync52, renameSync as renameSync6, writeFileSync as writeFileSync15 } from "node:fs";
33734
+ import { join as join63, relative as relative2, sep as sep4 } from "node:path";
33735
+ function tuiConfigPath(configDir = opencodeConfigDir()) {
33736
+ const jsonc = join63(configDir, "tui.jsonc");
33737
+ if (existsSync51(jsonc))
33738
+ return jsonc;
33739
+ return join63(configDir, "tui.json");
33740
+ }
33741
+ function tuiPluginEntry(configDir = opencodeConfigDir()) {
33742
+ const file = join63(opencodePluginDir(), OPENCODE_TUI_PACKAGE, "tui.js");
33743
+ return `./${relative2(configDir, file).split(sep4).join("/")}`;
33744
+ }
33745
+ function tokenize(src) {
33746
+ const out = [];
33747
+ let i = 0;
33748
+ while (i < src.length) {
33749
+ const c = src[i];
33750
+ if (c === " " || c === " " || c === "\n" || c === "\r" || c === "\uFEFF") {
33751
+ i += 1;
33752
+ continue;
33753
+ }
33754
+ if (c === "/" && src[i + 1] === "/") {
33755
+ const e = src.indexOf("\n", i);
33756
+ i = e < 0 ? src.length : e + 1;
33757
+ continue;
33758
+ }
33759
+ if (c === "/" && src[i + 1] === "*") {
33760
+ const e = src.indexOf("*/", i + 2);
33761
+ if (e < 0)
33762
+ throw new SyntaxError(`unterminated comment at ${i}`);
33763
+ i = e + 2;
33764
+ continue;
33765
+ }
33766
+ if (c === "{" || c === "}" || c === "[" || c === "]" || c === ":" || c === ",") {
33767
+ out.push({ t: "p", v: c, start: i, end: i + 1 });
33768
+ i += 1;
33769
+ continue;
33770
+ }
33771
+ if (c === '"') {
33772
+ let j3 = i + 1;
33773
+ while (j3 < src.length && src[j3] !== '"') {
33774
+ if (src[j3] === "\\")
33775
+ j3 += 1;
33776
+ j3 += 1;
33777
+ }
33778
+ if (j3 >= src.length)
33779
+ throw new SyntaxError(`unterminated string at ${i}`);
33780
+ out.push({ t: "s", v: JSON.parse(src.slice(i, j3 + 1)), start: i, end: j3 + 1 });
33781
+ i = j3 + 1;
33782
+ continue;
33783
+ }
33784
+ let j2 = i;
33785
+ while (j2 < src.length && !/[\s,:{}[\]"/]/.test(src[j2]))
33786
+ j2 += 1;
33787
+ if (j2 === i)
33788
+ throw new SyntaxError(`unexpected character at ${i}`);
33789
+ out.push({ t: "a", v: src.slice(i, j2), start: i, end: j2 });
33790
+ i = j2;
33791
+ }
33792
+ return out;
33793
+ }
33794
+ function parseRoot(src) {
33795
+ const toks = tokenize(src);
33796
+ if (toks.length === 0)
33797
+ return null;
33798
+ const p = new Parser(toks);
33799
+ const root = p.value();
33800
+ if (root.k !== "obj")
33801
+ throw new SyntaxError("the top level is not an object");
33802
+ const rest = toks.findIndex((t) => t.start >= root.end);
33803
+ if (rest !== -1)
33804
+ throw new SyntaxError(`unexpected "${toks[rest].v}" after the top-level object`);
33805
+ return root;
33806
+ }
33807
+ function pluginArray(root) {
33808
+ if (!root || root.k !== "obj")
33809
+ return {};
33810
+ const prop = root.props.find((p) => p.key === "plugin");
33811
+ if (!prop)
33812
+ return {};
33813
+ if (prop.value.k !== "arr")
33814
+ return { error: '"plugin" is not a list' };
33815
+ return { arr: prop.value };
33816
+ }
33817
+ function splice(src, from, to, insert) {
33818
+ return src.slice(0, from) + insert + src.slice(to);
33819
+ }
33820
+ function addTuiPluginEntry(src, entry) {
33821
+ let root;
33822
+ try {
33823
+ root = parseRoot(src);
33824
+ } catch (e) {
33825
+ return { ok: false, reason: `not valid JSONC: ${e.message}` };
33826
+ }
33827
+ const literal = JSON.stringify(entry);
33828
+ if (!root) {
33829
+ return { ok: true, changed: true, text: `{
33830
+ "plugin": [${literal}]
33831
+ }
33832
+ ` };
33833
+ }
33834
+ const { arr, error } = pluginArray(root);
33835
+ if (error)
33836
+ return { ok: false, reason: error };
33837
+ if (arr) {
33838
+ if (arr.items.some((it) => it.k === "str" && it.v === entry))
33839
+ return { ok: true, changed: false, text: src };
33840
+ const last = arr.items[arr.items.length - 1];
33841
+ const text = last ? splice(src, last.end, last.end, `, ${literal}`) : splice(src, arr.closeStart, arr.closeStart, literal);
33842
+ return { ok: true, changed: true, text };
33843
+ }
33844
+ const props = root.props;
33845
+ if (props.length === 0) {
33846
+ return { ok: true, changed: true, text: splice(src, root.start + 1, root.start + 1, `
33847
+ "plugin": [${literal}]
33848
+ `) };
33849
+ }
33850
+ const lastValue = props[props.length - 1].value;
33851
+ return { ok: true, changed: true, text: splice(src, lastValue.end, lastValue.end, `,
33852
+ "plugin": [${literal}]`) };
33853
+ }
33854
+ function removeTuiPluginEntry(src, entry) {
33855
+ let text = src;
33856
+ let changed = false;
33857
+ for (; ; ) {
33858
+ let root;
33859
+ try {
33860
+ root = parseRoot(text);
33861
+ } catch (e) {
33862
+ return { ok: false, reason: `not valid JSONC: ${e.message}` };
33863
+ }
33864
+ const { arr, error } = pluginArray(root);
33865
+ if (error)
33866
+ return { ok: false, reason: error };
33867
+ if (!arr)
33868
+ break;
33869
+ const i = arr.items.findIndex((it) => it.k === "str" && it.v === entry);
33870
+ if (i === -1)
33871
+ break;
33872
+ const item = arr.items[i];
33873
+ const comma = arr.commas[i];
33874
+ if (comma !== null) {
33875
+ text = splice(text, item.start, comma + 1, "");
33876
+ } else if (i > 0 && arr.commas[i - 1] !== null) {
33877
+ text = splice(text, arr.commas[i - 1], item.end, "");
33878
+ } else {
33879
+ text = splice(text, item.start, item.end, "");
33880
+ }
33881
+ changed = true;
33882
+ }
33883
+ return { ok: true, changed, text };
33884
+ }
33885
+ function writeTextAtomic(path2, text) {
33886
+ const tmp = `${path2}.${process.pid}.tmp`;
33887
+ writeFileSync15(tmp, text);
33888
+ renameSync6(tmp, path2);
33889
+ }
33890
+ function registerTuiPlugin(path2 = tuiConfigPath(), entry = tuiPluginEntry()) {
33891
+ const current = existsSync51(path2) ? readFileSync52(path2, "utf-8") : "";
33892
+ const edit = addTuiPluginEntry(current, entry);
33893
+ if (!edit.ok)
33894
+ return { status: "unparseable", path: path2, reason: edit.reason };
33895
+ if (!edit.changed)
33896
+ return { status: "present", path: path2 };
33897
+ writeTextAtomic(path2, edit.text);
33898
+ return { status: "added", path: path2 };
33899
+ }
33900
+ function unregisterTuiPlugin(path2 = tuiConfigPath(), entry = tuiPluginEntry()) {
33901
+ if (!existsSync51(path2))
33902
+ return { removed: false, path: path2 };
33903
+ const edit = removeTuiPluginEntry(readFileSync52(path2, "utf-8"), entry);
33904
+ if (!edit.ok || !edit.changed)
33905
+ return { removed: false, path: path2 };
33906
+ writeTextAtomic(path2, edit.text);
33907
+ return { removed: true, path: path2 };
33908
+ }
33909
+ var ATOM, Parser;
33910
+ var init_opencode_tui_config = __esm({
33911
+ "../engine/dist/core/opencode-tui-config.js"() {
33912
+ "use strict";
33913
+ init_guard_registration();
33914
+ init_message_registration();
33915
+ ATOM = /^(true|false|null|-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?)$/;
33916
+ Parser = class {
33917
+ toks;
33918
+ i = 0;
33919
+ constructor(toks) {
33920
+ this.toks = toks;
33921
+ }
33922
+ at() {
33923
+ return this.toks[this.i];
33924
+ }
33925
+ isP(t, v) {
33926
+ return !!t && t.t === "p" && t.v === v;
33927
+ }
33928
+ value() {
33929
+ const t = this.at();
33930
+ if (!t)
33931
+ throw new SyntaxError("unexpected end of file");
33932
+ if (t.t === "s") {
33933
+ this.i += 1;
33934
+ return { k: "str", start: t.start, end: t.end, v: t.v };
33935
+ }
33936
+ if (t.t === "a") {
33937
+ if (!ATOM.test(t.v))
33938
+ throw new SyntaxError(`unknown word "${t.v}" at ${t.start}`);
33939
+ this.i += 1;
33940
+ return { k: "atom", start: t.start, end: t.end, v: t.v };
33941
+ }
33942
+ if (this.isP(t, "{"))
33943
+ return this.object(t);
33944
+ if (this.isP(t, "["))
33945
+ return this.array(t);
33946
+ throw new SyntaxError(`unexpected "${t.v}" at ${t.start}`);
33947
+ }
33948
+ object(open3) {
33949
+ this.i += 1;
33950
+ const props = [];
33951
+ for (; ; ) {
33952
+ const k = this.at();
33953
+ if (this.isP(k, "}")) {
33954
+ this.i += 1;
33955
+ return { k: "obj", start: open3.start, end: k.end, closeStart: k.start, props };
33956
+ }
33957
+ if (!k || k.t !== "s")
33958
+ throw new SyntaxError(`expected a key at ${k ? k.start : "end"}`);
33959
+ this.i += 1;
33960
+ if (!this.isP(this.at(), ":"))
33961
+ throw new SyntaxError(`expected ":" after key at ${k.start}`);
33962
+ this.i += 1;
33963
+ props.push({ key: k.v, value: this.value() });
33964
+ const n = this.at();
33965
+ if (this.isP(n, ",")) {
33966
+ this.i += 1;
33967
+ continue;
33968
+ }
33969
+ if (this.isP(n, "}"))
33970
+ continue;
33971
+ throw new SyntaxError(`expected "," or "}" at ${n ? n.start : "end"}`);
33972
+ }
33973
+ }
33974
+ array(open3) {
33975
+ this.i += 1;
33976
+ const items = [];
33977
+ const commas = [];
33978
+ for (; ; ) {
33979
+ const n = this.at();
33980
+ if (this.isP(n, "]")) {
33981
+ this.i += 1;
33982
+ return { k: "arr", start: open3.start, end: n.end, closeStart: n.start, items, commas };
33983
+ }
33984
+ items.push(this.value());
33985
+ const c = this.at();
33986
+ if (this.isP(c, ",")) {
33987
+ commas.push(c.start);
33988
+ this.i += 1;
33989
+ continue;
33990
+ }
33991
+ commas.push(null);
33992
+ if (!this.isP(this.at(), "]"))
33993
+ throw new SyntaxError(`expected "," or "]" at ${c ? c.start : "end"}`);
33994
+ }
33995
+ }
33996
+ };
33391
33997
  }
33392
33998
  });
33393
33999
 
@@ -33405,8 +34011,8 @@ __export(install_hooks_exports, {
33405
34011
  removeOurEntries: () => removeOurEntries,
33406
34012
  uninstallHooks: () => uninstallHooks
33407
34013
  });
33408
- import { chmodSync as chmodSync7, copyFileSync as copyFileSync3, existsSync as existsSync51, mkdirSync as mkdirSync16, readFileSync as readFileSync49, realpathSync as realpathSync6, renameSync as renameSync6, unlinkSync as unlinkSync4, writeFileSync as writeFileSync14 } from "node:fs";
33409
- import { dirname as dirname21, join as join62 } from "node:path";
34014
+ import { chmodSync as chmodSync7, copyFileSync as copyFileSync3, existsSync as existsSync52, mkdirSync as mkdirSync17, readFileSync as readFileSync53, realpathSync as realpathSync6, renameSync as renameSync7, rmSync as rmSync10, unlinkSync as unlinkSync5, writeFileSync as writeFileSync16 } from "node:fs";
34015
+ import { dirname as dirname21, join as join64 } from "node:path";
33410
34016
  function isOurEntry(entry) {
33411
34017
  const cmd = entry?.hooks?.[0]?.command;
33412
34018
  if (typeof cmd !== "string") return false;
@@ -33416,8 +34022,8 @@ function claudeSettingsFiles() {
33416
34022
  const out = [];
33417
34023
  const seen = /* @__PURE__ */ new Set();
33418
34024
  for (const home of claudeHomeDirs()) {
33419
- if (!existsSync51(join62(home, "projects"))) continue;
33420
- const file = join62(home, "settings.json");
34025
+ if (!existsSync52(join64(home, "projects"))) continue;
34026
+ const file = join64(home, "settings.json");
33421
34027
  let key2;
33422
34028
  try {
33423
34029
  key2 = realpathSync6(file);
@@ -33433,10 +34039,10 @@ function claudeSettingsFiles() {
33433
34039
  }
33434
34040
  function findScript(distDir, name) {
33435
34041
  return [
33436
- join62(distDir, "..", "hooks", name),
33437
- join62(distDir, "..", "..", "hooks", name),
33438
- join62(distDir, "..", "..", "..", "hooks", name)
33439
- ].find((p) => existsSync51(p));
34042
+ join64(distDir, "..", "hooks", name),
34043
+ join64(distDir, "..", "..", "hooks", name),
34044
+ join64(distDir, "..", "..", "..", "hooks", name)
34045
+ ].find((p) => existsSync52(p));
33440
34046
  }
33441
34047
  function hookEntries(sel, paths) {
33442
34048
  const cmd = (command, extra = {}) => [{ type: "command", command, ...extra }];
@@ -33480,9 +34086,9 @@ function removeOurEntries(config2) {
33480
34086
  return removed;
33481
34087
  }
33482
34088
  function readJson4(file) {
33483
- if (!existsSync51(file)) return {};
34089
+ if (!existsSync52(file)) return {};
33484
34090
  try {
33485
- const v = JSON.parse(readFileSync49(file, "utf-8"));
34091
+ const v = JSON.parse(readFileSync53(file, "utf-8"));
33486
34092
  return v && typeof v === "object" && !Array.isArray(v) ? v : null;
33487
34093
  } catch {
33488
34094
  return null;
@@ -33494,17 +34100,17 @@ function writeJsonAtomic(file, value) {
33494
34100
  target = realpathSync6(file);
33495
34101
  } catch {
33496
34102
  }
33497
- mkdirSync16(dirname21(target), { recursive: true });
34103
+ mkdirSync17(dirname21(target), { recursive: true });
33498
34104
  const tmp = `${target}.chat-recall-${process.pid}.tmp`;
33499
- writeFileSync14(tmp, JSON.stringify(value, null, 2) + "\n");
33500
- renameSync6(tmp, target);
34105
+ writeFileSync16(tmp, JSON.stringify(value, null, 2) + "\n");
34106
+ renameSync7(tmp, target);
33501
34107
  }
33502
34108
  function statePath() {
33503
- return join62(getHooksDir(), "install.json");
34109
+ return join64(getHooksDir(), "install.json");
33504
34110
  }
33505
34111
  function readState() {
33506
34112
  try {
33507
- return JSON.parse(readFileSync49(statePath(), "utf-8"));
34113
+ return JSON.parse(readFileSync53(statePath(), "utf-8"));
33508
34114
  } catch {
33509
34115
  return null;
33510
34116
  }
@@ -33518,7 +34124,7 @@ async function installHooks(distDir, sel = ALL_HOOKS) {
33518
34124
  if (!sel[key2]) continue;
33519
34125
  const source = findScript(distDir, SCRIPTS[key2]);
33520
34126
  if (!source) continue;
33521
- const target = join62(scriptsDir, SCRIPTS[key2]);
34127
+ const target = join64(scriptsDir, SCRIPTS[key2]);
33522
34128
  copyFileSync3(source, target);
33523
34129
  chmodSync7(target, 493);
33524
34130
  scripts[key2] = target;
@@ -33549,30 +34155,31 @@ async function installHooks(distDir, sel = ALL_HOOKS) {
33549
34155
  mergeOurEntries(config2, entries);
33550
34156
  writeJsonAtomic(settingsFile, config2);
33551
34157
  report.written.push(settingsFile);
33552
- report.migrated += migrateHooksJson(join62(dirname21(settingsFile), "hooks.json"));
34158
+ report.migrated += migrateHooksJson(join64(dirname21(settingsFile), "hooks.json"));
33553
34159
  }
33554
34160
  if (sel.guard && scripts.guard) report.guardTargets = await addGuardToOtherTools(scriptsDir, scripts.guard);
33555
34161
  if (sel.messages && !shellSkipped) {
33556
34162
  report.messageTargets = await addMessagesToOtherTools(scriptsDir, process.execPath, resolveMessageHookEntry(distDir));
33557
34163
  }
34164
+ if (!sel.messages) unregisterTuiPlugin();
33558
34165
  writeJsonAtomic(statePath(), { version: cliVersion(), selection: sel });
33559
34166
  return report;
33560
34167
  }
33561
34168
  function migrateHooksJson(file) {
33562
- if (!existsSync51(file)) return 0;
34169
+ if (!existsSync52(file)) return 0;
33563
34170
  const config2 = readJson4(file);
33564
34171
  if (!config2) return 0;
33565
34172
  const removed = removeOurEntries(config2);
33566
34173
  if (removed === 0) return 0;
33567
- if (!Object.keys(config2).length) unlinkSync4(file);
34174
+ if (!Object.keys(config2).length) unlinkSync5(file);
33568
34175
  else writeJsonAtomic(file, config2);
33569
34176
  return removed;
33570
34177
  }
33571
34178
  async function uninstallHooks() {
33572
34179
  const report = { removed: 0, files: [], guardRemoved: [], messagesRemoved: [] };
33573
34180
  for (const settingsFile of claudeSettingsFiles()) {
33574
- for (const file of [settingsFile, join62(dirname21(settingsFile), "hooks.json")]) {
33575
- if (!existsSync51(file)) continue;
34181
+ for (const file of [settingsFile, join64(dirname21(settingsFile), "hooks.json")]) {
34182
+ if (!existsSync52(file)) continue;
33576
34183
  const config2 = readJson4(file);
33577
34184
  if (!config2) continue;
33578
34185
  const removed = removeOurEntries(config2);
@@ -33609,13 +34216,13 @@ async function addGuardToOtherTools(scriptsDir, guardScript) {
33609
34216
  const out = [];
33610
34217
  removeLegacyAgyGuard(reg);
33611
34218
  for (const target of reg.guardTargets()) {
33612
- if (!existsSync51(target.homeDir)) continue;
33613
- const wrapper = join62(scriptsDir, reg.guardWrapperName(target.tool));
33614
- writeFileSync14(wrapper, reg.guardWrapperSource(target.tool, guardScript));
34219
+ if (!existsSync52(target.homeDir)) continue;
34220
+ const wrapper = join64(scriptsDir, reg.guardWrapperName(target.tool));
34221
+ writeFileSync16(wrapper, reg.guardWrapperSource(target.tool, guardScript));
33615
34222
  chmodSync7(wrapper, 493);
33616
- mkdirSync16(dirname21(target.configPath), { recursive: true });
34223
+ mkdirSync17(dirname21(target.configPath), { recursive: true });
33617
34224
  if (target.tool === "opencode") {
33618
- writeFileSync14(target.configPath, reg.opencodePluginSource(wrapper));
34225
+ writeFileSync16(target.configPath, reg.opencodePluginSource(wrapper));
33619
34226
  } else {
33620
34227
  const merged = reg.registerGuard(target.tool, readJson4(target.configPath) ?? {}, reg.guardCommand(wrapper));
33621
34228
  writeJsonAtomic(target.configPath, merged);
@@ -33629,10 +34236,10 @@ async function removeGuardFromOtherTools() {
33629
34236
  const out = [];
33630
34237
  removeLegacyAgyGuard(reg);
33631
34238
  for (const target of reg.guardTargets()) {
33632
- if (!existsSync51(target.configPath)) continue;
34239
+ if (!existsSync52(target.configPath)) continue;
33633
34240
  if (target.tool === "opencode") {
33634
- if (!readFileSync49(target.configPath, "utf-8").includes("chat-recall install-hooks")) continue;
33635
- unlinkSync4(target.configPath);
34241
+ if (!readFileSync53(target.configPath, "utf-8").includes("chat-recall install-hooks")) continue;
34242
+ unlinkSync5(target.configPath);
33636
34243
  } else {
33637
34244
  const r = reg.unregisterGuard(target.tool, readJson4(target.configPath) ?? {});
33638
34245
  if (r.removed === 0) continue;
@@ -33644,7 +34251,7 @@ async function removeGuardFromOtherTools() {
33644
34251
  }
33645
34252
  function removeLegacyAgyGuard(reg) {
33646
34253
  const file = reg.legacyAgyHooksFile();
33647
- if (!existsSync51(file)) return;
34254
+ if (!existsSync52(file)) return;
33648
34255
  const r = reg.unregisterGuard("agy", readJson4(file) ?? {});
33649
34256
  if (r.removed) writeJsonAtomic(file, r.config);
33650
34257
  }
@@ -33652,15 +34259,26 @@ async function addMessagesToOtherTools(scriptsDir, nodePath, hookEntry) {
33652
34259
  const reg = await Promise.resolve().then(() => (init_message_registration(), message_registration_exports));
33653
34260
  const out = [];
33654
34261
  for (const target of reg.messageTargets()) {
33655
- if (!existsSync51(target.homeDir)) continue;
33656
- const wrapper = join62(scriptsDir, reg.messageWrapperName(target.tool));
33657
- writeFileSync14(wrapper, reg.messageWrapperSource(target.tool, nodePath, hookEntry));
34262
+ if (!existsSync52(target.homeDir)) continue;
34263
+ const wrapper = join64(scriptsDir, reg.messageWrapperName(target.tool));
34264
+ writeFileSync16(wrapper, reg.messageWrapperSource(target.tool, nodePath, hookEntry));
33658
34265
  chmodSync7(wrapper, 493);
33659
- mkdirSync16(dirname21(target.configPath), { recursive: true });
34266
+ mkdirSync17(dirname21(target.configPath), { recursive: true });
33660
34267
  if (target.tool === "opencode") {
33661
- writeFileSync14(target.configPath, reg.opencodeMessagesSource(wrapper));
34268
+ writeFileSync16(target.configPath, reg.opencodeMessagesSource(wrapper));
34269
+ const dir = join64(dirname21(target.configPath), reg.OPENCODE_TUI_PACKAGE);
34270
+ mkdirSync17(dir, { recursive: true });
34271
+ for (const file of reg.opencodeTuiFiles(wrapper)) writeFileSync16(join64(dir, file.name), file.source);
34272
+ const tui = registerTuiPlugin();
34273
+ if (tui.status === "unparseable") {
34274
+ out.push({
34275
+ label: "OpenCode TUI",
34276
+ configPath: tui.path,
34277
+ note: `Not added: ${tui.reason}. Add "${tuiPluginEntry()}" to its plugin list by hand.`
34278
+ });
34279
+ }
33662
34280
  } else if (target.tool === "pi") {
33663
- writeFileSync14(target.configPath, reg.piMessagesSource(wrapper));
34281
+ writeFileSync16(target.configPath, reg.piMessagesSource(wrapper));
33664
34282
  } else {
33665
34283
  const config2 = readJson4(target.configPath);
33666
34284
  if (!config2) continue;
@@ -33673,11 +34291,18 @@ async function addMessagesToOtherTools(scriptsDir, nodePath, hookEntry) {
33673
34291
  async function removeMessagesFromOtherTools() {
33674
34292
  const reg = await Promise.resolve().then(() => (init_message_registration(), message_registration_exports));
33675
34293
  const out = [];
34294
+ const tui = unregisterTuiPlugin();
34295
+ if (tui.removed) out.push({ label: "OpenCode TUI", configPath: tui.path });
33676
34296
  for (const target of reg.messageTargets()) {
33677
- if (!existsSync51(target.configPath)) continue;
34297
+ if (!existsSync52(target.configPath)) continue;
33678
34298
  if (target.tool === "opencode" || target.tool === "pi") {
33679
- if (!reg.isOurPluginSource(readFileSync49(target.configPath, "utf-8"))) continue;
33680
- unlinkSync4(target.configPath);
34299
+ if (!reg.isOurPluginSource(readFileSync53(target.configPath, "utf-8"))) continue;
34300
+ unlinkSync5(target.configPath);
34301
+ if (target.tool === "opencode") {
34302
+ const dir = join64(dirname21(target.configPath), reg.OPENCODE_TUI_PACKAGE);
34303
+ const tui2 = join64(dir, "tui.js");
34304
+ if (existsSync52(tui2) && reg.isOurTuiSource(readFileSync53(tui2, "utf-8"))) rmSync10(dir, { recursive: true, force: true });
34305
+ }
33681
34306
  } else {
33682
34307
  const config2 = readJson4(target.configPath);
33683
34308
  if (!config2) continue;
@@ -33698,6 +34323,7 @@ var init_install_hooks = __esm({
33698
34323
  init_tool_paths();
33699
34324
  init_board_hooks();
33700
34325
  init_http();
34326
+ init_opencode_tui_config();
33701
34327
  ALL_HOOKS = {
33702
34328
  save: true,
33703
34329
  resume: true,
@@ -33722,7 +34348,7 @@ var init_install_hooks = __esm({
33722
34348
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
33723
34349
  import { spawn as spawn4 } from "child_process";
33724
34350
  import { createServer, connect } from "node:net";
33725
- import { unlinkSync as unlinkSync5 } from "node:fs";
34351
+ import { unlinkSync as unlinkSync6 } from "node:fs";
33726
34352
 
33727
34353
  // src/mcp-socket.ts
33728
34354
  import { createHash } from "node:crypto";
@@ -34978,7 +35604,7 @@ function isMultiTenant() {
34978
35604
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
34979
35605
  import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ListPromptsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
34980
35606
  import { z } from "zod";
34981
- import { existsSync as existsSync23, readFileSync as readFileSync22, statSync as statSync23 } from "fs";
35607
+ import { existsSync as existsSync23, readFileSync as readFileSync23, statSync as statSync23 } from "fs";
34982
35608
  import { join as join31 } from "path";
34983
35609
 
34984
35610
  // ../engine/dist/core/context.js
@@ -35131,7 +35757,10 @@ async function spawnChild(input) {
35131
35757
  ...process.env,
35132
35758
  CHAT_RECALL_PARENT_SESSION: input.parentId,
35133
35759
  ...input.name ? { CHAT_RECALL_SESSION_NAME: input.name } : {},
35134
- ...input.doing ? { CHAT_RECALL_SESSION_DOING: input.doing } : {}
35760
+ ...input.doing ? { CHAT_RECALL_SESSION_DOING: input.doing } : {},
35761
+ // The hook reports a child as a background Claude session, which
35762
+ // `claude attach` opens.
35763
+ CHAT_RECALL_SESSION_KIND: "claude-bg"
35135
35764
  };
35136
35765
  if (parentState && typeof parentState.configDir === "string") {
35137
35766
  if (parentState.configDir)
@@ -35167,6 +35796,60 @@ async function spawnChild(input) {
35167
35796
 
35168
35797
  // ../engine/dist/mcp/tools.js
35169
35798
  init_session_messages();
35799
+
35800
+ // ../engine/dist/core/local-processes.js
35801
+ import { readdirSync as readdirSync15, readFileSync as readFileSync17, readlinkSync } from "node:fs";
35802
+ var AI_COMMANDS = /* @__PURE__ */ new Set(["opencode", "claude"]);
35803
+ function dedupe(processes) {
35804
+ const seen = /* @__PURE__ */ new Map();
35805
+ for (const p of processes) {
35806
+ const key2 = `${p.command}\0${p.cwd}`;
35807
+ if (!seen.has(key2))
35808
+ seen.set(key2, p);
35809
+ }
35810
+ return [...seen.values()].sort((a, b) => a.command.localeCompare(b.command) || a.cwd.localeCompare(b.cwd));
35811
+ }
35812
+ async function localAiProcesses() {
35813
+ if (process.platform !== "linux")
35814
+ return [];
35815
+ let entries;
35816
+ try {
35817
+ entries = readdirSync15("/proc");
35818
+ } catch {
35819
+ return [];
35820
+ }
35821
+ const out = [];
35822
+ for (const entry of entries) {
35823
+ if (!/^\d+$/.test(entry))
35824
+ continue;
35825
+ const pid = Number(entry);
35826
+ if (pid === process.pid)
35827
+ continue;
35828
+ let command;
35829
+ try {
35830
+ command = readFileSync17(`/proc/${pid}/comm`, "utf-8").trim();
35831
+ } catch {
35832
+ continue;
35833
+ }
35834
+ if (!AI_COMMANDS.has(command))
35835
+ continue;
35836
+ let cwd;
35837
+ try {
35838
+ cwd = readlinkSync(`/proc/${pid}/cwd`);
35839
+ } catch {
35840
+ continue;
35841
+ }
35842
+ if (!cwd || cwd.endsWith(" (deleted)"))
35843
+ continue;
35844
+ out.push({ pid, command, cwd });
35845
+ }
35846
+ return dedupe(out);
35847
+ }
35848
+
35849
+ // ../engine/dist/core/store/driver.js
35850
+ var LIVE_SESSION_STALE_MS = 9e4;
35851
+
35852
+ // ../engine/dist/mcp/tools.js
35170
35853
  init_backends();
35171
35854
  init_tool_backend();
35172
35855
 
@@ -35936,9 +36619,11 @@ var RecallSessionRegisterSchema = z.object({
35936
36619
  });
35937
36620
  var RecallMessageSendSchema = z.object({
35938
36621
  from: z.string().optional().describe(`The sending session, so the recipient can answer. ${SESSION_ARG}`),
35939
- to: z.string().min(1).describe('The recipient: a session id, the start of one, a session name, or "parent" / "children" / "group" (relative to `from`).'),
36622
+ to: z.string().min(1).describe('The recipient: a session id, the start of one, a session name, an absolute folder, or "parent" / "children" / "group" (relative to `from`).'),
35940
36623
  body: z.string().min(1).max(16e3).describe("The message. Secrets in it are redacted before it leaves this machine."),
35941
- reply_to: z.string().optional().describe("The id of the message this answers.")
36624
+ interrupt: z.boolean().optional().describe("Stop what the recipient is doing and act on this now. A runtime that can interrupt a turn does so; every other runtime delivers it at the next opportunity."),
36625
+ reply_to: z.string().optional().describe("The id of the message this answers."),
36626
+ expect_cwd: z.string().min(1).optional().describe("The folder the recipient must be in. The send is refused when the recipient is elsewhere.")
35942
36627
  });
35943
36628
  var RecallInboxSchema = z.object({
35944
36629
  session: z.string().min(1).describe(`The session whose messages to receive, usually this one. ${SESSION_ARG}`),
@@ -37150,17 +37835,24 @@ remembering specific keys.`,
37150
37835
  description: `Send a message to another running AI session of this account. Use it when one
37151
37836
  session coordinates others: a parent gives work to its children, a child reports back.
37152
37837
 
37153
- The recipient gets the message at its next prompt, tool call or turn end (Claude Code, through the
37154
- chat-recall message hook). A session that waits for its user reads it when the user types next.
37838
+ The recipient gets the message at its next prompt, tool call or turn end. A session with a live
37839
+ watcher (opencode and pi start one when a run ends) is idle only in name: the message starts its
37840
+ next turn with nobody typing. \`interrupt: true\` stops what the recipient is doing first.
37155
37841
  "children" sends to every running child of \`from\`; "parent" sends to its parent; "group" sends to
37156
- the parent and every running child \u2014 use it to announce a decision to the whole group.`,
37842
+ the parent and every running child \u2014 use it to announce a decision to the whole group.
37843
+
37844
+ \`to\` also takes an absolute folder: the session running there is the recipient, and zero or more
37845
+ than one is refused instead of guessed. When the folder is known, pass it in both \`to\` and
37846
+ \`expect_cwd\`; a recipient that is in another folder is refused and nothing is sent. An opencode TUI
37847
+ that has no session yet appears as its folder, and the message becomes its first prompt.`,
37157
37848
  inputSchema: {
37158
37849
  type: "object",
37159
37850
  properties: {
37160
37851
  from: { type: "string", description: "The sending session id, so the recipient can answer." },
37161
- to: { type: "string", description: 'A session id, the start of one, a session name, "parent", "children" or "group".' },
37852
+ to: { type: "string", description: 'A session id, the start of one, a session name, an absolute folder, "parent", "children" or "group".' },
37162
37853
  body: { type: "string", description: "The message. Secrets are redacted before it is sent." },
37163
- reply_to: { type: "string", description: "The id of the message this answers." }
37854
+ reply_to: { type: "string", description: "The id of the message this answers." },
37855
+ expect_cwd: { type: "string", description: "The folder the recipient must be in; the send is refused when it is elsewhere." }
37164
37856
  },
37165
37857
  required: ["to", "body"]
37166
37858
  }
@@ -37209,11 +37901,14 @@ recall_session_status shows that. Pass a permission mode only when the user chos
37209
37901
  {
37210
37902
  name: "recall_session_status",
37211
37903
  description: `See which sessions of this account are running, what each works on, and what state each
37212
- is in: working, idle and waiting for input, or ended. Each line shows the folder, the "doing" line the
37213
- session set, the board cards in progress linked to it, and unread messages. With \`parent\`, list the
37214
- children of one session \u2014 the check a coordinating session runs on the sessions it started.
37215
- With \`session\`, show one session and its message thread. To read what a session did, follow up
37216
- with recall_show and from_end.`,
37904
+ is in: working, idle and waiting for input, or ended. Each line starts with the name, the folder and
37905
+ the tool and process kind (an opencode TUI, a headless \`serve\` or \`run\`, a Claude Code session), so a
37906
+ recipient is checked before anything is sent to it; \`serve\` and \`run\` say "no window". The rest of the
37907
+ line is the state, the "doing" line the session set, the board cards in progress linked to it, and
37908
+ unread messages. An opencode TUI that has no session yet is listed by its folder, and so is any local
37909
+ opencode or claude process with no session (Linux). With \`parent\`, list the children of one session \u2014
37910
+ the check a coordinating session runs on the sessions it started. With \`session\`, show one session and
37911
+ its message thread. To read what a session did, follow up with recall_show and from_end.`,
37217
37912
  inputSchema: {
37218
37913
  type: "object",
37219
37914
  properties: {
@@ -39558,15 +40253,20 @@ ${row.value}`
39558
40253
  case "recall_message_send": {
39559
40254
  const params = RecallMessageSendSchema.parse(args);
39560
40255
  requireRemote();
39561
- const body2 = redactSecrets(params.body, { force: true });
39562
- getWAL().log("message_send", { from: params.from, to: params.to, chars: body2.length });
39563
- const r = await remotePost("/api/live-sessions/messages", { from: params.from, to: params.to, body: body2, replyTo: params.reply_to });
40256
+ const redactedBody = redactSecrets(params.body, { force: true });
40257
+ const body2 = params.interrupt ? interruptBody(redactedBody) : redactedBody;
40258
+ getWAL().log("message_send", { from: params.from, to: params.to, chars: body2.length, interrupt: !!params.interrupt });
40259
+ const r = await remotePost("/api/live-sessions/messages", { from: params.from, to: params.to, body: body2, replyTo: params.reply_to, expectCwd: params.expect_cwd });
39564
40260
  const lines = r.recipients.map((rc, i) => {
39565
- const name2 = rc.label ? `${rc.label} (${rc.sessionId})` : rc.sessionId;
39566
- const when2 = rc.state === "ended" ? "That session has ended. The message waits in case it resumes." : rc.state === "idle" ? "That session waits for its user, so it reads the message when the user types next." : "It receives the message at its next tool call or turn end.";
39567
- return `- ${name2}: message ${r.messages[i]?.id}. ${when2}`;
40261
+ const presence = rc.sessionId.startsWith(PRESENCE_PREFIX);
40262
+ const name2 = presence ? `The opencode TUI${rc.cwd ? ` in ${rc.cwd}` : ""}` : rc.label ? `${rc.label} (${rc.sessionId})` : rc.sessionId;
40263
+ const tool = toolOfSession(rc.sessionId);
40264
+ const where = !presence && rc.cwd ? ` in ${rc.cwd}` : "";
40265
+ const process2 = rc.processKind ? ` (${tool}, ${rc.processKind})` : ` (${tool})`;
40266
+ const when2 = presence ? "It has no session yet, so the message becomes its first prompt." : rc.state === "ended" ? "That session has ended. The message waits in case it resumes." : rc.state === "idle" && (tool === "opencode" || tool === "pi") ? "It is idle, and its plugin starts a turn with the message." : rc.state === "idle" ? "That session is idle. A session with a live watcher reads it and starts a turn by itself; one without reads it when its user types next." : "It receives the message at its next tool call or turn end.";
40267
+ return `- ${name2}${where}${process2}: message ${r.messages[i]?.id}. ${when2}`;
39568
40268
  });
39569
- const redacted = body2 !== params.body ? "\nSecrets in the body were redacted before sending." : "";
40269
+ const redacted = redactedBody !== params.body ? "\nSecrets in the body were redacted before sending." : "";
39570
40270
  return { content: [{ type: "text", text: `Sent.
39571
40271
  ${lines.join("\n")}${redacted}` }] };
39572
40272
  }
@@ -39669,12 +40369,28 @@ ${lines.join("\n")}${redacted}` }] };
39669
40369
  return { content: [{ type: "text", text: lines.join("\n") }] };
39670
40370
  }
39671
40371
  const { sessions } = await remoteGetQS("/api/live-sessions", { parent: params.parent, includeEnded: params.include_ended });
39672
- if (!sessions.length) {
39673
- const text = params.parent ? `No ${params.include_ended ? "" : "running "}children of ${params.parent}. A child links itself with recall_session_register.` : "No running sessions reported. A Claude Code session reports here after its first prompt, once the message hook is installed (`chat-recall install-hooks`).";
39674
- return { content: [{ type: "text", text }] };
39675
- }
39676
- const head = params.parent ? `Children of ${params.parent} (${sessions.length}):` : `Sessions (${sessions.length}), most recent first:`;
39677
- return { content: [{ type: "text", text: [head, ...sessions.map((x) => formatSessionLine(withLocal(x), now))].join("\n") }] };
40372
+ const live = sessions.filter((x) => !x.sessionId.startsWith(PRESENCE_PREFIX) || (x.lastSeen ?? x.updatedAt) >= now - LIVE_SESSION_STALE_MS);
40373
+ const processes = await localAiProcesses().catch(() => []);
40374
+ const reportedPids = new Set(sessions.map((x) => x.pid).filter((p) => typeof p === "number"));
40375
+ const folders = new Set(sessions.filter((x) => x.state !== "ended" && x.cwd).map((x) => x.cwd));
40376
+ const unlisted = processes.filter((p) => !reportedPids.has(p.pid) && !folders.has(p.cwd));
40377
+ const localLines = unlisted.length ? [
40378
+ "",
40379
+ `Local AI processes with no session yet (${unlisted.length}):`,
40380
+ ...unlisted.map((p) => `- ${p.command} in ${p.cwd} (pid ${p.pid})`),
40381
+ "Send to one by its folder: recall_message_send with to set to the folder."
40382
+ ] : [];
40383
+ if (!live.length) {
40384
+ const text = params.parent ? `No ${params.include_ended ? "" : "running "}children of ${params.parent}. A child links itself with recall_session_register.` : "No running sessions reported. A session reports here after its first prompt, once the message hook is installed (`chat-recall install-hooks`); an opencode TUI registers when it opens.";
40385
+ return { content: [{ type: "text", text: [text, ...localLines].join("\n") }] };
40386
+ }
40387
+ const head = params.parent ? `Children of ${params.parent} (${live.length}):` : `Sessions (${live.length}), most recent first:`;
40388
+ return {
40389
+ content: [{
40390
+ type: "text",
40391
+ text: [head, ...live.map((x) => formatSessionLine(withLocal(x), now)), ...localLines].join("\n")
40392
+ }]
40393
+ };
39678
40394
  }
39679
40395
  case "recall_session_register": {
39680
40396
  const params = RecallSessionRegisterSchema.parse(args);
@@ -39701,7 +40417,7 @@ ${lines.join("\n")}${redacted}` }] };
39701
40417
  const idFile = getIdentityFilePath();
39702
40418
  if (existsSync23(idFile)) {
39703
40419
  try {
39704
- identity = readFileSync22(idFile, "utf-8").trim() || identity;
40420
+ identity = readFileSync23(idFile, "utf-8").trim() || identity;
39705
40421
  } catch {
39706
40422
  }
39707
40423
  }
@@ -40196,9 +40912,267 @@ function openBrowser(url) {
40196
40912
  // src/mcp.ts
40197
40913
  init_client_events();
40198
40914
  init_update_notice();
40199
- import { readFileSync as readFileSync50 } from "node:fs";
40915
+ import { readFileSync as readFileSync54 } from "node:fs";
40916
+
40917
+ // src/channel.ts
40918
+ init_session_messages();
40919
+
40920
+ // src/channel-detect.ts
40921
+ import { execFileSync as execFileSync4 } from "node:child_process";
40922
+ import { readFileSync as readFileSync48 } from "node:fs";
40923
+ var OURS = /* @__PURE__ */ new Set(["server:chat-recall", "chat-recall"]);
40924
+ var FLAGS = /* @__PURE__ */ new Set(["--channels", "--dangerously-load-development-channels"]);
40925
+ function listsOurServer(args) {
40926
+ for (let i = 0; i < args.length; i += 1) {
40927
+ if (!FLAGS.has(args[i])) continue;
40928
+ for (let j2 = i + 1; j2 < args.length && !args[j2].startsWith("-"); j2 += 1) {
40929
+ if (OURS.has(args[j2])) return true;
40930
+ }
40931
+ }
40932
+ return false;
40933
+ }
40934
+ function commandLineOf(pid) {
40935
+ try {
40936
+ const parts = readFileSync48(`/proc/${pid}/cmdline`, "utf-8").split("\0").filter(Boolean);
40937
+ if (parts.length) return parts;
40938
+ } catch {
40939
+ }
40940
+ if (process.platform === "win32") return null;
40941
+ try {
40942
+ const out = execFileSync4("ps", ["-o", "args=", "-p", String(pid)], {
40943
+ encoding: "utf8",
40944
+ timeout: 2e3,
40945
+ stdio: ["ignore", "pipe", "ignore"]
40946
+ }).trim();
40947
+ return out ? out.split(/\s+/) : null;
40948
+ } catch {
40949
+ return null;
40950
+ }
40951
+ }
40952
+ function parentOf(pid) {
40953
+ try {
40954
+ const stat3 = readFileSync48(`/proc/${pid}/stat`, "utf-8");
40955
+ const ppid = Number(stat3.slice(stat3.lastIndexOf(")") + 2).split(" ")[1]);
40956
+ return ppid > 1 ? ppid : null;
40957
+ } catch {
40958
+ return null;
40959
+ }
40960
+ }
40961
+ function ancestorPids(from = process.ppid, depth = 2) {
40962
+ const out = [];
40963
+ let pid = from;
40964
+ for (let i = 0; i < depth && pid !== null; i += 1) {
40965
+ out.push(pid);
40966
+ pid = parentOf(pid);
40967
+ }
40968
+ return out;
40969
+ }
40970
+ function ancestorCommandLines(pids = ancestorPids()) {
40971
+ const out = [];
40972
+ for (const pid of pids) {
40973
+ const argv = commandLineOf(pid);
40974
+ if (argv) out.push(argv);
40975
+ }
40976
+ return out;
40977
+ }
40978
+ function channelDecision(env = process.env, args = process.argv.slice(2), ancestors = ancestorCommandLines) {
40979
+ const asked = env.CHAT_RECALL_CHANNEL;
40980
+ if (asked === "0") return { enabled: false, reason: "CHAT_RECALL_CHANNEL=0" };
40981
+ if (asked === "1") return { enabled: true, reason: "CHAT_RECALL_CHANNEL=1" };
40982
+ if (asked !== void 0 && asked !== "") return { enabled: false, reason: `CHAT_RECALL_CHANNEL=${asked} is neither 0 nor 1` };
40983
+ if (listsOurServer(args)) return { enabled: true, reason: "our own --channels flag" };
40984
+ if (ancestors().some(listsOurServer)) return { enabled: true, reason: "a --channels flag above us" };
40985
+ return { enabled: false, reason: "no channel flag" };
40986
+ }
40987
+
40988
+ // src/channel-state.ts
40989
+ init_data_dir();
40990
+ import { mkdirSync as mkdirSync14, readFileSync as readFileSync49, readdirSync as readdirSync35, statSync as statSync47, unlinkSync as unlinkSync4, writeFileSync as writeFileSync12 } from "node:fs";
40991
+ import { join as join57 } from "node:path";
40992
+ function channelStateDir() {
40993
+ return join57(getDataDir(), "hook-state", "messages");
40994
+ }
40995
+ function byPidDir() {
40996
+ return join57(channelStateDir(), "by-pid");
40997
+ }
40998
+ function markerPath(sessionId) {
40999
+ return join57(channelStateDir(), `${sessionId}.channel`);
41000
+ }
41001
+ function readText(path2) {
41002
+ try {
41003
+ return readFileSync49(path2, "utf-8").trim();
41004
+ } catch {
41005
+ return null;
41006
+ }
41007
+ }
41008
+ function startTimeOf(pid) {
41009
+ try {
41010
+ const stat3 = readFileSync49(`/proc/${pid}/stat`, "utf-8");
41011
+ const rest = stat3.slice(stat3.lastIndexOf(")") + 2).split(" ");
41012
+ const started = rest[19];
41013
+ return started && /^\d+$/.test(started) ? started : null;
41014
+ } catch {
41015
+ return null;
41016
+ }
41017
+ }
41018
+ function sessionIdFromPids(pids) {
41019
+ for (const pid of pids) {
41020
+ const raw = readText(join57(byPidDir(), String(pid)));
41021
+ if (!raw) continue;
41022
+ const [id, started] = raw.split(" ");
41023
+ if (started !== void 0 && started !== startTimeOf(pid)) continue;
41024
+ if (id) return id;
41025
+ }
41026
+ return null;
41027
+ }
41028
+ function markChannelAlive(sessionId) {
41029
+ try {
41030
+ mkdirSync14(channelStateDir(), { recursive: true });
41031
+ const started = startTimeOf(process.pid);
41032
+ writeFileSync12(markerPath(sessionId), started ? `${process.pid} ${started}` : String(process.pid));
41033
+ } catch {
41034
+ }
41035
+ }
41036
+ function clearChannelAlive(sessionId) {
41037
+ try {
41038
+ if (readMarker(sessionId)?.pid !== process.pid) return;
41039
+ unlinkSync4(markerPath(sessionId));
41040
+ } catch {
41041
+ }
41042
+ }
41043
+ function readMarker(sessionId) {
41044
+ try {
41045
+ const path2 = markerPath(sessionId);
41046
+ const [pidText, started] = readFileSync49(path2, "utf-8").trim().split(" ");
41047
+ const pid = Number(pidText);
41048
+ if (!Number.isInteger(pid) || pid <= 1) return null;
41049
+ return { pid, started, mtime: statSync47(path2).mtimeMs };
41050
+ } catch {
41051
+ return null;
41052
+ }
41053
+ }
41054
+
41055
+ // src/channel.ts
41056
+ init_http();
41057
+ var WAIT_SECS = 25;
41058
+ var SESSION_ID_WAIT_MS = 9e4;
41059
+ var MARK_EVERY_MS = 3e4;
41060
+ function declareChannel(server) {
41061
+ server.registerCapabilities({ experimental: { "claude/channel": {} } });
41062
+ }
41063
+ function beginChannel(server, debug) {
41064
+ const decision = channelDecision();
41065
+ const log6 = debug ?? ((reason) => {
41066
+ if (process.env.CHAT_RECALL_MESSAGE_HOOK_DEBUG === "1") process.stderr.write(`chat-recall channel: ${reason}
41067
+ `);
41068
+ });
41069
+ if (!decision.enabled) return null;
41070
+ const target = recallTarget();
41071
+ if (!target) {
41072
+ log6("asked for, but this machine has no login");
41073
+ return null;
41074
+ }
41075
+ declareChannel(server);
41076
+ const pids = ancestorPids();
41077
+ return () => {
41078
+ void runChannel({ server, target, sessionId: () => sessionIdFromPids(pids), debug: log6 }).catch((e) => log6(`stopped: ${e instanceof Error ? e.message : String(e)}`));
41079
+ };
41080
+ }
41081
+ function headers(target) {
41082
+ const h = { "content-type": "application/json" };
41083
+ if (target.token) h.authorization = `Bearer ${target.token}`;
41084
+ return h;
41085
+ }
41086
+ async function postJson(target, path2, body2, ms) {
41087
+ const res = await fetchWithTimeout(`${target.base}${path2}`, {
41088
+ method: "POST",
41089
+ headers: headers(target),
41090
+ body: JSON.stringify(body2)
41091
+ }, ms);
41092
+ return { status: res.status, body: res.ok ? await res.json() : null };
41093
+ }
41094
+ async function runChannel(deps) {
41095
+ const debug = deps.debug ?? (() => {
41096
+ });
41097
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => {
41098
+ setTimeout(r, ms);
41099
+ }));
41100
+ const post = deps.post ?? postJson;
41101
+ let sessionId = deps.sessionId();
41102
+ const giveUpAt = Date.now() + SESSION_ID_WAIT_MS;
41103
+ while (!sessionId) {
41104
+ if (Date.now() > giveUpAt) {
41105
+ debug("channel: the hook never recorded this session");
41106
+ return;
41107
+ }
41108
+ await sleep(500);
41109
+ sessionId = deps.sessionId();
41110
+ }
41111
+ debug(`channel: delivering for ${sessionId}`);
41112
+ markChannelAlive(sessionId);
41113
+ let markedAt = Date.now();
41114
+ let failures = 0;
41115
+ let notFound = 0;
41116
+ try {
41117
+ for (; ; ) {
41118
+ if (Date.now() - markedAt >= MARK_EVERY_MS) {
41119
+ markChannelAlive(sessionId);
41120
+ markedAt = Date.now();
41121
+ }
41122
+ let r;
41123
+ try {
41124
+ r = await post(deps.target, "/api/live-sessions/wait", { sessionId, timeoutSecs: WAIT_SECS }, (WAIT_SECS + 15) * 1e3);
41125
+ } catch (e) {
41126
+ r = { status: 0, body: null };
41127
+ debug(`channel: request failed: ${e instanceof Error ? e.message : String(e)}`);
41128
+ }
41129
+ if (r.status === 401 || r.status === 402 || r.status === 403) {
41130
+ debug(`channel: HTTP ${r.status}`);
41131
+ return;
41132
+ }
41133
+ const body2 = r.body;
41134
+ if (!body2) {
41135
+ failures += 1;
41136
+ notFound = r.status === 404 ? notFound + 1 : 0;
41137
+ if (notFound >= 5 || failures > 120) {
41138
+ debug("channel: giving up on the server");
41139
+ return;
41140
+ }
41141
+ await sleep(Math.min(3e4, 1e3 * 2 ** Math.min(failures, 5)));
41142
+ continue;
41143
+ }
41144
+ failures = 0;
41145
+ notFound = 0;
41146
+ if (body2.ended) {
41147
+ debug("channel: the session ended");
41148
+ return;
41149
+ }
41150
+ const messages = body2.messages ?? [];
41151
+ if (!messages.length) continue;
41152
+ const content = formatDelivery(sessionId, messages, {
41153
+ now: (deps.now ?? Date.now)(),
41154
+ labels: new Map(Object.entries(body2.labels ?? {}))
41155
+ });
41156
+ try {
41157
+ await deps.server.notification({
41158
+ method: "notifications/claude/channel",
41159
+ params: { content, meta: { from: "chat-recall", session: sessionId } }
41160
+ });
41161
+ } catch (e) {
41162
+ debug(`channel: could not emit: ${e instanceof Error ? e.message : String(e)}`);
41163
+ return;
41164
+ }
41165
+ await post(deps.target, "/api/live-sessions/ack", { sessionId, ids: messages.map((m) => m.id) }, 3e3).catch(() => {
41166
+ });
41167
+ }
41168
+ } finally {
41169
+ clearChannelAlive(sessionId);
41170
+ }
41171
+ }
41172
+
41173
+ // src/mcp.ts
40200
41174
  setServerVersion(JSON.parse(
40201
- readFileSync50(new URL("../package.json", import.meta.url), "utf-8")
41175
+ readFileSync54(new URL("../package.json", import.meta.url), "utf-8")
40202
41176
  ).version);
40203
41177
  setEventReporter(reportClientEvent2);
40204
41178
  setIndexRunner(runIndexChild2);
@@ -40371,7 +41345,7 @@ function installCrashGuards() {
40371
41345
  reportClientEvent2("mcp_crash", { message: err.stack || err.message });
40372
41346
  });
40373
41347
  }
40374
- var RELAY_VERSION = true ? "0.7.26" : "0.0.0";
41348
+ var RELAY_VERSION = true ? "0.7.30" : "0.0.0";
40375
41349
  function daemonIdleSecs() {
40376
41350
  const raw = process.env.CHAT_RECALL_DAEMON_IDLE_SECS;
40377
41351
  if (raw === void 0) return 900;
@@ -40398,7 +41372,7 @@ function listen(path2) {
40398
41372
  if (err.code !== "EADDRINUSE") return resolve3(null);
40399
41373
  if (await addressIsLive(path2)) return resolve3(null);
40400
41374
  try {
40401
- unlinkSync5(path2);
41375
+ unlinkSync6(path2);
40402
41376
  } catch {
40403
41377
  }
40404
41378
  const retry = createServer();
@@ -40449,7 +41423,7 @@ async function runDaemon() {
40449
41423
  clearInterval(timer);
40450
41424
  server.close(() => {
40451
41425
  try {
40452
- if (process.platform !== "win32") unlinkSync5(path2);
41426
+ if (process.platform !== "win32") unlinkSync6(path2);
40453
41427
  } catch {
40454
41428
  }
40455
41429
  process.exit(0);
@@ -40460,7 +41434,7 @@ async function runDaemon() {
40460
41434
  const shutdown = () => {
40461
41435
  try {
40462
41436
  server.close();
40463
- if (process.platform !== "win32") unlinkSync5(path2);
41437
+ if (process.platform !== "win32") unlinkSync6(path2);
40464
41438
  } catch {
40465
41439
  }
40466
41440
  process.exit(0);
@@ -40480,7 +41454,7 @@ async function runDaemon() {
40480
41454
  }
40481
41455
  function installedVersion2() {
40482
41456
  try {
40483
- const pkg = JSON.parse(readFileSync50(new URL("../package.json", import.meta.url), "utf-8"));
41457
+ const pkg = JSON.parse(readFileSync54(new URL("../package.json", import.meta.url), "utf-8"));
40484
41458
  return typeof pkg.version === "string" ? pkg.version : null;
40485
41459
  } catch {
40486
41460
  return null;
@@ -40492,7 +41466,10 @@ async function main() {
40492
41466
  if (!await runDaemon()) return;
40493
41467
  } else {
40494
41468
  const transport2 = new StdioServerTransport();
40495
- await createMcpServer().connect(transport2);
41469
+ const server = createMcpServer();
41470
+ const beginChannelDelivery = beginChannel(server);
41471
+ await server.connect(transport2);
41472
+ beginChannelDelivery?.();
40496
41473
  const leave = () => process.exit(0);
40497
41474
  onInputFinished(process.stdin, leave);
40498
41475
  watchParent(leave);