@adhdev/daemon-core 0.7.42 → 0.7.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cli-adapters/provider-cli-adapter.d.ts +2 -4
  2. package/dist/cli-adapters/pty-transport.d.ts +1 -0
  3. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +4 -0
  4. package/dist/cli-adapters/terminal-backends/types.d.ts +4 -0
  5. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +4 -0
  6. package/dist/cli-adapters/terminal-screen.d.ts +4 -0
  7. package/dist/commands/upgrade-helper.d.ts +10 -0
  8. package/dist/config/chat-history.d.ts +0 -3
  9. package/dist/index.d.ts +1 -0
  10. package/dist/index.js +509 -364
  11. package/dist/index.js.map +1 -1
  12. package/dist/index.mjs +497 -353
  13. package/dist/index.mjs.map +1 -1
  14. package/dist/providers/provider-instance.d.ts +0 -1
  15. package/dist/status/normalize.js +0 -7
  16. package/dist/status/normalize.js.map +1 -1
  17. package/dist/status/normalize.mjs +0 -7
  18. package/dist/status/normalize.mjs.map +1 -1
  19. package/node_modules/@adhdev/session-host-core/dist/index.js +2 -2
  20. package/node_modules/@adhdev/session-host-core/dist/index.js.map +1 -1
  21. package/node_modules/@adhdev/session-host-core/dist/index.mjs +2 -2
  22. package/node_modules/@adhdev/session-host-core/dist/index.mjs.map +1 -1
  23. package/node_modules/@adhdev/session-host-core/package.json +1 -1
  24. package/package.json +1 -1
  25. package/src/cli-adapters/provider-cli-adapter.ts +79 -70
  26. package/src/cli-adapters/pty-transport.ts +2 -0
  27. package/src/cli-adapters/session-host-transport.ts +1 -0
  28. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +5 -0
  29. package/src/cli-adapters/terminal-backends/types.ts +1 -0
  30. package/src/cli-adapters/terminal-backends/xterm-backend.ts +10 -0
  31. package/src/cli-adapters/terminal-screen.ts +4 -0
  32. package/src/commands/router.ts +29 -23
  33. package/src/commands/upgrade-helper.ts +214 -0
  34. package/src/config/chat-history.ts +3 -55
  35. package/src/index.ts +1 -0
  36. package/src/providers/cli-provider-instance.ts +1 -11
  37. package/src/providers/provider-instance.d.ts +0 -1
  38. package/src/providers/provider-instance.ts +0 -1
  39. package/src/status/normalize.ts +0 -4
