adhdev 0.8.12 → 0.8.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -9,7 +9,7 @@ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
9
  var __esm = (fn, res) => function __init() {
10
10
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
11
  };
12
- var __commonJS = (cb, mod) => function __require() {
12
+ var __commonJS = (cb, mod) => function __require2() {
13
13
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
14
  };
15
15
  var __export = (target, all) => {
@@ -572,18 +572,18 @@ function checkPathExists(paths) {
572
572
  return null;
573
573
  }
574
574
  async function detectIDEs() {
575
- const os22 = (0, import_os2.platform)();
575
+ const os24 = (0, import_os2.platform)();
576
576
  const results = [];
577
577
  for (const def of getMergedDefinitions()) {
578
578
  const cliPath = findCliCommand(def.cli);
579
- const appPath = checkPathExists(def.paths[os22] || []);
579
+ const appPath = checkPathExists(def.paths[os24] || []);
580
580
  const installed = !!(cliPath || appPath);
581
581
  let resolvedCli = cliPath;
582
- if (!resolvedCli && appPath && os22 === "darwin") {
582
+ if (!resolvedCli && appPath && os24 === "darwin") {
583
583
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
584
584
  if ((0, import_fs2.existsSync)(bundledCli)) resolvedCli = bundledCli;
585
585
  }
586
- if (!resolvedCli && appPath && os22 === "win32") {
586
+ if (!resolvedCli && appPath && os24 === "win32") {
587
587
  const { dirname: dirname9 } = await import("path");
588
588
  const appDir = dirname9(appPath);
589
589
  const candidates = [
@@ -644,8 +644,8 @@ function execAsync(cmd, timeoutMs = 5e3) {
644
644
  });
645
645
  }
646
646
  async function detectCLIs(providerLoader) {
647
- const platform10 = os2.platform();
648
- const whichCmd = platform10 === "win32" ? "where" : "which";
647
+ const platform11 = os2.platform();
648
+ const whichCmd = platform11 === "win32" ? "where" : "which";
649
649
  const cliList = providerLoader ? providerLoader.getCliDetectionList() : [];
650
650
  const results = await Promise.all(
651
651
  cliList.map(async (cli) => {
@@ -680,6 +680,39 @@ async function detectCLIs(providerLoader) {
680
680
  }
681
681
  async function detectCLI(cliId, providerLoader) {
682
682
  const resolvedId = providerLoader ? providerLoader.resolveAlias(cliId) : cliId;
683
+ if (providerLoader) {
684
+ const cliList = providerLoader.getCliDetectionList();
685
+ const target = cliList.find((c) => c.id === resolvedId);
686
+ if (target) {
687
+ const platform11 = os2.platform();
688
+ const whichCmd = platform11 === "win32" ? "where" : "which";
689
+ try {
690
+ const pathResult = await execAsync(`${whichCmd} ${target.command}`);
691
+ if (!pathResult) return null;
692
+ const firstPath = pathResult.split("\n")[0];
693
+ let version2;
694
+ try {
695
+ const versionCommands = [
696
+ target.versionCommand,
697
+ `${target.command} --version`,
698
+ `${target.command} -V`,
699
+ `${target.command} -v`
700
+ ].filter((v) => !!v);
701
+ for (const versionCommand of versionCommands) {
702
+ const versionResult = await execAsync(versionCommand, 3e3);
703
+ if (versionResult) {
704
+ version2 = parseVersion(versionResult);
705
+ break;
706
+ }
707
+ }
708
+ } catch {
709
+ }
710
+ return { ...target, installed: true, version: version2, path: firstPath };
711
+ } catch {
712
+ return null;
713
+ }
714
+ }
715
+ }
683
716
  const all = await detectCLIs(providerLoader);
684
717
  return all.find((c) => c.id === resolvedId && c.installed) || null;
685
718
  }
@@ -5426,8 +5459,24 @@ var init_stream_commands = __esm({
5426
5459
  });
5427
5460
 
5428
5461
  // ../../oss/packages/daemon-core/src/commands/workspace-commands.ts
5462
+ function loadWorkspaceConfig() {
5463
+ try {
5464
+ return loadConfig();
5465
+ } catch (e) {
5466
+ return { error: `Could not load config: ${e?.message || "unknown error"}` };
5467
+ }
5468
+ }
5469
+ function persistWorkspaceConfig(config2) {
5470
+ try {
5471
+ saveConfig(config2);
5472
+ return { ok: true };
5473
+ } catch (e) {
5474
+ return { error: `Could not save config: ${e?.message || "unknown error"}` };
5475
+ }
5476
+ }
5429
5477
  function handleWorkspaceList() {
5430
- const config2 = loadConfig();
5478
+ const config2 = loadWorkspaceConfig();
5479
+ if ("error" in config2) return { success: false, error: config2.error };
5431
5480
  const state = getWorkspaceState(config2);
5432
5481
  return {
5433
5482
  success: true,
@@ -5441,31 +5490,37 @@ function handleWorkspaceAdd(args) {
5441
5490
  const label = (args?.label || "").trim() || void 0;
5442
5491
  const createIfMissing = args?.createIfMissing === true;
5443
5492
  if (!rawPath) return { success: false, error: "path required" };
5444
- const config2 = loadConfig();
5493
+ const config2 = loadWorkspaceConfig();
5494
+ if ("error" in config2) return { success: false, error: config2.error };
5445
5495
  const result = addWorkspaceEntry(config2, rawPath, label, { createIfMissing });
5446
5496
  if ("error" in result) return { success: false, error: result.error };
5447
- saveConfig(result.config);
5497
+ const saveResult = persistWorkspaceConfig(result.config);
5498
+ if ("error" in saveResult) return { success: false, error: saveResult.error };
5448
5499
  const state = getWorkspaceState(result.config);
5449
5500
  return { success: true, entry: result.entry, ...state };
5450
5501
  }
5451
5502
  function handleWorkspaceRemove(args) {
5452
5503
  const id = (args?.id || "").trim();
5453
5504
  if (!id) return { success: false, error: "id required" };
5454
- const config2 = loadConfig();
5505
+ const config2 = loadWorkspaceConfig();
5506
+ if ("error" in config2) return { success: false, error: config2.error };
5455
5507
  const removed = (config2.workspaces || []).find((w) => w.id === id);
5456
5508
  const result = removeWorkspaceEntry(config2, id);
5457
5509
  if ("error" in result) return { success: false, error: result.error };
5458
- saveConfig(result.config);
5510
+ const saveResult = persistWorkspaceConfig(result.config);
5511
+ if ("error" in saveResult) return { success: false, error: saveResult.error };
5459
5512
  const state = getWorkspaceState(result.config);
5460
5513
  return { success: true, removedId: id, ...state };
5461
5514
  }
5462
5515
  function handleWorkspaceSetDefault(args) {
5463
5516
  const clear = args?.clear === true || args?.id === null || args?.id === "";
5464
5517
  if (clear) {
5465
- const config3 = loadConfig();
5518
+ const config3 = loadWorkspaceConfig();
5519
+ if ("error" in config3) return { success: false, error: config3.error };
5466
5520
  const result2 = setDefaultWorkspaceId(config3, null);
5467
5521
  if ("error" in result2) return { success: false, error: result2.error };
5468
- saveConfig(result2.config);
5522
+ const saveResult2 = persistWorkspaceConfig(result2.config);
5523
+ if ("error" in saveResult2) return { success: false, error: saveResult2.error };
5469
5524
  const state2 = getWorkspaceState(result2.config);
5470
5525
  return {
5471
5526
  success: true,
@@ -5477,7 +5532,9 @@ function handleWorkspaceSetDefault(args) {
5477
5532
  if (!pathArg && !idArg) {
5478
5533
  return { success: false, error: "id or path required (or clear: true)" };
5479
5534
  }
5480
- let config2 = loadConfig();
5535
+ const configResult = loadWorkspaceConfig();
5536
+ if ("error" in configResult) return { success: false, error: configResult.error };
5537
+ let config2 = configResult;
5481
5538
  let nextId;
5482
5539
  if (pathArg) {
5483
5540
  let w = findWorkspaceByPath(config2, pathArg);
@@ -5493,7 +5550,8 @@ function handleWorkspaceSetDefault(args) {
5493
5550
  }
5494
5551
  const result = setDefaultWorkspaceId(config2, nextId);
5495
5552
  if ("error" in result) return { success: false, error: result.error };
5496
- saveConfig(result.config);
5553
+ const saveResult = persistWorkspaceConfig(result.config);
5554
+ if ("error" in saveResult) return { success: false, error: saveResult.error };
5497
5555
  const state = getWorkspaceState(result.config);
5498
5556
  return { success: true, ...state };
5499
5557
  }
@@ -6196,6 +6254,13 @@ function logTerminalBackendSelection(preference, ghosttyAvailable, backendKind)
6196
6254
  const key = `${preference}:${ghosttyAvailable}:${backendKind}`;
6197
6255
  if (loggedTerminalBackends.has(key)) return;
6198
6256
  loggedTerminalBackends.add(key);
6257
+ if (backendKind === "xterm" && preference !== "xterm" && !ghosttyAvailable) {
6258
+ LOG.warn(
6259
+ "Terminal",
6260
+ `[terminal-screen] ghostty-vt unavailable; using xterm fallback (preference=${preference})`
6261
+ );
6262
+ return;
6263
+ }
6199
6264
  LOG.info(
6200
6265
  "Terminal",
6201
6266
  `[terminal-screen] backend=${backendKind} preference=${preference} ghosttyAvailable=${ghosttyAvailable}`
@@ -6258,10 +6323,11 @@ var init_terminal_screen = __esm({
6258
6323
  });
6259
6324
 
6260
6325
  // ../../oss/packages/daemon-core/src/cli-adapters/pty-transport.ts
6261
- var pty, NodePtyRuntimeTransport, NodePtyTransportFactory;
6326
+ var os7, pty, NodePtyRuntimeTransport, NodePtyTransportFactory;
6262
6327
  var init_pty_transport = __esm({
6263
6328
  "../../oss/packages/daemon-core/src/cli-adapters/pty-transport.ts"() {
6264
6329
  "use strict";
6330
+ os7 = __toESM(require("os"));
6265
6331
  try {
6266
6332
  pty = require("node-pty");
6267
6333
  } catch {
@@ -6298,11 +6364,21 @@ var init_pty_transport = __esm({
6298
6364
  NodePtyTransportFactory = class {
6299
6365
  spawn(command, args, options) {
6300
6366
  if (!pty) throw new Error("node-pty is not installed");
6367
+ let cwd = options.cwd;
6368
+ if (cwd) {
6369
+ try {
6370
+ const fs19 = require("fs");
6371
+ const stat4 = fs19.statSync(cwd);
6372
+ if (!stat4.isDirectory()) cwd = os7.homedir();
6373
+ } catch {
6374
+ cwd = os7.homedir();
6375
+ }
6376
+ }
6301
6377
  const handle = pty.spawn(command, args, {
6302
6378
  name: "xterm-256color",
6303
6379
  cols: options.cols,
6304
6380
  rows: options.rows,
6305
- cwd: options.cwd,
6381
+ cwd,
6306
6382
  env: options.env
6307
6383
  });
6308
6384
  return new NodePtyRuntimeTransport(handle);
@@ -6311,33 +6387,39 @@ var init_pty_transport = __esm({
6311
6387
  }
6312
6388
  });
6313
6389
 
6314
- // ../../oss/packages/daemon-core/src/cli-adapters/provider-cli-adapter.ts
6315
- var provider_cli_adapter_exports = {};
6316
- __export(provider_cli_adapter_exports, {
6317
- ProviderCliAdapter: () => ProviderCliAdapter,
6318
- normalizeCliProviderForRuntime: () => normalizeCliProviderForRuntime
6319
- });
6320
- function stripAnsi(str) {
6321
- return str.replace(/\x1B\][^\x07]*\x07/g, "").replace(/\x1B\][\s\S]*?\x1B\\/g, "").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, "").replace(/\x1B\[\d*[A-HJKSTfG]/g, " ").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "").replace(/ +/g, " ");
6322
- }
6323
- function stripTerminalNoise(str) {
6324
- return String(str || "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, "").replace(/(^|[\s([])(?:\??\d{1,4}(?:;\d{1,4})*[A-Za-z])(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\[\??\d{1,4}(?:;\d{1,4})*[A-Za-z])(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\d{1,4};\?)(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\d+\$r[0-9;\" ]*[A-Za-z]?)(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:>\|[A-Za-z0-9_.:-]+(?:\([^)]*\))?)(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:[A-Z]\d(?:\s+[A-Z]\d)+)(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\d+;[^\s)\]]+)(?=$|[\s)\]])/g, "$1").replace(/\r+/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").replace(/ {2,}/g, " ");
6325
- }
6326
- function sanitizeTerminalText(str) {
6327
- return stripTerminalNoise(stripAnsi(str));
6328
- }
6329
- function applyPreferredTerminalColorEnv(env) {
6330
- if (env.NO_COLOR) return;
6331
- if (!env.TERM || env.TERM === "xterm-color") {
6332
- env.TERM = "xterm-256color";
6333
- }
6334
- if (!env.COLORTERM) env.COLORTERM = "truecolor";
6390
+ // ../../oss/packages/session-host-core/dist/index.mjs
6391
+ function getDefaultSessionHostEndpoint(appName = "adhdev") {
6335
6392
  if (process.platform === "win32") {
6336
- if (!env.FORCE_COLOR) env.FORCE_COLOR = "1";
6337
- if (!env.CLICOLOR) env.CLICOLOR = "1";
6393
+ return {
6394
+ kind: "pipe",
6395
+ path: `\\\\.\\pipe\\${appName}-session-host`
6396
+ };
6338
6397
  }
6398
+ return {
6399
+ kind: "unix",
6400
+ path: path22.join(os8.tmpdir(), `${appName}-session-host.sock`)
6401
+ };
6339
6402
  }
6340
- function buildCliSpawnEnv(baseEnv, overrides) {
6403
+ function serializeEnvelope(envelope) {
6404
+ return `${JSON.stringify(envelope)}
6405
+ `;
6406
+ }
6407
+ function createLineParser(onEnvelope) {
6408
+ let buffer = "";
6409
+ return (chunk) => {
6410
+ buffer += chunk.toString();
6411
+ let newlineIndex = buffer.indexOf("\n");
6412
+ while (newlineIndex >= 0) {
6413
+ const rawLine = buffer.slice(0, newlineIndex).trim();
6414
+ buffer = buffer.slice(newlineIndex + 1);
6415
+ if (rawLine) {
6416
+ onEnvelope(JSON.parse(rawLine));
6417
+ }
6418
+ newlineIndex = buffer.indexOf("\n");
6419
+ }
6420
+ };
6421
+ }
6422
+ function sanitizeSpawnEnv(baseEnv, overrides) {
6341
6423
  const env = {};
6342
6424
  const source = { ...baseEnv, ...overrides || {} };
6343
6425
  for (const [key, value] of Object.entries(source)) {
@@ -6349,9 +6431,185 @@ function buildCliSpawnEnv(baseEnv, overrides) {
6349
6431
  delete env[key];
6350
6432
  }
6351
6433
  }
6352
- applyPreferredTerminalColorEnv(env);
6434
+ applyTerminalColorEnv(env);
6353
6435
  return env;
6354
6436
  }
6437
+ function applyTerminalColorEnv(env) {
6438
+ if (env.NO_COLOR) return;
6439
+ if (!env.TERM || env.TERM === "xterm-color") {
6440
+ env.TERM = "xterm-256color";
6441
+ }
6442
+ if (!env.COLORTERM) env.COLORTERM = "truecolor";
6443
+ if (process.platform === "win32") {
6444
+ if (!env.FORCE_COLOR) env.FORCE_COLOR = "1";
6445
+ if (!env.CLICOLOR) env.CLICOLOR = "1";
6446
+ }
6447
+ }
6448
+ function ensureNodePtySpawnHelperPermissions(logFn) {
6449
+ if (os22.platform() === "win32") return;
6450
+ try {
6451
+ const fs19 = __require("fs");
6452
+ const ptyDir = path32.resolve(path32.dirname(__require.resolve("node-pty")), "..");
6453
+ const platformArch = `${os22.platform()}-${os22.arch()}`;
6454
+ const helper = path32.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
6455
+ if (fs19.existsSync(helper)) {
6456
+ const stat4 = fs19.statSync(helper);
6457
+ if (!(stat4.mode & 73)) {
6458
+ fs19.chmodSync(helper, stat4.mode | 493);
6459
+ logFn?.(`Fixed spawn-helper permissions: ${helper}`);
6460
+ }
6461
+ }
6462
+ } catch {
6463
+ }
6464
+ }
6465
+ var os8, path22, net, import_crypto3, os22, path32, __require, SessionHostClient;
6466
+ var init_dist = __esm({
6467
+ "../../oss/packages/session-host-core/dist/index.mjs"() {
6468
+ "use strict";
6469
+ os8 = __toESM(require("os"), 1);
6470
+ path22 = __toESM(require("path"), 1);
6471
+ net = __toESM(require("net"), 1);
6472
+ import_crypto3 = require("crypto");
6473
+ os22 = __toESM(require("os"), 1);
6474
+ path32 = __toESM(require("path"), 1);
6475
+ __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
6476
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6477
+ }) : x)(function(x) {
6478
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6479
+ throw Error('Dynamic require of "' + x + '" is not supported');
6480
+ });
6481
+ SessionHostClient = class {
6482
+ endpoint;
6483
+ socket = null;
6484
+ requestWaiters = /* @__PURE__ */ new Map();
6485
+ eventListeners = /* @__PURE__ */ new Set();
6486
+ constructor(options = {}) {
6487
+ this.endpoint = options.endpoint || getDefaultSessionHostEndpoint(options.appName || "adhdev");
6488
+ }
6489
+ async connect() {
6490
+ if (this.socket && !this.socket.destroyed) return;
6491
+ if (this.socket) {
6492
+ try {
6493
+ this.socket.destroy();
6494
+ } catch {
6495
+ }
6496
+ this.socket = null;
6497
+ }
6498
+ const socket = net.createConnection(this.endpoint.path);
6499
+ this.socket = socket;
6500
+ socket.on("data", createLineParser((envelope) => {
6501
+ if (envelope.kind === "response") {
6502
+ const waiter = this.requestWaiters.get(envelope.requestId);
6503
+ if (waiter) {
6504
+ this.requestWaiters.delete(envelope.requestId);
6505
+ waiter.resolve(envelope.response);
6506
+ }
6507
+ return;
6508
+ }
6509
+ if (envelope.kind === "event") {
6510
+ for (const listener of this.eventListeners) listener(envelope.event);
6511
+ }
6512
+ }));
6513
+ socket.on("error", (error48) => {
6514
+ for (const waiter of this.requestWaiters.values()) {
6515
+ waiter.reject(error48);
6516
+ }
6517
+ this.requestWaiters.clear();
6518
+ if (this.socket === socket) {
6519
+ this.socket = null;
6520
+ }
6521
+ try {
6522
+ socket.destroy();
6523
+ } catch {
6524
+ }
6525
+ });
6526
+ await new Promise((resolve22, reject) => {
6527
+ socket.once("connect", () => resolve22());
6528
+ socket.once("error", reject);
6529
+ });
6530
+ }
6531
+ onEvent(listener) {
6532
+ this.eventListeners.add(listener);
6533
+ return () => {
6534
+ this.eventListeners.delete(listener);
6535
+ };
6536
+ }
6537
+ async request(request) {
6538
+ await this.connect();
6539
+ if (!this.socket) throw new Error("Session host socket unavailable");
6540
+ const requestId = (0, import_crypto3.randomUUID)();
6541
+ const envelope = {
6542
+ kind: "request",
6543
+ requestId,
6544
+ request
6545
+ };
6546
+ const response = await new Promise((resolve22, reject) => {
6547
+ const timeout = setTimeout(() => {
6548
+ this.requestWaiters.delete(requestId);
6549
+ reject(new Error(`Session host request timed out after 30s (${request.type})`));
6550
+ }, 3e4);
6551
+ this.requestWaiters.set(requestId, {
6552
+ resolve: (value) => {
6553
+ clearTimeout(timeout);
6554
+ resolve22(value);
6555
+ },
6556
+ reject: (error48) => {
6557
+ clearTimeout(timeout);
6558
+ reject(error48);
6559
+ }
6560
+ });
6561
+ this.socket?.write(serializeEnvelope(envelope));
6562
+ });
6563
+ return response;
6564
+ }
6565
+ async close() {
6566
+ if (!this.socket) return;
6567
+ const socket = this.socket;
6568
+ this.socket = null;
6569
+ for (const waiter of this.requestWaiters.values()) {
6570
+ waiter.reject(new Error("Session host client closed"));
6571
+ }
6572
+ this.requestWaiters.clear();
6573
+ await new Promise((resolve22) => {
6574
+ let settled = false;
6575
+ const done = () => {
6576
+ if (settled) return;
6577
+ settled = true;
6578
+ resolve22();
6579
+ };
6580
+ socket.once("close", done);
6581
+ socket.end();
6582
+ socket.destroy();
6583
+ setTimeout(done, 50);
6584
+ });
6585
+ }
6586
+ };
6587
+ }
6588
+ });
6589
+
6590
+ // ../../oss/packages/daemon-core/src/cli-adapters/spawn-env.ts
6591
+ var init_spawn_env = __esm({
6592
+ "../../oss/packages/daemon-core/src/cli-adapters/spawn-env.ts"() {
6593
+ "use strict";
6594
+ init_dist();
6595
+ }
6596
+ });
6597
+
6598
+ // ../../oss/packages/daemon-core/src/cli-adapters/provider-cli-adapter.ts
6599
+ var provider_cli_adapter_exports = {};
6600
+ __export(provider_cli_adapter_exports, {
6601
+ ProviderCliAdapter: () => ProviderCliAdapter,
6602
+ normalizeCliProviderForRuntime: () => normalizeCliProviderForRuntime
6603
+ });
6604
+ function stripAnsi(str) {
6605
+ return str.replace(/\x1B\][^\x07]*\x07/g, "").replace(/\x1B\][\s\S]*?\x1B\\/g, "").replace(/\x1B[P^_X][\s\S]*?(?:\x07|\x1B\\)/g, "").replace(/\x1B\[\d*[A-HJKSTfG]/g, " ").replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, "").replace(/ +/g, " ");
6606
+ }
6607
+ function stripTerminalNoise(str) {
6608
+ return String(str || "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, "").replace(/(^|[\s([])(?:\??\d{1,4}(?:;\d{1,4})*[A-Za-z])(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\[\??\d{1,4}(?:;\d{1,4})*[A-Za-z])(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\d{1,4};\?)(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\d+\$r[0-9;\" ]*[A-Za-z]?)(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:>\|[A-Za-z0-9_.:-]+(?:\([^)]*\))?)(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:[A-Z]\d(?:\s+[A-Z]\d)+)(?=$|[\s)\]])/g, "$1").replace(/(^|[\s([])(?:\d+;[^\s)\]]+)(?=$|[\s)\]])/g, "$1").replace(/\r+/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").replace(/ {2,}/g, " ");
6609
+ }
6610
+ function sanitizeTerminalText(str) {
6611
+ return stripTerminalNoise(stripAnsi(str));
6612
+ }
6355
6613
  function computeTerminalQueryTail(buffer) {
6356
6614
  const prefixes = ["\x1B[6n", "\x1B[?6n"];
6357
6615
  const maxLength = prefixes.reduce((n, value) => Math.max(n, value.length), 0) - 1;
@@ -6365,7 +6623,7 @@ function computeTerminalQueryTail(buffer) {
6365
6623
  return "";
6366
6624
  }
6367
6625
  function findBinary(name) {
6368
- const isWin = os7.platform() === "win32";
6626
+ const isWin = os9.platform() === "win32";
6369
6627
  try {
6370
6628
  const cmd = isWin ? `where ${name}` : `which ${name}`;
6371
6629
  return (0, import_child_process4.execSync)(cmd, { encoding: "utf-8", timeout: 5e3, stdio: ["pipe", "pipe", "pipe"] }).trim().split("\n")[0].trim();
@@ -6413,7 +6671,7 @@ function looksLikeMachOOrElf(filePath) {
6413
6671
  }
6414
6672
  function shSingleQuote(arg) {
6415
6673
  if (/^[a-zA-Z0-9@%_+=:,./-]+$/.test(arg)) return arg;
6416
- if (os7.platform() === "win32") {
6674
+ if (os9.platform() === "win32") {
6417
6675
  return `"${arg.replace(/"/g, '""')}"`;
6418
6676
  }
6419
6677
  return `'${arg.replace(/'/g, `'\\''`)}'`;
@@ -6480,37 +6738,24 @@ function normalizeCliProviderForRuntime(raw) {
6480
6738
  }
6481
6739
  };
6482
6740
  }
6483
- var os7, path7, import_child_process4, pty2, ProviderCliAdapter;
6741
+ var os9, path7, import_child_process4, pty2, buildCliSpawnEnv, ProviderCliAdapter;
6484
6742
  var init_provider_cli_adapter = __esm({
6485
6743
  "../../oss/packages/daemon-core/src/cli-adapters/provider-cli-adapter.ts"() {
6486
6744
  "use strict";
6487
- os7 = __toESM(require("os"));
6745
+ os9 = __toESM(require("os"));
6488
6746
  path7 = __toESM(require("path"));
6489
6747
  import_child_process4 = require("child_process");
6490
6748
  init_logger();
6491
6749
  init_terminal_screen();
6492
6750
  init_pty_transport();
6751
+ init_spawn_env();
6493
6752
  try {
6494
6753
  pty2 = require("node-pty");
6495
- if (os7.platform() !== "win32") {
6496
- try {
6497
- const fs19 = require("fs");
6498
- const ptyDir = path7.resolve(path7.dirname(require.resolve("node-pty")), "..");
6499
- const platformArch = `${os7.platform()}-${os7.arch()}`;
6500
- const helper = path7.join(ptyDir, "prebuilds", platformArch, "spawn-helper");
6501
- if (fs19.existsSync(helper)) {
6502
- const stat4 = fs19.statSync(helper);
6503
- if (!(stat4.mode & 73)) {
6504
- fs19.chmodSync(helper, stat4.mode | 493);
6505
- LOG.info("CLI", "[node-pty] Fixed spawn-helper permissions");
6506
- }
6507
- }
6508
- } catch {
6509
- }
6510
- }
6754
+ ensureNodePtySpawnHelperPermissions((msg) => LOG.info("CLI", msg));
6511
6755
  } catch {
6512
6756
  LOG.error("CLI", "[ProviderCliAdapter] node-pty not found. Terminal features disabled.");
6513
6757
  }
6758
+ buildCliSpawnEnv = sanitizeSpawnEnv;
6514
6759
  ProviderCliAdapter = class _ProviderCliAdapter {
6515
6760
  constructor(provider, workingDir, extraArgs = [], transportFactory = new NodePtyTransportFactory()) {
6516
6761
  this.extraArgs = extraArgs;
@@ -6518,7 +6763,7 @@ var init_provider_cli_adapter = __esm({
6518
6763
  this.transportFactory = transportFactory;
6519
6764
  this.cliType = provider.type;
6520
6765
  this.cliName = provider.name;
6521
- this.workingDir = workingDir.startsWith("~") ? workingDir.replace(/^~/, os7.homedir()) : workingDir;
6766
+ this.workingDir = workingDir.startsWith("~") ? workingDir.replace(/^~/, os9.homedir()) : workingDir;
6522
6767
  const t = provider.timeouts || {};
6523
6768
  this.timeouts = {
6524
6769
  ptyFlush: t.ptyFlush ?? 50,
@@ -6825,7 +7070,7 @@ var init_provider_cli_adapter = __esm({
6825
7070
  if (this.ptyProcess) return;
6826
7071
  const { spawn: spawnConfig } = this.provider;
6827
7072
  const binaryPath = findBinary(spawnConfig.command);
6828
- const isWin = os7.platform() === "win32";
7073
+ const isWin = os9.platform() === "win32";
6829
7074
  const allArgs = [...spawnConfig.args, ...this.extraArgs];
6830
7075
  LOG.info("CLI", `[${this.cliType}] Spawning in ${this.workingDir}`);
6831
7076
  this.resetTraceSession();
@@ -6833,13 +7078,16 @@ var init_provider_cli_adapter = __esm({
6833
7078
  let shellArgs;
6834
7079
  const useShellUnix = !isWin && (!!spawnConfig.shell || !path7.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
6835
7080
  const isCmdShim = isWin && /\.(cmd|bat)$/i.test(binaryPath);
6836
- const useShell = isWin ? !!spawnConfig.shell || isCmdShim : useShellUnix;
7081
+ const useShellWin = isCmdShim || !path7.isAbsolute(binaryPath) || isScriptBinary(binaryPath);
7082
+ const useShell = isWin ? useShellWin : useShellUnix;
6837
7083
  if (useShell) {
6838
7084
  if (!spawnConfig.shell && !isWin) {
6839
7085
  LOG.info("CLI", `[${this.cliType}] Using login shell (script shim or non-native binary)`);
6840
7086
  }
6841
7087
  if (isCmdShim) {
6842
7088
  LOG.info("CLI", `[${this.cliType}] Using cmd.exe shell for .cmd/.bat shim: ${binaryPath}`);
7089
+ } else if (isWin) {
7090
+ LOG.info("CLI", `[${this.cliType}] Using cmd.exe shell on Windows: ${binaryPath}`);
6843
7091
  }
6844
7092
  shellCmd = isWin ? "cmd.exe" : process.env.SHELL || "/bin/zsh";
6845
7093
  if (isWin) {
@@ -6849,6 +7097,9 @@ var init_provider_cli_adapter = __esm({
6849
7097
  shellArgs = ["-l", "-c", fullCmd];
6850
7098
  }
6851
7099
  } else {
7100
+ if (isWin && spawnConfig.shell) {
7101
+ LOG.info("CLI", `[${this.cliType}] Spawning Windows binary directly without cmd.exe: ${binaryPath}`);
7102
+ }
6852
7103
  shellCmd = binaryPath;
6853
7104
  shellArgs = allArgs;
6854
7105
  }
@@ -6877,6 +7128,12 @@ var init_provider_cli_adapter = __esm({
6877
7128
  shellArgs = ["-l", "-c", fullCmd];
6878
7129
  this.ptyProcess = this.transportFactory.spawn(shellCmd, shellArgs, ptyOpts);
6879
7130
  } else {
7131
+ if (isWin) {
7132
+ const hint = /error code 267|ERROR_DIRECTORY/i.test(msg) ? " (working directory does not exist or is not a directory)" : /error code 740|elevation/i.test(msg) ? " (requires administrator privileges)" : /error code 2|ENOENT|not found/i.test(msg) ? ` (executable not found: ${shellCmd})` : "";
7133
+ if (hint) {
7134
+ throw new Error(`Failed to spawn CLI${hint}: ${msg}`);
7135
+ }
7136
+ }
6880
7137
  throw err;
6881
7138
  }
6882
7139
  }
@@ -7629,7 +7886,8 @@ ${data.message || ""}`.trim();
7629
7886
  const payload = stopCommand.endsWith("\r") || stopCommand.endsWith("\n") ? stopCommand : `${stopCommand}${this.sendKey}`;
7630
7887
  this.ptyProcess.write(payload);
7631
7888
  };
7632
- if (wasProcessing) setTimeout(writeCommand, 250);
7889
+ const interruptGraceMs = typeof resume.interruptGraceMs === "number" ? Math.max(100, resume.interruptGraceMs) : 500;
7890
+ if (wasProcessing) setTimeout(writeCommand, interruptGraceMs);
7633
7891
  else writeCommand();
7634
7892
  } else {
7635
7893
  this.ptyProcess.write("");
@@ -7674,6 +7932,18 @@ ${data.message || ""}`.trim();
7674
7932
  clearTimeout(this.submitRetryTimer);
7675
7933
  this.submitRetryTimer = null;
7676
7934
  }
7935
+ if (this.responseTimeout) {
7936
+ clearTimeout(this.responseTimeout);
7937
+ this.responseTimeout = null;
7938
+ }
7939
+ if (this.idleTimeout) {
7940
+ clearTimeout(this.idleTimeout);
7941
+ this.idleTimeout = null;
7942
+ }
7943
+ if (this.pendingScriptStatusTimer) {
7944
+ clearTimeout(this.pendingScriptStatusTimer);
7945
+ this.pendingScriptStatusTimer = null;
7946
+ }
7677
7947
  if (this.pendingOutputParseTimer) {
7678
7948
  clearTimeout(this.pendingOutputParseTimer);
7679
7949
  this.pendingOutputParseTimer = null;
@@ -7715,6 +7985,18 @@ ${data.message || ""}`.trim();
7715
7985
  clearTimeout(this.submitRetryTimer);
7716
7986
  this.submitRetryTimer = null;
7717
7987
  }
7988
+ if (this.responseTimeout) {
7989
+ clearTimeout(this.responseTimeout);
7990
+ this.responseTimeout = null;
7991
+ }
7992
+ if (this.idleTimeout) {
7993
+ clearTimeout(this.idleTimeout);
7994
+ this.idleTimeout = null;
7995
+ }
7996
+ if (this.pendingScriptStatusTimer) {
7997
+ clearTimeout(this.pendingScriptStatusTimer);
7998
+ this.pendingScriptStatusTimer = null;
7999
+ }
7718
8000
  if (this.pendingOutputParseTimer) {
7719
8001
  clearTimeout(this.pendingOutputParseTimer);
7720
8002
  this.pendingOutputParseTimer = null;
@@ -7909,11 +8191,11 @@ function getDatabaseSync() {
7909
8191
  }
7910
8192
  return CachedDatabaseSync;
7911
8193
  }
7912
- var os8, path8, crypto3, fs5, import_node_module, CachedDatabaseSync, CliProviderInstance;
8194
+ var os10, path8, crypto3, fs5, import_node_module, CachedDatabaseSync, CliProviderInstance;
7913
8195
  var init_cli_provider_instance = __esm({
7914
8196
  "../../oss/packages/daemon-core/src/providers/cli-provider-instance.ts"() {
7915
8197
  "use strict";
7916
- os8 = __toESM(require("os"));
8198
+ os10 = __toESM(require("os"));
7917
8199
  path8 = __toESM(require("path"));
7918
8200
  crypto3 = __toESM(require("crypto"));
7919
8201
  fs5 = __toESM(require("fs"));
@@ -7994,17 +8276,60 @@ var init_cli_provider_instance = __esm({
7994
8276
  async onTick() {
7995
8277
  if (this.providerSessionId) return;
7996
8278
  let probedSessionId = null;
7997
- if (this.type === "opencode-cli") {
7998
- probedSessionId = this.probeOpenCodeSessionId();
7999
- } else if (this.type === "codex-cli") {
8000
- probedSessionId = this.probeCodexSessionId();
8001
- } else if (this.type === "goose-cli") {
8002
- probedSessionId = this.probeGooseSessionId();
8279
+ const probeConfig = this.provider.sessionProbe;
8280
+ if (probeConfig) {
8281
+ probedSessionId = this.probeSessionIdFromConfig(probeConfig);
8282
+ } else {
8283
+ if (this.type === "opencode-cli") {
8284
+ probedSessionId = this.probeSessionIdFromConfig({
8285
+ dbPath: "~/.local/share/opencode/opencode.db",
8286
+ query: "select id from session where directory in ({dirs}) and time_created >= ? and time_archived is null order by time_updated desc limit 1",
8287
+ timestampFormat: "unix_ms"
8288
+ });
8289
+ } else if (this.type === "codex-cli") {
8290
+ probedSessionId = this.probeSessionIdFromConfig({
8291
+ dbPath: "~/.codex/state_5.sqlite",
8292
+ query: "select id from threads where cwd in ({dirs}) and created_at >= ? and archived = 0 order by created_at desc limit 1",
8293
+ timestampFormat: "unix_s"
8294
+ });
8295
+ } else if (this.type === "goose-cli") {
8296
+ probedSessionId = this.probeSessionIdFromConfig({
8297
+ dbPath: "~/.local/share/goose/sessions/sessions.db",
8298
+ query: "select id from sessions where working_dir in ({dirs}) and created_at >= ? order by updated_at desc limit 1",
8299
+ timestampFormat: "iso"
8300
+ });
8301
+ }
8003
8302
  }
8004
8303
  if (probedSessionId) {
8005
8304
  this.promoteProviderSessionId(probedSessionId);
8006
8305
  }
8007
8306
  }
8307
+ /**
8308
+ * Generic session ID probe using declarative ProviderSessionProbe config.
8309
+ * Replaces the previously duplicated probeOpenCode/Codex/Goose functions.
8310
+ */
8311
+ probeSessionIdFromConfig(probe) {
8312
+ const resolvedDbPath = probe.dbPath.replace(/^~/, os10.homedir());
8313
+ if (!fs5.existsSync(resolvedDbPath)) return null;
8314
+ const directories = this.getProbeDirectories();
8315
+ const minCreatedAt = Math.max(0, this.startedAt - 6e4);
8316
+ const tsFormat = probe.timestampFormat || "unix_ms";
8317
+ let timestampParam;
8318
+ if (tsFormat === "unix_s") {
8319
+ timestampParam = Math.floor(minCreatedAt / 1e3);
8320
+ } else if (tsFormat === "iso") {
8321
+ timestampParam = new Date(minCreatedAt).toISOString().slice(0, 19).replace("T", " ");
8322
+ } else {
8323
+ timestampParam = minCreatedAt;
8324
+ }
8325
+ const placeholders = this.buildSqlPlaceholderList(directories.length);
8326
+ const query = probe.query.replace("{dirs}", placeholders);
8327
+ try {
8328
+ return this.querySqliteText(resolvedDbPath, query, [...directories, timestampParam]);
8329
+ } catch {
8330
+ return null;
8331
+ }
8332
+ }
8008
8333
  getState() {
8009
8334
  const adapterStatus = this.adapter.getStatus();
8010
8335
  const parsedStatus = this.adapter.getScriptParsedStatus?.() || null;
@@ -8302,34 +8627,6 @@ var init_cli_provider_instance = __esm({
8302
8627
  });
8303
8628
  LOG.info("CLI", `[${this.type}] discovered provider session id: ${nextSessionId}`);
8304
8629
  }
8305
- probeOpenCodeSessionId() {
8306
- const dbPath = path8.join(os8.homedir(), ".local", "share", "opencode", "opencode.db");
8307
- if (!fs5.existsSync(dbPath)) return null;
8308
- const minCreatedAt = Math.max(0, this.startedAt - 6e4);
8309
- const directories = this.getProbeDirectories();
8310
- const query = `select id from session where directory in (${this.buildSqlPlaceholderList(directories.length)}) and time_created >= ? and time_archived is null order by time_updated desc limit 1;`;
8311
- return this.querySqliteText(dbPath, query, [...directories, minCreatedAt]);
8312
- }
8313
- probeCodexSessionId() {
8314
- const dbPath = path8.join(os8.homedir(), ".codex", "state_5.sqlite");
8315
- if (!fs5.existsSync(dbPath)) return null;
8316
- const minCreatedAt = Math.max(0, Math.floor((this.startedAt - 6e4) / 1e3));
8317
- const directories = this.getProbeDirectories();
8318
- const query = `select id from threads where cwd in (${this.buildSqlPlaceholderList(directories.length)}) and created_at >= ? and archived = 0 order by created_at desc limit 1;`;
8319
- return this.querySqliteText(dbPath, query, [...directories, minCreatedAt]);
8320
- }
8321
- probeGooseSessionId() {
8322
- const dbPath = path8.join(os8.homedir(), ".local", "share", "goose", "sessions", "sessions.db");
8323
- if (!fs5.existsSync(dbPath)) return null;
8324
- const minCreatedAtIso = new Date(Math.max(0, this.startedAt - 6e4)).toISOString().slice(0, 19).replace("T", " ");
8325
- const directories = this.getProbeDirectories();
8326
- const query = `select id from sessions where working_dir in (${this.buildSqlPlaceholderList(directories.length)}) and created_at >= ? order by updated_at desc limit 1;`;
8327
- try {
8328
- return this.querySqliteText(dbPath, query, [...directories, minCreatedAtIso]);
8329
- } catch {
8330
- return null;
8331
- }
8332
- }
8333
8630
  getProbeDirectories() {
8334
8631
  const dirs = /* @__PURE__ */ new Set();
8335
8632
  const addDir = (value) => {
@@ -25688,11 +25985,11 @@ function resolveCliSessionBinding(provider, normalizedType, cliArgs, requestedRe
25688
25985
  launchMode: "new"
25689
25986
  };
25690
25987
  }
25691
- var os9, path9, crypto4, import_chalk, chalkApi, DaemonCliManager;
25988
+ var os11, path9, crypto4, import_chalk, chalkApi, DaemonCliManager;
25692
25989
  var init_cli_manager = __esm({
25693
25990
  "../../oss/packages/daemon-core/src/commands/cli-manager.ts"() {
25694
25991
  "use strict";
25695
- os9 = __toESM(require("os"));
25992
+ os11 = __toESM(require("os"));
25696
25993
  path9 = __toESM(require("path"));
25697
25994
  crypto4 = __toESM(require("crypto"));
25698
25995
  import_chalk = __toESM(require("chalk"));
@@ -25844,7 +26141,7 @@ var init_cli_manager = __esm({
25844
26141
  async startSession(cliType, workingDir, cliArgs, initialModel, options) {
25845
26142
  const trimmed = (workingDir || "").trim();
25846
26143
  if (!trimmed) throw new Error("working directory required");
25847
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os9.homedir()) : path9.resolve(trimmed);
26144
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os11.homedir()) : path9.resolve(trimmed);
25848
26145
  const normalizedType = this.providerLoader.resolveAlias(cliType);
25849
26146
  const provider = this.providerLoader.getByAlias(cliType);
25850
26147
  const key = crypto4.randomUUID();
@@ -25928,7 +26225,19 @@ ${installInfo}`
25928
26225
  return { runtimeSessionId: sessionId };
25929
26226
  }
25930
26227
  const cliInfo = await detectCLI(cliType, this.providerLoader);
25931
- if (!cliInfo) throw new Error(`${cliType} not found`);
26228
+ if (!cliInfo) {
26229
+ const installHint = provider?.install || "";
26230
+ const displayName = provider?.displayName || provider?.name || cliType;
26231
+ const spawnCmd = provider?.spawn?.command || cliType;
26232
+ throw new Error(
26233
+ `${displayName} is not installed.
26234
+ Command '${spawnCmd}' not found on PATH.
26235
+ ` + (installHint ? `
26236
+ ${installHint}
26237
+ ` : "") + `
26238
+ Run 'adhdev doctor' for detailed diagnostics.`
26239
+ );
26240
+ }
25932
26241
  console.log(colorize("yellow", ` \u26A1 Starting CLI ${cliType} in ${resolvedDir}...`));
25933
26242
  if (provider) {
25934
26243
  console.log(colorize("cyan", ` \u{1F4E6} Using provider: ${provider.name} (${provider.type})`));
@@ -26244,8 +26553,9 @@ ${installInfo}`
26244
26553
  const dir = rdir.path;
26245
26554
  if (!cliType) throw new Error("cliType required");
26246
26555
  const found = this.findAdapter(cliType, { instanceKey: args?.targetSessionId, dir });
26556
+ const prevCliArgs = found ? found.adapter.extraArgs : void 0;
26247
26557
  if (found) await this.stopSession(found.key);
26248
- await this.startSession(cliType, dir);
26558
+ await this.startSession(cliType, dir, args?.cliArgs || prevCliArgs, args?.initialModel);
26249
26559
  return { success: true, restarted: true };
26250
26560
  }
26251
26561
  case "agent_command": {
@@ -28029,13 +28339,13 @@ var init_chokidar = __esm({
28029
28339
  });
28030
28340
 
28031
28341
  // ../../oss/packages/daemon-core/src/providers/provider-loader.ts
28032
- var fs6, path10, os10, ProviderLoader;
28342
+ var fs6, path10, os12, ProviderLoader;
28033
28343
  var init_provider_loader = __esm({
28034
28344
  "../../oss/packages/daemon-core/src/providers/provider-loader.ts"() {
28035
28345
  "use strict";
28036
28346
  fs6 = __toESM(require("fs"));
28037
28347
  path10 = __toESM(require("path"));
28038
- os10 = __toESM(require("os"));
28348
+ os12 = __toESM(require("os"));
28039
28349
  init_chokidar();
28040
28350
  init_ide_detector();
28041
28351
  init_logger();
@@ -28056,7 +28366,7 @@ var init_provider_loader = __esm({
28056
28366
  static META_FILE = ".meta.json";
28057
28367
  constructor(options) {
28058
28368
  this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
28059
- const defaultProvidersDir = path10.join(os10.homedir(), ".adhdev", "providers");
28369
+ const defaultProvidersDir = path10.join(os12.homedir(), ".adhdev", "providers");
28060
28370
  if (options?.userDir) {
28061
28371
  this.userDir = options.userDir;
28062
28372
  this.log(`Config 'providerDir' applied: ${this.userDir}`);
@@ -28656,8 +28966,8 @@ var init_provider_loader = __esm({
28656
28966
  return { updated: false };
28657
28967
  }
28658
28968
  this.log("Downloading latest providers from GitHub...");
28659
- const tmpTar = path10.join(os10.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
28660
- const tmpExtract = path10.join(os10.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
28969
+ const tmpTar = path10.join(os12.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
28970
+ const tmpExtract = path10.join(os12.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
28661
28971
  await this.downloadFile(_ProviderLoader.GITHUB_TARBALL_URL, tmpTar);
28662
28972
  fs6.mkdirSync(tmpExtract, { recursive: true });
28663
28973
  execSync7(`tar -xzf "${tmpTar}" -C "${tmpExtract}"`, { timeout: 3e4 });
@@ -29091,7 +29401,7 @@ async function findFreePort(ports) {
29091
29401
  }
29092
29402
  function checkPortFree(port) {
29093
29403
  return new Promise((resolve14) => {
29094
- const server = net.createServer();
29404
+ const server = net2.createServer();
29095
29405
  server.unref();
29096
29406
  server.on("error", () => resolve14(false));
29097
29407
  server.listen(port, "127.0.0.1", () => {
@@ -29123,7 +29433,7 @@ async function isCdpActive(port) {
29123
29433
  });
29124
29434
  }
29125
29435
  async function killIdeProcess(ideId) {
29126
- const plat = os11.platform();
29436
+ const plat = os13.platform();
29127
29437
  const appName = getMacAppIdentifiers()[ideId];
29128
29438
  const winProcesses = getWinProcessNames()[ideId];
29129
29439
  try {
@@ -29182,7 +29492,7 @@ async function killIdeProcess(ideId) {
29182
29492
  }
29183
29493
  }
29184
29494
  function isIdeRunning(ideId) {
29185
- const plat = os11.platform();
29495
+ const plat = os13.platform();
29186
29496
  try {
29187
29497
  if (plat === "darwin") {
29188
29498
  const appName = getMacAppIdentifiers()[ideId];
@@ -29218,7 +29528,7 @@ function isIdeRunning(ideId) {
29218
29528
  }
29219
29529
  }
29220
29530
  function detectCurrentWorkspace(ideId) {
29221
- const plat = os11.platform();
29531
+ const plat = os13.platform();
29222
29532
  if (plat === "darwin") {
29223
29533
  try {
29224
29534
  const appName = getMacAppIdentifiers()[ideId];
@@ -29238,7 +29548,7 @@ function detectCurrentWorkspace(ideId) {
29238
29548
  const appName = appNameMap[ideId];
29239
29549
  if (appName) {
29240
29550
  const storagePath = path11.join(
29241
- process.env.APPDATA || path11.join(os11.homedir(), "AppData", "Roaming"),
29551
+ process.env.APPDATA || path11.join(os13.homedir(), "AppData", "Roaming"),
29242
29552
  appName,
29243
29553
  "storage.json"
29244
29554
  );
@@ -29260,7 +29570,7 @@ function detectCurrentWorkspace(ideId) {
29260
29570
  return void 0;
29261
29571
  }
29262
29572
  async function launchWithCdp(options = {}) {
29263
- const platform10 = os11.platform();
29573
+ const platform11 = os13.platform();
29264
29574
  let targetIde;
29265
29575
  const ides = await detectIDEs();
29266
29576
  if (options.ideId) {
@@ -29329,9 +29639,9 @@ async function launchWithCdp(options = {}) {
29329
29639
  }
29330
29640
  const port = await findFreePort(portPair);
29331
29641
  try {
29332
- if (platform10 === "darwin") {
29642
+ if (platform11 === "darwin") {
29333
29643
  await launchMacOS(targetIde, port, workspace, options.newWindow);
29334
- } else if (platform10 === "win32") {
29644
+ } else if (platform11 === "win32") {
29335
29645
  await launchWindows(targetIde, port, workspace, options.newWindow);
29336
29646
  } else {
29337
29647
  await launchLinux(targetIde, port, workspace, options.newWindow);
@@ -29404,13 +29714,13 @@ async function launchLinux(ide, port, workspace, newWindow) {
29404
29714
  function getAvailableIdeIds() {
29405
29715
  return getProviderLoader().getAvailableIdeTypes();
29406
29716
  }
29407
- var import_child_process6, net, os11, path11, _providerLoader;
29717
+ var import_child_process6, net2, os13, path11, _providerLoader;
29408
29718
  var init_launch = __esm({
29409
29719
  "../../oss/packages/daemon-core/src/launch.ts"() {
29410
29720
  "use strict";
29411
29721
  import_child_process6 = require("child_process");
29412
- net = __toESM(require("net"));
29413
- os11 = __toESM(require("os"));
29722
+ net2 = __toESM(require("net"));
29723
+ os13 = __toESM(require("os"));
29414
29724
  path11 = __toESM(require("path"));
29415
29725
  init_ide_detector();
29416
29726
  init_provider_loader();
@@ -29523,14 +29833,14 @@ function getRecentCommands(count = 50) {
29523
29833
  return [];
29524
29834
  }
29525
29835
  }
29526
- var fs7, path12, os12, LOG_DIR2, MAX_FILE_SIZE, MAX_DAYS, SENSITIVE_KEYS, currentDate2, currentFile, writeCount2, SKIP_COMMANDS;
29836
+ var fs7, path12, os14, LOG_DIR2, MAX_FILE_SIZE, MAX_DAYS, SENSITIVE_KEYS, currentDate2, currentFile, writeCount2, SKIP_COMMANDS;
29527
29837
  var init_command_log = __esm({
29528
29838
  "../../oss/packages/daemon-core/src/logging/command-log.ts"() {
29529
29839
  "use strict";
29530
29840
  fs7 = __toESM(require("fs"));
29531
29841
  path12 = __toESM(require("path"));
29532
- os12 = __toESM(require("os"));
29533
- LOG_DIR2 = process.platform === "win32" ? path12.join(process.env.LOCALAPPDATA || process.env.APPDATA || path12.join(os12.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path12.join(os12.homedir(), "Library", "Logs", "adhdev") : path12.join(os12.homedir(), ".local", "share", "adhdev", "logs");
29842
+ os14 = __toESM(require("os"));
29843
+ LOG_DIR2 = process.platform === "win32" ? path12.join(process.env.LOCALAPPDATA || process.env.APPDATA || path12.join(os14.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path12.join(os14.homedir(), "Library", "Logs", "adhdev") : path12.join(os14.homedir(), ".local", "share", "adhdev", "logs");
29534
29844
  MAX_FILE_SIZE = 5 * 1024 * 1024;
29535
29845
  MAX_DAYS = 7;
29536
29846
  try {
@@ -29671,16 +29981,16 @@ function buildStatusSnapshot(options) {
29671
29981
  version: options.version,
29672
29982
  daemonMode: options.daemonMode,
29673
29983
  machine: {
29674
- hostname: os13.hostname(),
29675
- platform: os13.platform(),
29676
- arch: os13.arch(),
29677
- cpus: os13.cpus().length,
29984
+ hostname: os15.hostname(),
29985
+ platform: os15.platform(),
29986
+ arch: os15.arch(),
29987
+ cpus: os15.cpus().length,
29678
29988
  totalMem: memSnap.totalMem,
29679
29989
  freeMem: memSnap.freeMem,
29680
29990
  availableMem: memSnap.availableMem,
29681
- loadavg: os13.loadavg(),
29682
- uptime: os13.uptime(),
29683
- release: os13.release()
29991
+ loadavg: os15.loadavg(),
29992
+ uptime: os15.uptime(),
29993
+ release: os15.release()
29684
29994
  },
29685
29995
  machineNickname: options.machineNickname ?? cfg.machineNickname ?? null,
29686
29996
  timestamp: options.timestamp ?? Date.now(),
@@ -29695,11 +30005,11 @@ function buildStatusSnapshot(options) {
29695
30005
  availableProviders: buildAvailableProviders(options.providerLoader)
29696
30006
  };
29697
30007
  }
29698
- var os13, READ_DEBUG_ENABLED;
30008
+ var os15, READ_DEBUG_ENABLED;
29699
30009
  var init_snapshot = __esm({
29700
30010
  "../../oss/packages/daemon-core/src/status/snapshot.ts"() {
29701
30011
  "use strict";
29702
- os13 = __toESM(require("os"));
30012
+ os15 = __toESM(require("os"));
29703
30013
  init_config();
29704
30014
  init_recent_activity();
29705
30015
  init_workspaces();
@@ -29713,7 +30023,7 @@ var init_snapshot = __esm({
29713
30023
 
29714
30024
  // ../../oss/packages/daemon-core/src/commands/upgrade-helper.ts
29715
30025
  function getUpgradeLogPath() {
29716
- const home = os14.homedir();
30026
+ const home = os16.homedir();
29717
30027
  const dir = path13.join(home, ".adhdev");
29718
30028
  fs8.mkdirSync(dir, { recursive: true });
29719
30029
  return path13.join(dir, "daemon-upgrade.log");
@@ -29753,7 +30063,7 @@ async function waitForPidExit(pid, timeoutMs) {
29753
30063
  }
29754
30064
  }
29755
30065
  function stopSessionHostProcesses(appName) {
29756
- const pidFile = path13.join(os14.homedir(), ".adhdev", `${appName}-session-host.pid`);
30066
+ const pidFile = path13.join(os16.homedir(), ".adhdev", `${appName}-session-host.pid`);
29757
30067
  try {
29758
30068
  if (fs8.existsSync(pidFile)) {
29759
30069
  const pid = Number.parseInt(fs8.readFileSync(pidFile, "utf8").trim(), 10);
@@ -29782,7 +30092,7 @@ function stopSessionHostProcesses(appName) {
29782
30092
  }
29783
30093
  }
29784
30094
  function removeDaemonPidFile() {
29785
- const pidFile = path13.join(os14.homedir(), ".adhdev", "daemon.pid");
30095
+ const pidFile = path13.join(os16.homedir(), ".adhdev", "daemon.pid");
29786
30096
  try {
29787
30097
  fs8.unlinkSync(pidFile);
29788
30098
  } catch {
@@ -29887,14 +30197,14 @@ async function maybeRunDaemonUpgradeHelperFromEnv() {
29887
30197
  process.exit(1);
29888
30198
  }
29889
30199
  }
29890
- var import_child_process7, import_child_process8, fs8, os14, path13, UPGRADE_HELPER_ENV;
30200
+ var import_child_process7, import_child_process8, fs8, os16, path13, UPGRADE_HELPER_ENV;
29891
30201
  var init_upgrade_helper = __esm({
29892
30202
  "../../oss/packages/daemon-core/src/commands/upgrade-helper.ts"() {
29893
30203
  "use strict";
29894
30204
  import_child_process7 = require("child_process");
29895
30205
  import_child_process8 = require("child_process");
29896
30206
  fs8 = __toESM(require("fs"));
29897
- os14 = __toESM(require("os"));
30207
+ os16 = __toESM(require("os"));
29898
30208
  path13 = __toESM(require("path"));
29899
30209
  UPGRADE_HELPER_ENV = "ADHDEV_DAEMON_UPGRADE_HELPER";
29900
30210
  }
@@ -31418,7 +31728,7 @@ function getVersion(binary, versionCommand) {
31418
31728
  function checkPathExists2(paths) {
31419
31729
  for (const p of paths) {
31420
31730
  if (p.includes("*")) {
31421
- const home = os15.homedir();
31731
+ const home = os17.homedir();
31422
31732
  const resolved = p.replace(/\*/g, home.split(path14.sep).pop() || "");
31423
31733
  if (fs10.existsSync(resolved)) return resolved;
31424
31734
  } else {
@@ -31493,16 +31803,16 @@ async function detectAllVersions(loader, archive) {
31493
31803
  }
31494
31804
  return results;
31495
31805
  }
31496
- var fs10, path14, os15, import_child_process9, import_os3, ARCHIVE_PATH, MAX_ENTRIES_PER_PROVIDER, VersionArchive;
31806
+ var fs10, path14, os17, import_child_process9, import_os3, ARCHIVE_PATH, MAX_ENTRIES_PER_PROVIDER, VersionArchive;
31497
31807
  var init_version_archive = __esm({
31498
31808
  "../../oss/packages/daemon-core/src/providers/version-archive.ts"() {
31499
31809
  "use strict";
31500
31810
  fs10 = __toESM(require("fs"));
31501
31811
  path14 = __toESM(require("path"));
31502
- os15 = __toESM(require("os"));
31812
+ os17 = __toESM(require("os"));
31503
31813
  import_child_process9 = require("child_process");
31504
31814
  import_os3 = require("os");
31505
- ARCHIVE_PATH = path14.join(os15.homedir(), ".adhdev", "version-history.json");
31815
+ ARCHIVE_PATH = path14.join(os17.homedir(), ".adhdev", "version-history.json");
31506
31816
  MAX_ENTRIES_PER_PROVIDER = 20;
31507
31817
  VersionArchive = class {
31508
31818
  history = {};
@@ -34019,7 +34329,7 @@ async function handleAutoImplement(ctx, type, req, res) {
34019
34329
  });
34020
34330
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
34021
34331
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
34022
- const tmpDir = path17.join(os16.tmpdir(), "adhdev-autoimpl");
34332
+ const tmpDir = path17.join(os18.tmpdir(), "adhdev-autoimpl");
34023
34333
  if (!fs13.existsSync(tmpDir)) fs13.mkdirSync(tmpDir, { recursive: true });
34024
34334
  const promptFile = path17.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
34025
34335
  fs13.writeFileSync(promptFile, prompt, "utf-8");
@@ -34173,7 +34483,7 @@ async function handleAutoImplement(ctx, type, req, res) {
34173
34483
  const interactiveFlags = ["--yolo", "--interactive", "-i"];
34174
34484
  const baseArgs = [...spawn5.args || []].filter((a) => !interactiveFlags.includes(a));
34175
34485
  let shellCmd;
34176
- const isWin = os16.platform() === "win32";
34486
+ const isWin = os18.platform() === "win32";
34177
34487
  const escapeArg = (a) => isWin ? `"${a.replace(/"/g, '""')}"` : `'${a.replace(/'/g, "'\\''")}'`;
34178
34488
  if (command === "claude") {
34179
34489
  const args = [...baseArgs, "--dangerously-skip-permissions"];
@@ -34217,7 +34527,7 @@ async function handleAutoImplement(ctx, type, req, res) {
34217
34527
  try {
34218
34528
  const pty3 = require("node-pty");
34219
34529
  ctx.log(`Auto-implement spawn (PTY): ${shellCmd}`);
34220
- const isWin2 = os16.platform() === "win32";
34530
+ const isWin2 = os18.platform() === "win32";
34221
34531
  child = pty3.spawn(isWin2 ? "cmd.exe" : process.env.SHELL || "/bin/zsh", [isWin2 ? "/c" : "-c", shellCmd], {
34222
34532
  name: "xterm-256color",
34223
34533
  cols: 120,
@@ -35124,13 +35434,13 @@ data: ${JSON.stringify(msg.data)}
35124
35434
  }
35125
35435
  }
35126
35436
  }
35127
- var fs13, path17, os16;
35437
+ var fs13, path17, os18;
35128
35438
  var init_dev_auto_implement = __esm({
35129
35439
  "../../oss/packages/daemon-core/src/daemon/dev-auto-implement.ts"() {
35130
35440
  "use strict";
35131
35441
  fs13 = __toESM(require("fs"));
35132
35442
  path17 = __toESM(require("path"));
35133
- os16 = __toESM(require("os"));
35443
+ os18 = __toESM(require("os"));
35134
35444
  init_dev_server();
35135
35445
  init_dev_cli_debug();
35136
35446
  }
@@ -36651,141 +36961,6 @@ data: ${JSON.stringify(msg.data)}
36651
36961
  }
36652
36962
  });
36653
36963
 
36654
- // ../../oss/packages/session-host-core/dist/index.mjs
36655
- function getDefaultSessionHostEndpoint(appName = "adhdev") {
36656
- if (process.platform === "win32") {
36657
- return {
36658
- kind: "pipe",
36659
- path: `\\\\.\\pipe\\${appName}-session-host`
36660
- };
36661
- }
36662
- return {
36663
- kind: "unix",
36664
- path: path22.join(os17.tmpdir(), `${appName}-session-host.sock`)
36665
- };
36666
- }
36667
- function serializeEnvelope(envelope) {
36668
- return `${JSON.stringify(envelope)}
36669
- `;
36670
- }
36671
- function createLineParser(onEnvelope) {
36672
- let buffer = "";
36673
- return (chunk) => {
36674
- buffer += chunk.toString();
36675
- let newlineIndex = buffer.indexOf("\n");
36676
- while (newlineIndex >= 0) {
36677
- const rawLine = buffer.slice(0, newlineIndex).trim();
36678
- buffer = buffer.slice(newlineIndex + 1);
36679
- if (rawLine) {
36680
- onEnvelope(JSON.parse(rawLine));
36681
- }
36682
- newlineIndex = buffer.indexOf("\n");
36683
- }
36684
- };
36685
- }
36686
- var os17, path22, net2, import_crypto3, SessionHostClient;
36687
- var init_dist = __esm({
36688
- "../../oss/packages/session-host-core/dist/index.mjs"() {
36689
- "use strict";
36690
- os17 = __toESM(require("os"), 1);
36691
- path22 = __toESM(require("path"), 1);
36692
- net2 = __toESM(require("net"), 1);
36693
- import_crypto3 = require("crypto");
36694
- SessionHostClient = class {
36695
- endpoint;
36696
- socket = null;
36697
- requestWaiters = /* @__PURE__ */ new Map();
36698
- eventListeners = /* @__PURE__ */ new Set();
36699
- constructor(options = {}) {
36700
- this.endpoint = options.endpoint || getDefaultSessionHostEndpoint(options.appName || "adhdev");
36701
- }
36702
- async connect() {
36703
- if (this.socket && !this.socket.destroyed) return;
36704
- const socket = net2.createConnection(this.endpoint.path);
36705
- this.socket = socket;
36706
- socket.on("data", createLineParser((envelope) => {
36707
- if (envelope.kind === "response") {
36708
- const waiter = this.requestWaiters.get(envelope.requestId);
36709
- if (waiter) {
36710
- this.requestWaiters.delete(envelope.requestId);
36711
- waiter.resolve(envelope.response);
36712
- }
36713
- return;
36714
- }
36715
- if (envelope.kind === "event") {
36716
- for (const listener of this.eventListeners) listener(envelope.event);
36717
- }
36718
- }));
36719
- socket.on("error", (error48) => {
36720
- for (const waiter of this.requestWaiters.values()) {
36721
- waiter.reject(error48);
36722
- }
36723
- this.requestWaiters.clear();
36724
- });
36725
- await new Promise((resolve14, reject) => {
36726
- socket.once("connect", () => resolve14());
36727
- socket.once("error", reject);
36728
- });
36729
- }
36730
- onEvent(listener) {
36731
- this.eventListeners.add(listener);
36732
- return () => {
36733
- this.eventListeners.delete(listener);
36734
- };
36735
- }
36736
- async request(request) {
36737
- await this.connect();
36738
- if (!this.socket) throw new Error("Session host socket unavailable");
36739
- const requestId = (0, import_crypto3.randomUUID)();
36740
- const envelope = {
36741
- kind: "request",
36742
- requestId,
36743
- request
36744
- };
36745
- const response = await new Promise((resolve14, reject) => {
36746
- const timeout = setTimeout(() => {
36747
- this.requestWaiters.delete(requestId);
36748
- reject(new Error(`Session host request timed out after 30s (${request.type})`));
36749
- }, 3e4);
36750
- this.requestWaiters.set(requestId, {
36751
- resolve: (value) => {
36752
- clearTimeout(timeout);
36753
- resolve14(value);
36754
- },
36755
- reject: (error48) => {
36756
- clearTimeout(timeout);
36757
- reject(error48);
36758
- }
36759
- });
36760
- this.socket?.write(serializeEnvelope(envelope));
36761
- });
36762
- return response;
36763
- }
36764
- async close() {
36765
- if (!this.socket) return;
36766
- const socket = this.socket;
36767
- this.socket = null;
36768
- for (const waiter of this.requestWaiters.values()) {
36769
- waiter.reject(new Error("Session host client closed"));
36770
- }
36771
- this.requestWaiters.clear();
36772
- await new Promise((resolve14) => {
36773
- let settled = false;
36774
- const done = () => {
36775
- if (settled) return;
36776
- settled = true;
36777
- resolve14();
36778
- };
36779
- socket.once("close", done);
36780
- socket.end();
36781
- socket.destroy();
36782
- setTimeout(done, 50);
36783
- });
36784
- }
36785
- };
36786
- }
36787
- });
36788
-
36789
36964
  // ../../oss/packages/daemon-core/src/cli-adapters/session-host-transport.ts
36790
36965
  var SessionHostRuntimeTransport, SessionHostPtyTransportFactory;
36791
36966
  var init_session_host_transport = __esm({
@@ -38242,17 +38417,17 @@ function canPeerUsePrivilegedShareCommand(commandType, permission) {
38242
38417
  return false;
38243
38418
  }
38244
38419
  }
38245
- var fs15, path19, os18, import_node_module2, esmRequire, logFile, log, logDebug, DaemonP2PSender;
38420
+ var fs15, path19, os19, import_node_module2, esmRequire, logFile, log, logDebug, DaemonP2PSender;
38246
38421
  var init_daemon_p2p = __esm({
38247
38422
  "src/daemon-p2p.ts"() {
38248
38423
  "use strict";
38249
38424
  fs15 = __toESM(require("fs"));
38250
38425
  init_src();
38251
38426
  path19 = __toESM(require("path"));
38252
- os18 = __toESM(require("os"));
38427
+ os19 = __toESM(require("os"));
38253
38428
  import_node_module2 = require("module");
38254
38429
  esmRequire = (0, import_node_module2.createRequire)(__filename);
38255
- logFile = path19.join(os18.tmpdir(), "adhdev_daemon_p2p.log");
38430
+ logFile = path19.join(os19.tmpdir(), "adhdev_daemon_p2p.log");
38256
38431
  log = (msg) => {
38257
38432
  LOG.info("P2P", `[${(/* @__PURE__ */ new Date()).toISOString()}] [P2P] ${msg}`);
38258
38433
  };
@@ -38315,9 +38490,9 @@ var init_daemon_p2p = __esm({
38315
38490
  log(`node-datachannel not found: ${e?.message}
38316
38491
  ${e?.stack || ""}`);
38317
38492
  }
38318
- const platform10 = process.platform;
38493
+ const platform11 = process.platform;
38319
38494
  const arch3 = process.arch;
38320
- const prebuildKey = `${platform10}-${arch3}`;
38495
+ const prebuildKey = `${platform11}-${arch3}`;
38321
38496
  try {
38322
38497
  const candidates = [
38323
38498
  path19.join(__dirname, "node_modules", "node-datachannel"),
@@ -41040,7 +41215,7 @@ var require_sharp = __commonJS({
41040
41215
  if (sharp) {
41041
41216
  module2.exports = sharp;
41042
41217
  } else {
41043
- const [isLinux2, isMacOs, isWindows2] = ["linux", "darwin", "win32"].map((os22) => runtimePlatform.startsWith(os22));
41218
+ const [isLinux2, isMacOs, isWindows2] = ["linux", "darwin", "win32"].map((os24) => runtimePlatform.startsWith(os24));
41044
41219
  const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`];
41045
41220
  errors.forEach((err) => {
41046
41221
  if (err.code !== "MODULE_NOT_FOUND") {
@@ -41057,15 +41232,15 @@ var require_sharp = __commonJS({
41057
41232
  ` Requires ${expected}`
41058
41233
  );
41059
41234
  } else if (prebuiltPlatforms.includes(runtimePlatform)) {
41060
- const [os22, cpu] = runtimePlatform.split("-");
41061
- const libc = os22.endsWith("musl") ? " --libc=musl" : "";
41235
+ const [os24, cpu] = runtimePlatform.split("-");
41236
+ const libc = os24.endsWith("musl") ? " --libc=musl" : "";
41062
41237
  help.push(
41063
41238
  "- Ensure optional dependencies can be installed:",
41064
41239
  " npm install --include=optional sharp",
41065
41240
  "- Ensure your package manager supports multi-platform installation:",
41066
41241
  " See https://sharp.pixelplumbing.com/install#cross-platform",
41067
41242
  "- Add platform-specific dependencies:",
41068
- ` npm install --os=${os22.replace("musl", "")}${libc} --cpu=${cpu} sharp`
41243
+ ` npm install --os=${os24.replace("musl", "")}${libc} --cpu=${cpu} sharp`
41069
41244
  );
41070
41245
  } else {
41071
41246
  help.push(
@@ -45806,24 +45981,7 @@ __export(session_host_exports, {
45806
45981
  stopSessionHost: () => stopSessionHost
45807
45982
  });
45808
45983
  function buildSessionHostEnv(baseEnv) {
45809
- const env = {};
45810
- for (const [key, value] of Object.entries(baseEnv)) {
45811
- if (typeof value !== "string") continue;
45812
- env[key] = value;
45813
- }
45814
- for (const key of Object.keys(env)) {
45815
- if (key === "INIT_CWD" || 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_")) {
45816
- delete env[key];
45817
- }
45818
- }
45819
- if (!env.NO_COLOR) {
45820
- if (!env.TERM || env.TERM === "xterm-color") env.TERM = "xterm-256color";
45821
- if (!env.COLORTERM) env.COLORTERM = "truecolor";
45822
- if (process.platform === "win32") {
45823
- if (!env.FORCE_COLOR) env.FORCE_COLOR = "1";
45824
- if (!env.CLICOLOR) env.CLICOLOR = "1";
45825
- }
45826
- }
45984
+ const env = sanitizeSpawnEnv(baseEnv);
45827
45985
  env.ADHDEV_SESSION_HOST_NAME = SESSION_HOST_APP_NAME;
45828
45986
  return env;
45829
45987
  }
@@ -45840,7 +45998,7 @@ function resolveSessionHostEntry() {
45840
45998
  return require.resolve("@adhdev/session-host-daemon");
45841
45999
  }
45842
46000
  function getSessionHostPidFile() {
45843
- return path20.join(os19.homedir(), ".adhdev", `${SESSION_HOST_APP_NAME}-session-host.pid`);
46001
+ return path20.join(os20.homedir(), ".adhdev", `${SESSION_HOST_APP_NAME}-session-host.pid`);
45844
46002
  }
45845
46003
  function getSessionHostStatusPaths() {
45846
46004
  return {
@@ -45861,7 +46019,7 @@ function getSessionHostPid() {
45861
46019
  function killPid2(pid) {
45862
46020
  try {
45863
46021
  if (process.platform === "win32") {
45864
- (0, import_child_process11.execFileSync)("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore" });
46022
+ (0, import_child_process11.execFileSync)("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
45865
46023
  } else {
45866
46024
  process.kill(pid, "SIGTERM");
45867
46025
  }
@@ -45870,6 +46028,35 @@ function killPid2(pid) {
45870
46028
  return false;
45871
46029
  }
45872
46030
  }
46031
+ function getWindowsProcessCommandLine(pid) {
46032
+ const pidFilter = `ProcessId=${pid}`;
46033
+ try {
46034
+ const wmicOut = (0, import_child_process11.execFileSync)("wmic", [
46035
+ "process",
46036
+ "where",
46037
+ pidFilter,
46038
+ "get",
46039
+ "CommandLine"
46040
+ ], { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
46041
+ const text = wmicOut.trim();
46042
+ if (text) return text;
46043
+ } catch {
46044
+ }
46045
+ try {
46046
+ const psOut = (0, import_child_process11.execFileSync)("powershell.exe", [
46047
+ "-NoProfile",
46048
+ "-NonInteractive",
46049
+ "-ExecutionPolicy",
46050
+ "Bypass",
46051
+ "-Command",
46052
+ `(Get-CimInstance Win32_Process -Filter "${pidFilter}").CommandLine`
46053
+ ], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
46054
+ const text = psOut.trim();
46055
+ if (text) return text;
46056
+ } catch {
46057
+ }
46058
+ return null;
46059
+ }
45873
46060
  function stopSessionHost() {
45874
46061
  let stopped = false;
45875
46062
  const pidFile = getSessionHostPidFile();
@@ -45887,7 +46074,27 @@ function stopSessionHost() {
45887
46074
  } catch {
45888
46075
  }
45889
46076
  }
45890
- if (process.platform !== "win32") {
46077
+ if (process.platform === "win32") {
46078
+ try {
46079
+ const raw = (0, import_child_process11.execFileSync)("tasklist", ["/FO", "CSV", "/NH", "/FI", "IMAGENAME eq node.exe"], {
46080
+ encoding: "utf8",
46081
+ timeout: 5e3,
46082
+ stdio: ["ignore", "pipe", "ignore"],
46083
+ windowsHide: true
46084
+ }).trim();
46085
+ for (const line of raw.split(/\r?\n/)) {
46086
+ const match = line.match(/^"node\.exe","(\d+)"/i);
46087
+ if (!match) continue;
46088
+ const candidatePid = Number.parseInt(match[1], 10);
46089
+ if (!Number.isFinite(candidatePid) || candidatePid === process.pid) continue;
46090
+ const commandLine = getWindowsProcessCommandLine(candidatePid);
46091
+ if (commandLine?.includes("session-host-daemon")) {
46092
+ stopped = killPid2(candidatePid) || stopped;
46093
+ }
46094
+ }
46095
+ } catch {
46096
+ }
46097
+ } else {
45891
46098
  try {
45892
46099
  const raw = (0, import_child_process11.execFileSync)("pgrep", ["-f", "session-host-daemon"], { encoding: "utf8" }).trim();
45893
46100
  for (const line of raw.split("\n")) {
@@ -45904,13 +46111,20 @@ function stopSessionHost() {
45904
46111
  async function ensureSessionHostReady2() {
45905
46112
  const spawnHost = () => {
45906
46113
  const entry = resolveSessionHostEntry();
46114
+ const logDir = path20.join(os20.homedir(), ".adhdev", "logs");
46115
+ fs16.mkdirSync(logDir, { recursive: true });
46116
+ const logFd = fs16.openSync(path20.join(logDir, "session-host.log"), "a");
45907
46117
  const child = (0, import_child_process11.spawn)(process.execPath, [entry], {
45908
46118
  detached: true,
45909
- stdio: "ignore",
46119
+ stdio: ["ignore", logFd, logFd],
45910
46120
  windowsHide: true,
45911
46121
  env: buildSessionHostEnv(process.env)
45912
46122
  });
45913
46123
  child.unref();
46124
+ try {
46125
+ fs16.closeSync(logFd);
46126
+ } catch {
46127
+ }
45914
46128
  };
45915
46129
  try {
45916
46130
  return await ensureSessionHostReady({
@@ -45961,13 +46175,13 @@ async function probeSessionHostStatus() {
45961
46175
  };
45962
46176
  }
45963
46177
  }
45964
- var import_child_process11, fs16, os19, path20, SESSION_HOST_APP_NAME, SESSION_HOST_START_TIMEOUT_MS;
46178
+ var import_child_process11, fs16, os20, path20, SESSION_HOST_APP_NAME, SESSION_HOST_START_TIMEOUT_MS;
45965
46179
  var init_session_host = __esm({
45966
46180
  "src/session-host.ts"() {
45967
46181
  "use strict";
45968
46182
  import_child_process11 = require("child_process");
45969
46183
  fs16 = __toESM(require("fs"));
45970
- os19 = __toESM(require("os"));
46184
+ os20 = __toESM(require("os"));
45971
46185
  path20 = __toESM(require("path"));
45972
46186
  init_src();
45973
46187
  init_dist();
@@ -46012,7 +46226,7 @@ __export(adhdev_daemon_exports, {
46012
46226
  stopDaemon: () => stopDaemon
46013
46227
  });
46014
46228
  function getDaemonPidFile() {
46015
- const dir = path21.join(os20.homedir(), ".adhdev");
46229
+ const dir = path21.join(os21.homedir(), ".adhdev");
46016
46230
  if (!fs17.existsSync(dir)) fs17.mkdirSync(dir, { recursive: true });
46017
46231
  return path21.join(dir, "daemon.pid");
46018
46232
  }
@@ -46060,7 +46274,7 @@ function stopDaemon() {
46060
46274
  return false;
46061
46275
  }
46062
46276
  }
46063
- var os20, fs17, path21, import_http, import_ws3, import_chalk2, pkgVersion, DANGEROUS_PATTERNS, AdhdevDaemon;
46277
+ var os21, fs17, path21, import_http, import_ws3, import_chalk2, pkgVersion, DANGEROUS_PATTERNS, AdhdevDaemon;
46064
46278
  var init_adhdev_daemon = __esm({
46065
46279
  "src/adhdev-daemon.ts"() {
46066
46280
  "use strict";
@@ -46070,14 +46284,14 @@ var init_adhdev_daemon = __esm({
46070
46284
  init_screenshot_controller();
46071
46285
  init_session_host();
46072
46286
  init_dist();
46073
- os20 = __toESM(require("os"));
46287
+ os21 = __toESM(require("os"));
46074
46288
  fs17 = __toESM(require("fs"));
46075
46289
  path21 = __toESM(require("path"));
46076
46290
  import_http = require("http");
46077
46291
  import_ws3 = require("ws");
46078
46292
  import_chalk2 = __toESM(require("chalk"));
46079
46293
  init_version();
46080
- pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.12" });
46294
+ pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.14" });
46081
46295
  DANGEROUS_PATTERNS = [
46082
46296
  /\brm\s+(-[a-z]*f|-[a-z]*r|--force|--recursive)/i,
46083
46297
  /\bsudo\b/i,
@@ -46214,8 +46428,8 @@ ${err?.stack || ""}`);
46214
46428
  cliInfo: {
46215
46429
  type: "adhdev-daemon",
46216
46430
  version: pkgVersion,
46217
- platform: os20.platform(),
46218
- hostname: os20.hostname(),
46431
+ platform: os21.platform(),
46432
+ hostname: os21.hostname(),
46219
46433
  machineId: config2.machineId,
46220
46434
  instanceId
46221
46435
  }
@@ -46824,16 +47038,16 @@ async function loginFlow() {
46824
47038
  let verificationUrl;
46825
47039
  try {
46826
47040
  const config2 = loadConfig();
46827
- const os22 = await import("os");
47041
+ const os24 = await import("os");
46828
47042
  const res = await fetch(`${SERVER_URL}/auth/cli/init`, {
46829
47043
  method: "POST",
46830
47044
  headers: { "Content-Type": "application/json" },
46831
47045
  body: JSON.stringify({
46832
47046
  clientMachineId: config2.machineId,
46833
47047
  registeredMachineId: config2.registeredMachineId,
46834
- hostname: os22.hostname(),
46835
- platform: os22.platform(),
46836
- arch: os22.arch()
47048
+ hostname: os24.hostname(),
47049
+ platform: os24.platform(),
47050
+ arch: os24.arch()
46837
47051
  })
46838
47052
  });
46839
47053
  if (!res.ok) {
@@ -46934,10 +47148,10 @@ async function startDaemonFlow() {
46934
47148
  const { execSync: execSync7 } = await import("child_process");
46935
47149
  const { getCurrentDaemonLogPath: getCurrentDaemonLogPath2 } = await Promise.resolve().then(() => (init_src(), src_exports));
46936
47150
  const logPath = getCurrentDaemonLogPath2();
46937
- const os22 = await import("os");
46938
- const platform10 = os22.platform();
47151
+ const os24 = await import("os");
47152
+ const platform11 = os24.platform();
46939
47153
  try {
46940
- if (platform10 === "win32") {
47154
+ if (platform11 === "win32") {
46941
47155
  execSync7("start /B adhdev daemon >NUL 2>&1", {
46942
47156
  timeout: 3e3,
46943
47157
  stdio: "ignore",
@@ -47598,6 +47812,7 @@ function registerDaemonCommands(program2, pkgVersion3) {
47598
47812
  const child = spawn5(process.execPath, [process.argv[1], ...args], {
47599
47813
  detached: true,
47600
47814
  stdio: "ignore",
47815
+ windowsHide: true,
47601
47816
  env: { ...process.env }
47602
47817
  });
47603
47818
  child.unref();
@@ -47676,6 +47891,7 @@ function registerDaemonCommands(program2, pkgVersion3) {
47676
47891
  const child = spawn5(process.execPath, [process.argv[1], "daemon", "-p", "19222"], {
47677
47892
  detached: true,
47678
47893
  stdio: "ignore",
47894
+ windowsHide: true,
47679
47895
  env: { ...process.env }
47680
47896
  });
47681
47897
  child.unref();
@@ -47703,9 +47919,10 @@ function registerDaemonCommands(program2, pkgVersion3) {
47703
47919
  var import_chalk6 = __toESM(require("chalk"));
47704
47920
  var import_child_process12 = require("child_process");
47705
47921
  var fs18 = __toESM(require("fs"));
47706
- var os21 = __toESM(require("os"));
47922
+ var os23 = __toESM(require("os"));
47707
47923
  var path23 = __toESM(require("path"));
47708
47924
  init_src();
47925
+ init_session_host();
47709
47926
  function resolvePackageRoot() {
47710
47927
  return path23.resolve(__dirname, "..", "..");
47711
47928
  }
@@ -47724,6 +47941,111 @@ function resolveModuleFromPackage(specifier, packageRoot) {
47724
47941
  return null;
47725
47942
  }
47726
47943
  }
47944
+ function probeNodeDatachannel(packageRoot) {
47945
+ const resolved = resolveModuleFromPackage("node-datachannel", packageRoot);
47946
+ if (!resolved) {
47947
+ return {
47948
+ label: "node-datachannel",
47949
+ ok: false,
47950
+ detail: "module not found",
47951
+ fatal: true
47952
+ };
47953
+ }
47954
+ try {
47955
+ const mod = require(resolved);
47956
+ const Ctor = mod?.PeerConnection || mod?.default?.PeerConnection;
47957
+ if (!Ctor) {
47958
+ return {
47959
+ label: "node-datachannel",
47960
+ ok: false,
47961
+ detail: `${resolved} (PeerConnection export missing)`,
47962
+ fatal: true
47963
+ };
47964
+ }
47965
+ const testPc = new Ctor("doctor-smoke", { iceServers: ["stun:stun.cloudflare.com:3478"] });
47966
+ try {
47967
+ testPc.close?.();
47968
+ } catch {
47969
+ }
47970
+ return {
47971
+ label: "node-datachannel",
47972
+ ok: true,
47973
+ detail: resolved
47974
+ };
47975
+ } catch (error48) {
47976
+ return {
47977
+ label: "node-datachannel",
47978
+ ok: false,
47979
+ detail: `${resolved} (${error48?.message || "load failed"})`,
47980
+ fatal: true
47981
+ };
47982
+ }
47983
+ }
47984
+ function probeConfigAccess() {
47985
+ const configDir = path23.join(os23.homedir(), ".adhdev");
47986
+ const configPath = path23.join(configDir, "config.json");
47987
+ const checks = [];
47988
+ try {
47989
+ fs18.mkdirSync(configDir, { recursive: true });
47990
+ checks.push({
47991
+ label: "Config directory",
47992
+ ok: true,
47993
+ detail: configDir
47994
+ });
47995
+ } catch (error48) {
47996
+ return [{
47997
+ label: "Config directory",
47998
+ ok: false,
47999
+ detail: `${configDir} (${error48?.message || "mkdir failed"})`,
48000
+ fatal: true
48001
+ }];
48002
+ }
48003
+ try {
48004
+ if (fs18.existsSync(configPath)) {
48005
+ fs18.readFileSync(configPath, "utf-8");
48006
+ checks.push({
48007
+ label: "Config file",
48008
+ ok: true,
48009
+ detail: configPath
48010
+ });
48011
+ } else {
48012
+ checks.push({
48013
+ label: "Config file",
48014
+ ok: true,
48015
+ detail: `${configPath} (will be created on demand)`
48016
+ });
48017
+ }
48018
+ } catch (error48) {
48019
+ checks.push({
48020
+ label: "Config file",
48021
+ ok: false,
48022
+ detail: `${configPath} (${error48?.message || "read failed"})`,
48023
+ fatal: true
48024
+ });
48025
+ }
48026
+ const probePath = path23.join(configDir, `.doctor-write-${process.pid}-${Date.now()}.tmp`);
48027
+ try {
48028
+ fs18.writeFileSync(probePath, "ok", "utf-8");
48029
+ fs18.rmSync(probePath, { force: true });
48030
+ checks.push({
48031
+ label: "Config write",
48032
+ ok: true,
48033
+ detail: configDir
48034
+ });
48035
+ } catch (error48) {
48036
+ try {
48037
+ fs18.rmSync(probePath, { force: true });
48038
+ } catch {
48039
+ }
48040
+ checks.push({
48041
+ label: "Config write",
48042
+ ok: false,
48043
+ detail: `${configDir} (${error48?.message || "write failed"})`,
48044
+ fatal: true
48045
+ });
48046
+ }
48047
+ return checks;
48048
+ }
47727
48049
  function findCommandPaths(command) {
47728
48050
  try {
47729
48051
  const bin = process.platform === "win32" ? "where.exe" : "which";
@@ -47744,7 +48066,7 @@ function readLogHints(logPath) {
47744
48066
  const lines = content.split(/\r?\n/);
47745
48067
  const recent = lines.slice(-400);
47746
48068
  const hits = recent.filter(
47747
- (line) => line.includes("sharp native module unavailable") || line.includes("node-pty not found") || line.includes("Could not browse folder") || line.includes("ENOENT")
48069
+ (line) => line.includes("sharp native module unavailable") || line.includes("node-pty not found") || line.includes("Could not browse folder") || line.includes("Could not save config") || line.includes("Could not load config") || line.includes("ENOENT")
47748
48070
  );
47749
48071
  return hits.slice(-5);
47750
48072
  } catch {
@@ -47754,8 +48076,8 @@ function readLogHints(logPath) {
47754
48076
  function buildBrowseProbeChecks() {
47755
48077
  const probes = process.platform === "win32" ? [
47756
48078
  process.env.SystemDrive ? `${process.env.SystemDrive.replace(/[\\/]+$/, "")}\\` : "C:\\",
47757
- os21.homedir()
47758
- ] : ["/", os21.homedir()];
48079
+ os23.homedir()
48080
+ ] : ["/", os23.homedir()];
47759
48081
  return probes.map((probePath, index) => {
47760
48082
  try {
47761
48083
  const entries = fs18.readdirSync(probePath, { withFileTypes: true });
@@ -47806,29 +48128,77 @@ function registerDoctorCommands(program2, pkgVersion3) {
47806
48128
  detail: resolveModuleFromPackage("node-pty", packageRoot) || "module not found",
47807
48129
  fatal: true
47808
48130
  },
48131
+ probeNodeDatachannel(packageRoot),
47809
48132
  {
47810
48133
  label: "sharp",
47811
48134
  ok: Boolean(resolveModuleFromPackage("sharp", packageRoot)),
47812
48135
  detail: resolveModuleFromPackage("sharp", packageRoot) || "module not found",
47813
- fatal: process.platform === "win32"
48136
+ fatal: false
47814
48137
  },
47815
48138
  {
47816
48139
  label: nativeSharpPackage,
47817
48140
  ok: Boolean(resolveModuleFromPackage(nativeSharpPackage, packageRoot)),
47818
48141
  detail: resolveModuleFromPackage(nativeSharpPackage, packageRoot) || "module not found",
47819
- fatal: process.platform === "win32"
48142
+ fatal: false
47820
48143
  },
48144
+ ...probeConfigAccess(),
47821
48145
  ...buildBrowseProbeChecks()
47822
48146
  ];
48147
+ try {
48148
+ const sessionHostPid = getSessionHostPid();
48149
+ const probe = await probeSessionHostStatus();
48150
+ checks.push({
48151
+ label: "Session host PID",
48152
+ ok: !!sessionHostPid,
48153
+ detail: sessionHostPid ? `PID ${sessionHostPid} (${probe.pidFile})` : `no PID file (${probe.pidFile})`
48154
+ });
48155
+ checks.push({
48156
+ label: "Session host IPC",
48157
+ ok: probe.reachable,
48158
+ detail: probe.reachable ? `reachable (${probe.runtimeCount} runtime(s), ${probe.endpoint.kind}:${probe.endpoint.path})` : `unreachable (${probe.endpoint.kind}:${probe.endpoint.path})`
48159
+ });
48160
+ } catch (e) {
48161
+ checks.push({
48162
+ label: "Session host",
48163
+ ok: false,
48164
+ detail: `probe failed: ${e?.message || String(e)}`
48165
+ });
48166
+ }
48167
+ try {
48168
+ const termScreenMod = require("@adhdev/daemon-core/cli-adapters/terminal-screen.js");
48169
+ if (typeof termScreenMod?.getTerminalBackendRuntimeStatus === "function") {
48170
+ const backendStatus = termScreenMod.getTerminalBackendRuntimeStatus();
48171
+ checks.push({
48172
+ label: "Terminal backend",
48173
+ ok: true,
48174
+ detail: `${backendStatus.backend} (preference=${backendStatus.preference}, ghostty=${backendStatus.ghosttyAvailable})`
48175
+ });
48176
+ }
48177
+ } catch {
48178
+ }
48179
+ try {
48180
+ const providerLoader = new ProviderLoader();
48181
+ const cliResults = await detectCLIs(providerLoader);
48182
+ for (const cli of cliResults) {
48183
+ checks.push({
48184
+ label: `CLI: ${cli.displayName}`,
48185
+ ok: cli.installed,
48186
+ detail: cli.installed ? `${cli.path || cli.command} (v${cli.version || "unknown"})` : `not found (command: ${cli.command})`
48187
+ });
48188
+ }
48189
+ } catch {
48190
+ }
47823
48191
  const failures = checks.filter((check2) => !check2.ok && check2.fatal);
47824
48192
  const warnings = checks.filter((check2) => !check2.ok && !check2.fatal);
47825
48193
  const logHints = readLogHints(logPath);
48194
+ const sessionHostLogPath = path23.join(os23.homedir(), ".adhdev", "logs", "session-host.log");
47826
48195
  console.log(import_chalk6.default.bold("\n\u{1FA7A} ADHDev Doctor\n"));
47827
48196
  console.log(import_chalk6.default.gray(` Version: ${pkgVersion3}`));
47828
48197
  console.log(import_chalk6.default.gray(` Platform: ${process.platform} ${process.arch}`));
47829
48198
  console.log(import_chalk6.default.gray(` Node: ${process.version}`));
47830
- console.log(import_chalk6.default.gray(` Home: ${os21.homedir()}`));
48199
+ console.log(import_chalk6.default.gray(` Home: ${os23.homedir()}`));
47831
48200
  console.log(import_chalk6.default.gray(` Log file: ${logPath}`));
48201
+ console.log(import_chalk6.default.gray(` SH log: ${sessionHostLogPath}`));
47832
48202
  console.log();
47833
48203
  for (const check2 of checks) {
47834
48204
  console.log(formatCheck(check2));
@@ -48085,8 +48455,8 @@ function registerProviderCommands(program2) {
48085
48455
  if (category === "ide") {
48086
48456
  const fs19 = await import("fs");
48087
48457
  const path24 = await import("path");
48088
- const os22 = await import("os");
48089
- if (os22.platform() === "darwin") {
48458
+ const os24 = await import("os");
48459
+ if (os24.platform() === "darwin") {
48090
48460
  while (true) {
48091
48461
  const p = (await rl.question(`macOS Application Path (e.g. /Applications/${defaultName}.app): `)).trim() || `/Applications/${defaultName}.app`;
48092
48462
  if (p === "skip") break;
@@ -48100,7 +48470,7 @@ function registerProviderCommands(program2) {
48100
48470
  processNames["darwin"] = path24.basename(p, ".app");
48101
48471
  break;
48102
48472
  }
48103
- } else if (os22.platform() === "win32") {
48473
+ } else if (os24.platform() === "win32") {
48104
48474
  while (true) {
48105
48475
  const p = (await rl.question(`Windows Executable Path (e.g. C:\\Program Files\\${defaultName}\\${defaultName}.exe): `)).trim();
48106
48476
  if (!p || p === "skip") break;