package/dist/index.js CHANGED
@@ -520,6 +520,9 @@ var init_ghostty_vt_backend = __esm({
520
520
  getText() {
521
521
  return this.terminal.formatPlainText({ trim: true }) || "";
522
522
  }
523
+ getCursorPosition() {
524
+ return this.terminal.getCursorPosition();
525
+ }
523
526
  dispose() {
524
527
  this.terminal.dispose();
525
528
  }
@@ -577,6 +580,13 @@ var init_xterm_backend = __esm({
577
580
  while (last > first && !lines[last - 1]?.trim()) last--;
578
581
  return lines.slice(first, last).join("\n");
579
582
  }
583
+ getCursorPosition() {
584
+ const buffer = this.terminal.buffer.active;
585
+ return {
586
+ col: Math.max(0, buffer.cursorX || 0),
587
+ row: Math.max(0, buffer.cursorY || 0)
588
+ };
589
+ }
580
590
  dispose() {
581
591
  this.terminal.dispose();
582
592
  }
@@ -663,6 +673,9 @@ var init_terminal_screen = __esm({
663
673
  getText() {
664
674
  return this.terminal.getText();
665
675
  }
676
+ getCursorPosition() {
677
+ return this.terminal.getCursorPosition();
678
+ }
666
679
  dispose() {
667
680
  this.terminal.dispose();
668
681
  }
@@ -678,11 +691,11 @@ var init_terminal_screen = __esm({
678
691
  });
679
692
 
680
693
  // src/cli-adapters/pty-transport.ts
681
- var os11, pty, NodePtyRuntimeTransport, NodePtyTransportFactory;
694
+ var os12, pty, NodePtyRuntimeTransport, NodePtyTransportFactory;
682
695
  var init_pty_transport = __esm({
683
696
  "src/cli-adapters/pty-transport.ts"() {
684
697
  "use strict";
685
- os11 = __toESM(require("os"));
698
+ os12 = __toESM(require("os"));
686
699
  try {
687
700
  pty = require("node-pty");
688
701
  } catch {
@@ -693,6 +706,7 @@ var init_pty_transport = __esm({
693
706
  this.handle = handle;
694
707
  }
695
708
  ready = Promise.resolve();
709
+ terminalQueriesHandled = false;
696
710
  get pid() {
697
711
  return this.handle.pid;
698
712
  }
@@ -719,7 +733,7 @@ var init_pty_transport = __esm({
719
733
  spawn(command, args, options) {
720
734
  if (!pty) throw new Error("node-pty is not installed");
721
735
  const handle = pty.spawn(command, args, {
722
- name: os11.platform() === "win32" ? "xterm-color" : "xterm-256color",
736
+ name: os12.platform() === "win32" ? "xterm-color" : "xterm-256color",
723
737
  cols: options.cols,
724
738
  rows: options.rows,
725
739
  cwd: options.cwd,
@@ -746,24 +760,50 @@ function stripTerminalNoise(str) {
746
760
  function sanitizeTerminalText(str) {
747
761
  return stripTerminalNoise(stripAnsi(str));
748
762
  }
763
+ function buildCliSpawnEnv(baseEnv, overrides) {
764
+ const env = {};
765
+ const source = { ...baseEnv, ...overrides || {} };
766
+ for (const [key, value] of Object.entries(source)) {
767
+ if (typeof value !== "string") continue;
768
+ env[key] = value;
769
+ }
770
+ for (const key of Object.keys(env)) {
771
+ if (key === "INIT_CWD" || key === "NO_COLOR" || key === "FORCE_COLOR" || key === "npm_command" || key === "npm_execpath" || key === "npm_node_execpath" || key.startsWith("npm_") || key.startsWith("npm_config_") || key.startsWith("npm_package_") || key.startsWith("npm_lifecycle_") || key.startsWith("PNPM_") || key.startsWith("YARN_") || key.startsWith("BUN_")) {
772
+ delete env[key];
773
+ }
774
+ }
775
+ return env;
776
+ }
777
+ function computeTerminalQueryTail(buffer) {
778
+ const prefixes = ["\x1B[6n", "\x1B[?6n"];
779
+ const maxLength = prefixes.reduce((n, value) => Math.max(n, value.length), 0) - 1;
780
+ const start = Math.max(0, buffer.length - maxLength);
781
+ for (let i = start; i < buffer.length; i++) {
782
+ const suffix = buffer.slice(i);
783
+ if (prefixes.some((pattern) => suffix.length < pattern.length && pattern.startsWith(suffix))) {
784
+ return suffix;
785
+ }
786
+ }
787
+ return "";
788
+ }
749
789
  function findBinary(name) {
750
- const isWin = os12.platform() === "win32";
790
+ const isWin = os13.platform() === "win32";
751
791
  try {
752
792
  const cmd = isWin ? `where ${name}` : `which ${name}`;
753
- return (0, import_child_process5.execSync)(cmd, { encoding: "utf-8", timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }).trim().split("\n")[0].trim();
793
+ return (0, import_child_process7.execSync)(cmd, { encoding: "utf-8", timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }).trim().split("\n")[0].trim();
754
794
  } catch {
755
795
  return isWin ? `${name}.cmd` : name;
756
796
  }
757
797
  }
758
798
  function isScriptBinary(binaryPath) {
759
- if (!path9.isAbsolute(binaryPath)) return false;
799
+ if (!path10.isAbsolute(binaryPath)) return false;
760
800
  try {
761
- const fs12 = require("fs");
762
- const resolved = fs12.realpathSync(binaryPath);
801
+ const fs13 = require("fs");
802
+ const resolved = fs13.realpathSync(binaryPath);
763
803
  const head = Buffer.alloc(8);
764
- const fd = fs12.openSync(resolved, "r");
765
- fs12.readSync(fd, head, 0, 8, 0);
766
- fs12.closeSync(fd);
804
+ const fd = fs13.openSync(resolved, "r");
805
+ fs13.readSync(fd, head, 0, 8, 0);
806
+ fs13.closeSync(fd);
767
807
  let i = 0;
768
808
  if (head[0] === 239 && head[1] === 187 && head[2] === 191) i = 3;
769
809
  return head[i] === 35 && head[i + 1] === 33;
@@ -772,14 +812,14 @@ function isScriptBinary(binaryPath) {
772
812
  }
773
813
  }
774
814
  function looksLikeMachOOrElf(filePath) {
775
- if (!path9.isAbsolute(filePath)) return false;
815
+ if (!path10.isAbsolute(filePath)) return false;
776
816
  try {
777
- const fs12 = require("fs");
778
- const resolved = fs12.realpathSync(filePath);
817
+ const fs13 = require("fs");
818
+ const resolved = fs13.realpathSync(filePath);
779
819
  const buf = Buffer.alloc(8);
780
- const fd = fs12.openSync(resolved, "r");
781
- fs12.readSync(fd, buf, 0, 8, 0);
782
- fs12.closeSync(fd);
820
+ const fd = fs13.openSync(resolved, "r");
821
+ fs13.readSync(fd, buf, 0, 8, 0);
822
+ fs13.closeSync(fd);
783
823
  let i = 0;
784
824
  if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) i = 3;
785
825
  const b = buf.subarray(i);
@@ -795,7 +835,7 @@ function looksLikeMachOOrElf(filePath) {
795
835
  }
796
836
  function shSingleQuote(arg) {
797
837
  if (/^[a-zA-Z0-9@%_+=:,./-]+$/.test(arg)) return arg;
798
- if (os12.platform() === "win32") {
838
+ if (os13.platform() === "win32") {
799
839
  return `"${arg.replace(/"/g, '""')}"`;
800
840
  }
801
841
  return `'${arg.replace(/'/g, `'\\''`)}'`;
@@ -832,36 +872,6 @@ function promptLikelyVisible(screenText, promptSnippet) {
832
872
  ).length;
833
873
  return matched >= required;
834
874
  }
835
- function splitHistoryLines(text) {
836
- return String(text || "").split("\n").map((line) => line.replace(/\s+$/, ""));
837
- }
838
- function normalizeHistoryLine(line) {
839
- return String(line || "").replace(/\s+/g, " ").trim();
840
- }
841
- function mergeTerminalHistory(existing, snapshot) {
842
- const next = String(snapshot || "").trim();
843
- if (!next) return existing;
844
- const prev = String(existing || "").trim();
845
- if (!prev) return next;
846
- if (prev === next || prev.endsWith(next)) return prev;
847
- const prevLines = splitHistoryLines(prev);
848
- const nextLines = splitHistoryLines(next);
849
- const prevNorm = prevLines.map(normalizeHistoryLine);
850
- const nextNorm = nextLines.map(normalizeHistoryLine);
851
- const maxOverlap = Math.min(prevLines.length, nextLines.length);
852
- for (let overlap = maxOverlap; overlap >= 1; overlap -= 1) {
853
- const prevTail = prevNorm.slice(prevNorm.length - overlap);
854
- const nextHead = nextNorm.slice(0, overlap);
855
- if (prevTail.every((line, index) => line === nextHead[index])) {
856
- return [...prevLines, ...nextLines.slice(overlap)].join("\n").trim();
857
- }
858
- }
859
- const compactPrev = prevNorm.join("\n");
860
- const compactNext = nextNorm.join("\n");
861
- if (compactPrev.includes(compactNext)) return prev;
862
- return `${prev}
863
- ${next}`.trim();
864
- }
865
875
  function parsePatternEntry(x) {
866
876
  if (x instanceof RegExp) return x;
867
877
  if (x && typeof x === "object" && typeof x.source === "string") {
@@ -886,28 +896,28 @@ function normalizeCliProviderForRuntime(raw) {
886
896
  }
887
897
  };
888
898
  }
889
- var os12, path9, import_child_process5, pty2, ProviderCliAdapter;
899
+ var os13, path10, import_child_process7, pty2, ProviderCliAdapter;
890
900
  var init_provider_cli_adapter = __esm({
891
901
  "src/cli-adapters/provider-cli-adapter.ts"() {
892
902
  "use strict";
893
- os12 = __toESM(require("os"));
894
- path9 = __toESM(require("path"));
895
- import_child_process5 = require("child_process");
903
+ os13 = __toESM(require("os"));
904
+ path10 = __toESM(require("path"));
905
+ import_child_process7 = require("child_process");
896
906
  init_logger();
897
907
  init_terminal_screen();
898
908
  init_pty_transport();
899
909
  try {
900
910
  pty2 = require("node-pty");
901
- if (os12.platform() !== "win32") {
911
+ if (os13.platform() !== "win32") {
902
912
  try {
903
- const fs12 = require("fs");
904
- const ptyDir = path9.resolve(path9.dirname(require.resolve("node-pty")), "..");
905
- const platformArch = `${os12.platform()}-${os12.arch()}`;
906
- const helper = path9.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
907
- if (fs12.existsSync(helper)) {
908
- const stat = fs12.statSync(helper);
913
+ const fs13 = require("fs");
914
+ const ptyDir = path10.resolve(path10.dirname(require.resolve("node-pty")), "..");
915
+ const platformArch = `${os13.platform()}-${os13.arch()}`;
916
+ const helper = path10.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
917
+ if (fs13.existsSync(helper)) {
918
+ const stat = fs13.statSync(helper);
909
919
  if (!(stat.mode & 73)) {
910
- fs12.chmodSync(helper, stat.mode | 493);
920
+ fs13.chmodSync(helper, stat.mode | 493);
911
921
  LOG.info("CLI", "[node-pty] Fixed spawn-helper permissions");
912
922
  }
913
923
  }
@@ -924,7 +934,7 @@ var init_provider_cli_adapter = __esm({
924
934
  this.transportFactory = transportFactory;
925
935
  this.cliType = provider.type;
926
936
  this.cliName = provider.name;
927
- this.workingDir = workingDir.startsWith("~") ? workingDir.replace(/^~/, os12.homedir()) : workingDir;
937
+ this.workingDir = workingDir.startsWith("~") ? workingDir.replace(/^~/, os13.homedir()) : workingDir;
928
938
  const t = provider.timeouts || {};
929
939
  this.timeouts = {
930
940
  ptyFlush: t.ptyFlush ?? 50,
@@ -976,6 +986,7 @@ var init_provider_cli_adapter = __esm({
976
986
  pendingOutputParseTimer = null;
977
987
  ptyOutputBuffer = "";
978
988
  ptyOutputFlushTimer = null;
989
+ pendingTerminalQueryTail = "";
979
990
  // Server log forwarding
980
991
  serverConn = null;
981
992
  logBuffer = [];
@@ -1007,9 +1018,7 @@ var init_provider_cli_adapter = __esm({
1007
1018
  /** Full accumulated raw PTY output (with ANSI) */
1008
1019
  accumulatedRawBuffer = "";
1009
1020
  /** Current visible terminal screen snapshot */
1010
- terminalScreen = new TerminalScreen(40, 120);
1011
- /** Rolling append-only terminal transcript built from screen snapshots */
1012
- terminalHistory = "";
1021
+ terminalScreen = new TerminalScreen(30, 100);
1013
1022
  /** Max accumulated buffer size (last 50KB) */
1014
1023
  static MAX_ACCUMULATED_BUFFER = 5e4;
1015
1024
  currentTurnScope = null;
@@ -1031,15 +1040,13 @@ var init_provider_cli_adapter = __esm({
1031
1040
  return text.slice(start);
1032
1041
  }
1033
1042
  buildParseInput(baseMessages, partialResponse, scope) {
1034
- const buffer = scope ? this.sliceFromOffset(this.terminalHistory, scope.terminalHistoryStart) || this.sliceFromOffset(this.accumulatedBuffer, scope.bufferStart) || this.accumulatedBuffer : this.accumulatedBuffer;
1043
+ const buffer = scope ? this.sliceFromOffset(this.accumulatedBuffer, scope.bufferStart) || this.accumulatedBuffer : this.accumulatedBuffer;
1035
1044
  const rawBuffer = scope ? this.sliceFromOffset(this.accumulatedRawBuffer, scope.rawBufferStart) || this.accumulatedRawBuffer : this.accumulatedRawBuffer;
1036
- const terminalHistory = scope ? this.sliceFromOffset(this.terminalHistory, scope.terminalHistoryStart) || this.terminalHistory : this.terminalHistory;
1037
1045
  return {
1038
1046
  buffer,
1039
1047
  rawBuffer,
1040
1048
  recentBuffer: buffer.slice(-1e3) || this.recentOutputBuffer,
1041
1049
  screenText: this.terminalScreen.getText(),
1042
- terminalHistory,
1043
1050
  messages: [...baseMessages],
1044
1051
  partialResponse
1045
1052
  };
@@ -1094,12 +1101,12 @@ var init_provider_cli_adapter = __esm({
1094
1101
  if (this.ptyProcess) return;
1095
1102
  const { spawn: spawnConfig } = this.provider;
1096
1103
  const binaryPath = findBinary(spawnConfig.command);
1097
- const isWin = os12.platform() === "win32";
1104
+ const isWin = os13.platform() === "win32";
1098
1105
  const allArgs = [...spawnConfig.args, ...this.extraArgs];
1099
1106
  LOG.info("CLI", `[${this.cliType}] Spawning in ${this.workingDir}`);
1100
1107
  let shellCmd;
1101
1108
  let shellArgs;
1102
- const useShellUnix = !isWin && (!!spawnConfig.shell || !path9.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
1109
+ const useShellUnix = !isWin && (!!spawnConfig.shell || !path10.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
1103
1110
  const useShell = isWin ? !!spawnConfig.shell : useShellUnix;
1104
1111
  if (useShell) {
1105
1112
  if (!spawnConfig.shell && !isWin) {
@@ -1117,13 +1124,10 @@ var init_provider_cli_adapter = __esm({
1117
1124
  shellArgs = allArgs;
1118
1125
  }
1119
1126
  const ptyOpts = {
1120
- cols: 120,
1121
- rows: 40,
1127
+ cols: 100,
1128
+ rows: 30,
1122
1129
  cwd: this.workingDir,
1123
- env: {
1124
- ...process.env,
1125
- ...spawnConfig.env
1126
- }
1130
+ env: buildCliSpawnEnv(process.env, spawnConfig.env)
1127
1131
  };
1128
1132
  try {
1129
1133
  this.ptyProcess = this.transportFactory.spawn(shellCmd, shellArgs, ptyOpts);
@@ -1141,8 +1145,8 @@ var init_provider_cli_adapter = __esm({
1141
1145
  }
1142
1146
  this.ptyProcess.onData((data) => {
1143
1147
  if (Date.now() < this.resizeSuppressUntil) return;
1144
- if (data.includes("\x1B[6n") || data.includes("\x1B[?6n")) {
1145
- this.ptyProcess?.write("\x1B[1;1R");
1148
+ if (!this.ptyProcess?.terminalQueriesHandled) {
1149
+ this.respondToTerminalQueries(data);
1146
1150
  }
1147
1151
  this.pendingOutputParseBuffer += data;
1148
1152
  if (!this.pendingOutputParseTimer) {
@@ -1177,8 +1181,8 @@ var init_provider_cli_adapter = __esm({
1177
1181
  this.spawnAt = Date.now();
1178
1182
  this.startupParseGate = true;
1179
1183
  this.startupBuffer = "";
1180
- this.terminalScreen.reset(40, 120);
1181
- this.terminalHistory = "";
1184
+ this.terminalScreen.reset(30, 100);
1185
+ this.pendingTerminalQueryTail = "";
1182
1186
  this.currentTurnScope = null;
1183
1187
  this.ready = false;
1184
1188
  await this.ptyProcess.ready;
@@ -1188,7 +1192,6 @@ var init_provider_cli_adapter = __esm({
1188
1192
  // ─── Output Handling ────────────────────────────
1189
1193
  handleOutput(rawData) {
1190
1194
  this.terminalScreen.write(rawData);
1191
- this.terminalHistory = mergeTerminalHistory(this.terminalHistory, this.terminalScreen.getText());
1192
1195
  const cleanData = sanitizeTerminalText(rawData);
1193
1196
  if (this.isWaitingForResponse && cleanData) {
1194
1197
  this.responseBuffer = (this.responseBuffer + cleanData).slice(-8e3);
@@ -1464,8 +1467,7 @@ var init_provider_cli_adapter = __esm({
1464
1467
  status: this.currentStatus,
1465
1468
  messages: [...this.committedMessages],
1466
1469
  workingDir: this.workingDir,
1467
- activeModal: this.activeModal,
1468
- terminalHistory: this.terminalHistory
1470
+ activeModal: this.activeModal
1469
1471
  };
1470
1472
  }
1471
1473
  /**
@@ -1483,7 +1485,6 @@ var init_provider_cli_adapter = __esm({
1483
1485
  id: parsed.id || "cli_session",
1484
1486
  status: parsed.status || this.currentStatus,
1485
1487
  title: parsed.title || this.cliName,
1486
- terminalHistory: this.terminalHistory,
1487
1488
  messages: parsed.messages,
1488
1489
  activeModal: parsed.activeModal ?? this.activeModal
1489
1490
  };
@@ -1493,7 +1494,6 @@ var init_provider_cli_adapter = __esm({
1493
1494
  id: "cli_session",
1494
1495
  status: this.currentStatus,
1495
1496
  title: this.cliName,
1496
- terminalHistory: this.terminalHistory,
1497
1497
  messages: messages.slice(-50).map((message, index) => ({
1498
1498
  id: `msg_${index}`,
1499
1499
  role: message.role,
@@ -1561,10 +1561,9 @@ ${data.message || ""}`.trim();
1561
1561
  prompt: text,
1562
1562
  startedAt: Date.now(),
1563
1563
  bufferStart: this.accumulatedBuffer.length,
1564
- rawBufferStart: this.accumulatedRawBuffer.length,
1565
- terminalHistoryStart: this.terminalHistory.length
1564
+ rawBufferStart: this.accumulatedRawBuffer.length
1566
1565
  };
1567
- LOG.info("CLI", `[${this.cliType}] sendMessage turn scope buffer=${this.currentTurnScope.bufferStart} raw=${this.currentTurnScope.rawBufferStart} terminal=${this.currentTurnScope.terminalHistoryStart} prompt=${JSON.stringify(text).slice(0, 120)}`);
1566
+ LOG.info("CLI", `[${this.cliType}] sendMessage turn scope buffer=${this.currentTurnScope.bufferStart} raw=${this.currentTurnScope.rawBufferStart} prompt=${JSON.stringify(text).slice(0, 120)}`);
1568
1567
  this.submitRetryUsed = false;
1569
1568
  this.submitRetryPromptSnippet = extractPromptRetrySnippet(text);
1570
1569
  const normalizedPromptSnippet = normalizePromptText(this.submitRetryPromptSnippet);
@@ -1749,6 +1748,7 @@ ${data.message || ""}`.trim();
1749
1748
  this.pendingOutputParseTimer = null;
1750
1749
  }
1751
1750
  this.pendingOutputParseBuffer = "";
1751
+ this.pendingTerminalQueryTail = "";
1752
1752
  if (this.ptyOutputFlushTimer) {
1753
1753
  clearTimeout(this.ptyOutputFlushTimer);
1754
1754
  this.ptyOutputFlushTimer = null;
@@ -1788,6 +1788,7 @@ ${data.message || ""}`.trim();
1788
1788
  this.pendingOutputParseTimer = null;
1789
1789
  }
1790
1790
  this.pendingOutputParseBuffer = "";
1791
+ this.pendingTerminalQueryTail = "";
1791
1792
  if (this.ptyOutputFlushTimer) {
1792
1793
  clearTimeout(this.ptyOutputFlushTimer);
1793
1794
  this.ptyOutputFlushTimer = null;
@@ -1814,7 +1815,6 @@ ${data.message || ""}`.trim();
1814
1815
  this.syncMessageViews();
1815
1816
  this.accumulatedBuffer = "";
1816
1817
  this.accumulatedRawBuffer = "";
1817
- this.terminalHistory = "";
1818
1818
  this.currentTurnScope = null;
1819
1819
  this.submitRetryUsed = false;
1820
1820
  this.submitRetryPromptSnippet = "";
@@ -1823,6 +1823,7 @@ ${data.message || ""}`.trim();
1823
1823
  this.pendingOutputParseTimer = null;
1824
1824
  }
1825
1825
  this.pendingOutputParseBuffer = "";
1826
+ this.pendingTerminalQueryTail = "";
1826
1827
  if (this.ptyOutputFlushTimer) {
1827
1828
  clearTimeout(this.ptyOutputFlushTimer);
1828
1829
  this.ptyOutputFlushTimer = null;
@@ -1884,7 +1885,6 @@ ${data.message || ""}`.trim();
1884
1885
  structuredMessages: this.structuredMessages.slice(-20),
1885
1886
  messageCount: this.committedMessages.length,
1886
1887
  screenText: sanitizeTerminalText(this.terminalScreen.getText()).slice(-4e3),
1887
- terminalHistory: this.terminalHistory.slice(-8e3),
1888
1888
  currentTurnScope: this.currentTurnScope,
1889
1889
  startupBuffer: this.startupBuffer.slice(-4e3),
1890
1890
  recentOutputBuffer: this.recentOutputBuffer.slice(-500),
@@ -1912,6 +1912,20 @@ ${data.message || ""}`.trim();
1912
1912
  ptyAlive: !!this.ptyProcess
1913
1913
  };
1914
1914
  }
1915
+ respondToTerminalQueries(data) {
1916
+ if (!this.ptyProcess || !data) return;
1917
+ const combined = this.pendingTerminalQueryTail + data;
1918
+ const regex = /\x1b\[(\?)?6n/g;
1919
+ let match;
1920
+ while ((match = regex.exec(combined)) !== null) {
1921
+ const cursor = this.terminalScreen.getCursorPosition();
1922
+ const row = Math.max(1, (cursor.row | 0) + 1);
1923
+ const col = Math.max(1, (cursor.col | 0) + 1);
1924
+ const response = match[1] ? `\x1B[?${row};${col}R` : `\x1B[${row};${col}R`;
1925
+ this.ptyProcess.write(response);
1926
+ }
1927
+ this.pendingTerminalQueryTail = computeTerminalQueryTail(combined);
1928
+ }
1915
1929
  };
1916
1930
  }
1917
1931
  });
@@ -1977,6 +1991,7 @@ __export(index_exports, {
1977
1991
  loadConfig: () => loadConfig,
1978
1992
  logCommand: () => logCommand,
1979
1993
  markSetupComplete: () => markSetupComplete,
1994
+ maybeRunDaemonUpgradeHelperFromEnv: () => maybeRunDaemonUpgradeHelperFromEnv,
1980
1995
  normalizeActiveChatData: () => normalizeActiveChatData,
1981
1996
  normalizeManagedStatus: () => normalizeManagedStatus,
1982
1997
  probeCdpPort: () => probeCdpPort,
@@ -2269,18 +2284,18 @@ function checkPathExists(paths) {
2269
2284
  return null;
2270
2285
  }
2271
2286
  async function detectIDEs() {
2272
- const os16 = (0, import_os2.platform)();
2287
+ const os17 = (0, import_os2.platform)();
2273
2288
  const results = [];
2274
2289
  for (const def of getMergedDefinitions()) {
2275
2290
  const cliPath = findCliCommand(def.cli);
2276
- const appPath = checkPathExists(def.paths[os16] || []);
2291
+ const appPath = checkPathExists(def.paths[os17] || []);
2277
2292
  const installed = !!(cliPath || appPath);
2278
2293
  let resolvedCli = cliPath;
2279
- if (!resolvedCli && appPath && os16 === "darwin") {
2294
+ if (!resolvedCli && appPath && os17 === "darwin") {
2280
2295
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
2281
2296
  if ((0, import_fs2.existsSync)(bundledCli)) resolvedCli = bundledCli;
2282
2297
  }
2283
- if (!resolvedCli && appPath && os16 === "win32") {
2298
+ if (!resolvedCli && appPath && os17 === "win32") {
2284
2299
  const { dirname: dirname7 } = await import("path");
2285
2300
  const appDir = dirname7(appPath);
2286
2301
  const candidates = [
@@ -4006,8 +4021,6 @@ var ChatHistoryWriter = class {
4006
4021
  lastSeenCounts = /* @__PURE__ */ new Map();
4007
4022
  /** Last seen message hash per agent (deduplication) */
4008
4023
  lastSeenHashes = /* @__PURE__ */ new Map();
4009
- /** Last seen append-only terminal transcript per agent */
4010
- lastSeenTerminal = /* @__PURE__ */ new Map();
4011
4024
  rotated = false;
4012
4025
  /**
4013
4026
  * Append new messages to history
@@ -4065,51 +4078,10 @@ var ChatHistoryWriter = class {
4065
4078
  } catch {
4066
4079
  }
4067
4080
  }
4068
- appendTerminalHistory(agentType, terminalHistory, sessionTitle, instanceId) {
4069
- const next = String(terminalHistory || "");
4070
- if (!next.trim()) return;
4071
- try {
4072
- const dedupKey = instanceId ? `${agentType}:${instanceId}:terminal` : `${agentType}:terminal`;
4073
- const prev = this.lastSeenTerminal.get(dedupKey) || "";
4074
- if (prev === next) return;
4075
- let delta = "";
4076
- if (!prev) {
4077
- delta = next;
4078
- } else if (next.startsWith(prev)) {
4079
- delta = next.slice(prev.length);
4080
- } else if (prev.includes(next)) {
4081
- this.lastSeenTerminal.set(dedupKey, next);
4082
- return;
4083
- } else {
4084
- delta = `
4085
-
4086
- [terminal snapshot reset ${(/* @__PURE__ */ new Date()).toISOString()} | ${sessionTitle || agentType}]
4087
- ${next}`;
4088
- }
4089
- if (!delta) {
4090
- this.lastSeenTerminal.set(dedupKey, next);
4091
- return;
4092
- }
4093
- const dir = path4.join(HISTORY_DIR, this.sanitize(agentType));
4094
- fs3.mkdirSync(dir, { recursive: true });
4095
- const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
4096
- const filePrefix = instanceId ? `${this.sanitize(instanceId)}_` : "";
4097
- const filePath = path4.join(dir, `${filePrefix}${date}.terminal.log`);
4098
- fs3.appendFileSync(filePath, delta, "utf-8");
4099
- this.lastSeenTerminal.set(dedupKey, next);
4100
- if (!this.rotated) {
4101
- this.rotated = true;
4102
- this.rotateOldFiles().catch(() => {
4103
- });
4104
- }
4105
- } catch {
4106
- }
4107
- }
4108
4081
  /** Called when agent session is explicitly changed */
4109
4082
  onSessionChange(agentType) {
4110
4083
  this.lastSeenHashes.delete(agentType);
4111
4084
  this.lastSeenCounts.delete(agentType);
4112
- this.lastSeenTerminal.delete(`${agentType}:terminal`);
4113
4085
  }
4114
4086
  /** Delete history files older than 30 days */
4115
4087
  async rotateOldFiles() {
@@ -4962,7 +4934,6 @@ var STATUS_ACTIVE_CHAT_MESSAGE_LIMIT = 60;
4962
4934
  var STATUS_ACTIVE_CHAT_TOTAL_BYTES_LIMIT = 96 * 1024;
4963
4935
  var STATUS_ACTIVE_CHAT_STRING_LIMIT = 4 * 1024;
4964
4936
  var STATUS_ACTIVE_CHAT_FALLBACK_STRING_LIMIT = 1024;
4965
- var STATUS_TERMINAL_HISTORY_LIMIT = 8 * 1024;
4966
4937
  var STATUS_INPUT_CONTENT_LIMIT = 2 * 1024;
4967
4938
  var STATUS_MODAL_MESSAGE_LIMIT = 2 * 1024;
4968
4939
  var STATUS_MODAL_BUTTON_LIMIT = 120;
@@ -4971,11 +4942,6 @@ function truncateString(value, maxChars) {
4971
4942
  if (maxChars <= 12) return value.slice(0, Math.max(0, maxChars));
4972
4943
  return `${value.slice(0, maxChars - 12)}...[truncated]`;
4973
4944
  }
4974
- function truncateStringTail(value, maxChars) {
4975
- if (value.length <= maxChars) return value;
4976
- if (maxChars <= 12) return value.slice(value.length - Math.max(0, maxChars));
4977
- return `...[truncated]${value.slice(value.length - (maxChars - 12))}`;
4978
- }
4979
4945
  function trimStructuredStrings(value, maxChars) {
4980
4946
  if (typeof value === "string") return truncateString(value, maxChars);
4981
4947
  if (Array.isArray(value)) return value.map((item) => trimStructuredStrings(item, maxChars));
@@ -5049,7 +5015,6 @@ function normalizeActiveChatData(activeChat) {
5049
5015
  (button) => truncateString(String(button || ""), STATUS_MODAL_BUTTON_LIMIT)
5050
5016
  )
5051
5017
  } : activeChat.activeModal,
5052
- terminalHistory: activeChat.terminalHistory ? truncateStringTail(activeChat.terminalHistory, STATUS_TERMINAL_HISTORY_LIMIT) : activeChat.terminalHistory,
5053
5018
  inputContent: activeChat.inputContent ? truncateString(activeChat.inputContent, STATUS_INPUT_CONTENT_LIMIT) : activeChat.inputContent
5054
5019
  };
5055
5020
  }
@@ -8349,7 +8314,7 @@ function detectCurrentWorkspace(ideId) {
8349
8314
  }
8350
8315
  } else if (plat === "win32") {
8351
8316
  try {
8352
- const fs12 = require("fs");
8317
+ const fs13 = require("fs");
8353
8318
  const appNameMap = getMacAppIdentifiers();
8354
8319
  const appName = appNameMap[ideId];
8355
8320
  if (appName) {
@@ -8358,8 +8323,8 @@ function detectCurrentWorkspace(ideId) {
8358
8323
  appName,
8359
8324
  "storage.json"
8360
8325
  );
8361
- if (fs12.existsSync(storagePath)) {
8362
- const data = JSON.parse(fs12.readFileSync(storagePath, "utf-8"));
8326
+ if (fs13.existsSync(storagePath)) {
8327
+ const data = JSON.parse(fs13.readFileSync(storagePath, "utf-8"));
8363
8328
  const workspaces = data?.openedPathsList?.workspaces3 || data?.openedPathsList?.entries || [];
8364
8329
  if (workspaces.length > 0) {
8365
8330
  const recent = workspaces[0];
@@ -8804,8 +8769,191 @@ function buildStatusSnapshot(options) {
8804
8769
  };
8805
8770
  }
8806
8771
 
8807
- // src/commands/router.ts
8772
+ // src/commands/upgrade-helper.ts
8773
+ var import_child_process5 = require("child_process");
8774
+ var import_child_process6 = require("child_process");
8808
8775
  var fs7 = __toESM(require("fs"));
8776
+ var os11 = __toESM(require("os"));
8777
+ var path9 = __toESM(require("path"));
8778
+ var UPGRADE_HELPER_ENV = "ADHDEV_DAEMON_UPGRADE_HELPER";
8779
+ function getUpgradeLogPath() {
8780
+ const home = os11.homedir();
8781
+ const dir = path9.join(home, ".adhdev");
8782
+ fs7.mkdirSync(dir, { recursive: true });
8783
+ return path9.join(dir, "daemon-upgrade.log");
8784
+ }
8785
+ function appendUpgradeLog(message) {
8786
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
8787
+ `;
8788
+ try {
8789
+ fs7.appendFileSync(getUpgradeLogPath(), line, "utf8");
8790
+ } catch {
8791
+ }
8792
+ }
8793
+ function getNpmExecutable() {
8794
+ return process.platform === "win32" ? "npm.cmd" : "npm";
8795
+ }
8796
+ function killPid(pid) {
8797
+ try {
8798
+ if (process.platform === "win32") {
8799
+ (0, import_child_process5.execFileSync)("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore" });
8800
+ } else {
8801
+ process.kill(pid, "SIGTERM");
8802
+ }
8803
+ return true;
8804
+ } catch {
8805
+ return false;
8806
+ }
8807
+ }
8808
+ async function waitForPidExit(pid, timeoutMs) {
8809
+ const start = Date.now();
8810
+ while (Date.now() - start < timeoutMs) {
8811
+ try {
8812
+ process.kill(pid, 0);
8813
+ await new Promise((resolve9) => setTimeout(resolve9, 250));
8814
+ } catch {
8815
+ return;
8816
+ }
8817
+ }
8818
+ }
8819
+ function stopSessionHostProcesses(appName) {
8820
+ const pidFile = path9.join(os11.homedir(), ".adhdev", `${appName}-session-host.pid`);
8821
+ try {
8822
+ if (fs7.existsSync(pidFile)) {
8823
+ const pid = Number.parseInt(fs7.readFileSync(pidFile, "utf8").trim(), 10);
8824
+ if (Number.isFinite(pid)) {
8825
+ killPid(pid);
8826
+ }
8827
+ }
8828
+ } catch {
8829
+ } finally {
8830
+ try {
8831
+ fs7.unlinkSync(pidFile);
8832
+ } catch {
8833
+ }
8834
+ }
8835
+ if (process.platform !== "win32") {
8836
+ try {
8837
+ const raw = (0, import_child_process5.execFileSync)("pgrep", ["-f", "session-host-daemon"], { encoding: "utf8" }).trim();
8838
+ for (const line of raw.split("\n")) {
8839
+ const pid = Number.parseInt(line.trim(), 10);
8840
+ if (Number.isFinite(pid)) {
8841
+ killPid(pid);
8842
+ }
8843
+ }
8844
+ } catch {
8845
+ }
8846
+ }
8847
+ }
8848
+ function removeDaemonPidFile() {
8849
+ const pidFile = path9.join(os11.homedir(), ".adhdev", "daemon.pid");
8850
+ try {
8851
+ fs7.unlinkSync(pidFile);
8852
+ } catch {
8853
+ }
8854
+ }
8855
+ function cleanupStaleGlobalInstallDirs(pkgName) {
8856
+ const npmRoot = (0, import_child_process5.execFileSync)(getNpmExecutable(), ["root", "-g"], { encoding: "utf8" }).trim();
8857
+ if (!npmRoot) return;
8858
+ const npmPrefix = (0, import_child_process5.execFileSync)(getNpmExecutable(), ["prefix", "-g"], { encoding: "utf8" }).trim();
8859
+ const binDir = process.platform === "win32" ? npmPrefix : path9.join(npmPrefix, "bin");
8860
+ const packageBaseName = pkgName.startsWith("@") ? pkgName.split("/")[1] : pkgName;
8861
+ const binNames = /* @__PURE__ */ new Set([packageBaseName]);
8862
+ if (pkgName === "@adhdev/daemon-standalone") {
8863
+ binNames.add("adhdev-standalone");
8864
+ }
8865
+ if (pkgName.startsWith("@")) {
8866
+ const [scope, name] = pkgName.split("/");
8867
+ const scopeDir = path9.join(npmRoot, scope);
8868
+ if (!fs7.existsSync(scopeDir)) return;
8869
+ for (const entry of fs7.readdirSync(scopeDir)) {
8870
+ if (!entry.startsWith(`.${name}-`)) continue;
8871
+ fs7.rmSync(path9.join(scopeDir, entry), { recursive: true, force: true });
8872
+ appendUpgradeLog(`Removed stale scoped staging dir: ${path9.join(scopeDir, entry)}`);
8873
+ }
8874
+ } else {
8875
+ for (const entry of fs7.readdirSync(npmRoot)) {
8876
+ if (!entry.startsWith(`.${pkgName}-`)) continue;
8877
+ fs7.rmSync(path9.join(npmRoot, entry), { recursive: true, force: true });
8878
+ appendUpgradeLog(`Removed stale staging dir: ${path9.join(npmRoot, entry)}`);
8879
+ }
8880
+ }
8881
+ if (fs7.existsSync(binDir)) {
8882
+ for (const entry of fs7.readdirSync(binDir)) {
8883
+ if (![...binNames].some((name) => entry.startsWith(`.${name}-`))) continue;
8884
+ fs7.rmSync(path9.join(binDir, entry), { recursive: true, force: true });
8885
+ appendUpgradeLog(`Removed stale bin staging entry: ${path9.join(binDir, entry)}`);
8886
+ }
8887
+ }
8888
+ }
8889
+ function spawnDetachedDaemonUpgradeHelper(payload) {
8890
+ const env = { ...process.env, [UPGRADE_HELPER_ENV]: JSON.stringify(payload) };
8891
+ const child = (0, import_child_process6.spawn)(process.execPath, process.argv.slice(1), {
8892
+ detached: true,
8893
+ stdio: "ignore",
8894
+ windowsHide: true,
8895
+ cwd: payload.cwd || process.cwd(),
8896
+ env
8897
+ });
8898
+ child.unref();
8899
+ }
8900
+ async function runDaemonUpgradeHelper(payload) {
8901
+ const restartArgv = Array.isArray(payload.restartArgv) ? payload.restartArgv : [];
8902
+ const sessionHostAppName = payload.sessionHostAppName || process.env.ADHDEV_SESSION_HOST_NAME || "adhdev";
8903
+ appendUpgradeLog(`Upgrade helper started for ${payload.packageName}@${payload.targetVersion}`);
8904
+ if (Number.isFinite(payload.parentPid) && payload.parentPid > 0) {
8905
+ appendUpgradeLog(`Waiting for parent pid ${payload.parentPid} to exit`);
8906
+ await waitForPidExit(payload.parentPid, 15e3);
8907
+ }
8908
+ stopSessionHostProcesses(sessionHostAppName);
8909
+ removeDaemonPidFile();
8910
+ cleanupStaleGlobalInstallDirs(payload.packageName);
8911
+ const spec = `${payload.packageName}@${payload.targetVersion || "latest"}`;
8912
+ appendUpgradeLog(`Installing ${spec}`);
8913
+ const installOutput = (0, import_child_process5.execFileSync)(
8914
+ getNpmExecutable(),
8915
+ ["install", "-g", spec, "--force"],
8916
+ {
8917
+ encoding: "utf8",
8918
+ stdio: "pipe",
8919
+ maxBuffer: 20 * 1024 * 1024
8920
+ }
8921
+ );
8922
+ if (installOutput.trim()) {
8923
+ appendUpgradeLog(installOutput.trim());
8924
+ }
8925
+ if (restartArgv.length > 0) {
8926
+ const env = { ...process.env };
8927
+ delete env[UPGRADE_HELPER_ENV];
8928
+ appendUpgradeLog(`Restarting daemon with args: ${restartArgv.join(" ")}`);
8929
+ const child = (0, import_child_process6.spawn)(process.execPath, restartArgv, {
8930
+ detached: true,
8931
+ stdio: "ignore",
8932
+ windowsHide: true,
8933
+ cwd: payload.cwd || process.cwd(),
8934
+ env
8935
+ });
8936
+ child.unref();
8937
+ } else {
8938
+ appendUpgradeLog("No restart argv provided; upgrade completed without restart");
8939
+ }
8940
+ }
8941
+ async function maybeRunDaemonUpgradeHelperFromEnv() {
8942
+ const raw = process.env[UPGRADE_HELPER_ENV];
8943
+ if (!raw) return false;
8944
+ delete process.env[UPGRADE_HELPER_ENV];
8945
+ try {
8946
+ const payload = JSON.parse(raw);
8947
+ await runDaemonUpgradeHelper(payload);
8948
+ process.exit(0);
8949
+ } catch (error) {
8950
+ appendUpgradeLog(`Upgrade helper failed: ${error?.stack || error?.message || String(error)}`);
8951
+ process.exit(1);
8952
+ }
8953
+ }
8954
+
8955
+ // src/commands/router.ts
8956
+ var fs8 = __toESM(require("fs"));
8809
8957
  var CHAT_COMMANDS = [
8810
8958
  "send_chat",
8811
8959
  "new_chat",
@@ -8876,8 +9024,8 @@ var DaemonCommandRouter = class {
8876
9024
  if (logs.length > 0) {
8877
9025
  return { success: true, logs, totalBuffered: logs.length };
8878
9026
  }
8879
- if (fs7.existsSync(LOG_PATH)) {
8880
- const content = fs7.readFileSync(LOG_PATH, "utf-8");
9027
+ if (fs8.existsSync(LOG_PATH)) {
9028
+ const content = fs8.readFileSync(LOG_PATH, "utf-8");
8881
9029
  const allLines = content.split("\n");
8882
9030
  const recent = allLines.slice(-count).join("\n");
8883
9031
  return { success: true, logs: recent, totalLines: allLines.length };
@@ -9025,31 +9173,35 @@ var DaemonCommandRouter = class {
9025
9173
  const pkgName = isStandalone ? "@adhdev/daemon-standalone" : "adhdev";
9026
9174
  const latest = execSync7(`npm view ${pkgName} version`, { encoding: "utf-8", timeout: 1e4 }).trim();
9027
9175
  LOG.info("Upgrade", `Latest ${pkgName}: v${latest}`);
9028
- execSync7(`npm install -g ${pkgName}@latest --force`, {
9029
- encoding: "utf-8",
9030
- timeout: 12e4,
9031
- stdio: ["pipe", "pipe", "pipe"]
9176
+ let currentInstalled = null;
9177
+ try {
9178
+ const currentJson = execSync7(`npm ls -g ${pkgName} --depth=0 --json`, {
9179
+ encoding: "utf-8",
9180
+ timeout: 1e4,
9181
+ stdio: ["pipe", "pipe", "pipe"]
9182
+ }).trim();
9183
+ const parsed = JSON.parse(currentJson);
9184
+ currentInstalled = parsed?.dependencies?.[pkgName]?.version || null;
9185
+ } catch {
9186
+ }
9187
+ if (currentInstalled === latest) {
9188
+ LOG.info("Upgrade", `Already on latest version v${latest}; skipping install`);
9189
+ return { success: true, upgraded: false, alreadyLatest: true, version: latest };
9190
+ }
9191
+ spawnDetachedDaemonUpgradeHelper({
9192
+ packageName: pkgName,
9193
+ targetVersion: latest,
9194
+ parentPid: process.pid,
9195
+ restartArgv: process.argv.slice(1),
9196
+ cwd: process.cwd(),
9197
+ sessionHostAppName: process.env.ADHDEV_SESSION_HOST_NAME || "adhdev"
9032
9198
  });
9033
- LOG.info("Upgrade", `\u2705 Upgraded to v${latest}`);
9199
+ LOG.info("Upgrade", `Scheduled detached upgrade to v${latest}`);
9034
9200
  setTimeout(() => {
9035
- LOG.info("Upgrade", "Restarting daemon with new version...");
9036
- try {
9037
- const path15 = require("path");
9038
- const fs12 = require("fs");
9039
- const pidFile = path15.join(process.env.HOME || process.env.USERPROFILE || "", ".adhdev", "daemon.pid");
9040
- if (fs12.existsSync(pidFile)) fs12.unlinkSync(pidFile);
9041
- } catch {
9042
- }
9043
- const { spawn: spawn3 } = require("child_process");
9044
- const child = spawn3(process.execPath, process.argv.slice(1), {
9045
- detached: true,
9046
- stdio: "ignore",
9047
- env: { ...process.env }
9048
- });
9049
- child.unref();
9201
+ LOG.info("Upgrade", "Exiting daemon so detached upgrader can continue...");
9050
9202
  process.exit(0);
9051
9203
  }, 3e3);
9052
- return { success: true, upgraded: true, version: latest };
9204
+ return { success: true, upgraded: true, version: latest, restarting: true };
9053
9205
  } catch (e) {
9054
9206
  LOG.error("Upgrade", `Failed: ${e.message}`);
9055
9207
  return { success: false, error: e.message };
@@ -9345,8 +9497,8 @@ var DaemonStatusReporter = class {
9345
9497
  init_logger();
9346
9498
 
9347
9499
  // src/commands/cli-manager.ts
9348
- var os13 = __toESM(require("os"));
9349
- var path10 = __toESM(require("path"));
9500
+ var os14 = __toESM(require("os"));
9501
+ var path11 = __toESM(require("path"));
9350
9502
  var crypto4 = __toESM(require("crypto"));
9351
9503
  var import_chalk = __toESM(require("chalk"));
9352
9504
  init_provider_cli_adapter();
@@ -9363,7 +9515,7 @@ var CliProviderInstance = class {
9363
9515
  this.cliArgs = cliArgs;
9364
9516
  this.type = provider.type;
9365
9517
  this.instanceId = instanceId || crypto3.randomUUID();
9366
- this.presentationMode = "terminal";
9518
+ this.presentationMode = "chat";
9367
9519
  this.adapter = new ProviderCliAdapter(provider, workingDir, cliArgs, transportFactory);
9368
9520
  this.monitor = new StatusMonitor();
9369
9521
  this.historyWriter = new ChatHistoryWriter();
@@ -9410,14 +9562,6 @@ var CliProviderInstance = class {
9410
9562
  const parsedStatus = this.adapter.getScriptParsedStatus?.() || null;
9411
9563
  const runtime = this.adapter.getRuntimeMetadata();
9412
9564
  const dirName = this.workingDir.split("/").filter(Boolean).pop() || "session";
9413
- if (adapterStatus.terminalHistory?.trim()) {
9414
- this.historyWriter.appendTerminalHistory(
9415
- this.type,
9416
- adapterStatus.terminalHistory,
9417
- `${this.provider.name} \xB7 ${dirName}`,
9418
- this.instanceId
9419
- );
9420
- }
9421
9565
  return {
9422
9566
  type: this.type,
9423
9567
  name: this.provider.name,
@@ -9430,7 +9574,6 @@ var CliProviderInstance = class {
9430
9574
  status: parsedStatus?.status || adapterStatus.status,
9431
9575
  messages: Array.isArray(parsedStatus?.messages) ? parsedStatus.messages : [],
9432
9576
  activeModal: parsedStatus?.activeModal ?? adapterStatus.activeModal,
9433
- terminalHistory: adapterStatus.terminalHistory,
9434
9577
  inputContent: ""
9435
9578
  },
9436
9579
  workspace: this.workingDir,
@@ -9602,7 +9745,7 @@ var CliProviderInstance = class {
9602
9745
 
9603
9746
  // src/providers/acp-provider-instance.ts
9604
9747
  var import_stream = require("stream");
9605
- var import_child_process6 = require("child_process");
9748
+ var import_child_process8 = require("child_process");
9606
9749
  var import_sdk = require("@agentclientprotocol/sdk");
9607
9750
 
9608
9751
  // src/providers/contracts.ts
@@ -9932,7 +10075,7 @@ var AcpProviderInstance = class {
9932
10075
  this.errorMessage = null;
9933
10076
  this.errorReason = null;
9934
10077
  this.stderrBuffer = [];
9935
- this.process = (0, import_child_process6.spawn)(command, args, {
10078
+ this.process = (0, import_child_process8.spawn)(command, args, {
9936
10079
  cwd: this.workingDir,
9937
10080
  env,
9938
10081
  stdio: ["pipe", "pipe", "pipe"],
@@ -10615,7 +10758,7 @@ var DaemonCliManager = class {
10615
10758
  async startSession(cliType, workingDir, cliArgs, initialModel) {
10616
10759
  const trimmed = (workingDir || "").trim();
10617
10760
  if (!trimmed) throw new Error("working directory required");
10618
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os13.homedir()) : path10.resolve(trimmed);
10761
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os14.homedir()) : path11.resolve(trimmed);
10619
10762
  const normalizedType = this.providerLoader.resolveAlias(cliType);
10620
10763
  const provider = this.providerLoader.getByAlias(cliType);
10621
10764
  const key = crypto4.randomUUID();
@@ -11812,12 +11955,12 @@ var ProviderInstanceManager = class {
11812
11955
  };
11813
11956
 
11814
11957
  // src/providers/version-archive.ts
11815
- var fs8 = __toESM(require("fs"));
11816
- var path11 = __toESM(require("path"));
11817
- var os14 = __toESM(require("os"));
11818
- var import_child_process7 = require("child_process");
11958
+ var fs9 = __toESM(require("fs"));
11959
+ var path12 = __toESM(require("path"));
11960
+ var os15 = __toESM(require("os"));
11961
+ var import_child_process9 = require("child_process");
11819
11962
  var import_os3 = require("os");
11820
- var ARCHIVE_PATH = path11.join(os14.homedir(), ".adhdev", "version-history.json");
11963
+ var ARCHIVE_PATH = path12.join(os15.homedir(), ".adhdev", "version-history.json");
11821
11964
  var MAX_ENTRIES_PER_PROVIDER = 20;
11822
11965
  var VersionArchive = class {
11823
11966
  history = {};
@@ -11826,8 +11969,8 @@ var VersionArchive = class {
11826
11969
  }
11827
11970
  load() {
11828
11971
  try {
11829
- if (fs8.existsSync(ARCHIVE_PATH)) {
11830
- this.history = JSON.parse(fs8.readFileSync(ARCHIVE_PATH, "utf-8"));
11972
+ if (fs9.existsSync(ARCHIVE_PATH)) {
11973
+ this.history = JSON.parse(fs9.readFileSync(ARCHIVE_PATH, "utf-8"));
11831
11974
  }
11832
11975
  } catch {
11833
11976
  this.history = {};
@@ -11864,15 +12007,15 @@ var VersionArchive = class {
11864
12007
  }
11865
12008
  save() {
11866
12009
  try {
11867
- fs8.mkdirSync(path11.dirname(ARCHIVE_PATH), { recursive: true });
11868
- fs8.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
12010
+ fs9.mkdirSync(path12.dirname(ARCHIVE_PATH), { recursive: true });
12011
+ fs9.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
11869
12012
  } catch {
11870
12013
  }
11871
12014
  }
11872
12015
  };
11873
12016
  function runCommand(cmd, timeout = 1e4) {
11874
12017
  try {
11875
- return (0, import_child_process7.execSync)(cmd, {
12018
+ return (0, import_child_process9.execSync)(cmd, {
11876
12019
  encoding: "utf-8",
11877
12020
  timeout,
11878
12021
  stdio: ["pipe", "pipe", "pipe"]
@@ -11904,19 +12047,19 @@ function getVersion(binary, versionCommand) {
11904
12047
  function checkPathExists2(paths) {
11905
12048
  for (const p of paths) {
11906
12049
  if (p.includes("*")) {
11907
- const home = os14.homedir();
11908
- const resolved = p.replace(/\*/g, home.split(path11.sep).pop() || "");
11909
- if (fs8.existsSync(resolved)) return resolved;
12050
+ const home = os15.homedir();
12051
+ const resolved = p.replace(/\*/g, home.split(path12.sep).pop() || "");
12052
+ if (fs9.existsSync(resolved)) return resolved;
11910
12053
  } else {
11911
- if (fs8.existsSync(p)) return p;
12054
+ if (fs9.existsSync(p)) return p;
11912
12055
  }
11913
12056
  }
11914
12057
  return null;
11915
12058
  }
11916
12059
  function getMacAppVersion(appPath) {
11917
12060
  if ((0, import_os3.platform)() !== "darwin" || !appPath.endsWith(".app")) return null;
11918
- const plistPath = path11.join(appPath, "Contents", "Info.plist");
11919
- if (!fs8.existsSync(plistPath)) return null;
12061
+ const plistPath = path12.join(appPath, "Contents", "Info.plist");
12062
+ if (!fs9.existsSync(plistPath)) return null;
11920
12063
  const raw = runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
11921
12064
  return raw || null;
11922
12065
  }
@@ -11942,8 +12085,8 @@ async function detectAllVersions(loader, archive) {
11942
12085
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
11943
12086
  let resolvedBin = cliBin;
11944
12087
  if (!resolvedBin && appPath && currentOs === "darwin") {
11945
- const bundled = path11.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
11946
- if (provider.cli && fs8.existsSync(bundled)) resolvedBin = bundled;
12088
+ const bundled = path12.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
12089
+ if (provider.cli && fs9.existsSync(bundled)) resolvedBin = bundled;
11947
12090
  }
11948
12091
  info.installed = !!(appPath || resolvedBin);
11949
12092
  info.path = appPath || null;
@@ -11982,8 +12125,8 @@ async function detectAllVersions(loader, archive) {
11982
12125
 
11983
12126
  // src/daemon/dev-server.ts
11984
12127
  var http2 = __toESM(require("http"));
11985
- var fs11 = __toESM(require("fs"));
11986
- var path14 = __toESM(require("path"));
12128
+ var fs12 = __toESM(require("fs"));
12129
+ var path15 = __toESM(require("path"));
11987
12130
 
11988
12131
  // src/daemon/scaffold-template.ts
11989
12132
  function generateFiles(type, name, category, opts = {}) {
@@ -12318,8 +12461,8 @@ async (params) => {
12318
12461
  init_logger();
12319
12462
 
12320
12463
  // src/daemon/dev-cdp-handlers.ts
12321
- var fs9 = __toESM(require("fs"));
12322
- var path12 = __toESM(require("path"));
12464
+ var fs10 = __toESM(require("fs"));
12465
+ var path13 = __toESM(require("path"));
12323
12466
  init_logger();
12324
12467
  async function handleCdpEvaluate(ctx, req, res) {
12325
12468
  const body = await ctx.readBody(req);
@@ -12498,18 +12641,18 @@ async function handleScriptHints(ctx, type, _req, res) {
12498
12641
  return;
12499
12642
  }
12500
12643
  let scriptsPath = "";
12501
- const directScripts = path12.join(dir, "scripts.js");
12502
- if (fs9.existsSync(directScripts)) {
12644
+ const directScripts = path13.join(dir, "scripts.js");
12645
+ if (fs10.existsSync(directScripts)) {
12503
12646
  scriptsPath = directScripts;
12504
12647
  } else {
12505
- const scriptsDir = path12.join(dir, "scripts");
12506
- if (fs9.existsSync(scriptsDir)) {
12507
- const versions = fs9.readdirSync(scriptsDir).filter((d) => {
12508
- return fs9.statSync(path12.join(scriptsDir, d)).isDirectory();
12648
+ const scriptsDir = path13.join(dir, "scripts");
12649
+ if (fs10.existsSync(scriptsDir)) {
12650
+ const versions = fs10.readdirSync(scriptsDir).filter((d) => {
12651
+ return fs10.statSync(path13.join(scriptsDir, d)).isDirectory();
12509
12652
  }).sort().reverse();
12510
12653
  for (const ver of versions) {
12511
- const p = path12.join(scriptsDir, ver, "scripts.js");
12512
- if (fs9.existsSync(p)) {
12654
+ const p = path13.join(scriptsDir, ver, "scripts.js");
12655
+ if (fs10.existsSync(p)) {
12513
12656
  scriptsPath = p;
12514
12657
  break;
12515
12658
  }
@@ -12521,7 +12664,7 @@ async function handleScriptHints(ctx, type, _req, res) {
12521
12664
  return;
12522
12665
  }
12523
12666
  try {
12524
- const source = fs9.readFileSync(scriptsPath, "utf-8");
12667
+ const source = fs10.readFileSync(scriptsPath, "utf-8");
12525
12668
  const hints = {};
12526
12669
  const funcRegex = /module\.exports\.(\w+)\s*=\s*function\s+\w+\s*\(params\)/g;
12527
12670
  let match;
@@ -13562,9 +13705,9 @@ async function handleCliRaw(ctx, req, res) {
13562
13705
  }
13563
13706
 
13564
13707
  // src/daemon/dev-auto-implement.ts
13565
- var fs10 = __toESM(require("fs"));
13566
- var path13 = __toESM(require("path"));
13567
- var os15 = __toESM(require("os"));
13708
+ var fs11 = __toESM(require("fs"));
13709
+ var path14 = __toESM(require("path"));
13710
+ var os16 = __toESM(require("os"));
13568
13711
  function getDefaultAutoImplReference(ctx, category, type) {
13569
13712
  if (category === "cli") {
13570
13713
  return type === "codex-cli" ? "claude-cli" : "codex-cli";
@@ -13580,45 +13723,45 @@ function resolveAutoImplReference(ctx, category, requestedReference, targetType)
13580
13723
  return fallback?.type || null;
13581
13724
  }
13582
13725
  function getLatestScriptVersionDir(scriptsDir) {
13583
- if (!fs10.existsSync(scriptsDir)) return null;
13584
- const versions = fs10.readdirSync(scriptsDir).filter((d) => {
13726
+ if (!fs11.existsSync(scriptsDir)) return null;
13727
+ const versions = fs11.readdirSync(scriptsDir).filter((d) => {
13585
13728
  try {
13586
- return fs10.statSync(path13.join(scriptsDir, d)).isDirectory();
13729
+ return fs11.statSync(path14.join(scriptsDir, d)).isDirectory();
13587
13730
  } catch {
13588
13731
  return false;
13589
13732
  }
13590
13733
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
13591
13734
  if (versions.length === 0) return null;
13592
- return path13.join(scriptsDir, versions[0]);
13735
+ return path14.join(scriptsDir, versions[0]);
13593
13736
  }
13594
13737
  function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
13595
- const canonicalUserDir = path13.resolve(ctx.providerLoader.getUserProviderDir(category, type));
13596
- const desiredDir = requestedDir ? path13.resolve(requestedDir) : canonicalUserDir;
13597
- const upstreamRoot = path13.resolve(ctx.providerLoader.getUpstreamDir());
13598
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path13.sep}`)) {
13738
+ const canonicalUserDir = path14.resolve(ctx.providerLoader.getUserProviderDir(category, type));
13739
+ const desiredDir = requestedDir ? path14.resolve(requestedDir) : canonicalUserDir;
13740
+ const upstreamRoot = path14.resolve(ctx.providerLoader.getUpstreamDir());
13741
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path14.sep}`)) {
13599
13742
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
13600
13743
  }
13601
- if (path13.basename(desiredDir) !== type) {
13744
+ if (path14.basename(desiredDir) !== type) {
13602
13745
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
13603
13746
  }
13604
13747
  const sourceDir = ctx.findProviderDir(type);
13605
13748
  if (!sourceDir) {
13606
13749
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
13607
13750
  }
13608
- if (!fs10.existsSync(desiredDir)) {
13609
- fs10.mkdirSync(path13.dirname(desiredDir), { recursive: true });
13610
- fs10.cpSync(sourceDir, desiredDir, { recursive: true });
13751
+ if (!fs11.existsSync(desiredDir)) {
13752
+ fs11.mkdirSync(path14.dirname(desiredDir), { recursive: true });
13753
+ fs11.cpSync(sourceDir, desiredDir, { recursive: true });
13611
13754
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
13612
13755
  }
13613
- const providerJson = path13.join(desiredDir, "provider.json");
13614
- if (!fs10.existsSync(providerJson)) {
13756
+ const providerJson = path14.join(desiredDir, "provider.json");
13757
+ if (!fs11.existsSync(providerJson)) {
13615
13758
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
13616
13759
  }
13617
13760
  try {
13618
- const providerData = JSON.parse(fs10.readFileSync(providerJson, "utf-8"));
13761
+ const providerData = JSON.parse(fs11.readFileSync(providerJson, "utf-8"));
13619
13762
  if (providerData.disableUpstream !== true) {
13620
13763
  providerData.disableUpstream = true;
13621
- fs10.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
13764
+ fs11.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
13622
13765
  }
13623
13766
  } catch (error) {
13624
13767
  return {
@@ -13631,15 +13774,15 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
13631
13774
  function loadAutoImplReferenceScripts(ctx, referenceType) {
13632
13775
  if (!referenceType) return {};
13633
13776
  const refDir = ctx.findProviderDir(referenceType);
13634
- if (!refDir || !fs10.existsSync(refDir)) return {};
13777
+ if (!refDir || !fs11.existsSync(refDir)) return {};
13635
13778
  const referenceScripts = {};
13636
- const scriptsDir = path13.join(refDir, "scripts");
13779
+ const scriptsDir = path14.join(refDir, "scripts");
13637
13780
  const latestDir = getLatestScriptVersionDir(scriptsDir);
13638
13781
  if (!latestDir) return referenceScripts;
13639
- for (const file of fs10.readdirSync(latestDir)) {
13782
+ for (const file of fs11.readdirSync(latestDir)) {
13640
13783
  if (!file.endsWith(".js")) continue;
13641
13784
  try {
13642
- referenceScripts[file] = fs10.readFileSync(path13.join(latestDir, file), "utf-8");
13785
+ referenceScripts[file] = fs11.readFileSync(path14.join(latestDir, file), "utf-8");
13643
13786
  } catch {
13644
13787
  }
13645
13788
  }
@@ -13690,16 +13833,16 @@ async function handleAutoImplement(ctx, type, req, res) {
13690
13833
  });
13691
13834
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
13692
13835
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference);
13693
- const tmpDir = path13.join(os15.tmpdir(), "adhdev-autoimpl");
13694
- if (!fs10.existsSync(tmpDir)) fs10.mkdirSync(tmpDir, { recursive: true });
13695
- const promptFile = path13.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
13696
- fs10.writeFileSync(promptFile, prompt, "utf-8");
13836
+ const tmpDir = path14.join(os16.tmpdir(), "adhdev-autoimpl");
13837
+ if (!fs11.existsSync(tmpDir)) fs11.mkdirSync(tmpDir, { recursive: true });
13838
+ const promptFile = path14.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
13839
+ fs11.writeFileSync(promptFile, prompt, "utf-8");
13697
13840
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
13698
13841
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
13699
- const spawn3 = agentProvider?.spawn;
13700
- if (!spawn3?.command) {
13842
+ const spawn4 = agentProvider?.spawn;
13843
+ if (!spawn4?.command) {
13701
13844
  try {
13702
- fs10.unlinkSync(promptFile);
13845
+ fs11.unlinkSync(promptFile);
13703
13846
  } catch {
13704
13847
  }
13705
13848
  ctx.json(res, 400, { error: `Agent '${agent}' has no spawn config. Select a CLI provider with a spawn configuration.` });
@@ -13707,21 +13850,21 @@ async function handleAutoImplement(ctx, type, req, res) {
13707
13850
  }
13708
13851
  const agentCategory = agentProvider?.category;
13709
13852
  if (agentCategory === "acp") {
13710
- sendAutoImplSSE(ctx, { event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn3.command} ${(spawn3.args || []).join(" ")}` } });
13853
+ sendAutoImplSSE(ctx, { event: "progress", data: { function: "_init", status: "spawning", message: `Spawning ACP agent: ${spawn4.command} ${(spawn4.args || []).join(" ")}` } });
13711
13854
  ctx.autoImplStatus = { running: true, type, progress: [] };
13712
13855
  const { ClientSideConnection: ClientSideConnection2, ndJsonStream: ndJsonStream2, PROTOCOL_VERSION: PROTOCOL_VERSION2 } = await import("@agentclientprotocol/sdk");
13713
13856
  const { Readable: Readable2, Writable: Writable2 } = await import("stream");
13714
13857
  const { spawn: spawnFn2 } = await import("child_process");
13715
- const acpArgs = [...spawn3.args || []];
13858
+ const acpArgs = [...spawn4.args || []];
13716
13859
  if (model) {
13717
13860
  acpArgs.push("--model", model);
13718
13861
  ctx.log(`Auto-implement ACP using model: ${model}`);
13719
13862
  }
13720
- const child2 = spawnFn2(spawn3.command, acpArgs, {
13863
+ const child2 = spawnFn2(spawn4.command, acpArgs, {
13721
13864
  cwd: providerDir,
13722
13865
  stdio: ["pipe", "pipe", "pipe"],
13723
- shell: spawn3.shell ?? false,
13724
- env: { ...process.env, ...spawn3.env || {} }
13866
+ shell: spawn4.shell ?? false,
13867
+ env: { ...process.env, ...spawn4.env || {} }
13725
13868
  });
13726
13869
  ctx.autoImplProcess = child2;
13727
13870
  child2.stderr?.on("data", (d) => {
@@ -13800,7 +13943,7 @@ async function handleAutoImplement(ctx, type, req, res) {
13800
13943
  } catch {
13801
13944
  }
13802
13945
  try {
13803
- fs10.unlinkSync(promptFile);
13946
+ fs11.unlinkSync(promptFile);
13804
13947
  } catch {
13805
13948
  }
13806
13949
  ctx.log(`Auto-implement (ACP) ${success ? "completed" : "failed"}: ${type} (exit: ${code})`);
@@ -13831,7 +13974,7 @@ async function handleAutoImplement(ctx, type, req, res) {
13831
13974
  ctx.json(res, 202, {
13832
13975
  started: true,
13833
13976
  type,
13834
- agent: spawn3.command,
13977
+ agent: spawn4.command,
13835
13978
  functions,
13836
13979
  providerDir,
13837
13980
  message: "ACP Auto-implement started. Connect to SSE for progress.",
@@ -13839,11 +13982,11 @@ async function handleAutoImplement(ctx, type, req, res) {
13839
13982
  });
13840
13983
  return;
13841
13984
  }
13842
- const command = spawn3.command;
13985
+ const command = spawn4.command;
13843
13986
  const interactiveFlags = ["--yolo", "--interactive", "-i"];
13844
- const baseArgs = [...spawn3.args || []].filter((a) => !interactiveFlags.includes(a));
13987
+ const baseArgs = [...spawn4.args || []].filter((a) => !interactiveFlags.includes(a));
13845
13988
  let shellCmd;
13846
- const isWin = os15.platform() === "win32";
13989
+ const isWin = os16.platform() === "win32";
13847
13990
  const escapeArg = (a) => isWin ? `"${a.replace(/"/g, '""')}"` : `'${a.replace(/'/g, "'\\''")}'`;
13848
13991
  if (command === "claude") {
13849
13992
  const args = [...baseArgs, "--dangerously-skip-permissions"];
@@ -13886,13 +14029,13 @@ async function handleAutoImplement(ctx, type, req, res) {
13886
14029
  try {
13887
14030
  const pty3 = require("node-pty");
13888
14031
  ctx.log(`Auto-implement spawn (PTY): ${shellCmd}`);
13889
- const isWin2 = os15.platform() === "win32";
14032
+ const isWin2 = os16.platform() === "win32";
13890
14033
  child = pty3.spawn(isWin2 ? "cmd.exe" : process.env.SHELL || "/bin/zsh", [isWin2 ? "/c" : "-c", shellCmd], {
13891
14034
  name: "xterm-256color",
13892
14035
  cols: 120,
13893
14036
  rows: 40,
13894
14037
  cwd: providerDir,
13895
- env: { ...process.env, ...spawn3.env || {} }
14038
+ env: { ...process.env, ...spawn4.env || {} }
13896
14039
  });
13897
14040
  isPty = true;
13898
14041
  } catch (err) {
@@ -13904,7 +14047,7 @@ async function handleAutoImplement(ctx, type, req, res) {
13904
14047
  stdio: ["pipe", "pipe", "pipe"],
13905
14048
  env: {
13906
14049
  ...process.env,
13907
- ...spawn3.env || {},
14050
+ ...spawn4.env || {},
13908
14051
  ...command === "gemini" ? { SANDBOX: "1", GEMINI_CLI_NO_RELAUNCH: "1" } : {}
13909
14052
  }
13910
14053
  });
@@ -13980,7 +14123,7 @@ async function handleAutoImplement(ctx, type, req, res) {
13980
14123
  } catch {
13981
14124
  }
13982
14125
  try {
13983
- fs10.unlinkSync(promptFile);
14126
+ fs11.unlinkSync(promptFile);
13984
14127
  } catch {
13985
14128
  }
13986
14129
  });
@@ -14016,7 +14159,7 @@ async function handleAutoImplement(ctx, type, req, res) {
14016
14159
  } catch {
14017
14160
  }
14018
14161
  try {
14019
- fs10.unlinkSync(promptFile);
14162
+ fs11.unlinkSync(promptFile);
14020
14163
  } catch {
14021
14164
  }
14022
14165
  ctx.log(`Auto-implement ${success ? "completed" : "failed"}: ${type} (exit: ${code})`);
@@ -14063,7 +14206,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
14063
14206
  setMode: "set_mode.js"
14064
14207
  };
14065
14208
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
14066
- const scriptsDir = path13.join(providerDir, "scripts");
14209
+ const scriptsDir = path14.join(providerDir, "scripts");
14067
14210
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
14068
14211
  if (latestScriptsDir) {
14069
14212
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -14071,10 +14214,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
14071
14214
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
14072
14215
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
14073
14216
  lines.push("");
14074
- for (const file of fs10.readdirSync(latestScriptsDir)) {
14217
+ for (const file of fs11.readdirSync(latestScriptsDir)) {
14075
14218
  if (file.endsWith(".js") && targetFileNames.has(file)) {
14076
14219
  try {
14077
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file), "utf-8");
14220
+ const content = fs11.readFileSync(path14.join(latestScriptsDir, file), "utf-8");
14078
14221
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
14079
14222
  lines.push("```javascript");
14080
14223
  lines.push(content);
@@ -14084,14 +14227,14 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
14084
14227
  }
14085
14228
  }
14086
14229
  }
14087
- const refFiles = fs10.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
14230
+ const refFiles = fs11.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
14088
14231
  if (refFiles.length > 0) {
14089
14232
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
14090
14233
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
14091
14234
  lines.push("");
14092
14235
  for (const file of refFiles) {
14093
14236
  try {
14094
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file), "utf-8");
14237
+ const content = fs11.readFileSync(path14.join(latestScriptsDir, file), "utf-8");
14095
14238
  lines.push(`### \`${file}\` \u{1F512}`);
14096
14239
  lines.push("```javascript");
14097
14240
  lines.push(content);
@@ -14132,11 +14275,11 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
14132
14275
  lines.push("");
14133
14276
  }
14134
14277
  }
14135
- const docsDir = path13.join(providerDir, "../../docs");
14278
+ const docsDir = path14.join(providerDir, "../../docs");
14136
14279
  const loadGuide = (name) => {
14137
14280
  try {
14138
- const p = path13.join(docsDir, name);
14139
- if (fs10.existsSync(p)) return fs10.readFileSync(p, "utf-8");
14281
+ const p = path14.join(docsDir, name);
14282
+ if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
14140
14283
  } catch {
14141
14284
  }
14142
14285
  return null;
@@ -14309,7 +14452,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
14309
14452
  parseApproval: "parse_approval.js"
14310
14453
  };
14311
14454
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
14312
- const scriptsDir = path13.join(providerDir, "scripts");
14455
+ const scriptsDir = path14.join(providerDir, "scripts");
14313
14456
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
14314
14457
  if (latestScriptsDir) {
14315
14458
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -14317,11 +14460,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
14317
14460
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
14318
14461
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
14319
14462
  lines.push("");
14320
- for (const file of fs10.readdirSync(latestScriptsDir)) {
14463
+ for (const file of fs11.readdirSync(latestScriptsDir)) {
14321
14464
  if (!file.endsWith(".js")) continue;
14322
14465
  if (!targetFileNames.has(file)) continue;
14323
14466
  try {
14324
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file), "utf-8");
14467
+ const content = fs11.readFileSync(path14.join(latestScriptsDir, file), "utf-8");
14325
14468
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
14326
14469
  lines.push("```javascript");
14327
14470
  lines.push(content);
@@ -14330,14 +14473,14 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
14330
14473
  } catch {
14331
14474
  }
14332
14475
  }
14333
- const refFiles = fs10.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
14476
+ const refFiles = fs11.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
14334
14477
  if (refFiles.length > 0) {
14335
14478
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
14336
14479
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
14337
14480
  lines.push("");
14338
14481
  for (const file of refFiles) {
14339
14482
  try {
14340
- const content = fs10.readFileSync(path13.join(latestScriptsDir, file), "utf-8");
14483
+ const content = fs11.readFileSync(path14.join(latestScriptsDir, file), "utf-8");
14341
14484
  lines.push(`### \`${file}\` \u{1F512}`);
14342
14485
  lines.push("```javascript");
14343
14486
  lines.push(content);
@@ -14370,11 +14513,11 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
14370
14513
  lines.push("");
14371
14514
  }
14372
14515
  }
14373
- const docsDir = path13.join(providerDir, "../../docs");
14516
+ const docsDir = path14.join(providerDir, "../../docs");
14374
14517
  const loadGuide = (name) => {
14375
14518
  try {
14376
- const p = path13.join(docsDir, name);
14377
- if (fs10.existsSync(p)) return fs10.readFileSync(p, "utf-8");
14519
+ const p = path14.join(docsDir, name);
14520
+ if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
14378
14521
  } catch {
14379
14522
  }
14380
14523
  return null;
@@ -14631,8 +14774,8 @@ var DevServer = class _DevServer {
14631
14774
  }
14632
14775
  getEndpointList() {
14633
14776
  return this.routes.map((r) => {
14634
- const path15 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
14635
- return `${r.method.padEnd(5)} ${path15}`;
14777
+ const path16 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
14778
+ return `${r.method.padEnd(5)} ${path16}`;
14636
14779
  });
14637
14780
  }
14638
14781
  async start(port = DEV_SERVER_PORT) {
@@ -14733,16 +14876,16 @@ var DevServer = class _DevServer {
14733
14876
  this.json(res, 404, { error: `Provider not found: ${type}` });
14734
14877
  return;
14735
14878
  }
14736
- const spawn3 = provider.spawn;
14737
- if (!spawn3) {
14879
+ const spawn4 = provider.spawn;
14880
+ if (!spawn4) {
14738
14881
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
14739
14882
  return;
14740
14883
  }
14741
14884
  const { spawn: spawnFn } = await import("child_process");
14742
14885
  const start = Date.now();
14743
14886
  try {
14744
- const child = spawnFn(spawn3.command, [...spawn3.args || []], {
14745
- shell: spawn3.shell ?? false,
14887
+ const child = spawnFn(spawn4.command, [...spawn4.args || []], {
14888
+ shell: spawn4.shell ?? false,
14746
14889
  timeout: 5e3,
14747
14890
  stdio: ["pipe", "pipe", "pipe"]
14748
14891
  });
@@ -14774,7 +14917,7 @@ var DevServer = class _DevServer {
14774
14917
  const elapsed = Date.now() - start;
14775
14918
  this.json(res, 200, {
14776
14919
  success: true,
14777
- command: `${spawn3.command} ${(spawn3.args || []).join(" ")}`,
14920
+ command: `${spawn4.command} ${(spawn4.args || []).join(" ")}`,
14778
14921
  elapsed,
14779
14922
  stdout: stdout.trim(),
14780
14923
  stderr: stderr.trim(),
@@ -14784,7 +14927,7 @@ var DevServer = class _DevServer {
14784
14927
  const elapsed = Date.now() - start;
14785
14928
  this.json(res, 200, {
14786
14929
  success: false,
14787
- command: `${spawn3.command} ${(spawn3.args || []).join(" ")}`,
14930
+ command: `${spawn4.command} ${(spawn4.args || []).join(" ")}`,
14788
14931
  elapsed,
14789
14932
  error: e.message
14790
14933
  });
@@ -14914,12 +15057,12 @@ var DevServer = class _DevServer {
14914
15057
  // ─── DevConsole SPA ───
14915
15058
  getConsoleDistDir() {
14916
15059
  const candidates = [
14917
- path14.resolve(__dirname, "../../web-devconsole/dist"),
14918
- path14.resolve(__dirname, "../../../web-devconsole/dist"),
14919
- path14.join(process.cwd(), "packages/web-devconsole/dist")
15060
+ path15.resolve(__dirname, "../../web-devconsole/dist"),
15061
+ path15.resolve(__dirname, "../../../web-devconsole/dist"),
15062
+ path15.join(process.cwd(), "packages/web-devconsole/dist")
14920
15063
  ];
14921
15064
  for (const dir of candidates) {
14922
- if (fs11.existsSync(path14.join(dir, "index.html"))) return dir;
15065
+ if (fs12.existsSync(path15.join(dir, "index.html"))) return dir;
14923
15066
  }
14924
15067
  return null;
14925
15068
  }
@@ -14929,9 +15072,9 @@ var DevServer = class _DevServer {
14929
15072
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
14930
15073
  return;
14931
15074
  }
14932
- const htmlPath = path14.join(distDir, "index.html");
15075
+ const htmlPath = path15.join(distDir, "index.html");
14933
15076
  try {
14934
- const html = fs11.readFileSync(htmlPath, "utf-8");
15077
+ const html = fs12.readFileSync(htmlPath, "utf-8");
14935
15078
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
14936
15079
  res.end(html);
14937
15080
  } catch (e) {
@@ -14954,15 +15097,15 @@ var DevServer = class _DevServer {
14954
15097
  this.json(res, 404, { error: "Not found" });
14955
15098
  return;
14956
15099
  }
14957
- const safePath = path14.normalize(pathname).replace(/^\.\.\//, "");
14958
- const filePath = path14.join(distDir, safePath);
15100
+ const safePath = path15.normalize(pathname).replace(/^\.\.\//, "");
15101
+ const filePath = path15.join(distDir, safePath);
14959
15102
  if (!filePath.startsWith(distDir)) {
14960
15103
  this.json(res, 403, { error: "Forbidden" });
14961
15104
  return;
14962
15105
  }
14963
15106
  try {
14964
- const content = fs11.readFileSync(filePath);
14965
- const ext = path14.extname(filePath);
15107
+ const content = fs12.readFileSync(filePath);
15108
+ const ext = path15.extname(filePath);
14966
15109
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
14967
15110
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
14968
15111
  res.end(content);
@@ -15070,14 +15213,14 @@ var DevServer = class _DevServer {
15070
15213
  const files = [];
15071
15214
  const scan = (d, prefix) => {
15072
15215
  try {
15073
- for (const entry of fs11.readdirSync(d, { withFileTypes: true })) {
15216
+ for (const entry of fs12.readdirSync(d, { withFileTypes: true })) {
15074
15217
  if (entry.name.startsWith(".") || entry.name.endsWith(".bak")) continue;
15075
15218
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
15076
15219
  if (entry.isDirectory()) {
15077
15220
  files.push({ path: rel, size: 0, type: "dir" });
15078
- scan(path14.join(d, entry.name), rel);
15221
+ scan(path15.join(d, entry.name), rel);
15079
15222
  } else {
15080
- const stat = fs11.statSync(path14.join(d, entry.name));
15223
+ const stat = fs12.statSync(path15.join(d, entry.name));
15081
15224
  files.push({ path: rel, size: stat.size, type: "file" });
15082
15225
  }
15083
15226
  }
@@ -15100,16 +15243,16 @@ var DevServer = class _DevServer {
15100
15243
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
15101
15244
  return;
15102
15245
  }
15103
- const fullPath = path14.resolve(dir, path14.normalize(filePath));
15246
+ const fullPath = path15.resolve(dir, path15.normalize(filePath));
15104
15247
  if (!fullPath.startsWith(dir)) {
15105
15248
  this.json(res, 403, { error: "Forbidden" });
15106
15249
  return;
15107
15250
  }
15108
- if (!fs11.existsSync(fullPath) || fs11.statSync(fullPath).isDirectory()) {
15251
+ if (!fs12.existsSync(fullPath) || fs12.statSync(fullPath).isDirectory()) {
15109
15252
  this.json(res, 404, { error: `File not found: ${filePath}` });
15110
15253
  return;
15111
15254
  }
15112
- const content = fs11.readFileSync(fullPath, "utf-8");
15255
+ const content = fs12.readFileSync(fullPath, "utf-8");
15113
15256
  this.json(res, 200, { type, path: filePath, content, lines: content.split("\n").length });
15114
15257
  }
15115
15258
  /** POST /api/providers/:type/file — write a file { path, content } */
@@ -15125,15 +15268,15 @@ var DevServer = class _DevServer {
15125
15268
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
15126
15269
  return;
15127
15270
  }
15128
- const fullPath = path14.resolve(dir, path14.normalize(filePath));
15271
+ const fullPath = path15.resolve(dir, path15.normalize(filePath));
15129
15272
  if (!fullPath.startsWith(dir)) {
15130
15273
  this.json(res, 403, { error: "Forbidden" });
15131
15274
  return;
15132
15275
  }
15133
15276
  try {
15134
- if (fs11.existsSync(fullPath)) fs11.copyFileSync(fullPath, fullPath + ".bak");
15135
- fs11.mkdirSync(path14.dirname(fullPath), { recursive: true });
15136
- fs11.writeFileSync(fullPath, content, "utf-8");
15277
+ if (fs12.existsSync(fullPath)) fs12.copyFileSync(fullPath, fullPath + ".bak");
15278
+ fs12.mkdirSync(path15.dirname(fullPath), { recursive: true });
15279
+ fs12.writeFileSync(fullPath, content, "utf-8");
15137
15280
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
15138
15281
  this.providerLoader.reload();
15139
15282
  this.json(res, 200, { saved: true, path: filePath, chars: content.length });
@@ -15149,9 +15292,9 @@ var DevServer = class _DevServer {
15149
15292
  return;
15150
15293
  }
15151
15294
  for (const name of ["scripts.js", "provider.json"]) {
15152
- const p = path14.join(dir, name);
15153
- if (fs11.existsSync(p)) {
15154
- const source = fs11.readFileSync(p, "utf-8");
15295
+ const p = path15.join(dir, name);
15296
+ if (fs12.existsSync(p)) {
15297
+ const source = fs12.readFileSync(p, "utf-8");
15155
15298
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
15156
15299
  return;
15157
15300
  }
@@ -15170,11 +15313,11 @@ var DevServer = class _DevServer {
15170
15313
  this.json(res, 404, { error: `Provider not found: ${type}` });
15171
15314
  return;
15172
15315
  }
15173
- const target = fs11.existsSync(path14.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
15174
- const targetPath = path14.join(dir, target);
15316
+ const target = fs12.existsSync(path15.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
15317
+ const targetPath = path15.join(dir, target);
15175
15318
  try {
15176
- if (fs11.existsSync(targetPath)) fs11.copyFileSync(targetPath, targetPath + ".bak");
15177
- fs11.writeFileSync(targetPath, source, "utf-8");
15319
+ if (fs12.existsSync(targetPath)) fs12.copyFileSync(targetPath, targetPath + ".bak");
15320
+ fs12.writeFileSync(targetPath, source, "utf-8");
15178
15321
  this.log(`Saved provider: ${targetPath} (${source.length} chars)`);
15179
15322
  this.providerLoader.reload();
15180
15323
  this.json(res, 200, { saved: true, path: targetPath, chars: source.length });
@@ -15253,20 +15396,20 @@ var DevServer = class _DevServer {
15253
15396
  this.json(res, 404, { error: `Provider not found: ${type}` });
15254
15397
  return;
15255
15398
  }
15256
- const spawn3 = provider.spawn;
15257
- if (!spawn3) {
15399
+ const spawn4 = provider.spawn;
15400
+ if (!spawn4) {
15258
15401
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
15259
15402
  return;
15260
15403
  }
15261
15404
  const { spawn: spawnFn } = await import("child_process");
15262
15405
  const start = Date.now();
15263
15406
  try {
15264
- const args = [...spawn3.args || [], message];
15265
- const child = spawnFn(spawn3.command, args, {
15266
- shell: spawn3.shell ?? false,
15407
+ const args = [...spawn4.args || [], message];
15408
+ const child = spawnFn(spawn4.command, args, {
15409
+ shell: spawn4.shell ?? false,
15267
15410
  timeout,
15268
15411
  stdio: ["pipe", "pipe", "pipe"],
15269
- env: { ...process.env, ...spawn3.env || {} }
15412
+ env: { ...process.env, ...spawn4.env || {} }
15270
15413
  });
15271
15414
  let stdout = "";
15272
15415
  let stderr = "";
@@ -15331,21 +15474,21 @@ var DevServer = class _DevServer {
15331
15474
  }
15332
15475
  let targetDir;
15333
15476
  targetDir = this.providerLoader.getUserProviderDir(category, type);
15334
- const jsonPath = path14.join(targetDir, "provider.json");
15335
- if (fs11.existsSync(jsonPath)) {
15477
+ const jsonPath = path15.join(targetDir, "provider.json");
15478
+ if (fs12.existsSync(jsonPath)) {
15336
15479
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
15337
15480
  return;
15338
15481
  }
15339
15482
  try {
15340
15483
  const result = generateFiles(type, name, category, { cdpPorts, cli, processName, installPath, binary, extensionId, version, osPaths, processNames });
15341
- fs11.mkdirSync(targetDir, { recursive: true });
15342
- fs11.writeFileSync(jsonPath, result["provider.json"], "utf-8");
15484
+ fs12.mkdirSync(targetDir, { recursive: true });
15485
+ fs12.writeFileSync(jsonPath, result["provider.json"], "utf-8");
15343
15486
  const createdFiles = ["provider.json"];
15344
15487
  if (result.files) {
15345
15488
  for (const [relPath, content] of Object.entries(result.files)) {
15346
- const fullPath = path14.join(targetDir, relPath);
15347
- fs11.mkdirSync(path14.dirname(fullPath), { recursive: true });
15348
- fs11.writeFileSync(fullPath, content, "utf-8");
15489
+ const fullPath = path15.join(targetDir, relPath);
15490
+ fs12.mkdirSync(path15.dirname(fullPath), { recursive: true });
15491
+ fs12.writeFileSync(fullPath, content, "utf-8");
15349
15492
  createdFiles.push(relPath);
15350
15493
  }
15351
15494
  }
@@ -15394,45 +15537,45 @@ var DevServer = class _DevServer {
15394
15537
  }
15395
15538
  // ─── Phase 2: Auto-Implement Backend ───
15396
15539
  getLatestScriptVersionDir(scriptsDir) {
15397
- if (!fs11.existsSync(scriptsDir)) return null;
15398
- const versions = fs11.readdirSync(scriptsDir).filter((d) => {
15540
+ if (!fs12.existsSync(scriptsDir)) return null;
15541
+ const versions = fs12.readdirSync(scriptsDir).filter((d) => {
15399
15542
  try {
15400
- return fs11.statSync(path14.join(scriptsDir, d)).isDirectory();
15543
+ return fs12.statSync(path15.join(scriptsDir, d)).isDirectory();
15401
15544
  } catch {
15402
15545
  return false;
15403
15546
  }
15404
15547
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
15405
15548
  if (versions.length === 0) return null;
15406
- return path14.join(scriptsDir, versions[0]);
15549
+ return path15.join(scriptsDir, versions[0]);
15407
15550
  }
15408
15551
  resolveAutoImplWritableProviderDir(category, type, requestedDir) {
15409
- const canonicalUserDir = path14.resolve(this.providerLoader.getUserProviderDir(category, type));
15410
- const desiredDir = requestedDir ? path14.resolve(requestedDir) : canonicalUserDir;
15411
- const upstreamRoot = path14.resolve(this.providerLoader.getUpstreamDir());
15412
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path14.sep}`)) {
15552
+ const canonicalUserDir = path15.resolve(this.providerLoader.getUserProviderDir(category, type));
15553
+ const desiredDir = requestedDir ? path15.resolve(requestedDir) : canonicalUserDir;
15554
+ const upstreamRoot = path15.resolve(this.providerLoader.getUpstreamDir());
15555
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path15.sep}`)) {
15413
15556
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
15414
15557
  }
15415
- if (path14.basename(desiredDir) !== type) {
15558
+ if (path15.basename(desiredDir) !== type) {
15416
15559
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
15417
15560
  }
15418
15561
  const sourceDir = this.findProviderDir(type);
15419
15562
  if (!sourceDir) {
15420
15563
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
15421
15564
  }
15422
- if (!fs11.existsSync(desiredDir)) {
15423
- fs11.mkdirSync(path14.dirname(desiredDir), { recursive: true });
15424
- fs11.cpSync(sourceDir, desiredDir, { recursive: true });
15565
+ if (!fs12.existsSync(desiredDir)) {
15566
+ fs12.mkdirSync(path15.dirname(desiredDir), { recursive: true });
15567
+ fs12.cpSync(sourceDir, desiredDir, { recursive: true });
15425
15568
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
15426
15569
  }
15427
- const providerJson = path14.join(desiredDir, "provider.json");
15428
- if (!fs11.existsSync(providerJson)) {
15570
+ const providerJson = path15.join(desiredDir, "provider.json");
15571
+ if (!fs12.existsSync(providerJson)) {
15429
15572
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
15430
15573
  }
15431
15574
  try {
15432
- const providerData = JSON.parse(fs11.readFileSync(providerJson, "utf-8"));
15575
+ const providerData = JSON.parse(fs12.readFileSync(providerJson, "utf-8"));
15433
15576
  if (providerData.disableUpstream !== true) {
15434
15577
  providerData.disableUpstream = true;
15435
- fs11.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
15578
+ fs12.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
15436
15579
  }
15437
15580
  } catch (error) {
15438
15581
  return {
@@ -15472,7 +15615,7 @@ var DevServer = class _DevServer {
15472
15615
  setMode: "set_mode.js"
15473
15616
  };
15474
15617
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
15475
- const scriptsDir = path14.join(providerDir, "scripts");
15618
+ const scriptsDir = path15.join(providerDir, "scripts");
15476
15619
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
15477
15620
  if (latestScriptsDir) {
15478
15621
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -15480,10 +15623,10 @@ var DevServer = class _DevServer {
15480
15623
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
15481
15624
  lines.push("These are the ONLY files you are allowed to modify. Replace the TODO stubs with working implementations.");
15482
15625
  lines.push("");
15483
- for (const file of fs11.readdirSync(latestScriptsDir)) {
15626
+ for (const file of fs12.readdirSync(latestScriptsDir)) {
15484
15627
  if (file.endsWith(".js") && targetFileNames.has(file)) {
15485
15628
  try {
15486
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file), "utf-8");
15629
+ const content = fs12.readFileSync(path15.join(latestScriptsDir, file), "utf-8");
15487
15630
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
15488
15631
  lines.push("```javascript");
15489
15632
  lines.push(content);
@@ -15493,14 +15636,14 @@ var DevServer = class _DevServer {
15493
15636
  }
15494
15637
  }
15495
15638
  }
15496
- const refFiles = fs11.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
15639
+ const refFiles = fs12.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
15497
15640
  if (refFiles.length > 0) {
15498
15641
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
15499
15642
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
15500
15643
  lines.push("");
15501
15644
  for (const file of refFiles) {
15502
15645
  try {
15503
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file), "utf-8");
15646
+ const content = fs12.readFileSync(path15.join(latestScriptsDir, file), "utf-8");
15504
15647
  lines.push(`### \`${file}\` \u{1F512}`);
15505
15648
  lines.push("```javascript");
15506
15649
  lines.push(content);
@@ -15541,11 +15684,11 @@ var DevServer = class _DevServer {
15541
15684
  lines.push("");
15542
15685
  }
15543
15686
  }
15544
- const docsDir = path14.join(providerDir, "../../docs");
15687
+ const docsDir = path15.join(providerDir, "../../docs");
15545
15688
  const loadGuide = (name) => {
15546
15689
  try {
15547
- const p = path14.join(docsDir, name);
15548
- if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
15690
+ const p = path15.join(docsDir, name);
15691
+ if (fs12.existsSync(p)) return fs12.readFileSync(p, "utf-8");
15549
15692
  } catch {
15550
15693
  }
15551
15694
  return null;
@@ -15718,7 +15861,7 @@ var DevServer = class _DevServer {
15718
15861
  parseApproval: "parse_approval.js"
15719
15862
  };
15720
15863
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
15721
- const scriptsDir = path14.join(providerDir, "scripts");
15864
+ const scriptsDir = path15.join(providerDir, "scripts");
15722
15865
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
15723
15866
  if (latestScriptsDir) {
15724
15867
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -15726,11 +15869,11 @@ var DevServer = class _DevServer {
15726
15869
  lines.push("## \u270F\uFE0F Target Files (EDIT THESE)");
15727
15870
  lines.push("These are the ONLY files you are allowed to modify. Replace TODO or heuristic-only logic with working PTY-aware implementations.");
15728
15871
  lines.push("");
15729
- for (const file of fs11.readdirSync(latestScriptsDir)) {
15872
+ for (const file of fs12.readdirSync(latestScriptsDir)) {
15730
15873
  if (!file.endsWith(".js")) continue;
15731
15874
  if (!targetFileNames.has(file)) continue;
15732
15875
  try {
15733
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file), "utf-8");
15876
+ const content = fs12.readFileSync(path15.join(latestScriptsDir, file), "utf-8");
15734
15877
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
15735
15878
  lines.push("```javascript");
15736
15879
  lines.push(content);
@@ -15739,14 +15882,14 @@ var DevServer = class _DevServer {
15739
15882
  } catch {
15740
15883
  }
15741
15884
  }
15742
- const refFiles = fs11.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
15885
+ const refFiles = fs12.readdirSync(latestScriptsDir).filter((f) => f.endsWith(".js") && !targetFileNames.has(f));
15743
15886
  if (refFiles.length > 0) {
15744
15887
  lines.push("## \u{1F512} Other Scripts (REFERENCE ONLY \u2014 DO NOT EDIT)");
15745
15888
  lines.push("These files are shown for context only. Do NOT modify them under any circumstances.");
15746
15889
  lines.push("");
15747
15890
  for (const file of refFiles) {
15748
15891
  try {
15749
- const content = fs11.readFileSync(path14.join(latestScriptsDir, file), "utf-8");
15892
+ const content = fs12.readFileSync(path15.join(latestScriptsDir, file), "utf-8");
15750
15893
  lines.push(`### \`${file}\` \u{1F512}`);
15751
15894
  lines.push("```javascript");
15752
15895
  lines.push(content);
@@ -15779,11 +15922,11 @@ var DevServer = class _DevServer {
15779
15922
  lines.push("");
15780
15923
  }
15781
15924
  }
15782
- const docsDir = path14.join(providerDir, "../../docs");
15925
+ const docsDir = path15.join(providerDir, "../../docs");
15783
15926
  const loadGuide = (name) => {
15784
15927
  try {
15785
- const p = path14.join(docsDir, name);
15786
- if (fs11.existsSync(p)) return fs11.readFileSync(p, "utf-8");
15928
+ const p = path15.join(docsDir, name);
15929
+ if (fs12.existsSync(p)) return fs12.readFileSync(p, "utf-8");
15787
15930
  } catch {
15788
15931
  }
15789
15932
  return null;
@@ -16014,6 +16157,7 @@ var SessionHostRuntimeTransport = class {
16014
16157
  this.ready = this.boot();
16015
16158
  }
16016
16159
  ready;
16160
+ terminalQueriesHandled = true;
16017
16161
  client;
16018
16162
  dataCallbacks = /* @__PURE__ */ new Set();
16019
16163
  exitCallbacks = /* @__PURE__ */ new Set();
@@ -16402,7 +16546,7 @@ async function listHostedCliRuntimes(endpoint) {
16402
16546
  }
16403
16547
 
16404
16548
  // src/installer.ts
16405
- var import_child_process8 = require("child_process");
16549
+ var import_child_process10 = require("child_process");
16406
16550
  var EXTENSION_CATALOG = [
16407
16551
  // AI Agent extensions
16408
16552
  {
@@ -16479,7 +16623,7 @@ var EXTENSION_CATALOG = [
16479
16623
  function isExtensionInstalled(ide, marketplaceId) {
16480
16624
  if (!ide.cliCommand) return false;
16481
16625
  try {
16482
- const result = (0, import_child_process8.execSync)(`"${ide.cliCommand}" --list-extensions`, {
16626
+ const result = (0, import_child_process10.execSync)(`"${ide.cliCommand}" --list-extensions`, {
16483
16627
  encoding: "utf-8",
16484
16628
  timeout: 15e3,
16485
16629
  stdio: ["pipe", "pipe", "pipe"]
@@ -16516,11 +16660,11 @@ async function installExtension(ide, extension) {
16516
16660
  const res = await fetch(extension.vsixUrl);
16517
16661
  if (res.ok) {
16518
16662
  const buffer = Buffer.from(await res.arrayBuffer());
16519
- const fs12 = await import("fs");
16520
- fs12.writeFileSync(vsixPath, buffer);
16663
+ const fs13 = await import("fs");
16664
+ fs13.writeFileSync(vsixPath, buffer);
16521
16665
  return new Promise((resolve9) => {
16522
16666
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
16523
- (0, import_child_process8.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
16667
+ (0, import_child_process10.exec)(cmd, { timeout: 6e4 }, (error, _stdout, stderr) => {
16524
16668
  resolve9({
16525
16669
  extensionId: extension.id,
16526
16670
  marketplaceId: extension.marketplaceId,
@@ -16536,7 +16680,7 @@ async function installExtension(ide, extension) {
16536
16680
  }
16537
16681
  return new Promise((resolve9) => {
16538
16682
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
16539
- (0, import_child_process8.exec)(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
16683
+ (0, import_child_process10.exec)(cmd, { timeout: 6e4 }, (error, stdout, stderr) => {
16540
16684
  if (error) {
16541
16685
  resolve9({
16542
16686
  extensionId: extension.id,
@@ -16573,7 +16717,7 @@ function launchIDE(ide, workspacePath) {
16573
16717
  if (!ide.cliCommand) return false;
16574
16718
  try {
16575
16719
  const args = workspacePath ? `"${workspacePath}"` : "";
16576
- (0, import_child_process8.exec)(`"${ide.cliCommand}" ${args}`, { timeout: 1e4 });
16720
+ (0, import_child_process10.exec)(`"${ide.cliCommand}" ${args}`, { timeout: 1e4 });
16577
16721
  return true;
16578
16722
  } catch {
16579
16723
  return false;
@@ -16885,6 +17029,7 @@ async function shutdownDaemonComponents(components) {
16885
17029
  loadConfig,
16886
17030
  logCommand,
16887
17031
  markSetupComplete,
17032
+ maybeRunDaemonUpgradeHelperFromEnv,
16888
17033
  normalizeActiveChatData,
16889
17034
  normalizeManagedStatus,
16890
17035
  probeCdpPort,