@adhdev/daemon-core 0.9.76-rc.1 → 0.9.76-rc.11

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/index.mjs CHANGED
@@ -41,6 +41,134 @@ var init_repo_mesh_types = __esm({
41
41
  }
42
42
  });
43
43
 
44
+ // src/git/git-worktree.ts
45
+ var git_worktree_exports = {};
46
+ __export(git_worktree_exports, {
47
+ createWorktree: () => createWorktree,
48
+ listWorktrees: () => listWorktrees,
49
+ parseWorktreeListOutput: () => parseWorktreeListOutput,
50
+ removeWorktree: () => removeWorktree,
51
+ resolveWorktreePath: () => resolveWorktreePath
52
+ });
53
+ import * as path4 from "path";
54
+ import { mkdir } from "fs/promises";
55
+ import { existsSync } from "fs";
56
+ import { execFile as execFile2 } from "child_process";
57
+ import { promisify as promisify2 } from "util";
58
+ function resolveWorktreePath(repoRoot, meshName, branch) {
59
+ const safeBranch = branch.replace(/[/\\:*?"<>|]/g, "-").replace(/^\.+|\.+$/g, "");
60
+ const safeMeshName = meshName.replace(/[/\\:*?"<>|]/g, "-").replace(/^\.+|\.+$/g, "");
61
+ const parentDir = path4.dirname(repoRoot);
62
+ return path4.join(parentDir, WORKTREE_DIR_NAME, safeMeshName, safeBranch);
63
+ }
64
+ async function createWorktree(opts) {
65
+ const { repoRoot, branch, baseBranch, meshName } = opts;
66
+ const targetDir = opts.targetDir || resolveWorktreePath(repoRoot, meshName, branch);
67
+ if (existsSync(targetDir)) {
68
+ throw new Error(`Worktree target directory already exists: ${targetDir}`);
69
+ }
70
+ await mkdir(path4.dirname(targetDir), { recursive: true });
71
+ const args = ["worktree", "add", targetDir, "-b", branch];
72
+ if (baseBranch) {
73
+ args.push(baseBranch);
74
+ }
75
+ try {
76
+ await execFileAsync2("git", args, {
77
+ cwd: repoRoot,
78
+ encoding: "utf8",
79
+ timeout: GIT_TIMEOUT_MS,
80
+ maxBuffer: GIT_MAX_BUFFER,
81
+ windowsHide: true
82
+ });
83
+ } catch (error) {
84
+ const stderr = typeof error.stderr === "string" ? error.stderr : "";
85
+ if (/already exists/i.test(stderr)) {
86
+ throw new Error(`Branch '${branch}' already exists or is checked out in another worktree`);
87
+ }
88
+ throw new Error(`git worktree add failed: ${stderr.trim() || error.message}`);
89
+ }
90
+ return {
91
+ success: true,
92
+ worktreePath: targetDir,
93
+ branch
94
+ };
95
+ }
96
+ async function removeWorktree(repoRoot, worktreePath) {
97
+ if (!existsSync(worktreePath)) {
98
+ await pruneWorktrees(repoRoot);
99
+ return { success: true, removedPath: worktreePath };
100
+ }
101
+ try {
102
+ await execFileAsync2("git", ["worktree", "remove", worktreePath, "--force"], {
103
+ cwd: repoRoot,
104
+ encoding: "utf8",
105
+ timeout: GIT_TIMEOUT_MS,
106
+ maxBuffer: GIT_MAX_BUFFER,
107
+ windowsHide: true
108
+ });
109
+ } catch (error) {
110
+ const stderr = typeof error.stderr === "string" ? error.stderr : "";
111
+ throw new Error(`git worktree remove failed: ${stderr.trim() || error.message}`);
112
+ }
113
+ return { success: true, removedPath: worktreePath };
114
+ }
115
+ async function listWorktrees(repoRoot) {
116
+ const { stdout } = await execFileAsync2("git", ["worktree", "list", "--porcelain"], {
117
+ cwd: repoRoot,
118
+ encoding: "utf8",
119
+ timeout: GIT_TIMEOUT_MS,
120
+ maxBuffer: GIT_MAX_BUFFER,
121
+ windowsHide: true
122
+ });
123
+ return parseWorktreeListOutput(stdout);
124
+ }
125
+ function parseWorktreeListOutput(output) {
126
+ const entries = [];
127
+ const blocks = output.trim().split(/\n\n+/);
128
+ for (const block of blocks) {
129
+ if (!block.trim()) continue;
130
+ const lines = block.trim().split("\n");
131
+ const entry = { path: "", head: "", branch: null, bare: false };
132
+ for (const line of lines) {
133
+ if (line.startsWith("worktree ")) {
134
+ entry.path = line.slice("worktree ".length).trim();
135
+ } else if (line.startsWith("HEAD ")) {
136
+ entry.head = line.slice("HEAD ".length).trim();
137
+ } else if (line.startsWith("branch ")) {
138
+ const ref = line.slice("branch ".length).trim();
139
+ entry.branch = ref.replace(/^refs\/heads\//, "");
140
+ } else if (line === "bare") {
141
+ entry.bare = true;
142
+ }
143
+ }
144
+ if (entry.path) {
145
+ entries.push(entry);
146
+ }
147
+ }
148
+ return entries;
149
+ }
150
+ async function pruneWorktrees(repoRoot) {
151
+ try {
152
+ await execFileAsync2("git", ["worktree", "prune"], {
153
+ cwd: repoRoot,
154
+ encoding: "utf8",
155
+ timeout: GIT_TIMEOUT_MS,
156
+ windowsHide: true
157
+ });
158
+ } catch {
159
+ }
160
+ }
161
+ var execFileAsync2, WORKTREE_DIR_NAME, GIT_TIMEOUT_MS, GIT_MAX_BUFFER;
162
+ var init_git_worktree = __esm({
163
+ "src/git/git-worktree.ts"() {
164
+ "use strict";
165
+ execFileAsync2 = promisify2(execFile2);
166
+ WORKTREE_DIR_NAME = ".adhdev-worktrees";
167
+ GIT_TIMEOUT_MS = 3e4;
168
+ GIT_MAX_BUFFER = 4 * 1024 * 1024;
169
+ }
170
+ });
171
+
44
172
  // src/config/config.ts
45
173
  var config_exports = {};
46
174
  __export(config_exports, {
@@ -56,8 +184,8 @@ __export(config_exports, {
56
184
  updateConfig: () => updateConfig
57
185
  });
58
186
  import { homedir } from "os";
59
- import { join } from "path";
60
- import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from "fs";
187
+ import { join as join2 } from "path";
188
+ import { existsSync as existsSync2, mkdirSync, readFileSync, writeFileSync, chmodSync } from "fs";
61
189
  import { randomUUID } from "crypto";
62
190
  function resolveProviderSourceMode(providerSourceMode, legacyDisableUpstream) {
63
191
  if (providerSourceMode === "normal" || providerSourceMode === "no-upstream") {
@@ -151,18 +279,18 @@ function ensureMachineId(config) {
151
279
  };
152
280
  }
153
281
  function getConfigDir() {
154
- const dir = join(homedir(), ".adhdev");
155
- if (!existsSync(dir)) {
282
+ const dir = join2(homedir(), ".adhdev");
283
+ if (!existsSync2(dir)) {
156
284
  mkdirSync(dir, { recursive: true });
157
285
  }
158
286
  return dir;
159
287
  }
160
288
  function getConfigPath() {
161
- return join(getConfigDir(), "config.json");
289
+ return join2(getConfigDir(), "config.json");
162
290
  }
163
291
  function migrateStateToStateFile(raw) {
164
- const statePath = join(getConfigDir(), "state.json");
165
- if (existsSync(statePath)) return;
292
+ const statePath = join2(getConfigDir(), "state.json");
293
+ if (existsSync2(statePath)) return;
166
294
  const recentActivity = Array.isArray(raw.recentActivity) ? raw.recentActivity : [];
167
295
  const savedProviderSessions = Array.isArray(raw.savedProviderSessions) ? raw.savedProviderSessions : [];
168
296
  const legacySessionReads = isPlainObject(raw.recentSessionReads) ? raw.recentSessionReads : {};
@@ -186,7 +314,7 @@ function migrateStateToStateFile(raw) {
186
314
  }
187
315
  function loadConfig() {
188
316
  const configPath = getConfigPath();
189
- if (!existsSync(configPath)) {
317
+ if (!existsSync2(configPath)) {
190
318
  const initialized = ensureMachineId({ ...DEFAULT_CONFIG });
191
319
  try {
192
320
  saveConfig(initialized.config);
@@ -217,7 +345,7 @@ function saveConfig(config) {
217
345
  const configPath = getConfigPath();
218
346
  const dir = getConfigDir();
219
347
  const normalized = normalizeConfig(config);
220
- if (!existsSync(dir)) {
348
+ if (!existsSync2(dir)) {
221
349
  mkdirSync(dir, { recursive: true, mode: 448 });
222
350
  }
223
351
  writeFileSync(configPath, JSON.stringify(normalized, null, 2), { encoding: "utf-8", mode: 384 });
@@ -295,17 +423,17 @@ __export(mesh_config_exports, {
295
423
  updateMesh: () => updateMesh,
296
424
  updateNode: () => updateNode
297
425
  });
298
- import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
299
- import { join as join3 } from "path";
426
+ import { existsSync as existsSync4, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
427
+ import { join as join4 } from "path";
300
428
  import { randomUUID as randomUUID3 } from "crypto";
301
429
  function getMeshConfigPath() {
302
- return join3(getConfigDir(), "meshes.json");
430
+ return join4(getConfigDir(), "meshes.json");
303
431
  }
304
432
  function loadMeshConfig() {
305
- const path26 = getMeshConfigPath();
306
- if (!existsSync3(path26)) return { meshes: [] };
433
+ const path27 = getMeshConfigPath();
434
+ if (!existsSync4(path27)) return { meshes: [] };
307
435
  try {
308
- const raw = JSON.parse(readFileSync2(path26, "utf-8"));
436
+ const raw = JSON.parse(readFileSync2(path27, "utf-8"));
309
437
  if (!raw || !Array.isArray(raw.meshes)) return { meshes: [] };
310
438
  return raw;
311
439
  } catch {
@@ -313,16 +441,16 @@ function loadMeshConfig() {
313
441
  }
314
442
  }
315
443
  function saveMeshConfig(config) {
316
- const path26 = getMeshConfigPath();
317
- writeFileSync2(path26, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
444
+ const path27 = getMeshConfigPath();
445
+ writeFileSync2(path27, JSON.stringify(config, null, 2), { encoding: "utf-8", mode: 384 });
318
446
  }
319
447
  function normalizeRepoIdentity(remoteUrl) {
320
448
  let identity = remoteUrl.trim();
321
449
  if (identity.startsWith("http://") || identity.startsWith("https://")) {
322
450
  try {
323
451
  const url = new URL(identity);
324
- const path26 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
325
- return `${url.hostname}/${path26}`;
452
+ const path27 = url.pathname.replace(/^\//, "").replace(/\.git$/, "");
453
+ return `${url.hostname}/${path27}`;
326
454
  } catch {
327
455
  }
328
456
  }
@@ -397,9 +525,12 @@ function addNode(meshId, opts) {
397
525
  id: `node_${randomUUID3().replace(/-/g, "")}`,
398
526
  workspace: opts.workspace.trim(),
399
527
  repoRoot: opts.repoRoot,
528
+ daemonId: opts.daemonId,
400
529
  userOverrides: opts.userOverrides || {},
401
530
  policy: opts.policy || {},
402
- isLocalWorktree: opts.isLocalWorktree
531
+ isLocalWorktree: opts.isLocalWorktree,
532
+ worktreeBranch: opts.worktreeBranch,
533
+ clonedFromNodeId: opts.clonedFromNodeId
403
534
  };
404
535
  mesh.nodes.push(node);
405
536
  mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -443,7 +574,7 @@ __export(coordinator_prompt_exports, {
443
574
  buildCoordinatorSystemPrompt: () => buildCoordinatorSystemPrompt
444
575
  });
445
576
  function buildCoordinatorSystemPrompt(ctx) {
446
- const { mesh, status, userInstruction } = ctx;
577
+ const { mesh, status, userInstruction, coordinatorCliType } = ctx;
447
578
  const sections = [];
448
579
  sections.push(`You are a **Repo Mesh Coordinator** \u2014 a technical team lead who orchestrates work across multiple agent sessions on a shared Git repository.
449
580
 
@@ -457,15 +588,15 @@ Default branch: \`${mesh.defaultBranch}\`` : ""}`);
457
588
  } else {
458
589
  sections.push("## Nodes\nNo nodes configured yet. Ask the user to add nodes with `adhdev mesh add-node`.");
459
590
  }
460
- sections.push(buildPolicySection(mesh.policy));
591
+ sections.push(buildPolicySection({ ...DEFAULT_MESH_POLICY, ...mesh.policy || {} }));
461
592
  sections.push(TOOLS_SECTION);
462
593
  sections.push(WORKFLOW_SECTION);
463
- sections.push(RULES_SECTION);
594
+ sections.push(buildRulesSection(coordinatorCliType));
464
595
  if (userInstruction) {
465
596
  sections.push(`## Additional Context
466
597
  ${userInstruction}`);
467
598
  }
468
- if (mesh.coordinator.systemPromptSuffix) {
599
+ if (mesh.coordinator?.systemPromptSuffix) {
469
600
  sections.push(mesh.coordinator.systemPromptSuffix);
470
601
  }
471
602
  return sections.join("\n\n");
@@ -510,10 +641,29 @@ function buildPolicySection(policy) {
510
641
  return `## Policy
511
642
  ${rules.join("\n")}`;
512
643
  }
513
- var TOOLS_SECTION, WORKFLOW_SECTION, RULES_SECTION;
644
+ function buildRulesSection(coordinatorCliType) {
645
+ const coordinatorNote = coordinatorCliType ? `
646
+ - **Coordinator runtime is not a delegation default.** This coordinator is running as \`${coordinatorCliType}\`, but delegated node sessions must follow the user's requested provider, not the coordinator's own runtime.` : "";
647
+ return `## Rules
648
+
649
+ - **Minimize coordinator context.** The coordinator's job is routing, not implementing. Do not read source files, run commands, or analyze code directly \u2014 delegate all of that to node agents. Your context should stay lean.
650
+ - **Delegate analysis too.** If you need to understand a bug or explore the codebase, send that investigation as a task to a node. Do not do it yourself.
651
+ - **Respect explicit provider requests.** If the user names an agent/provider, pass the matching provider type to \`mesh_launch_session\`: Hermes \u2192 \`hermes-cli\`, Claude Code/Claude \u2192 \`claude-cli\`, Codex \u2192 \`codex-cli\`, Gemini \u2192 \`gemini-cli\`. Never substitute \`claude-cli\` just because the coordinator itself is Claude Code.
652
+ - **Front-load the task message.** When calling \`mesh_send_task\`, include everything the agent needs: what files to touch, what the problem is, what the fix should look like. The agent won't ask follow-up questions.
653
+ - **Don't inspect code.** Trust the agent's output. Verify via \`mesh_git_status\`, not by reading source files.
654
+ - **Don't over-parallelize.** Start with 1-2 concurrent tasks. Scale up if they succeed.
655
+ - **Handle failures gracefully.** If a task fails, read the chat to understand why, then retry or reassign.
656
+ - **Keep the user informed.** Report progress after each delegation round \u2014 one or two sentences, not a narration.
657
+ - **Respect node capabilities.** Don't send build tasks to read-only nodes. Don't push from nodes that aren't allowed to.
658
+ - **Never fabricate tool results.** Always call the actual tool; never pretend you did.
659
+ - **Clean up worktree nodes.** After a worktree task completes and its changes are merged or checkpointed, call \`mesh_remove_node\` to free resources.
660
+ - **Name worktree branches meaningfully.** Use descriptive names like \`feat/auth-refactor\` or \`fix/build-123\`.${coordinatorNote}`;
661
+ }
662
+ var TOOLS_SECTION, WORKFLOW_SECTION;
514
663
  var init_coordinator_prompt = __esm({
515
664
  "src/mesh/coordinator-prompt.ts"() {
516
665
  "use strict";
666
+ init_repo_mesh_types();
517
667
  TOOLS_SECTION = `## Available Tools
518
668
 
519
669
  | Tool | Purpose |
@@ -525,36 +675,29 @@ var init_coordinator_prompt = __esm({
525
675
  | \`mesh_read_chat\` | Read an agent's recent messages to check progress |
526
676
  | \`mesh_git_status\` | Check git status on a specific node |
527
677
  | \`mesh_checkpoint\` | Create a git checkpoint on a node |
528
- | \`mesh_approve\` | Approve/reject a pending agent action |`;
678
+ | \`mesh_approve\` | Approve/reject a pending agent action |
679
+ | \`mesh_clone_node\` | Create a worktree node for isolated parallel branch work |
680
+ | \`mesh_remove_node\` | Remove a node (cleans up worktree if applicable) |`;
529
681
  WORKFLOW_SECTION = `## Orchestration Workflow
530
682
 
531
683
  1. **Assess** \u2014 Call \`mesh_status\` to see which nodes are healthy and available.
532
684
  2. **Plan** \u2014 Decompose the user's request into independent tasks for parallel execution, or sequential tasks when dependencies exist.
533
685
  3. **Delegate** \u2014 For each task:
534
686
  a. Pick the best node (consider: health, dirty state, current workload).
535
- b. If no session exists, call \`mesh_launch_session\` to start one.
536
- c. Call \`mesh_send_task\` with a **complete, self-contained** instruction that includes all context the agent needs (file paths, line numbers, what to change, why). Do not send partial instructions expecting future follow-up.
687
+ b. If you need branch isolation for parallel work, call \`mesh_clone_node\` to create a worktree node first.
688
+ c. If no session exists, call \`mesh_launch_session\` to start one.
689
+ d. Call \`mesh_send_task\` with a **complete, self-contained** instruction that includes all context the agent needs (file paths, line numbers, what to change, why). Do not send partial instructions expecting future follow-up.
537
690
  4. **Monitor** \u2014 Periodically call \`mesh_read_chat\` to check progress. Handle approvals via \`mesh_approve\`.
538
691
  5. **Verify** \u2014 When a task reports completion, call \`mesh_git_status\` to verify changes were made.
539
692
  6. **Checkpoint** \u2014 Call \`mesh_checkpoint\` to save the work.
540
- 7. **Report** \u2014 Summarize what was done, what changed, and any issues.`;
541
- RULES_SECTION = `## Rules
542
-
543
- - **Minimize coordinator context.** The coordinator's job is routing, not implementing. Do not read source files, run commands, or analyze code directly \u2014 delegate all of that to node agents. Your context should stay lean.
544
- - **Delegate analysis too.** If you need to understand a bug or explore the codebase, send that investigation as a task to a node. Do not do it yourself.
545
- - **Front-load the task message.** When calling \`mesh_send_task\`, include everything the agent needs: what files to touch, what the problem is, what the fix should look like. The agent won't ask follow-up questions.
546
- - **Don't inspect code.** Trust the agent's output. Verify via \`mesh_git_status\`, not by reading source files.
547
- - **Don't over-parallelize.** Start with 1-2 concurrent tasks. Scale up if they succeed.
548
- - **Handle failures gracefully.** If a task fails, read the chat to understand why, then retry or reassign.
549
- - **Keep the user informed.** Report progress after each delegation round \u2014 one or two sentences, not a narration.
550
- - **Respect node capabilities.** Don't send build tasks to read-only nodes. Don't push from nodes that aren't allowed to.
551
- - **Never fabricate tool results.** Always call the actual tool; never pretend you did.`;
693
+ 7. **Clean up** \u2014 Remove worktree nodes via \`mesh_remove_node\` after their work is merged or no longer needed.
694
+ 8. **Report** \u2014 Summarize what was done, what changed, and any issues.`;
552
695
  }
553
696
  });
554
697
 
555
698
  // src/logging/logger.ts
556
699
  import * as fs2 from "fs";
557
- import * as path9 from "path";
700
+ import * as path10 from "path";
558
701
  import * as os4 from "os";
559
702
  function setLogLevel(level) {
560
703
  currentLevel = level;
@@ -570,13 +713,13 @@ function getDaemonLogDir() {
570
713
  return LOG_DIR;
571
714
  }
572
715
  function getCurrentDaemonLogPath(date = /* @__PURE__ */ new Date()) {
573
- return path9.join(LOG_DIR, `daemon-${date.toISOString().slice(0, 10)}.log`);
716
+ return path10.join(LOG_DIR, `daemon-${date.toISOString().slice(0, 10)}.log`);
574
717
  }
575
718
  function checkDateRotation() {
576
719
  const today = getDateStr();
577
720
  if (today !== currentDate) {
578
721
  currentDate = today;
579
- currentLogFile = path9.join(LOG_DIR, `daemon-${currentDate}.log`);
722
+ currentLogFile = path10.join(LOG_DIR, `daemon-${currentDate}.log`);
580
723
  cleanOldLogs();
581
724
  }
582
725
  }
@@ -590,7 +733,7 @@ function cleanOldLogs() {
590
733
  const dateMatch = file.match(/daemon-(\d{4}-\d{2}-\d{2})/);
591
734
  if (dateMatch && dateMatch[1] < cutoffStr) {
592
735
  try {
593
- fs2.unlinkSync(path9.join(LOG_DIR, file));
736
+ fs2.unlinkSync(path10.join(LOG_DIR, file));
594
737
  } catch {
595
738
  }
596
739
  }
@@ -713,7 +856,7 @@ var init_logger = __esm({
713
856
  LEVEL_NUM = { debug: 0, info: 1, warn: 2, error: 3 };
714
857
  LEVEL_LABEL = { debug: "DBG", info: "INF", warn: "WRN", error: "ERR" };
715
858
  currentLevel = "info";
716
- LOG_DIR = process.platform === "win32" ? path9.join(process.env.LOCALAPPDATA || process.env.APPDATA || path9.join(os4.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path9.join(os4.homedir(), "Library", "Logs", "adhdev") : path9.join(os4.homedir(), ".local", "share", "adhdev", "logs");
859
+ LOG_DIR = process.platform === "win32" ? path10.join(process.env.LOCALAPPDATA || process.env.APPDATA || path10.join(os4.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path10.join(os4.homedir(), "Library", "Logs", "adhdev") : path10.join(os4.homedir(), ".local", "share", "adhdev", "logs");
717
860
  MAX_LOG_SIZE = 5 * 1024 * 1024;
718
861
  MAX_LOG_DAYS = 7;
719
862
  try {
@@ -721,16 +864,16 @@ var init_logger = __esm({
721
864
  } catch {
722
865
  }
723
866
  currentDate = getDateStr();
724
- currentLogFile = path9.join(LOG_DIR, `daemon-${currentDate}.log`);
867
+ currentLogFile = path10.join(LOG_DIR, `daemon-${currentDate}.log`);
725
868
  cleanOldLogs();
726
869
  try {
727
- const oldLog = path9.join(LOG_DIR, "daemon.log");
870
+ const oldLog = path10.join(LOG_DIR, "daemon.log");
728
871
  if (fs2.existsSync(oldLog)) {
729
872
  const stat2 = fs2.statSync(oldLog);
730
873
  const oldDate = stat2.mtime.toISOString().slice(0, 10);
731
- fs2.renameSync(oldLog, path9.join(LOG_DIR, `daemon-${oldDate}.log`));
874
+ fs2.renameSync(oldLog, path10.join(LOG_DIR, `daemon-${oldDate}.log`));
732
875
  }
733
- const oldLogBackup = path9.join(LOG_DIR, "daemon.log.old");
876
+ const oldLogBackup = path10.join(LOG_DIR, "daemon.log.old");
734
877
  if (fs2.existsSync(oldLogBackup)) {
735
878
  fs2.unlinkSync(oldLogBackup);
736
879
  }
@@ -762,7 +905,7 @@ var init_logger = __esm({
762
905
  }
763
906
  };
764
907
  interceptorInstalled = false;
765
- LOG_PATH = path9.join(LOG_DIR, `daemon-${getDateStr()}.log`);
908
+ LOG_PATH = path10.join(LOG_DIR, `daemon-${getDateStr()}.log`);
766
909
  }
767
910
  });
768
911
 
@@ -1171,7 +1314,7 @@ var init_pty_transport = __esm({
1171
1314
 
1172
1315
  // src/cli-adapters/provider-cli-shared.ts
1173
1316
  import * as os9 from "os";
1174
- import * as path13 from "path";
1317
+ import * as path14 from "path";
1175
1318
  import { execSync as execSync3 } from "child_process";
1176
1319
  function stripAnsi(str) {
1177
1320
  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, " ");
@@ -1236,9 +1379,9 @@ function buildCliScreenSnapshot(text) {
1236
1379
  function findBinary(name) {
1237
1380
  const trimmed = String(name || "").trim();
1238
1381
  if (!trimmed) return trimmed;
1239
- const expanded = trimmed.startsWith("~") ? path13.join(os9.homedir(), trimmed.slice(1)) : trimmed;
1240
- if (path13.isAbsolute(expanded) || expanded.includes("/") || expanded.includes("\\")) {
1241
- return path13.isAbsolute(expanded) ? expanded : path13.resolve(expanded);
1382
+ const expanded = trimmed.startsWith("~") ? path14.join(os9.homedir(), trimmed.slice(1)) : trimmed;
1383
+ if (path14.isAbsolute(expanded) || expanded.includes("/") || expanded.includes("\\")) {
1384
+ return path14.isAbsolute(expanded) ? expanded : path14.resolve(expanded);
1242
1385
  }
1243
1386
  const isWin = os9.platform() === "win32";
1244
1387
  try {
@@ -1254,7 +1397,7 @@ function findBinary(name) {
1254
1397
  }
1255
1398
  }
1256
1399
  function isScriptBinary(binaryPath) {
1257
- if (!path13.isAbsolute(binaryPath)) return false;
1400
+ if (!path14.isAbsolute(binaryPath)) return false;
1258
1401
  try {
1259
1402
  const fs16 = __require("fs");
1260
1403
  const resolved = fs16.realpathSync(binaryPath);
@@ -1270,7 +1413,7 @@ function isScriptBinary(binaryPath) {
1270
1413
  }
1271
1414
  }
1272
1415
  function looksLikeMachOOrElf(filePath) {
1273
- if (!path13.isAbsolute(filePath)) return false;
1416
+ if (!path14.isAbsolute(filePath)) return false;
1274
1417
  try {
1275
1418
  const fs16 = __require("fs");
1276
1419
  const resolved = fs16.realpathSync(filePath);
@@ -1484,7 +1627,7 @@ var init_provider_cli_config = __esm({
1484
1627
 
1485
1628
  // src/cli-adapters/provider-cli-runtime.ts
1486
1629
  import * as os10 from "os";
1487
- import * as path14 from "path";
1630
+ import * as path15 from "path";
1488
1631
  import { DEFAULT_SESSION_HOST_COLS, DEFAULT_SESSION_HOST_ROWS } from "@adhdev/session-host-core";
1489
1632
  function resolveCliSpawnPlan(options) {
1490
1633
  const { provider, runtimeSettings, workingDir, extraArgs } = options;
@@ -1495,9 +1638,9 @@ function resolveCliSpawnPlan(options) {
1495
1638
  const allArgs = [...spawnConfig.args, ...extraArgs];
1496
1639
  let shellCmd;
1497
1640
  let shellArgs;
1498
- const useShellUnix = !isWin && (!!spawnConfig.shell || !path14.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
1641
+ const useShellUnix = !isWin && (!!spawnConfig.shell || !path15.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
1499
1642
  const isCmdShim = isWin && /\.(cmd|bat)$/i.test(binaryPath);
1500
- const useShellWin = !!spawnConfig.shell || isCmdShim || !path14.isAbsolute(binaryPath) || isScriptBinary(binaryPath);
1643
+ const useShellWin = !!spawnConfig.shell || isCmdShim || !path15.isAbsolute(binaryPath) || isScriptBinary(binaryPath);
1501
1644
  const useShell = isWin ? useShellWin : useShellUnix;
1502
1645
  if (useShell) {
1503
1646
  shellCmd = isWin ? "cmd.exe" : process.env.SHELL || "/bin/zsh";
@@ -1762,8 +1905,9 @@ var init_provider_cli_adapter = __esm({
1762
1905
  const currentSnapshot = normalizeScreenSnapshot(screenText);
1763
1906
  const lastSnapshot = this.lastScreenSnapshot;
1764
1907
  if (!lastSnapshot || lastSnapshot === currentSnapshot) return screenText;
1765
- const staleSnapshotLooksActive = /\besc to (?:interrupt|stop)\b|Enter to interrupt, Ctrl\+C to cancel/i.test(lastSnapshot);
1766
- const currentScreenLooksIdle = /(?:^|\n|\r)\s*[❯›>]\s*(?:\n|\r|$)/.test(screenText) && !/\besc to (?:interrupt|stop)\b|Enter to interrupt, Ctrl\+C to cancel/i.test(screenText);
1908
+ const activeScreenPattern = /\besc to (?:interrupt|stop)\b|Enter to interrupt, Ctrl\+C to cancel|Enter to confirm\s*[·•-]\s*Esc to cancel|\b(?:MCP servers?|tool calls?)\b[^\n\r]{0,160}\brequire approval\b/i;
1909
+ const staleSnapshotLooksActive = activeScreenPattern.test(lastSnapshot);
1910
+ const currentScreenLooksIdle = /(?:^|\n|\r)\s*[❯›>]\s*(?:Try\s+["“][^\n\r"”]+["”])?\s*(?:\n|\r|$)/.test(screenText) && !activeScreenPattern.test(screenText);
1767
1911
  if (staleSnapshotLooksActive && currentScreenLooksIdle) return screenText;
1768
1912
  if (currentSnapshot.length >= lastSnapshot.length) return screenText;
1769
1913
  return `${screenText}
@@ -4983,20 +5127,23 @@ var TurnSnapshotTracker = class {
4983
5127
  }
4984
5128
  };
4985
5129
 
5130
+ // src/git/index.ts
5131
+ init_git_worktree();
5132
+
4986
5133
  // src/index.ts
4987
5134
  init_config();
4988
5135
 
4989
5136
  // src/config/workspaces.ts
4990
5137
  import * as fs from "fs";
4991
5138
  import * as os from "os";
4992
- import * as path4 from "path";
5139
+ import * as path5 from "path";
4993
5140
  import { randomUUID as randomUUID2 } from "crypto";
4994
5141
  var MAX_WORKSPACES = 50;
4995
5142
  function expandPath(p) {
4996
5143
  const t = (p || "").trim();
4997
5144
  if (!t) return "";
4998
- if (t.startsWith("~")) return path4.join(os.homedir(), t.slice(1).replace(/^\//, ""));
4999
- return path4.resolve(t);
5145
+ if (t.startsWith("~")) return path5.join(os.homedir(), t.slice(1).replace(/^\//, ""));
5146
+ return path5.resolve(t);
5000
5147
  }
5001
5148
  function validateWorkspacePath(absPath) {
5002
5149
  try {
@@ -5010,7 +5157,7 @@ function validateWorkspacePath(absPath) {
5010
5157
  }
5011
5158
  }
5012
5159
  function defaultWorkspaceLabel(absPath) {
5013
- const base = path4.basename(absPath) || absPath;
5160
+ const base = path5.basename(absPath) || absPath;
5014
5161
  return base;
5015
5162
  }
5016
5163
  function getDefaultWorkspacePath(config) {
@@ -5101,9 +5248,9 @@ function resolveIdeLaunchWorkspace(args, config) {
5101
5248
  return getDefaultWorkspacePath(config) || void 0;
5102
5249
  }
5103
5250
  function findWorkspaceByPath(config, rawPath) {
5104
- const abs = path4.resolve(expandPath(rawPath));
5251
+ const abs = path5.resolve(expandPath(rawPath));
5105
5252
  if (!abs) return void 0;
5106
- return (config.workspaces || []).find((w) => path4.resolve(expandPath(w.path)) === abs);
5253
+ return (config.workspaces || []).find((w) => path5.resolve(expandPath(w.path)) === abs);
5107
5254
  }
5108
5255
  function addWorkspaceEntry(config, rawPath, label, options) {
5109
5256
  const abs = expandPath(rawPath);
@@ -5119,7 +5266,7 @@ function addWorkspaceEntry(config, rawPath, label, options) {
5119
5266
  const v = validateWorkspacePath(abs);
5120
5267
  if (!v.ok) return { error: v.error };
5121
5268
  const list = [...config.workspaces || []];
5122
- if (list.some((w) => path4.resolve(w.path) === abs)) {
5269
+ if (list.some((w) => path5.resolve(w.path) === abs)) {
5123
5270
  return { error: "Workspace already in list" };
5124
5271
  }
5125
5272
  if (list.length >= MAX_WORKSPACES) {
@@ -5153,7 +5300,7 @@ function setDefaultWorkspaceId(config, id) {
5153
5300
  }
5154
5301
 
5155
5302
  // src/config/recent-activity.ts
5156
- import * as path5 from "path";
5303
+ import * as path6 from "path";
5157
5304
 
5158
5305
  // src/providers/summary-metadata.ts
5159
5306
  function normalizeSummaryItem(item) {
@@ -5222,9 +5369,9 @@ var MAX_ACTIVITY = 30;
5222
5369
  function normalizeWorkspace(workspace) {
5223
5370
  if (!workspace) return "";
5224
5371
  try {
5225
- return path5.resolve(expandPath(workspace));
5372
+ return path6.resolve(expandPath(workspace));
5226
5373
  } catch {
5227
- return path5.resolve(workspace);
5374
+ return path6.resolve(workspace);
5228
5375
  }
5229
5376
  }
5230
5377
  function buildRecentActivityKey(entry) {
@@ -5392,14 +5539,14 @@ function markSessionSeen(state, sessionId, seenAt = Date.now(), completionMarker
5392
5539
  }
5393
5540
 
5394
5541
  // src/config/saved-sessions.ts
5395
- import * as path6 from "path";
5542
+ import * as path7 from "path";
5396
5543
  var MAX_SAVED_SESSIONS = 500;
5397
5544
  function normalizeWorkspace2(workspace) {
5398
5545
  if (!workspace) return "";
5399
5546
  try {
5400
- return path6.resolve(expandPath(workspace));
5547
+ return path7.resolve(expandPath(workspace));
5401
5548
  } catch {
5402
- return path6.resolve(workspace);
5549
+ return path7.resolve(workspace);
5403
5550
  }
5404
5551
  }
5405
5552
  function buildSavedProviderSessionKey(providerSessionId) {
@@ -5505,8 +5652,8 @@ async function syncMeshes(transport) {
5505
5652
 
5506
5653
  // src/config/state-store.ts
5507
5654
  init_config();
5508
- import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
5509
- import { join as join4 } from "path";
5655
+ import { existsSync as existsSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync3 } from "fs";
5656
+ import { join as join5 } from "path";
5510
5657
  var DEFAULT_STATE = {
5511
5658
  recentActivity: [],
5512
5659
  savedProviderSessions: [],
@@ -5519,7 +5666,7 @@ function isPlainObject2(value) {
5519
5666
  return !!value && typeof value === "object" && !Array.isArray(value);
5520
5667
  }
5521
5668
  function getStatePath() {
5522
- return join4(getConfigDir(), "state.json");
5669
+ return join5(getConfigDir(), "state.json");
5523
5670
  }
5524
5671
  function normalizeState(raw) {
5525
5672
  const parsed = isPlainObject2(raw) ? raw : {};
@@ -5555,7 +5702,7 @@ function normalizeState(raw) {
5555
5702
  }
5556
5703
  function loadState() {
5557
5704
  const statePath = getStatePath();
5558
- if (!existsSync4(statePath)) {
5705
+ if (!existsSync5(statePath)) {
5559
5706
  return { ...DEFAULT_STATE };
5560
5707
  }
5561
5708
  try {
@@ -5576,9 +5723,9 @@ function resetState() {
5576
5723
 
5577
5724
  // src/detection/ide-detector.ts
5578
5725
  import { execSync } from "child_process";
5579
- import { existsSync as existsSync5 } from "fs";
5726
+ import { existsSync as existsSync6 } from "fs";
5580
5727
  import { platform, homedir as homedir3 } from "os";
5581
- import * as path7 from "path";
5728
+ import * as path8 from "path";
5582
5729
  var BUILTIN_IDE_DEFINITIONS = [];
5583
5730
  var registeredIDEs = /* @__PURE__ */ new Map();
5584
5731
  function registerIDEDefinition(def) {
@@ -5597,10 +5744,10 @@ function getMergedDefinitions() {
5597
5744
  function findCliCommand(command) {
5598
5745
  const trimmed = String(command || "").trim();
5599
5746
  if (!trimmed) return null;
5600
- if (path7.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~")) {
5601
- const candidate = trimmed.startsWith("~") ? path7.join(homedir3(), trimmed.slice(1)) : trimmed;
5602
- const resolved = path7.isAbsolute(candidate) ? candidate : path7.resolve(candidate);
5603
- return existsSync5(resolved) ? resolved : null;
5747
+ if (path8.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~")) {
5748
+ const candidate = trimmed.startsWith("~") ? path8.join(homedir3(), trimmed.slice(1)) : trimmed;
5749
+ const resolved = path8.isAbsolute(candidate) ? candidate : path8.resolve(candidate);
5750
+ return existsSync6(resolved) ? resolved : null;
5604
5751
  }
5605
5752
  try {
5606
5753
  const result = execSync(
@@ -5627,13 +5774,13 @@ function getIdeVersion(cliCommand) {
5627
5774
  function checkPathExists(paths) {
5628
5775
  const home = homedir3();
5629
5776
  for (const p of paths) {
5630
- const normalized = p.startsWith("~") ? path7.join(home, p.slice(1)) : p;
5777
+ const normalized = p.startsWith("~") ? path8.join(home, p.slice(1)) : p;
5631
5778
  if (normalized.includes("*")) {
5632
5779
  const username = home.split(/[\\/]/).pop() || "";
5633
5780
  const resolved = normalized.replace("*", username);
5634
- if (existsSync5(resolved)) return resolved;
5781
+ if (existsSync6(resolved)) return resolved;
5635
5782
  } else {
5636
- if (existsSync5(normalized)) return normalized;
5783
+ if (existsSync6(normalized)) return normalized;
5637
5784
  }
5638
5785
  }
5639
5786
  return null;
@@ -5647,11 +5794,11 @@ async function detectIDEs(providerLoader) {
5647
5794
  let resolvedCli = cliPath;
5648
5795
  if (!resolvedCli && appPath && os21 === "darwin") {
5649
5796
  const bundledCli = `${appPath}/Contents/Resources/app/bin/${def.cli}`;
5650
- if (existsSync5(bundledCli)) resolvedCli = bundledCli;
5797
+ if (existsSync6(bundledCli)) resolvedCli = bundledCli;
5651
5798
  }
5652
5799
  if (!resolvedCli && appPath && os21 === "win32") {
5653
- const { dirname: dirname8 } = await import("path");
5654
- const appDir = dirname8(appPath);
5800
+ const { dirname: dirname9 } = await import("path");
5801
+ const appDir = dirname9(appPath);
5655
5802
  const candidates = [
5656
5803
  `${appDir}\\\\bin\\\\${def.cli}.cmd`,
5657
5804
  `${appDir}\\\\bin\\\\${def.cli}`,
@@ -5660,7 +5807,7 @@ async function detectIDEs(providerLoader) {
5660
5807
  `${appDir}\\\\resources\\\\app\\\\bin\\\\${def.cli}.cmd`
5661
5808
  ];
5662
5809
  for (const c of candidates) {
5663
- if (existsSync5(c)) {
5810
+ if (existsSync6(c)) {
5664
5811
  resolvedCli = c;
5665
5812
  break;
5666
5813
  }
@@ -5685,8 +5832,8 @@ async function detectIDEs(providerLoader) {
5685
5832
  // src/detection/cli-detector.ts
5686
5833
  import { exec } from "child_process";
5687
5834
  import * as os2 from "os";
5688
- import * as path8 from "path";
5689
- import { existsSync as existsSync6 } from "fs";
5835
+ import * as path9 from "path";
5836
+ import { existsSync as existsSync7 } from "fs";
5690
5837
  function parseVersion(raw) {
5691
5838
  const match = raw.match(/v?(\d+\.\d+(?:\.\d+)?(?:-[a-zA-Z0-9.]+)?)/);
5692
5839
  return match ? match[1] : raw.split("\n")[0].slice(0, 100);
@@ -5698,19 +5845,19 @@ function shellQuote(value) {
5698
5845
  function expandHome(value) {
5699
5846
  const trimmed = value.trim();
5700
5847
  if (!trimmed.startsWith("~")) return trimmed;
5701
- return path8.join(os2.homedir(), trimmed.slice(1));
5848
+ return path9.join(os2.homedir(), trimmed.slice(1));
5702
5849
  }
5703
5850
  function isExplicitCommandPath(command) {
5704
5851
  const trimmed = command.trim();
5705
- return path8.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
5852
+ return path9.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
5706
5853
  }
5707
5854
  function resolveCommandPath(command) {
5708
5855
  const trimmed = command.trim();
5709
5856
  if (!trimmed) return null;
5710
5857
  if (isExplicitCommandPath(trimmed)) {
5711
5858
  const expanded = expandHome(trimmed);
5712
- const candidate = path8.isAbsolute(expanded) ? expanded : path8.resolve(expanded);
5713
- return existsSync6(candidate) ? candidate : null;
5859
+ const candidate = path9.isAbsolute(expanded) ? expanded : path9.resolve(expanded);
5860
+ return existsSync7(candidate) ? candidate : null;
5714
5861
  }
5715
5862
  return null;
5716
5863
  }
@@ -7978,9 +8125,9 @@ ${cleanBody}`;
7978
8125
 
7979
8126
  // src/config/chat-history.ts
7980
8127
  import * as fs3 from "fs";
7981
- import * as path10 from "path";
8128
+ import * as path11 from "path";
7982
8129
  import * as os5 from "os";
7983
- var HISTORY_DIR = path10.join(os5.homedir(), ".adhdev", "history");
8130
+ var HISTORY_DIR = path11.join(os5.homedir(), ".adhdev", "history");
7984
8131
  var RETAIN_DAYS = 30;
7985
8132
  var SAVED_HISTORY_INDEX_VERSION = 1;
7986
8133
  var SAVED_HISTORY_INDEX_FILE = ".saved-history-index.json";
@@ -8143,7 +8290,7 @@ function extractSavedHistorySessionIdFromFile(file) {
8143
8290
  function buildSavedHistoryFileSignatureMap(dir, files) {
8144
8291
  return new Map(files.map((file) => {
8145
8292
  try {
8146
- const stat2 = fs3.statSync(path10.join(dir, file));
8293
+ const stat2 = fs3.statSync(path11.join(dir, file));
8147
8294
  return [file, `${file}:${stat2.size}:${Math.trunc(stat2.mtimeMs)}`];
8148
8295
  } catch {
8149
8296
  return [file, `${file}:missing`];
@@ -8154,7 +8301,7 @@ function buildSavedHistoryCacheSignature(files, fileSignatures) {
8154
8301
  return files.map((file) => fileSignatures.get(file) || `${file}:missing`).join("|");
8155
8302
  }
8156
8303
  function getSavedHistoryIndexFilePath(dir) {
8157
- return path10.join(dir, SAVED_HISTORY_INDEX_FILE);
8304
+ return path11.join(dir, SAVED_HISTORY_INDEX_FILE);
8158
8305
  }
8159
8306
  function getSavedHistoryIndexLockPath(dir) {
8160
8307
  return `${getSavedHistoryIndexFilePath(dir)}${SAVED_HISTORY_INDEX_LOCK_SUFFIX}`;
@@ -8256,7 +8403,7 @@ function savePersistedSavedHistoryIndex(dir, entries) {
8256
8403
  }
8257
8404
  for (const file of Array.from(currentEntries.keys())) {
8258
8405
  if (incomingFiles.has(file)) continue;
8259
- if (!fs3.existsSync(path10.join(dir, file))) {
8406
+ if (!fs3.existsSync(path11.join(dir, file))) {
8260
8407
  currentEntries.delete(file);
8261
8408
  }
8262
8409
  }
@@ -8282,7 +8429,7 @@ function historyDirectoryHasFilesNewerThanIndex(dir) {
8282
8429
  const indexStat = fs3.statSync(getSavedHistoryIndexFilePath(dir));
8283
8430
  const files = listHistoryFiles(dir);
8284
8431
  for (const file of files) {
8285
- const stat2 = fs3.statSync(path10.join(dir, file));
8432
+ const stat2 = fs3.statSync(path11.join(dir, file));
8286
8433
  if (stat2.mtimeMs > indexStat.mtimeMs) return true;
8287
8434
  }
8288
8435
  return false;
@@ -8292,14 +8439,14 @@ function historyDirectoryHasFilesNewerThanIndex(dir) {
8292
8439
  }
8293
8440
  function buildSavedHistoryFileSignature(dir, file) {
8294
8441
  try {
8295
- const stat2 = fs3.statSync(path10.join(dir, file));
8442
+ const stat2 = fs3.statSync(path11.join(dir, file));
8296
8443
  return `${file}:${stat2.size}:${Math.trunc(stat2.mtimeMs)}`;
8297
8444
  } catch {
8298
8445
  return `${file}:missing`;
8299
8446
  }
8300
8447
  }
8301
8448
  function persistSavedHistoryFileSummaryEntry(agentType, dir, file, updater) {
8302
- const filePath = path10.join(dir, file);
8449
+ const filePath = path11.join(dir, file);
8303
8450
  const result = withLockedPersistedSavedHistoryIndex(dir, (entries) => {
8304
8451
  const currentEntry = entries.get(file) || null;
8305
8452
  const nextSummary = updater(currentEntry?.summary || null);
@@ -8372,7 +8519,7 @@ function updateSavedHistoryIndexForAppendedMessages(agentType, dir, file, histor
8372
8519
  function computeSavedHistoryFileSummary(dir, file) {
8373
8520
  const historySessionId = extractSavedHistorySessionIdFromFile(file);
8374
8521
  if (!historySessionId) return null;
8375
- const filePath = path10.join(dir, file);
8522
+ const filePath = path11.join(dir, file);
8376
8523
  const content = fs3.readFileSync(filePath, "utf-8");
8377
8524
  const lines = content.split("\n").filter(Boolean);
8378
8525
  let messageCount = 0;
@@ -8459,7 +8606,7 @@ function computeSavedHistorySessionSummaries(agentType, dir, files, fileSignatur
8459
8606
  const summaryBySessionId = /* @__PURE__ */ new Map();
8460
8607
  const nextPersistedEntries = /* @__PURE__ */ new Map();
8461
8608
  for (const file of files.slice().sort()) {
8462
- const filePath = path10.join(dir, file);
8609
+ const filePath = path11.join(dir, file);
8463
8610
  const signature = fileSignatures.get(file) || `${file}:missing`;
8464
8611
  const cached = savedHistoryFileSummaryCache.get(filePath);
8465
8612
  const persisted = persistedEntries.get(file);
@@ -8579,12 +8726,12 @@ var ChatHistoryWriter = class {
8579
8726
  });
8580
8727
  }
8581
8728
  if (newMessages.length === 0) return;
8582
- const dir = path10.join(HISTORY_DIR, this.sanitize(agentType));
8729
+ const dir = path11.join(HISTORY_DIR, this.sanitize(agentType));
8583
8730
  fs3.mkdirSync(dir, { recursive: true });
8584
8731
  const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
8585
8732
  const filePrefix = effectiveHistoryKey ? `${this.sanitize(effectiveHistoryKey)}_` : "";
8586
8733
  const fileName = `${filePrefix}${date}.jsonl`;
8587
- const filePath = path10.join(dir, fileName);
8734
+ const filePath = path11.join(dir, fileName);
8588
8735
  const lines = newMessages.map((m) => JSON.stringify(m)).join("\n") + "\n";
8589
8736
  fs3.appendFileSync(filePath, lines, "utf-8");
8590
8737
  updateSavedHistoryIndexForAppendedMessages(agentType, dir, fileName, effectiveHistoryKey, newMessages);
@@ -8675,11 +8822,11 @@ var ChatHistoryWriter = class {
8675
8822
  const ws = String(workspace || "").trim();
8676
8823
  if (!id || !ws) return;
8677
8824
  try {
8678
- const dir = path10.join(HISTORY_DIR, this.sanitize(agentType));
8825
+ const dir = path11.join(HISTORY_DIR, this.sanitize(agentType));
8679
8826
  fs3.mkdirSync(dir, { recursive: true });
8680
8827
  const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
8681
8828
  const fileName = `${this.sanitize(id)}_${date}.jsonl`;
8682
- const filePath = path10.join(dir, fileName);
8829
+ const filePath = path11.join(dir, fileName);
8683
8830
  const record = {
8684
8831
  ts: (/* @__PURE__ */ new Date()).toISOString(),
8685
8832
  receivedAt: Date.now(),
@@ -8725,14 +8872,14 @@ var ChatHistoryWriter = class {
8725
8872
  this.lastSeenCounts.set(toDedupKey, Math.max(fromCount, this.lastSeenCounts.get(toDedupKey) || 0));
8726
8873
  this.lastSeenCounts.delete(fromDedupKey);
8727
8874
  }
8728
- const dir = path10.join(HISTORY_DIR, this.sanitize(agentType));
8875
+ const dir = path11.join(HISTORY_DIR, this.sanitize(agentType));
8729
8876
  if (!fs3.existsSync(dir)) return;
8730
8877
  const fromPrefix = `${this.sanitize(fromId)}_`;
8731
8878
  const toPrefix = `${this.sanitize(toId)}_`;
8732
8879
  const files = fs3.readdirSync(dir).filter((file) => file.startsWith(fromPrefix) && file.endsWith(".jsonl"));
8733
8880
  for (const file of files) {
8734
- const sourcePath = path10.join(dir, file);
8735
- const targetPath = path10.join(dir, `${toPrefix}${file.slice(fromPrefix.length)}`);
8881
+ const sourcePath = path11.join(dir, file);
8882
+ const targetPath = path11.join(dir, `${toPrefix}${file.slice(fromPrefix.length)}`);
8736
8883
  const sourceLines = fs3.readFileSync(sourcePath, "utf-8").split("\n").filter(Boolean);
8737
8884
  const rewritten = sourceLines.map((line) => {
8738
8885
  try {
@@ -8766,13 +8913,13 @@ var ChatHistoryWriter = class {
8766
8913
  const sessionId = String(historySessionId || "").trim();
8767
8914
  if (!sessionId) return;
8768
8915
  try {
8769
- const dir = path10.join(HISTORY_DIR, this.sanitize(agentType));
8916
+ const dir = path11.join(HISTORY_DIR, this.sanitize(agentType));
8770
8917
  if (!fs3.existsSync(dir)) return;
8771
8918
  const prefix = `${this.sanitize(sessionId)}_`;
8772
8919
  const files = fs3.readdirSync(dir).filter((file) => file.startsWith(prefix) && file.endsWith(".jsonl")).sort();
8773
8920
  const seen = /* @__PURE__ */ new Set();
8774
8921
  for (const file of files) {
8775
- const filePath = path10.join(dir, file);
8922
+ const filePath = path11.join(dir, file);
8776
8923
  const lines = fs3.readFileSync(filePath, "utf-8").split("\n").filter(Boolean);
8777
8924
  const next = [];
8778
8925
  for (const line of lines) {
@@ -8826,11 +8973,11 @@ var ChatHistoryWriter = class {
8826
8973
  const cutoff = Date.now() - RETAIN_DAYS * 24 * 60 * 60 * 1e3;
8827
8974
  const agentDirs = fs3.readdirSync(HISTORY_DIR, { withFileTypes: true }).filter((d) => d.isDirectory());
8828
8975
  for (const dir of agentDirs) {
8829
- const dirPath = path10.join(HISTORY_DIR, dir.name);
8976
+ const dirPath = path11.join(HISTORY_DIR, dir.name);
8830
8977
  const files = fs3.readdirSync(dirPath).filter((f) => f.endsWith(".jsonl") || f.endsWith(".terminal.log"));
8831
8978
  let removedAny = false;
8832
8979
  for (const file of files) {
8833
- const filePath = path10.join(dirPath, file);
8980
+ const filePath = path11.join(dirPath, file);
8834
8981
  const stat2 = fs3.statSync(filePath);
8835
8982
  if (stat2.mtimeMs < cutoff) {
8836
8983
  fs3.unlinkSync(filePath);
@@ -8880,13 +9027,13 @@ function pageHistoryRecords(agentType, records, offset = 0, limit = 30, excludeR
8880
9027
  function readChatHistory(agentType, offset = 0, limit = 30, historySessionId, excludeRecentCount = 0, historyBehavior) {
8881
9028
  try {
8882
9029
  const sanitized = agentType.replace(/[^a-zA-Z0-9_-]/g, "_");
8883
- const dir = path10.join(HISTORY_DIR, sanitized);
9030
+ const dir = path11.join(HISTORY_DIR, sanitized);
8884
9031
  if (!fs3.existsSync(dir)) return { messages: [], hasMore: false };
8885
9032
  const files = listHistoryFiles(dir, historySessionId);
8886
9033
  const allMessages = [];
8887
9034
  const seen = /* @__PURE__ */ new Set();
8888
9035
  for (const file of files) {
8889
- const filePath = path10.join(dir, file);
9036
+ const filePath = path11.join(dir, file);
8890
9037
  const content = fs3.readFileSync(filePath, "utf-8");
8891
9038
  const lines = content.trim().split("\n").filter(Boolean);
8892
9039
  for (let i = 0; i < lines.length; i++) {
@@ -8910,7 +9057,7 @@ function readChatHistory(agentType, offset = 0, limit = 30, historySessionId, ex
8910
9057
  function listSavedHistorySessions(agentType, options = {}, historyBehavior) {
8911
9058
  try {
8912
9059
  const sanitized = agentType.replace(/[^a-zA-Z0-9_-]/g, "_");
8913
- const dir = path10.join(HISTORY_DIR, sanitized);
9060
+ const dir = path11.join(HISTORY_DIR, sanitized);
8914
9061
  if (!fs3.existsSync(dir)) {
8915
9062
  savedHistorySessionCache.delete(sanitized);
8916
9063
  return { sessions: [], hasMore: false };
@@ -8971,11 +9118,11 @@ function listSavedHistorySessions(agentType, options = {}, historyBehavior) {
8971
9118
  }
8972
9119
  function readExistingSessionStartRecord(agentType, historySessionId) {
8973
9120
  try {
8974
- const dir = path10.join(HISTORY_DIR, agentType);
9121
+ const dir = path11.join(HISTORY_DIR, agentType);
8975
9122
  if (!fs3.existsSync(dir)) return null;
8976
9123
  const files = listHistoryFiles(dir, historySessionId).sort();
8977
9124
  for (const file of files) {
8978
- const lines = fs3.readFileSync(path10.join(dir, file), "utf-8").split("\n").filter(Boolean);
9125
+ const lines = fs3.readFileSync(path11.join(dir, file), "utf-8").split("\n").filter(Boolean);
8979
9126
  for (const line of lines) {
8980
9127
  try {
8981
9128
  const parsed = JSON.parse(line);
@@ -8995,16 +9142,16 @@ function readExistingSessionStartRecord(agentType, historySessionId) {
8995
9142
  function rewriteCanonicalSavedHistory(agentType, historySessionId, records) {
8996
9143
  if (records.length === 0) return false;
8997
9144
  try {
8998
- const dir = path10.join(HISTORY_DIR, agentType);
9145
+ const dir = path11.join(HISTORY_DIR, agentType);
8999
9146
  fs3.mkdirSync(dir, { recursive: true });
9000
9147
  const prefix = `${historySessionId.replace(/[^a-zA-Z0-9_-]/g, "_")}_`;
9001
9148
  for (const file of fs3.readdirSync(dir)) {
9002
9149
  if (file.startsWith(prefix) && file.endsWith(".jsonl")) {
9003
- fs3.unlinkSync(path10.join(dir, file));
9150
+ fs3.unlinkSync(path11.join(dir, file));
9004
9151
  }
9005
9152
  }
9006
9153
  const targetDate = new Date(records[records.length - 1].receivedAt || Date.now()).toISOString().slice(0, 10);
9007
- const filePath = path10.join(dir, `${prefix}${targetDate}.jsonl`);
9154
+ const filePath = path11.join(dir, `${prefix}${targetDate}.jsonl`);
9008
9155
  fs3.writeFileSync(filePath, `${records.map((record) => JSON.stringify(record)).join("\n")}
9009
9156
  `, "utf-8");
9010
9157
  invalidatePersistedSavedHistoryIndex(agentType, dir);
@@ -10999,6 +11146,14 @@ function getActiveChatOptions(profile) {
10999
11146
  if (profile === "full") return {};
11000
11147
  return LIVE_STATUS_ACTIVE_CHAT_OPTIONS;
11001
11148
  }
11149
+ function resolveSessionStatus(activeChat, providerStatus) {
11150
+ const chatStatus = normalizeManagedStatus(activeChat?.status, { activeModal: activeChat?.activeModal || null });
11151
+ const topLevelStatus = normalizeManagedStatus(providerStatus, { activeModal: activeChat?.activeModal || null });
11152
+ if (chatStatus === "waiting_approval" || topLevelStatus === "waiting_approval") return "waiting_approval";
11153
+ if (chatStatus === "generating" || topLevelStatus === "generating") return "generating";
11154
+ if (topLevelStatus !== "idle") return topLevelStatus;
11155
+ return chatStatus;
11156
+ }
11002
11157
  function shouldIncludeSessionControls(profile) {
11003
11158
  return profile !== "live";
11004
11159
  }
@@ -11077,9 +11232,7 @@ function buildIdeWorkspaceSession(state, cdpManagers, options) {
11077
11232
  providerName: state.name,
11078
11233
  kind: "workspace",
11079
11234
  transport: "cdp-page",
11080
- status: normalizeManagedStatus(activeChat?.status || state.status, {
11081
- activeModal: activeChat?.activeModal || null
11082
- }),
11235
+ status: resolveSessionStatus(activeChat, state.status),
11083
11236
  title,
11084
11237
  workspace,
11085
11238
  ...git && { git },
@@ -11114,9 +11267,7 @@ function buildExtensionAgentSession(parent, ext, options) {
11114
11267
  providerSessionId: ext.providerSessionId,
11115
11268
  kind: "agent",
11116
11269
  transport: "cdp-webview",
11117
- status: normalizeManagedStatus(activeChat?.status || ext.status, {
11118
- activeModal: activeChat?.activeModal || null
11119
- }),
11270
+ status: resolveSessionStatus(activeChat, ext.status),
11120
11271
  title: activeChat?.title || ext.name,
11121
11272
  workspace,
11122
11273
  ...git && { git },
@@ -11166,9 +11317,7 @@ function buildCliSession(state, options) {
11166
11317
  providerSessionId: state.providerSessionId,
11167
11318
  kind: "agent",
11168
11319
  transport: "pty",
11169
- status: normalizeManagedStatus(activeChat?.status || state.status, {
11170
- activeModal: activeChat?.activeModal || null
11171
- }),
11320
+ status: resolveSessionStatus(activeChat, state.status),
11172
11321
  title: activeChat?.title || state.name,
11173
11322
  workspace,
11174
11323
  ...git && { git },
@@ -11216,9 +11365,7 @@ function buildAcpSession(state, options) {
11216
11365
  providerName: state.name,
11217
11366
  kind: "agent",
11218
11367
  transport: "acp",
11219
- status: normalizeManagedStatus(activeChat?.status || state.status, {
11220
- activeModal: activeChat?.activeModal || null
11221
- }),
11368
+ status: resolveSessionStatus(activeChat, state.status),
11222
11369
  title: activeChat?.title || state.name,
11223
11370
  workspace,
11224
11371
  ...git && { git },
@@ -11341,7 +11488,7 @@ function resolveLegacyProviderScript(fn, scriptName, params) {
11341
11488
  // src/commands/chat-commands.ts
11342
11489
  import * as fs4 from "fs";
11343
11490
  import * as os6 from "os";
11344
- import * as path11 from "path";
11491
+ import * as path12 from "path";
11345
11492
  import { randomUUID as randomUUID5 } from "crypto";
11346
11493
 
11347
11494
  // src/providers/provider-input-support.ts
@@ -11852,7 +11999,7 @@ function buildDebugBundleText(bundle) {
11852
11999
  }
11853
12000
  function getChatDebugBundleDir() {
11854
12001
  const override = typeof process.env.ADHDEV_DEBUG_BUNDLE_DIR === "string" ? process.env.ADHDEV_DEBUG_BUNDLE_DIR.trim() : "";
11855
- return override || path11.join(os6.homedir(), ".adhdev", "debug-bundles", "chat");
12002
+ return override || path12.join(os6.homedir(), ".adhdev", "debug-bundles", "chat");
11856
12003
  }
11857
12004
  function safeBundleIdSegment(value, fallback) {
11858
12005
  const normalized = String(value || fallback).trim().replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
@@ -11885,7 +12032,7 @@ function storeChatDebugBundleOnDaemon(bundle, targetSessionId) {
11885
12032
  const bundleId = createChatDebugBundleId(targetSessionId);
11886
12033
  const dir = getChatDebugBundleDir();
11887
12034
  fs4.mkdirSync(dir, { recursive: true });
11888
- const savedPath = path11.join(dir, `${bundleId}.json`);
12035
+ const savedPath = path12.join(dir, `${bundleId}.json`);
11889
12036
  const json = `${JSON.stringify(bundle, null, 2)}
11890
12037
  `;
11891
12038
  fs4.writeFileSync(savedPath, json, { encoding: "utf8", mode: 384 });
@@ -13029,7 +13176,7 @@ async function handleResolveAction(h, args) {
13029
13176
 
13030
13177
  // src/commands/cdp-commands.ts
13031
13178
  import * as fs5 from "fs";
13032
- import * as path12 from "path";
13179
+ import * as path13 from "path";
13033
13180
  import * as os7 from "os";
13034
13181
  var KEY_TO_VK = {
13035
13182
  Backspace: 8,
@@ -13286,25 +13433,25 @@ function resolveSafePath(requestedPath) {
13286
13433
  const inputPath = rawPath || ".";
13287
13434
  const home = os7.homedir();
13288
13435
  if (inputPath.startsWith("~")) {
13289
- return path12.resolve(path12.join(home, inputPath.slice(1)));
13436
+ return path13.resolve(path13.join(home, inputPath.slice(1)));
13290
13437
  }
13291
13438
  if (process.platform === "win32") {
13292
13439
  const normalized = normalizeWindowsRequestedPath(inputPath);
13293
- if (path12.win32.isAbsolute(normalized)) {
13294
- return path12.win32.normalize(normalized);
13440
+ if (path13.win32.isAbsolute(normalized)) {
13441
+ return path13.win32.normalize(normalized);
13295
13442
  }
13296
- return path12.win32.resolve(normalized);
13443
+ return path13.win32.resolve(normalized);
13297
13444
  }
13298
- if (path12.isAbsolute(inputPath)) {
13299
- return path12.normalize(inputPath);
13445
+ if (path13.isAbsolute(inputPath)) {
13446
+ return path13.normalize(inputPath);
13300
13447
  }
13301
- return path12.resolve(inputPath);
13448
+ return path13.resolve(inputPath);
13302
13449
  }
13303
13450
  function listDirectoryEntriesSafe(dirPath) {
13304
13451
  const entries = fs5.readdirSync(dirPath, { withFileTypes: true });
13305
13452
  const files = [];
13306
13453
  for (const entry of entries) {
13307
- const entryPath = path12.join(dirPath, entry.name);
13454
+ const entryPath = path13.join(dirPath, entry.name);
13308
13455
  try {
13309
13456
  if (entry.isDirectory()) {
13310
13457
  files.push({ name: entry.name, type: "directory" });
@@ -13358,7 +13505,7 @@ async function handleFileRead(h, args) {
13358
13505
  async function handleFileWrite(h, args) {
13359
13506
  try {
13360
13507
  const filePath = resolveSafePath(args?.path);
13361
- fs5.mkdirSync(path12.dirname(filePath), { recursive: true });
13508
+ fs5.mkdirSync(path13.dirname(filePath), { recursive: true });
13362
13509
  fs5.writeFileSync(filePath, args?.content || "", "utf-8");
13363
13510
  return { success: true, path: filePath };
13364
13511
  } catch (e) {
@@ -14478,16 +14625,16 @@ var DaemonCommandHandler = class {
14478
14625
  // src/commands/cli-manager.ts
14479
14626
  init_provider_cli_adapter();
14480
14627
  import * as os13 from "os";
14481
- import * as path16 from "path";
14628
+ import * as path17 from "path";
14482
14629
  import * as crypto4 from "crypto";
14483
- import { existsSync as existsSync11 } from "fs";
14630
+ import { existsSync as existsSync12 } from "fs";
14484
14631
  import { execFileSync } from "child_process";
14485
14632
  import chalk from "chalk";
14486
14633
  init_config();
14487
14634
 
14488
14635
  // src/providers/cli-provider-instance.ts
14489
14636
  import * as os12 from "os";
14490
- import * as path15 from "path";
14637
+ import * as path16 from "path";
14491
14638
  import * as crypto3 from "crypto";
14492
14639
  import * as fs6 from "fs";
14493
14640
  import { createRequire } from "module";
@@ -14546,7 +14693,7 @@ function buildIncrementalHistoryAppendMessages(previousMessages, currentMessages
14546
14693
  var CachedDatabaseSync = null;
14547
14694
  function getDatabaseSync() {
14548
14695
  if (CachedDatabaseSync) return CachedDatabaseSync;
14549
- const requireFn = typeof __require === "function" ? __require : createRequire(path15.join(process.cwd(), "__adhdev_sqlite_loader__.js"));
14696
+ const requireFn = typeof __require === "function" ? __require : createRequire(path16.join(process.cwd(), "__adhdev_sqlite_loader__.js"));
14550
14697
  const sqliteModule = requireFn(`node:${"sqlite"}`);
14551
14698
  CachedDatabaseSync = sqliteModule.DatabaseSync;
14552
14699
  if (!CachedDatabaseSync) {
@@ -16617,17 +16764,17 @@ function shouldRestoreHostedRuntime(record, managerTag) {
16617
16764
  // src/commands/cli-manager.ts
16618
16765
  function isExplicitCommand(command) {
16619
16766
  const trimmed = command.trim();
16620
- return path16.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
16767
+ return path17.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
16621
16768
  }
16622
16769
  function expandExecutable(command) {
16623
16770
  const trimmed = command.trim();
16624
- return trimmed.startsWith("~") ? path16.join(os13.homedir(), trimmed.slice(1)) : trimmed;
16771
+ return trimmed.startsWith("~") ? path17.join(os13.homedir(), trimmed.slice(1)) : trimmed;
16625
16772
  }
16626
16773
  function commandExists(command) {
16627
16774
  const trimmed = command.trim();
16628
16775
  if (!trimmed) return false;
16629
16776
  if (isExplicitCommand(trimmed)) {
16630
- return existsSync11(expandExecutable(trimmed));
16777
+ return existsSync12(expandExecutable(trimmed));
16631
16778
  }
16632
16779
  try {
16633
16780
  execFileSync(process.platform === "win32" ? "where" : "which", [trimmed], {
@@ -16902,7 +17049,7 @@ var DaemonCliManager = class {
16902
17049
  async startSession(cliType, workingDir, cliArgs, initialModel, options) {
16903
17050
  const trimmed = (workingDir || "").trim();
16904
17051
  if (!trimmed) throw new Error("working directory required");
16905
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os13.homedir()) : path16.resolve(trimmed);
17052
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os13.homedir()) : path17.resolve(trimmed);
16906
17053
  const normalizedType = this.providerLoader.resolveAlias(cliType);
16907
17054
  const rawProvider = this.providerLoader.getByAlias(cliType);
16908
17055
  const provider = rawProvider ? this.providerLoader.resolve(normalizedType) || rawProvider : void 0;
@@ -17403,11 +17550,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
17403
17550
  import { execSync as execSync4, spawn as spawn2 } from "child_process";
17404
17551
  import * as net from "net";
17405
17552
  import * as os15 from "os";
17406
- import * as path18 from "path";
17553
+ import * as path19 from "path";
17407
17554
 
17408
17555
  // src/providers/provider-loader.ts
17409
17556
  import * as fs7 from "fs";
17410
- import * as path17 from "path";
17557
+ import * as path18 from "path";
17411
17558
  import * as os14 from "os";
17412
17559
  import * as chokidar from "chokidar";
17413
17560
  init_logger();
@@ -17731,7 +17878,7 @@ var ProviderLoader = class _ProviderLoader {
17731
17878
  try {
17732
17879
  if (!fs7.existsSync(candidate) || !fs7.statSync(candidate).isDirectory()) return false;
17733
17880
  return ["ide", "extension", "cli", "acp"].some(
17734
- (category) => fs7.existsSync(path17.join(candidate, category))
17881
+ (category) => fs7.existsSync(path18.join(candidate, category))
17735
17882
  );
17736
17883
  } catch {
17737
17884
  return false;
@@ -17739,20 +17886,20 @@ var ProviderLoader = class _ProviderLoader {
17739
17886
  }
17740
17887
  static hasProviderRootMarker(candidate) {
17741
17888
  try {
17742
- return fs7.existsSync(path17.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
17889
+ return fs7.existsSync(path18.join(candidate, _ProviderLoader.SIBLING_MARKER_FILE));
17743
17890
  } catch {
17744
17891
  return false;
17745
17892
  }
17746
17893
  }
17747
17894
  detectDefaultUserDir() {
17748
- const fallback = path17.join(os14.homedir(), ".adhdev", "providers");
17895
+ const fallback = path18.join(os14.homedir(), ".adhdev", "providers");
17749
17896
  const envOptIn = process.env[_ProviderLoader.SIBLING_ENV_VAR] === "1";
17750
17897
  const visited = /* @__PURE__ */ new Set();
17751
17898
  for (const start of this.probeStarts) {
17752
- let current = path17.resolve(start);
17899
+ let current = path18.resolve(start);
17753
17900
  while (!visited.has(current)) {
17754
17901
  visited.add(current);
17755
- const siblingCandidate = path17.join(path17.dirname(current), _ProviderLoader.REPO_PROVIDER_DIRNAME);
17902
+ const siblingCandidate = path18.join(path18.dirname(current), _ProviderLoader.REPO_PROVIDER_DIRNAME);
17756
17903
  if (_ProviderLoader.looksLikeProviderRoot(siblingCandidate)) {
17757
17904
  const hasMarker = _ProviderLoader.hasProviderRootMarker(siblingCandidate);
17758
17905
  if (envOptIn || hasMarker) {
@@ -17774,7 +17921,7 @@ var ProviderLoader = class _ProviderLoader {
17774
17921
  return { path: siblingCandidate, source };
17775
17922
  }
17776
17923
  }
17777
- const parent = path17.dirname(current);
17924
+ const parent = path18.dirname(current);
17778
17925
  if (parent === current) break;
17779
17926
  current = parent;
17780
17927
  }
@@ -17784,11 +17931,11 @@ var ProviderLoader = class _ProviderLoader {
17784
17931
  constructor(options) {
17785
17932
  this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
17786
17933
  this.probeStarts = options?.probeStarts ?? [process.cwd(), __dirname];
17787
- this.defaultProvidersDir = path17.join(os14.homedir(), ".adhdev", "providers");
17934
+ this.defaultProvidersDir = path18.join(os14.homedir(), ".adhdev", "providers");
17788
17935
  const detected = this.detectDefaultUserDir();
17789
17936
  this.userDir = detected.path;
17790
17937
  this.userDirSource = detected.source;
17791
- this.upstreamDir = path17.join(this.defaultProvidersDir, ".upstream");
17938
+ this.upstreamDir = path18.join(this.defaultProvidersDir, ".upstream");
17792
17939
  this.disableUpstream = false;
17793
17940
  this.applySourceConfig({
17794
17941
  userDir: options?.userDir,
@@ -17847,7 +17994,7 @@ var ProviderLoader = class _ProviderLoader {
17847
17994
  this.userDir = detected.path;
17848
17995
  this.userDirSource = detected.source;
17849
17996
  }
17850
- this.upstreamDir = path17.join(this.defaultProvidersDir, ".upstream");
17997
+ this.upstreamDir = path18.join(this.defaultProvidersDir, ".upstream");
17851
17998
  this.disableUpstream = this.sourceMode === "no-upstream";
17852
17999
  if (this.explicitProviderDir) {
17853
18000
  this.log(`Config 'providerDir' applied: ${this.userDir}`);
@@ -17861,7 +18008,7 @@ var ProviderLoader = class _ProviderLoader {
17861
18008
  * Canonical provider directory shape for a given root.
17862
18009
  */
17863
18010
  getProviderDir(root, category, type) {
17864
- return path17.join(root, category, type);
18011
+ return path18.join(root, category, type);
17865
18012
  }
17866
18013
  /**
17867
18014
  * Canonical user override directory for a provider.
@@ -17888,7 +18035,7 @@ var ProviderLoader = class _ProviderLoader {
17888
18035
  resolveProviderFile(type, ...segments) {
17889
18036
  const dir = this.findProviderDirInternal(type);
17890
18037
  if (!dir) return null;
17891
- return path17.join(dir, ...segments);
18038
+ return path18.join(dir, ...segments);
17892
18039
  }
17893
18040
  /**
17894
18041
  * Load all providers (3-tier priority)
@@ -17927,7 +18074,7 @@ var ProviderLoader = class _ProviderLoader {
17927
18074
  if (!fs7.existsSync(this.upstreamDir)) return false;
17928
18075
  try {
17929
18076
  return fs7.readdirSync(this.upstreamDir).some(
17930
- (d) => fs7.statSync(path17.join(this.upstreamDir, d)).isDirectory()
18077
+ (d) => fs7.statSync(path18.join(this.upstreamDir, d)).isDirectory()
17931
18078
  );
17932
18079
  } catch {
17933
18080
  return false;
@@ -18424,8 +18571,8 @@ var ProviderLoader = class _ProviderLoader {
18424
18571
  resolved._resolvedScriptDir = entry.scriptDir;
18425
18572
  resolved._resolvedScriptsSource = `compatibility:${entry.ideVersion}`;
18426
18573
  if (providerDir) {
18427
- const fullDir = path17.join(providerDir, entry.scriptDir);
18428
- resolved._resolvedScriptsPath = fs7.existsSync(path17.join(fullDir, "scripts.js")) ? path17.join(fullDir, "scripts.js") : fullDir;
18574
+ const fullDir = path18.join(providerDir, entry.scriptDir);
18575
+ resolved._resolvedScriptsPath = fs7.existsSync(path18.join(fullDir, "scripts.js")) ? path18.join(fullDir, "scripts.js") : fullDir;
18429
18576
  }
18430
18577
  matched = true;
18431
18578
  }
@@ -18440,8 +18587,8 @@ var ProviderLoader = class _ProviderLoader {
18440
18587
  resolved._resolvedScriptDir = base.defaultScriptDir;
18441
18588
  resolved._resolvedScriptsSource = "defaultScriptDir:version_miss";
18442
18589
  if (providerDir) {
18443
- const fullDir = path17.join(providerDir, base.defaultScriptDir);
18444
- resolved._resolvedScriptsPath = fs7.existsSync(path17.join(fullDir, "scripts.js")) ? path17.join(fullDir, "scripts.js") : fullDir;
18590
+ const fullDir = path18.join(providerDir, base.defaultScriptDir);
18591
+ resolved._resolvedScriptsPath = fs7.existsSync(path18.join(fullDir, "scripts.js")) ? path18.join(fullDir, "scripts.js") : fullDir;
18445
18592
  }
18446
18593
  }
18447
18594
  resolved._versionWarning = `Version ${currentVersion} not in compatibility matrix. Using default scripts.`;
@@ -18458,8 +18605,8 @@ var ProviderLoader = class _ProviderLoader {
18458
18605
  resolved._resolvedScriptDir = dirOverride;
18459
18606
  resolved._resolvedScriptsSource = `versions:${range}`;
18460
18607
  if (providerDir) {
18461
- const fullDir = path17.join(providerDir, dirOverride);
18462
- resolved._resolvedScriptsPath = fs7.existsSync(path17.join(fullDir, "scripts.js")) ? path17.join(fullDir, "scripts.js") : fullDir;
18608
+ const fullDir = path18.join(providerDir, dirOverride);
18609
+ resolved._resolvedScriptsPath = fs7.existsSync(path18.join(fullDir, "scripts.js")) ? path18.join(fullDir, "scripts.js") : fullDir;
18463
18610
  }
18464
18611
  }
18465
18612
  } else if (override.scripts) {
@@ -18475,8 +18622,8 @@ var ProviderLoader = class _ProviderLoader {
18475
18622
  resolved._resolvedScriptDir = base.defaultScriptDir;
18476
18623
  resolved._resolvedScriptsSource = "defaultScriptDir:no_version";
18477
18624
  if (providerDir) {
18478
- const fullDir = path17.join(providerDir, base.defaultScriptDir);
18479
- resolved._resolvedScriptsPath = fs7.existsSync(path17.join(fullDir, "scripts.js")) ? path17.join(fullDir, "scripts.js") : fullDir;
18625
+ const fullDir = path18.join(providerDir, base.defaultScriptDir);
18626
+ resolved._resolvedScriptsPath = fs7.existsSync(path18.join(fullDir, "scripts.js")) ? path18.join(fullDir, "scripts.js") : fullDir;
18480
18627
  }
18481
18628
  }
18482
18629
  }
@@ -18508,14 +18655,14 @@ var ProviderLoader = class _ProviderLoader {
18508
18655
  this.log(` [loadScriptsFromDir] ${type}: providerDir not found`);
18509
18656
  return null;
18510
18657
  }
18511
- const dir = path17.join(providerDir, scriptDir);
18658
+ const dir = path18.join(providerDir, scriptDir);
18512
18659
  if (!fs7.existsSync(dir)) {
18513
18660
  this.log(` [loadScriptsFromDir] ${type}: dir not found: ${dir}`);
18514
18661
  return null;
18515
18662
  }
18516
18663
  const cached = this.scriptsCache.get(dir);
18517
18664
  if (cached) return cached;
18518
- const scriptsJs = path17.join(dir, "scripts.js");
18665
+ const scriptsJs = path18.join(dir, "scripts.js");
18519
18666
  if (fs7.existsSync(scriptsJs)) {
18520
18667
  try {
18521
18668
  delete __require.cache[__require.resolve(scriptsJs)];
@@ -18557,7 +18704,7 @@ var ProviderLoader = class _ProviderLoader {
18557
18704
  return;
18558
18705
  }
18559
18706
  if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
18560
- this.log(`File changed: ${path17.basename(filePath)}, reloading...`);
18707
+ this.log(`File changed: ${path18.basename(filePath)}, reloading...`);
18561
18708
  this.reload();
18562
18709
  }
18563
18710
  };
@@ -18612,7 +18759,7 @@ var ProviderLoader = class _ProviderLoader {
18612
18759
  }
18613
18760
  const https = __require("https");
18614
18761
  const { execSync: execSync7 } = __require("child_process");
18615
- const metaPath = path17.join(this.upstreamDir, _ProviderLoader.META_FILE);
18762
+ const metaPath = path18.join(this.upstreamDir, _ProviderLoader.META_FILE);
18616
18763
  let prevEtag = "";
18617
18764
  let prevTimestamp = 0;
18618
18765
  try {
@@ -18672,17 +18819,17 @@ var ProviderLoader = class _ProviderLoader {
18672
18819
  return { updated: false };
18673
18820
  }
18674
18821
  this.log("Downloading latest providers from GitHub...");
18675
- const tmpTar = path17.join(os14.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
18676
- const tmpExtract = path17.join(os14.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
18822
+ const tmpTar = path18.join(os14.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
18823
+ const tmpExtract = path18.join(os14.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
18677
18824
  await this.downloadFile(_ProviderLoader.GITHUB_TARBALL_URL, tmpTar);
18678
18825
  fs7.mkdirSync(tmpExtract, { recursive: true });
18679
18826
  execSync7(`tar -xzf "${tmpTar}" -C "${tmpExtract}"`, { timeout: 3e4 });
18680
18827
  const extracted = fs7.readdirSync(tmpExtract);
18681
18828
  const rootDir = extracted.find(
18682
- (d) => fs7.statSync(path17.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
18829
+ (d) => fs7.statSync(path18.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
18683
18830
  );
18684
18831
  if (!rootDir) throw new Error("Unexpected tarball structure");
18685
- const sourceDir = path17.join(tmpExtract, rootDir);
18832
+ const sourceDir = path18.join(tmpExtract, rootDir);
18686
18833
  const backupDir = this.upstreamDir + ".bak";
18687
18834
  if (fs7.existsSync(this.upstreamDir)) {
18688
18835
  if (fs7.existsSync(backupDir)) fs7.rmSync(backupDir, { recursive: true, force: true });
@@ -18757,8 +18904,8 @@ var ProviderLoader = class _ProviderLoader {
18757
18904
  copyDirRecursive(src, dest) {
18758
18905
  fs7.mkdirSync(dest, { recursive: true });
18759
18906
  for (const entry of fs7.readdirSync(src, { withFileTypes: true })) {
18760
- const srcPath = path17.join(src, entry.name);
18761
- const destPath = path17.join(dest, entry.name);
18907
+ const srcPath = path18.join(src, entry.name);
18908
+ const destPath = path18.join(dest, entry.name);
18762
18909
  if (entry.isDirectory()) {
18763
18910
  this.copyDirRecursive(srcPath, destPath);
18764
18911
  } else {
@@ -18769,7 +18916,7 @@ var ProviderLoader = class _ProviderLoader {
18769
18916
  /** .meta.json save */
18770
18917
  writeMeta(metaPath, etag, timestamp) {
18771
18918
  try {
18772
- fs7.mkdirSync(path17.dirname(metaPath), { recursive: true });
18919
+ fs7.mkdirSync(path18.dirname(metaPath), { recursive: true });
18773
18920
  fs7.writeFileSync(metaPath, JSON.stringify({
18774
18921
  etag,
18775
18922
  timestamp,
@@ -18786,7 +18933,7 @@ var ProviderLoader = class _ProviderLoader {
18786
18933
  const scan = (d) => {
18787
18934
  try {
18788
18935
  for (const entry of fs7.readdirSync(d, { withFileTypes: true })) {
18789
- if (entry.isDirectory()) scan(path17.join(d, entry.name));
18936
+ if (entry.isDirectory()) scan(path18.join(d, entry.name));
18790
18937
  else if (entry.name === "provider.json") count++;
18791
18938
  }
18792
18939
  } catch {
@@ -19014,17 +19161,17 @@ var ProviderLoader = class _ProviderLoader {
19014
19161
  for (const root of searchRoots) {
19015
19162
  if (!fs7.existsSync(root)) continue;
19016
19163
  const candidate = this.getProviderDir(root, cat, type);
19017
- if (fs7.existsSync(path17.join(candidate, "provider.json"))) return candidate;
19018
- const catDir = path17.join(root, cat);
19164
+ if (fs7.existsSync(path18.join(candidate, "provider.json"))) return candidate;
19165
+ const catDir = path18.join(root, cat);
19019
19166
  if (fs7.existsSync(catDir)) {
19020
19167
  try {
19021
19168
  for (const entry of fs7.readdirSync(catDir, { withFileTypes: true })) {
19022
19169
  if (!entry.isDirectory()) continue;
19023
- const jsonPath = path17.join(catDir, entry.name, "provider.json");
19170
+ const jsonPath = path18.join(catDir, entry.name, "provider.json");
19024
19171
  if (fs7.existsSync(jsonPath)) {
19025
19172
  try {
19026
19173
  const data = JSON.parse(fs7.readFileSync(jsonPath, "utf-8"));
19027
- if (data.type === type) return path17.join(catDir, entry.name);
19174
+ if (data.type === type) return path18.join(catDir, entry.name);
19028
19175
  } catch {
19029
19176
  }
19030
19177
  }
@@ -19041,7 +19188,7 @@ var ProviderLoader = class _ProviderLoader {
19041
19188
  * (template substitution is NOT applied here — scripts.js handles that)
19042
19189
  */
19043
19190
  buildScriptWrappersFromDir(dir) {
19044
- const scriptsJs = path17.join(dir, "scripts.js");
19191
+ const scriptsJs = path18.join(dir, "scripts.js");
19045
19192
  if (fs7.existsSync(scriptsJs)) {
19046
19193
  try {
19047
19194
  delete __require.cache[__require.resolve(scriptsJs)];
@@ -19055,7 +19202,7 @@ var ProviderLoader = class _ProviderLoader {
19055
19202
  for (const file of fs7.readdirSync(dir)) {
19056
19203
  if (!file.endsWith(".js")) continue;
19057
19204
  const scriptName = toCamel(file.replace(".js", ""));
19058
- const filePath = path17.join(dir, file);
19205
+ const filePath = path18.join(dir, file);
19059
19206
  result[scriptName] = (...args) => {
19060
19207
  try {
19061
19208
  let content = fs7.readFileSync(filePath, "utf-8");
@@ -19115,7 +19262,7 @@ var ProviderLoader = class _ProviderLoader {
19115
19262
  }
19116
19263
  const hasJson = entries.some((e) => e.name === "provider.json");
19117
19264
  if (hasJson) {
19118
- const jsonPath = path17.join(d, "provider.json");
19265
+ const jsonPath = path18.join(d, "provider.json");
19119
19266
  try {
19120
19267
  const raw = fs7.readFileSync(jsonPath, "utf-8");
19121
19268
  const mod = JSON.parse(raw);
@@ -19136,7 +19283,7 @@ var ProviderLoader = class _ProviderLoader {
19136
19283
  this.log(`\u26A0 Invalid provider at ${jsonPath}: ${validation.errors.join("; ")}`);
19137
19284
  } else {
19138
19285
  const hasCompatibility = Array.isArray(normalizedProvider.compatibility);
19139
- const scriptsPath = path17.join(d, "scripts.js");
19286
+ const scriptsPath = path18.join(d, "scripts.js");
19140
19287
  if (!hasCompatibility && fs7.existsSync(scriptsPath)) {
19141
19288
  try {
19142
19289
  delete __require.cache[__require.resolve(scriptsPath)];
@@ -19162,7 +19309,7 @@ var ProviderLoader = class _ProviderLoader {
19162
19309
  if (!entry.isDirectory()) continue;
19163
19310
  if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
19164
19311
  if (excludeDirs && d === dir && excludeDirs.includes(entry.name)) continue;
19165
- scan(path17.join(d, entry.name));
19312
+ scan(path18.join(d, entry.name));
19166
19313
  }
19167
19314
  }
19168
19315
  };
@@ -19487,8 +19634,8 @@ function detectCurrentWorkspace(ideId) {
19487
19634
  const appNameMap = getMacAppIdentifiers();
19488
19635
  const appName = appNameMap[ideId];
19489
19636
  if (appName) {
19490
- const storagePath = path18.join(
19491
- process.env.APPDATA || path18.join(os15.homedir(), "AppData", "Roaming"),
19637
+ const storagePath = path19.join(
19638
+ process.env.APPDATA || path19.join(os15.homedir(), "AppData", "Roaming"),
19492
19639
  appName,
19493
19640
  "storage.json"
19494
19641
  );
@@ -19677,9 +19824,9 @@ init_logger();
19677
19824
 
19678
19825
  // src/logging/command-log.ts
19679
19826
  import * as fs8 from "fs";
19680
- import * as path19 from "path";
19827
+ import * as path20 from "path";
19681
19828
  import * as os16 from "os";
19682
- var LOG_DIR2 = process.platform === "win32" ? path19.join(process.env.LOCALAPPDATA || process.env.APPDATA || path19.join(os16.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path19.join(os16.homedir(), "Library", "Logs", "adhdev") : path19.join(os16.homedir(), ".local", "share", "adhdev", "logs");
19829
+ var LOG_DIR2 = process.platform === "win32" ? path20.join(process.env.LOCALAPPDATA || process.env.APPDATA || path20.join(os16.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path20.join(os16.homedir(), "Library", "Logs", "adhdev") : path20.join(os16.homedir(), ".local", "share", "adhdev", "logs");
19683
19830
  var MAX_FILE_SIZE = 5 * 1024 * 1024;
19684
19831
  var MAX_DAYS = 7;
19685
19832
  try {
@@ -19717,13 +19864,13 @@ function getDateStr2() {
19717
19864
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
19718
19865
  }
19719
19866
  var currentDate2 = getDateStr2();
19720
- var currentFile = path19.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
19867
+ var currentFile = path20.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
19721
19868
  var writeCount2 = 0;
19722
19869
  function checkRotation() {
19723
19870
  const today = getDateStr2();
19724
19871
  if (today !== currentDate2) {
19725
19872
  currentDate2 = today;
19726
- currentFile = path19.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
19873
+ currentFile = path20.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
19727
19874
  cleanOldFiles();
19728
19875
  }
19729
19876
  }
@@ -19737,7 +19884,7 @@ function cleanOldFiles() {
19737
19884
  const dateMatch = file.match(/commands-(\d{4}-\d{2}-\d{2})/);
19738
19885
  if (dateMatch && dateMatch[1] < cutoffStr) {
19739
19886
  try {
19740
- fs8.unlinkSync(path19.join(LOG_DIR2, file));
19887
+ fs8.unlinkSync(path20.join(LOG_DIR2, file));
19741
19888
  } catch {
19742
19889
  }
19743
19890
  }
@@ -19823,9 +19970,9 @@ cleanOldFiles();
19823
19970
  init_logger();
19824
19971
 
19825
19972
  // src/commands/mesh-coordinator.ts
19826
- import { existsSync as existsSync14, realpathSync as realpathSync2 } from "fs";
19973
+ import { existsSync as existsSync15, realpathSync as realpathSync2 } from "fs";
19827
19974
  import { createRequire as createRequire2 } from "module";
19828
- import { dirname as dirname3, join as join17, resolve as resolve13 } from "path";
19975
+ import { dirname as dirname4, join as join18, resolve as resolve13 } from "path";
19829
19976
  var DEFAULT_SERVER_NAME = "adhdev-mesh";
19830
19977
  var DEFAULT_ADHDEV_MCP_COMMAND = "adhdev-mcp";
19831
19978
  function resolveMeshCoordinatorSetup(options) {
@@ -19846,8 +19993,8 @@ function resolveMeshCoordinatorSetup(options) {
19846
19993
  }
19847
19994
  const serverName = mcpConfig.serverName?.trim() || DEFAULT_SERVER_NAME;
19848
19995
  if (mcpConfig.mode === "auto_import") {
19849
- const path26 = mcpConfig.path?.trim();
19850
- if (!path26) {
19996
+ const path27 = mcpConfig.path?.trim();
19997
+ if (!path27) {
19851
19998
  return { kind: "unsupported", reason: "Provider auto-import MCP config is missing a config path" };
19852
19999
  }
19853
20000
  const mcpServer = resolveAdhdevMcpServerLaunch({
@@ -19864,7 +20011,7 @@ function resolveMeshCoordinatorSetup(options) {
19864
20011
  return {
19865
20012
  kind: "auto_import",
19866
20013
  serverName,
19867
- configPath: join17(workspace, path26),
20014
+ configPath: join18(workspace, path27),
19868
20015
  configFormat: mcpConfig.format,
19869
20016
  mcpServer
19870
20017
  };
@@ -19903,7 +20050,7 @@ function resolveAdhdevMcpServerLaunch(options) {
19903
20050
  if (!entryPath) return null;
19904
20051
  return {
19905
20052
  command: options.nodeExecutable?.trim() || process.execPath,
19906
- args: [entryPath, "--repo-mesh", options.meshId]
20053
+ args: [entryPath, "--mode", "ipc", "--repo-mesh", options.meshId]
19907
20054
  };
19908
20055
  }
19909
20056
  function resolveAdhdevMcpEntryPath(explicitPath) {
@@ -19918,7 +20065,7 @@ function resolveAdhdevMcpEntryPath(explicitPath) {
19918
20065
  const addPackagedCandidates = (baseFile) => {
19919
20066
  if (!baseFile) return;
19920
20067
  const realBase = normalizeExistingPath(baseFile) || baseFile;
19921
- const dir = dirname3(realBase);
20068
+ const dir = dirname4(realBase);
19922
20069
  addCandidate(resolve13(dir, "../vendor/mcp-server/index.js"));
19923
20070
  addCandidate(resolve13(dir, "../../vendor/mcp-server/index.js"));
19924
20071
  addCandidate(resolve13(dir, "../../../vendor/mcp-server/index.js"));
@@ -19931,7 +20078,7 @@ function resolveAdhdevMcpEntryPath(explicitPath) {
19931
20078
  if (normalized) return normalized;
19932
20079
  }
19933
20080
  try {
19934
- const requireBase = process.argv[1] ? normalizeExistingPath(process.argv[1]) || process.argv[1] : join17(process.cwd(), "adhdev-daemon.js");
20081
+ const requireBase = process.argv[1] ? normalizeExistingPath(process.argv[1]) || process.argv[1] : join18(process.cwd(), "adhdev-daemon.js");
19935
20082
  const req = createRequire2(requireBase);
19936
20083
  const resolvedModule = req.resolve("@adhdev/mcp-server");
19937
20084
  return normalizeExistingPath(resolvedModule) || resolvedModule;
@@ -19941,7 +20088,7 @@ function resolveAdhdevMcpEntryPath(explicitPath) {
19941
20088
  }
19942
20089
  function normalizeExistingPath(filePath) {
19943
20090
  try {
19944
- if (!existsSync14(filePath)) return null;
20091
+ if (!existsSync15(filePath)) return null;
19945
20092
  return realpathSync2.native(filePath);
19946
20093
  } catch {
19947
20094
  return null;
@@ -20266,13 +20413,13 @@ import { execFileSync as execFileSync2 } from "child_process";
20266
20413
  import { spawn as spawn3 } from "child_process";
20267
20414
  import * as fs9 from "fs";
20268
20415
  import * as os18 from "os";
20269
- import * as path20 from "path";
20416
+ import * as path21 from "path";
20270
20417
  var UPGRADE_HELPER_ENV = "ADHDEV_DAEMON_UPGRADE_HELPER";
20271
20418
  function getUpgradeLogPath() {
20272
20419
  const home = os18.homedir();
20273
- const dir = path20.join(home, ".adhdev");
20420
+ const dir = path21.join(home, ".adhdev");
20274
20421
  fs9.mkdirSync(dir, { recursive: true });
20275
- return path20.join(dir, "daemon-upgrade.log");
20422
+ return path21.join(dir, "daemon-upgrade.log");
20276
20423
  }
20277
20424
  function appendUpgradeLog(message) {
20278
20425
  const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
@@ -20283,14 +20430,14 @@ function appendUpgradeLog(message) {
20283
20430
  }
20284
20431
  }
20285
20432
  function resolveSiblingNpmInvocation(nodeExecutable, platform10 = process.platform) {
20286
- const binDir = path20.dirname(nodeExecutable);
20433
+ const binDir = path21.dirname(nodeExecutable);
20287
20434
  if (platform10 === "win32") {
20288
- const npmCliPath = path20.join(binDir, "node_modules", "npm", "bin", "npm-cli.js");
20435
+ const npmCliPath = path21.join(binDir, "node_modules", "npm", "bin", "npm-cli.js");
20289
20436
  if (fs9.existsSync(npmCliPath)) {
20290
20437
  return { executable: nodeExecutable, argsPrefix: [npmCliPath], execOptions: getNpmExecOptions(platform10) };
20291
20438
  }
20292
20439
  for (const candidate of ["npm.exe", "npm"]) {
20293
- const candidatePath = path20.join(binDir, candidate);
20440
+ const candidatePath = path21.join(binDir, candidate);
20294
20441
  if (fs9.existsSync(candidatePath)) {
20295
20442
  return { executable: candidatePath, argsPrefix: [], execOptions: getNpmExecOptions(platform10) };
20296
20443
  }
@@ -20298,7 +20445,7 @@ function resolveSiblingNpmInvocation(nodeExecutable, platform10 = process.platfo
20298
20445
  return { executable: nodeExecutable, argsPrefix: [npmCliPath], execOptions: getNpmExecOptions(platform10) };
20299
20446
  }
20300
20447
  for (const candidate of ["npm"]) {
20301
- const candidatePath = path20.join(binDir, candidate);
20448
+ const candidatePath = path21.join(binDir, candidate);
20302
20449
  if (fs9.existsSync(candidatePath)) {
20303
20450
  return { executable: candidatePath, argsPrefix: [], execOptions: getNpmExecOptions(platform10) };
20304
20451
  }
@@ -20315,13 +20462,13 @@ function findCurrentPackageRoot(currentCliPath, packageName) {
20315
20462
  let currentDir = resolvedPath;
20316
20463
  try {
20317
20464
  if (fs9.statSync(resolvedPath).isFile()) {
20318
- currentDir = path20.dirname(resolvedPath);
20465
+ currentDir = path21.dirname(resolvedPath);
20319
20466
  }
20320
20467
  } catch {
20321
- currentDir = path20.dirname(resolvedPath);
20468
+ currentDir = path21.dirname(resolvedPath);
20322
20469
  }
20323
20470
  while (true) {
20324
- const packageJsonPath = path20.join(currentDir, "package.json");
20471
+ const packageJsonPath = path21.join(currentDir, "package.json");
20325
20472
  try {
20326
20473
  if (fs9.existsSync(packageJsonPath)) {
20327
20474
  const parsed = JSON.parse(fs9.readFileSync(packageJsonPath, "utf8"));
@@ -20332,7 +20479,7 @@ function findCurrentPackageRoot(currentCliPath, packageName) {
20332
20479
  }
20333
20480
  } catch {
20334
20481
  }
20335
- const parentDir = path20.dirname(currentDir);
20482
+ const parentDir = path21.dirname(currentDir);
20336
20483
  if (parentDir === currentDir) {
20337
20484
  return null;
20338
20485
  }
@@ -20340,13 +20487,13 @@ function findCurrentPackageRoot(currentCliPath, packageName) {
20340
20487
  }
20341
20488
  }
20342
20489
  function resolveInstallPrefixFromPackageRoot(packageRoot, packageName) {
20343
- const nodeModulesDir = packageName.startsWith("@") ? path20.dirname(path20.dirname(packageRoot)) : path20.dirname(packageRoot);
20344
- if (path20.basename(nodeModulesDir) !== "node_modules") {
20490
+ const nodeModulesDir = packageName.startsWith("@") ? path21.dirname(path21.dirname(packageRoot)) : path21.dirname(packageRoot);
20491
+ if (path21.basename(nodeModulesDir) !== "node_modules") {
20345
20492
  return null;
20346
20493
  }
20347
- const maybeLibDir = path20.dirname(nodeModulesDir);
20348
- if (path20.basename(maybeLibDir) === "lib") {
20349
- return path20.dirname(maybeLibDir);
20494
+ const maybeLibDir = path21.dirname(nodeModulesDir);
20495
+ if (path21.basename(maybeLibDir) === "lib") {
20496
+ return path21.dirname(maybeLibDir);
20350
20497
  }
20351
20498
  return maybeLibDir;
20352
20499
  }
@@ -20461,7 +20608,7 @@ async function waitForPidExit(pid, timeoutMs) {
20461
20608
  }
20462
20609
  }
20463
20610
  function stopSessionHostProcesses(appName) {
20464
- const pidFile = path20.join(os18.homedir(), ".adhdev", `${appName}-session-host.pid`);
20611
+ const pidFile = path21.join(os18.homedir(), ".adhdev", `${appName}-session-host.pid`);
20465
20612
  try {
20466
20613
  if (fs9.existsSync(pidFile)) {
20467
20614
  const pid = Number.parseInt(fs9.readFileSync(pidFile, "utf8").trim(), 10);
@@ -20478,7 +20625,7 @@ function stopSessionHostProcesses(appName) {
20478
20625
  }
20479
20626
  }
20480
20627
  function removeDaemonPidFile() {
20481
- const pidFile = path20.join(os18.homedir(), ".adhdev", "daemon.pid");
20628
+ const pidFile = path21.join(os18.homedir(), ".adhdev", "daemon.pid");
20482
20629
  try {
20483
20630
  fs9.unlinkSync(pidFile);
20484
20631
  } catch {
@@ -20489,7 +20636,7 @@ function cleanupStaleGlobalInstallDirs(pkgName, surface) {
20489
20636
  const npmRoot = String(execNpmCommandSync(["root", "-g", ...prefixArgs], { encoding: "utf8" }, surface)).trim();
20490
20637
  if (!npmRoot) return;
20491
20638
  const npmPrefix = surface.installPrefix || String(execNpmCommandSync(["prefix", "-g", ...prefixArgs], { encoding: "utf8" }, surface)).trim();
20492
- const binDir = process.platform === "win32" ? npmPrefix : path20.join(npmPrefix, "bin");
20639
+ const binDir = process.platform === "win32" ? npmPrefix : path21.join(npmPrefix, "bin");
20493
20640
  const packageBaseName = pkgName.startsWith("@") ? pkgName.split("/")[1] : pkgName;
20494
20641
  const binNames = /* @__PURE__ */ new Set([packageBaseName]);
20495
20642
  if (pkgName === "@adhdev/daemon-standalone") {
@@ -20497,25 +20644,25 @@ function cleanupStaleGlobalInstallDirs(pkgName, surface) {
20497
20644
  }
20498
20645
  if (pkgName.startsWith("@")) {
20499
20646
  const [scope, name] = pkgName.split("/");
20500
- const scopeDir = path20.join(npmRoot, scope);
20647
+ const scopeDir = path21.join(npmRoot, scope);
20501
20648
  if (!fs9.existsSync(scopeDir)) return;
20502
20649
  for (const entry of fs9.readdirSync(scopeDir)) {
20503
20650
  if (!entry.startsWith(`.${name}-`)) continue;
20504
- fs9.rmSync(path20.join(scopeDir, entry), { recursive: true, force: true });
20505
- appendUpgradeLog(`Removed stale scoped staging dir: ${path20.join(scopeDir, entry)}`);
20651
+ fs9.rmSync(path21.join(scopeDir, entry), { recursive: true, force: true });
20652
+ appendUpgradeLog(`Removed stale scoped staging dir: ${path21.join(scopeDir, entry)}`);
20506
20653
  }
20507
20654
  } else {
20508
20655
  for (const entry of fs9.readdirSync(npmRoot)) {
20509
20656
  if (!entry.startsWith(`.${pkgName}-`)) continue;
20510
- fs9.rmSync(path20.join(npmRoot, entry), { recursive: true, force: true });
20511
- appendUpgradeLog(`Removed stale staging dir: ${path20.join(npmRoot, entry)}`);
20657
+ fs9.rmSync(path21.join(npmRoot, entry), { recursive: true, force: true });
20658
+ appendUpgradeLog(`Removed stale staging dir: ${path21.join(npmRoot, entry)}`);
20512
20659
  }
20513
20660
  }
20514
20661
  if (fs9.existsSync(binDir)) {
20515
20662
  for (const entry of fs9.readdirSync(binDir)) {
20516
20663
  if (!Array.from(binNames).some((name) => entry.startsWith(`.${name}-`))) continue;
20517
- fs9.rmSync(path20.join(binDir, entry), { recursive: true, force: true });
20518
- appendUpgradeLog(`Removed stale bin staging entry: ${path20.join(binDir, entry)}`);
20664
+ fs9.rmSync(path21.join(binDir, entry), { recursive: true, force: true });
20665
+ appendUpgradeLog(`Removed stale bin staging entry: ${path21.join(binDir, entry)}`);
20519
20666
  }
20520
20667
  }
20521
20668
  }
@@ -20602,6 +20749,10 @@ async function maybeRunDaemonUpgradeHelperFromEnv() {
20602
20749
  // src/commands/router.ts
20603
20750
  import * as fs10 from "fs";
20604
20751
  var CHANNEL_NPM_TAG = { stable: "latest", preview: "next" };
20752
+ var CHANNEL_SERVER_URL = {
20753
+ stable: "https://api.adhf.dev",
20754
+ preview: "https://api-preview.adhf.dev"
20755
+ };
20605
20756
  function normalizeReleaseChannel(value) {
20606
20757
  if (typeof value !== "string") return null;
20607
20758
  const normalized = value.trim().toLowerCase();
@@ -20710,6 +20861,40 @@ var DaemonCommandRouter = class {
20710
20861
  constructor(deps) {
20711
20862
  this.deps = deps;
20712
20863
  }
20864
+ getCachedInlineMesh(meshId, inlineMesh) {
20865
+ if (inlineMesh && typeof inlineMesh === "object") {
20866
+ this.inlineMeshCache.set(meshId, inlineMesh);
20867
+ return inlineMesh;
20868
+ }
20869
+ return this.inlineMeshCache.get(meshId);
20870
+ }
20871
+ async getMeshForCommand(meshId, inlineMesh) {
20872
+ try {
20873
+ const { getMesh: getMesh3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
20874
+ const mesh = getMesh3(meshId);
20875
+ if (mesh) return { mesh, inline: false };
20876
+ } catch {
20877
+ }
20878
+ const cached = this.getCachedInlineMesh(meshId, inlineMesh);
20879
+ return cached ? { mesh: cached, inline: true } : null;
20880
+ }
20881
+ updateInlineMeshNode(meshId, mesh, node) {
20882
+ if (!mesh || !Array.isArray(mesh.nodes) || !node?.id) return;
20883
+ const idx = mesh.nodes.findIndex((entry) => entry?.id === node.id || entry?.nodeId === node.id);
20884
+ if (idx >= 0) mesh.nodes[idx] = node;
20885
+ else mesh.nodes.push(node);
20886
+ mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
20887
+ this.inlineMeshCache.set(meshId, mesh);
20888
+ }
20889
+ removeInlineMeshNode(meshId, mesh, nodeId) {
20890
+ if (!mesh || !Array.isArray(mesh.nodes)) return false;
20891
+ const idx = mesh.nodes.findIndex((entry) => entry?.id === nodeId || entry?.nodeId === nodeId);
20892
+ if (idx === -1) return false;
20893
+ mesh.nodes.splice(idx, 1);
20894
+ mesh.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
20895
+ this.inlineMeshCache.set(meshId, mesh);
20896
+ return true;
20897
+ }
20713
20898
  async traceSessionHostAction(action, args, run, summarizeResult) {
20714
20899
  const interactionId = typeof args?._interactionId === "string" ? args._interactionId : void 0;
20715
20900
  const sessionId = typeof args?.sessionId === "string" ? args.sessionId : void 0;
@@ -21298,6 +21483,7 @@ var DaemonCommandRouter = class {
21298
21483
  const npmTag = CHANNEL_NPM_TAG[channel];
21299
21484
  const latest = String(execNpmCommandSync(["view", `${pkgName}@${npmTag}`, "version"], { encoding: "utf-8", timeout: 1e4 }, npmSurface)).trim();
21300
21485
  LOG.info("Upgrade", `Latest ${pkgName}@${npmTag}: v${latest}`);
21486
+ updateConfig({ updateChannel: channel, serverUrl: CHANNEL_SERVER_URL[channel] });
21301
21487
  let currentInstalled = null;
21302
21488
  try {
21303
21489
  const currentJson = String(execNpmCommandSync(["ls", "-g", pkgName, "--depth=0", "--json"], {
@@ -21408,13 +21594,94 @@ var DaemonCommandRouter = class {
21408
21594
  const nodeId = typeof args?.nodeId === "string" ? args.nodeId.trim() : "";
21409
21595
  if (!meshId || !nodeId) return { success: false, error: "meshId and nodeId required" };
21410
21596
  try {
21411
- const { removeNode: removeNode3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21412
- const removed = removeNode3(meshId, nodeId);
21597
+ const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh);
21598
+ const mesh = meshRecord?.mesh;
21599
+ const node = mesh?.nodes?.find((n) => n.id === nodeId || n.nodeId === nodeId);
21600
+ if (node?.isLocalWorktree && node.workspace) {
21601
+ try {
21602
+ const sourceNode = node.clonedFromNodeId ? mesh?.nodes.find((n) => n.id === node.clonedFromNodeId || n.nodeId === node.clonedFromNodeId) : mesh?.nodes.find((n) => !n.isLocalWorktree);
21603
+ const repoRoot = sourceNode?.repoRoot || sourceNode?.workspace;
21604
+ if (repoRoot) {
21605
+ const { removeWorktree: removeWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
21606
+ await removeWorktree2(repoRoot, node.workspace);
21607
+ }
21608
+ } catch (e) {
21609
+ LOG.warn("MeshNode", `Worktree cleanup failed for ${nodeId}: ${e.message}`);
21610
+ }
21611
+ }
21612
+ let removed = false;
21613
+ if (meshRecord?.inline) {
21614
+ removed = this.removeInlineMeshNode(meshId, mesh, nodeId);
21615
+ } else {
21616
+ const { removeNode: removeNode3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21617
+ removed = removeNode3(meshId, nodeId);
21618
+ }
21413
21619
  return { success: true, removed };
21414
21620
  } catch (e) {
21415
21621
  return { success: false, error: e.message };
21416
21622
  }
21417
21623
  }
21624
+ case "clone_mesh_node": {
21625
+ const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
21626
+ const sourceNodeId = typeof args?.sourceNodeId === "string" ? args.sourceNodeId.trim() : "";
21627
+ const branch = typeof args?.branch === "string" ? args.branch.trim() : "";
21628
+ const baseBranch = typeof args?.baseBranch === "string" ? args.baseBranch.trim() : void 0;
21629
+ if (!meshId) return { success: false, error: "meshId required" };
21630
+ if (!sourceNodeId) return { success: false, error: "sourceNodeId required" };
21631
+ if (!branch) return { success: false, error: "branch required" };
21632
+ try {
21633
+ const meshRecord = await this.getMeshForCommand(meshId, args?.inlineMesh);
21634
+ const mesh = meshRecord?.mesh;
21635
+ if (!mesh) return { success: false, error: "Mesh not found" };
21636
+ const sourceNode = mesh.nodes?.find((n) => n.id === sourceNodeId || n.nodeId === sourceNodeId);
21637
+ if (!sourceNode) return { success: false, error: `Source node '${sourceNodeId}' not found in mesh` };
21638
+ const repoRoot = sourceNode.repoRoot || sourceNode.workspace;
21639
+ const { createWorktree: createWorktree2 } = await Promise.resolve().then(() => (init_git_worktree(), git_worktree_exports));
21640
+ const result = await createWorktree2({
21641
+ repoRoot,
21642
+ branch,
21643
+ baseBranch,
21644
+ meshName: mesh.name
21645
+ });
21646
+ let node;
21647
+ if (meshRecord.inline) {
21648
+ const { randomUUID: randomUUID8 } = await import("crypto");
21649
+ node = {
21650
+ id: `node_${randomUUID8().replace(/-/g, "")}`,
21651
+ workspace: result.worktreePath,
21652
+ repoRoot: result.worktreePath,
21653
+ daemonId: sourceNode.daemonId,
21654
+ userOverrides: { ...sourceNode.userOverrides || {} },
21655
+ policy: { ...sourceNode.policy || {} },
21656
+ isLocalWorktree: true,
21657
+ worktreeBranch: result.branch,
21658
+ clonedFromNodeId: sourceNodeId
21659
+ };
21660
+ this.updateInlineMeshNode(meshId, mesh, node);
21661
+ } else {
21662
+ const { addNode: addNode3 } = await Promise.resolve().then(() => (init_mesh_config(), mesh_config_exports));
21663
+ node = addNode3(meshId, {
21664
+ workspace: result.worktreePath,
21665
+ repoRoot: result.worktreePath,
21666
+ daemonId: sourceNode.daemonId,
21667
+ userOverrides: { ...sourceNode.userOverrides || {} },
21668
+ isLocalWorktree: true,
21669
+ worktreeBranch: result.branch,
21670
+ clonedFromNodeId: sourceNodeId,
21671
+ policy: { ...sourceNode.policy || {} }
21672
+ });
21673
+ if (!node) return { success: false, error: "Failed to register worktree node" };
21674
+ }
21675
+ return {
21676
+ success: true,
21677
+ node,
21678
+ worktreePath: result.worktreePath,
21679
+ branch: result.branch
21680
+ };
21681
+ } catch (e) {
21682
+ return { success: false, error: e.message };
21683
+ }
21684
+ }
21418
21685
  // ─── Mesh Coordinator Launch ───
21419
21686
  case "launch_mesh_coordinator": {
21420
21687
  const meshId = typeof args?.meshId === "string" ? args.meshId.trim() : "";
@@ -21483,9 +21750,24 @@ var DaemonCommandRouter = class {
21483
21750
  workspace
21484
21751
  };
21485
21752
  }
21486
- const { existsSync: existsSync22, readFileSync: readFileSync15, writeFileSync: writeFileSync12, copyFileSync: copyFileSync3 } = await import("fs");
21753
+ let systemPrompt = "";
21754
+ try {
21755
+ systemPrompt = buildCoordinatorSystemPrompt2({ mesh, coordinatorCliType: cliType });
21756
+ } catch (error) {
21757
+ const message = error?.message || String(error);
21758
+ LOG.error("MeshCoordinator", `Failed to build coordinator prompt: ${message}`);
21759
+ return {
21760
+ success: false,
21761
+ code: "mesh_coordinator_prompt_failed",
21762
+ error: `Failed to build Repo Mesh coordinator prompt: ${message}`,
21763
+ meshId,
21764
+ cliType,
21765
+ workspace
21766
+ };
21767
+ }
21768
+ const { existsSync: existsSync23, readFileSync: readFileSync15, writeFileSync: writeFileSync12, copyFileSync: copyFileSync3 } = await import("fs");
21487
21769
  const mcpConfigPath = coordinatorSetup.configPath;
21488
- const hadExistingMcpConfig = existsSync22(mcpConfigPath);
21770
+ const hadExistingMcpConfig = existsSync23(mcpConfigPath);
21489
21771
  let existingMcpConfig = {};
21490
21772
  if (hadExistingMcpConfig) {
21491
21773
  try {
@@ -21500,7 +21782,8 @@ var DaemonCommandRouter = class {
21500
21782
  };
21501
21783
  if (args?.inlineMesh) {
21502
21784
  mcpServerEntry.env = {
21503
- ADHDEV_INLINE_MESH: JSON.stringify(mesh)
21785
+ ADHDEV_INLINE_MESH: JSON.stringify(mesh),
21786
+ ADHDEV_MCP_TRANSPORT: "ipc"
21504
21787
  };
21505
21788
  }
21506
21789
  const mcpConfig = {
@@ -21512,12 +21795,6 @@ var DaemonCommandRouter = class {
21512
21795
  };
21513
21796
  writeFileSync12(mcpConfigPath, JSON.stringify(mcpConfig, null, 2), "utf-8");
21514
21797
  LOG.info("MeshCoordinator", `Wrote ${mcpConfigPath} with ${coordinatorSetup.serverName} server`);
21515
- let systemPrompt = "";
21516
- try {
21517
- systemPrompt = buildCoordinatorSystemPrompt2({ mesh });
21518
- } catch {
21519
- systemPrompt = `You are a Repo Mesh Coordinator for "${mesh.name}". Use the adhdev-mesh MCP tools (mesh_status, mesh_list_nodes, mesh_send_task, mesh_read_chat, mesh_launch_session, etc.) to orchestrate work across ${mesh.nodes.length} node(s).`;
21520
- }
21521
21798
  const cliArgs = [];
21522
21799
  if (systemPrompt) {
21523
21800
  cliArgs.push("--append-system-prompt", systemPrompt);
@@ -23189,11 +23466,11 @@ var ProviderInstanceManager = class {
23189
23466
 
23190
23467
  // src/providers/version-archive.ts
23191
23468
  import * as fs11 from "fs";
23192
- import * as path21 from "path";
23469
+ import * as path22 from "path";
23193
23470
  import * as os19 from "os";
23194
23471
  import { execSync as execSync5 } from "child_process";
23195
23472
  import { platform as platform8 } from "os";
23196
- var ARCHIVE_PATH = path21.join(os19.homedir(), ".adhdev", "version-history.json");
23473
+ var ARCHIVE_PATH = path22.join(os19.homedir(), ".adhdev", "version-history.json");
23197
23474
  var MAX_ENTRIES_PER_PROVIDER = 20;
23198
23475
  var VersionArchive = class {
23199
23476
  history = {};
@@ -23240,7 +23517,7 @@ var VersionArchive = class {
23240
23517
  }
23241
23518
  save() {
23242
23519
  try {
23243
- fs11.mkdirSync(path21.dirname(ARCHIVE_PATH), { recursive: true });
23520
+ fs11.mkdirSync(path22.dirname(ARCHIVE_PATH), { recursive: true });
23244
23521
  fs11.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
23245
23522
  } catch {
23246
23523
  }
@@ -23297,7 +23574,7 @@ function checkPathExists2(paths) {
23297
23574
  for (const p of paths) {
23298
23575
  if (p.includes("*")) {
23299
23576
  const home = os19.homedir();
23300
- const resolved = p.replace(/\*/g, home.split(path21.sep).pop() || "");
23577
+ const resolved = p.replace(/\*/g, home.split(path22.sep).pop() || "");
23301
23578
  if (fs11.existsSync(resolved)) return resolved;
23302
23579
  } else {
23303
23580
  if (fs11.existsSync(p)) return p;
@@ -23307,7 +23584,7 @@ function checkPathExists2(paths) {
23307
23584
  }
23308
23585
  function getMacAppVersion(appPath) {
23309
23586
  if (platform8() !== "darwin" || !appPath.endsWith(".app")) return null;
23310
- const plistPath = path21.join(appPath, "Contents", "Info.plist");
23587
+ const plistPath = path22.join(appPath, "Contents", "Info.plist");
23311
23588
  if (!fs11.existsSync(plistPath)) return null;
23312
23589
  const raw = runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
23313
23590
  return raw || null;
@@ -23333,7 +23610,7 @@ async function detectAllVersions(loader, archive) {
23333
23610
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
23334
23611
  let resolvedBin = cliBin;
23335
23612
  if (!resolvedBin && appPath && currentOs === "darwin") {
23336
- const bundled = path21.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
23613
+ const bundled = path22.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
23337
23614
  if (provider.cli && fs11.existsSync(bundled)) resolvedBin = bundled;
23338
23615
  }
23339
23616
  info.installed = !!(appPath || resolvedBin);
@@ -23374,7 +23651,7 @@ async function detectAllVersions(loader, archive) {
23374
23651
  // src/daemon/dev-server.ts
23375
23652
  import * as http2 from "http";
23376
23653
  import * as fs15 from "fs";
23377
- import * as path25 from "path";
23654
+ import * as path26 from "path";
23378
23655
  init_config();
23379
23656
 
23380
23657
  // src/daemon/scaffold-template.ts
@@ -23726,7 +24003,7 @@ init_logger();
23726
24003
  // src/daemon/dev-cdp-handlers.ts
23727
24004
  init_logger();
23728
24005
  import * as fs12 from "fs";
23729
- import * as path22 from "path";
24006
+ import * as path23 from "path";
23730
24007
  async function handleCdpEvaluate(ctx, req, res) {
23731
24008
  const body = await ctx.readBody(req);
23732
24009
  const { expression, timeout, ideType } = body;
@@ -23904,17 +24181,17 @@ async function handleScriptHints(ctx, type, _req, res) {
23904
24181
  return;
23905
24182
  }
23906
24183
  let scriptsPath = "";
23907
- const directScripts = path22.join(dir, "scripts.js");
24184
+ const directScripts = path23.join(dir, "scripts.js");
23908
24185
  if (fs12.existsSync(directScripts)) {
23909
24186
  scriptsPath = directScripts;
23910
24187
  } else {
23911
- const scriptsDir = path22.join(dir, "scripts");
24188
+ const scriptsDir = path23.join(dir, "scripts");
23912
24189
  if (fs12.existsSync(scriptsDir)) {
23913
24190
  const versions = fs12.readdirSync(scriptsDir).filter((d) => {
23914
- return fs12.statSync(path22.join(scriptsDir, d)).isDirectory();
24191
+ return fs12.statSync(path23.join(scriptsDir, d)).isDirectory();
23915
24192
  }).sort().reverse();
23916
24193
  for (const ver of versions) {
23917
- const p = path22.join(scriptsDir, ver, "scripts.js");
24194
+ const p = path23.join(scriptsDir, ver, "scripts.js");
23918
24195
  if (fs12.existsSync(p)) {
23919
24196
  scriptsPath = p;
23920
24197
  break;
@@ -24743,7 +25020,7 @@ async function handleDomContext(ctx, type, req, res) {
24743
25020
 
24744
25021
  // src/daemon/dev-cli-debug.ts
24745
25022
  import * as fs13 from "fs";
24746
- import * as path23 from "path";
25023
+ import * as path24 from "path";
24747
25024
  function slugifyFixtureName(value) {
24748
25025
  const normalized = String(value || "").trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
24749
25026
  return normalized || `fixture-${Date.now()}`;
@@ -24753,11 +25030,11 @@ function getCliFixtureDir(ctx, type) {
24753
25030
  if (!providerDir) {
24754
25031
  throw new Error(`Provider directory not found for '${type}'`);
24755
25032
  }
24756
- return path23.join(providerDir, "fixtures");
25033
+ return path24.join(providerDir, "fixtures");
24757
25034
  }
24758
25035
  function readCliFixture(ctx, type, name) {
24759
25036
  const fixtureDir = getCliFixtureDir(ctx, type);
24760
- const filePath = path23.join(fixtureDir, `${name}.json`);
25037
+ const filePath = path24.join(fixtureDir, `${name}.json`);
24761
25038
  if (!fs13.existsSync(filePath)) {
24762
25039
  throw new Error(`Fixture not found: ${filePath}`);
24763
25040
  }
@@ -25524,7 +25801,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
25524
25801
  },
25525
25802
  notes: typeof body?.notes === "string" ? body.notes : void 0
25526
25803
  };
25527
- const filePath = path23.join(fixtureDir, `${name}.json`);
25804
+ const filePath = path24.join(fixtureDir, `${name}.json`);
25528
25805
  fs13.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
25529
25806
  ctx.json(res, 200, {
25530
25807
  saved: true,
@@ -25548,7 +25825,7 @@ async function handleCliFixtureList(ctx, type, _req, res) {
25548
25825
  return;
25549
25826
  }
25550
25827
  const fixtures = fs13.readdirSync(fixtureDir).filter((file) => file.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file) => {
25551
- const fullPath = path23.join(fixtureDir, file);
25828
+ const fullPath = path24.join(fixtureDir, file);
25552
25829
  try {
25553
25830
  const raw = JSON.parse(fs13.readFileSync(fullPath, "utf-8"));
25554
25831
  return {
@@ -25684,7 +25961,7 @@ async function handleCliRaw(ctx, req, res) {
25684
25961
 
25685
25962
  // src/daemon/dev-auto-implement.ts
25686
25963
  import * as fs14 from "fs";
25687
- import * as path24 from "path";
25964
+ import * as path25 from "path";
25688
25965
  import * as os20 from "os";
25689
25966
  function getAutoImplPid(ctx) {
25690
25967
  const pid = ctx.autoImplProcess?.pid;
@@ -25734,22 +26011,22 @@ function getLatestScriptVersionDir(scriptsDir) {
25734
26011
  if (!fs14.existsSync(scriptsDir)) return null;
25735
26012
  const versions = fs14.readdirSync(scriptsDir).filter((d) => {
25736
26013
  try {
25737
- return fs14.statSync(path24.join(scriptsDir, d)).isDirectory();
26014
+ return fs14.statSync(path25.join(scriptsDir, d)).isDirectory();
25738
26015
  } catch {
25739
26016
  return false;
25740
26017
  }
25741
26018
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
25742
26019
  if (versions.length === 0) return null;
25743
- return path24.join(scriptsDir, versions[0]);
26020
+ return path25.join(scriptsDir, versions[0]);
25744
26021
  }
25745
26022
  function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
25746
- const canonicalUserDir = path24.resolve(ctx.providerLoader.getUserProviderDir(category, type));
25747
- const desiredDir = requestedDir ? path24.resolve(requestedDir) : canonicalUserDir;
25748
- const upstreamRoot = path24.resolve(ctx.providerLoader.getUpstreamDir());
25749
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path24.sep}`)) {
26023
+ const canonicalUserDir = path25.resolve(ctx.providerLoader.getUserProviderDir(category, type));
26024
+ const desiredDir = requestedDir ? path25.resolve(requestedDir) : canonicalUserDir;
26025
+ const upstreamRoot = path25.resolve(ctx.providerLoader.getUpstreamDir());
26026
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path25.sep}`)) {
25750
26027
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
25751
26028
  }
25752
- if (path24.basename(desiredDir) !== type) {
26029
+ if (path25.basename(desiredDir) !== type) {
25753
26030
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
25754
26031
  }
25755
26032
  const sourceDir = ctx.findProviderDir(type);
@@ -25757,11 +26034,11 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
25757
26034
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
25758
26035
  }
25759
26036
  if (!fs14.existsSync(desiredDir)) {
25760
- fs14.mkdirSync(path24.dirname(desiredDir), { recursive: true });
26037
+ fs14.mkdirSync(path25.dirname(desiredDir), { recursive: true });
25761
26038
  fs14.cpSync(sourceDir, desiredDir, { recursive: true });
25762
26039
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
25763
26040
  }
25764
- const providerJson = path24.join(desiredDir, "provider.json");
26041
+ const providerJson = path25.join(desiredDir, "provider.json");
25765
26042
  if (!fs14.existsSync(providerJson)) {
25766
26043
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
25767
26044
  }
@@ -25772,13 +26049,13 @@ function loadAutoImplReferenceScripts(ctx, referenceType) {
25772
26049
  const refDir = ctx.findProviderDir(referenceType);
25773
26050
  if (!refDir || !fs14.existsSync(refDir)) return {};
25774
26051
  const referenceScripts = {};
25775
- const scriptsDir = path24.join(refDir, "scripts");
26052
+ const scriptsDir = path25.join(refDir, "scripts");
25776
26053
  const latestDir = getLatestScriptVersionDir(scriptsDir);
25777
26054
  if (!latestDir) return referenceScripts;
25778
26055
  for (const file of fs14.readdirSync(latestDir)) {
25779
26056
  if (!file.endsWith(".js")) continue;
25780
26057
  try {
25781
- referenceScripts[file] = fs14.readFileSync(path24.join(latestDir, file), "utf-8");
26058
+ referenceScripts[file] = fs14.readFileSync(path25.join(latestDir, file), "utf-8");
25782
26059
  } catch {
25783
26060
  }
25784
26061
  }
@@ -25886,9 +26163,9 @@ async function handleAutoImplement(ctx, type, req, res) {
25886
26163
  });
25887
26164
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
25888
26165
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
25889
- const tmpDir = path24.join(os20.tmpdir(), "adhdev-autoimpl");
26166
+ const tmpDir = path25.join(os20.tmpdir(), "adhdev-autoimpl");
25890
26167
  if (!fs14.existsSync(tmpDir)) fs14.mkdirSync(tmpDir, { recursive: true });
25891
- const promptFile = path24.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
26168
+ const promptFile = path25.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
25892
26169
  fs14.writeFileSync(promptFile, prompt, "utf-8");
25893
26170
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
25894
26171
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
@@ -26320,7 +26597,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
26320
26597
  setMode: "set_mode.js"
26321
26598
  };
26322
26599
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
26323
- const scriptsDir = path24.join(providerDir, "scripts");
26600
+ const scriptsDir = path25.join(providerDir, "scripts");
26324
26601
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
26325
26602
  if (latestScriptsDir) {
26326
26603
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -26331,7 +26608,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
26331
26608
  for (const file of fs14.readdirSync(latestScriptsDir)) {
26332
26609
  if (file.endsWith(".js") && targetFileNames.has(file)) {
26333
26610
  try {
26334
- const content = fs14.readFileSync(path24.join(latestScriptsDir, file), "utf-8");
26611
+ const content = fs14.readFileSync(path25.join(latestScriptsDir, file), "utf-8");
26335
26612
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
26336
26613
  lines.push("```javascript");
26337
26614
  lines.push(content);
@@ -26348,7 +26625,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
26348
26625
  lines.push("");
26349
26626
  for (const file of refFiles) {
26350
26627
  try {
26351
- const content = fs14.readFileSync(path24.join(latestScriptsDir, file), "utf-8");
26628
+ const content = fs14.readFileSync(path25.join(latestScriptsDir, file), "utf-8");
26352
26629
  lines.push(`### \`${file}\` \u{1F512}`);
26353
26630
  lines.push("```javascript");
26354
26631
  lines.push(content);
@@ -26389,10 +26666,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
26389
26666
  lines.push("");
26390
26667
  }
26391
26668
  }
26392
- const docsDir = path24.join(providerDir, "../../docs");
26669
+ const docsDir = path25.join(providerDir, "../../docs");
26393
26670
  const loadGuide = (name) => {
26394
26671
  try {
26395
- const p = path24.join(docsDir, name);
26672
+ const p = path25.join(docsDir, name);
26396
26673
  if (fs14.existsSync(p)) return fs14.readFileSync(p, "utf-8");
26397
26674
  } catch {
26398
26675
  }
@@ -26629,7 +26906,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
26629
26906
  parseApproval: "parse_approval.js"
26630
26907
  };
26631
26908
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
26632
- const scriptsDir = path24.join(providerDir, "scripts");
26909
+ const scriptsDir = path25.join(providerDir, "scripts");
26633
26910
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
26634
26911
  if (latestScriptsDir) {
26635
26912
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -26641,7 +26918,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
26641
26918
  if (!file.endsWith(".js")) continue;
26642
26919
  if (!targetFileNames.has(file)) continue;
26643
26920
  try {
26644
- const content = fs14.readFileSync(path24.join(latestScriptsDir, file), "utf-8");
26921
+ const content = fs14.readFileSync(path25.join(latestScriptsDir, file), "utf-8");
26645
26922
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
26646
26923
  lines.push("```javascript");
26647
26924
  lines.push(content);
@@ -26657,7 +26934,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
26657
26934
  lines.push("");
26658
26935
  for (const file of refFiles) {
26659
26936
  try {
26660
- const content = fs14.readFileSync(path24.join(latestScriptsDir, file), "utf-8");
26937
+ const content = fs14.readFileSync(path25.join(latestScriptsDir, file), "utf-8");
26661
26938
  lines.push(`### \`${file}\` \u{1F512}`);
26662
26939
  lines.push("```javascript");
26663
26940
  lines.push(content);
@@ -26690,10 +26967,10 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
26690
26967
  lines.push("");
26691
26968
  }
26692
26969
  }
26693
- const docsDir = path24.join(providerDir, "../../docs");
26970
+ const docsDir = path25.join(providerDir, "../../docs");
26694
26971
  const loadGuide = (name) => {
26695
26972
  try {
26696
- const p = path24.join(docsDir, name);
26973
+ const p = path25.join(docsDir, name);
26697
26974
  if (fs14.existsSync(p)) return fs14.readFileSync(p, "utf-8");
26698
26975
  } catch {
26699
26976
  }
@@ -27140,8 +27417,8 @@ var DevServer = class _DevServer {
27140
27417
  }
27141
27418
  getEndpointList() {
27142
27419
  return this.routes.map((r) => {
27143
- const path26 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
27144
- return `${r.method.padEnd(5)} ${path26}`;
27420
+ const path27 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
27421
+ return `${r.method.padEnd(5)} ${path27}`;
27145
27422
  });
27146
27423
  }
27147
27424
  async start(port = DEV_SERVER_PORT) {
@@ -27429,12 +27706,12 @@ var DevServer = class _DevServer {
27429
27706
  // ─── DevConsole SPA ───
27430
27707
  getConsoleDistDir() {
27431
27708
  const candidates = [
27432
- path25.resolve(__dirname, "../../web-devconsole/dist"),
27433
- path25.resolve(__dirname, "../../../web-devconsole/dist"),
27434
- path25.join(process.cwd(), "packages/web-devconsole/dist")
27709
+ path26.resolve(__dirname, "../../web-devconsole/dist"),
27710
+ path26.resolve(__dirname, "../../../web-devconsole/dist"),
27711
+ path26.join(process.cwd(), "packages/web-devconsole/dist")
27435
27712
  ];
27436
27713
  for (const dir of candidates) {
27437
- if (fs15.existsSync(path25.join(dir, "index.html"))) return dir;
27714
+ if (fs15.existsSync(path26.join(dir, "index.html"))) return dir;
27438
27715
  }
27439
27716
  return null;
27440
27717
  }
@@ -27444,7 +27721,7 @@ var DevServer = class _DevServer {
27444
27721
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
27445
27722
  return;
27446
27723
  }
27447
- const htmlPath = path25.join(distDir, "index.html");
27724
+ const htmlPath = path26.join(distDir, "index.html");
27448
27725
  try {
27449
27726
  const html = fs15.readFileSync(htmlPath, "utf-8");
27450
27727
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
@@ -27469,15 +27746,15 @@ var DevServer = class _DevServer {
27469
27746
  this.json(res, 404, { error: "Not found" });
27470
27747
  return;
27471
27748
  }
27472
- const safePath = path25.normalize(pathname).replace(/^\.\.\//, "");
27473
- const filePath = path25.join(distDir, safePath);
27749
+ const safePath = path26.normalize(pathname).replace(/^\.\.\//, "");
27750
+ const filePath = path26.join(distDir, safePath);
27474
27751
  if (!filePath.startsWith(distDir)) {
27475
27752
  this.json(res, 403, { error: "Forbidden" });
27476
27753
  return;
27477
27754
  }
27478
27755
  try {
27479
27756
  const content = fs15.readFileSync(filePath);
27480
- const ext = path25.extname(filePath);
27757
+ const ext = path26.extname(filePath);
27481
27758
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
27482
27759
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
27483
27760
  res.end(content);
@@ -27590,9 +27867,9 @@ var DevServer = class _DevServer {
27590
27867
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
27591
27868
  if (entry.isDirectory()) {
27592
27869
  files.push({ path: rel, size: 0, type: "dir" });
27593
- scan(path25.join(d, entry.name), rel);
27870
+ scan(path26.join(d, entry.name), rel);
27594
27871
  } else {
27595
- const stat2 = fs15.statSync(path25.join(d, entry.name));
27872
+ const stat2 = fs15.statSync(path26.join(d, entry.name));
27596
27873
  files.push({ path: rel, size: stat2.size, type: "file" });
27597
27874
  }
27598
27875
  }
@@ -27615,7 +27892,7 @@ var DevServer = class _DevServer {
27615
27892
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
27616
27893
  return;
27617
27894
  }
27618
- const fullPath = path25.resolve(dir, path25.normalize(filePath));
27895
+ const fullPath = path26.resolve(dir, path26.normalize(filePath));
27619
27896
  if (!fullPath.startsWith(dir)) {
27620
27897
  this.json(res, 403, { error: "Forbidden" });
27621
27898
  return;
@@ -27640,14 +27917,14 @@ var DevServer = class _DevServer {
27640
27917
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
27641
27918
  return;
27642
27919
  }
27643
- const fullPath = path25.resolve(dir, path25.normalize(filePath));
27920
+ const fullPath = path26.resolve(dir, path26.normalize(filePath));
27644
27921
  if (!fullPath.startsWith(dir)) {
27645
27922
  this.json(res, 403, { error: "Forbidden" });
27646
27923
  return;
27647
27924
  }
27648
27925
  try {
27649
27926
  if (fs15.existsSync(fullPath)) fs15.copyFileSync(fullPath, fullPath + ".bak");
27650
- fs15.mkdirSync(path25.dirname(fullPath), { recursive: true });
27927
+ fs15.mkdirSync(path26.dirname(fullPath), { recursive: true });
27651
27928
  fs15.writeFileSync(fullPath, content, "utf-8");
27652
27929
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
27653
27930
  this.providerLoader.reload();
@@ -27664,7 +27941,7 @@ var DevServer = class _DevServer {
27664
27941
  return;
27665
27942
  }
27666
27943
  for (const name of ["scripts.js", "provider.json"]) {
27667
- const p = path25.join(dir, name);
27944
+ const p = path26.join(dir, name);
27668
27945
  if (fs15.existsSync(p)) {
27669
27946
  const source = fs15.readFileSync(p, "utf-8");
27670
27947
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
@@ -27685,8 +27962,8 @@ var DevServer = class _DevServer {
27685
27962
  this.json(res, 404, { error: `Provider not found: ${type}` });
27686
27963
  return;
27687
27964
  }
27688
- const target = fs15.existsSync(path25.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
27689
- const targetPath = path25.join(dir, target);
27965
+ const target = fs15.existsSync(path26.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
27966
+ const targetPath = path26.join(dir, target);
27690
27967
  try {
27691
27968
  if (fs15.existsSync(targetPath)) fs15.copyFileSync(targetPath, targetPath + ".bak");
27692
27969
  fs15.writeFileSync(targetPath, source, "utf-8");
@@ -27833,7 +28110,7 @@ var DevServer = class _DevServer {
27833
28110
  }
27834
28111
  let targetDir;
27835
28112
  targetDir = this.providerLoader.getUserProviderDir(category, type);
27836
- const jsonPath = path25.join(targetDir, "provider.json");
28113
+ const jsonPath = path26.join(targetDir, "provider.json");
27837
28114
  if (fs15.existsSync(jsonPath)) {
27838
28115
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
27839
28116
  return;
@@ -27845,8 +28122,8 @@ var DevServer = class _DevServer {
27845
28122
  const createdFiles = ["provider.json"];
27846
28123
  if (result.files) {
27847
28124
  for (const [relPath, content] of Object.entries(result.files)) {
27848
- const fullPath = path25.join(targetDir, relPath);
27849
- fs15.mkdirSync(path25.dirname(fullPath), { recursive: true });
28125
+ const fullPath = path26.join(targetDir, relPath);
28126
+ fs15.mkdirSync(path26.dirname(fullPath), { recursive: true });
27850
28127
  fs15.writeFileSync(fullPath, content, "utf-8");
27851
28128
  createdFiles.push(relPath);
27852
28129
  }
@@ -27899,22 +28176,22 @@ var DevServer = class _DevServer {
27899
28176
  if (!fs15.existsSync(scriptsDir)) return null;
27900
28177
  const versions = fs15.readdirSync(scriptsDir).filter((d) => {
27901
28178
  try {
27902
- return fs15.statSync(path25.join(scriptsDir, d)).isDirectory();
28179
+ return fs15.statSync(path26.join(scriptsDir, d)).isDirectory();
27903
28180
  } catch {
27904
28181
  return false;
27905
28182
  }
27906
28183
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
27907
28184
  if (versions.length === 0) return null;
27908
- return path25.join(scriptsDir, versions[0]);
28185
+ return path26.join(scriptsDir, versions[0]);
27909
28186
  }
27910
28187
  resolveAutoImplWritableProviderDir(category, type, requestedDir) {
27911
- const canonicalUserDir = path25.resolve(this.providerLoader.getUserProviderDir(category, type));
27912
- const desiredDir = requestedDir ? path25.resolve(requestedDir) : canonicalUserDir;
27913
- const upstreamRoot = path25.resolve(this.providerLoader.getUpstreamDir());
27914
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path25.sep}`)) {
28188
+ const canonicalUserDir = path26.resolve(this.providerLoader.getUserProviderDir(category, type));
28189
+ const desiredDir = requestedDir ? path26.resolve(requestedDir) : canonicalUserDir;
28190
+ const upstreamRoot = path26.resolve(this.providerLoader.getUpstreamDir());
28191
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path26.sep}`)) {
27915
28192
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
27916
28193
  }
27917
- if (path25.basename(desiredDir) !== type) {
28194
+ if (path26.basename(desiredDir) !== type) {
27918
28195
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
27919
28196
  }
27920
28197
  const sourceDir = this.findProviderDir(type);
@@ -27922,11 +28199,11 @@ var DevServer = class _DevServer {
27922
28199
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
27923
28200
  }
27924
28201
  if (!fs15.existsSync(desiredDir)) {
27925
- fs15.mkdirSync(path25.dirname(desiredDir), { recursive: true });
28202
+ fs15.mkdirSync(path26.dirname(desiredDir), { recursive: true });
27926
28203
  fs15.cpSync(sourceDir, desiredDir, { recursive: true });
27927
28204
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
27928
28205
  }
27929
- const providerJson = path25.join(desiredDir, "provider.json");
28206
+ const providerJson = path26.join(desiredDir, "provider.json");
27930
28207
  if (!fs15.existsSync(providerJson)) {
27931
28208
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
27932
28209
  }
@@ -27962,7 +28239,7 @@ var DevServer = class _DevServer {
27962
28239
  setMode: "set_mode.js"
27963
28240
  };
27964
28241
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
27965
- const scriptsDir = path25.join(providerDir, "scripts");
28242
+ const scriptsDir = path26.join(providerDir, "scripts");
27966
28243
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
27967
28244
  if (latestScriptsDir) {
27968
28245
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -27973,7 +28250,7 @@ var DevServer = class _DevServer {
27973
28250
  for (const file of fs15.readdirSync(latestScriptsDir)) {
27974
28251
  if (file.endsWith(".js") && targetFileNames.has(file)) {
27975
28252
  try {
27976
- const content = fs15.readFileSync(path25.join(latestScriptsDir, file), "utf-8");
28253
+ const content = fs15.readFileSync(path26.join(latestScriptsDir, file), "utf-8");
27977
28254
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
27978
28255
  lines.push("```javascript");
27979
28256
  lines.push(content);
@@ -27990,7 +28267,7 @@ var DevServer = class _DevServer {
27990
28267
  lines.push("");
27991
28268
  for (const file of refFiles) {
27992
28269
  try {
27993
- const content = fs15.readFileSync(path25.join(latestScriptsDir, file), "utf-8");
28270
+ const content = fs15.readFileSync(path26.join(latestScriptsDir, file), "utf-8");
27994
28271
  lines.push(`### \`${file}\` \u{1F512}`);
27995
28272
  lines.push("```javascript");
27996
28273
  lines.push(content);
@@ -28031,10 +28308,10 @@ var DevServer = class _DevServer {
28031
28308
  lines.push("");
28032
28309
  }
28033
28310
  }
28034
- const docsDir = path25.join(providerDir, "../../docs");
28311
+ const docsDir = path26.join(providerDir, "../../docs");
28035
28312
  const loadGuide = (name) => {
28036
28313
  try {
28037
- const p = path25.join(docsDir, name);
28314
+ const p = path26.join(docsDir, name);
28038
28315
  if (fs15.existsSync(p)) return fs15.readFileSync(p, "utf-8");
28039
28316
  } catch {
28040
28317
  }
@@ -28208,7 +28485,7 @@ var DevServer = class _DevServer {
28208
28485
  parseApproval: "parse_approval.js"
28209
28486
  };
28210
28487
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
28211
- const scriptsDir = path25.join(providerDir, "scripts");
28488
+ const scriptsDir = path26.join(providerDir, "scripts");
28212
28489
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
28213
28490
  if (latestScriptsDir) {
28214
28491
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -28220,7 +28497,7 @@ var DevServer = class _DevServer {
28220
28497
  if (!file.endsWith(".js")) continue;
28221
28498
  if (!targetFileNames.has(file)) continue;
28222
28499
  try {
28223
- const content = fs15.readFileSync(path25.join(latestScriptsDir, file), "utf-8");
28500
+ const content = fs15.readFileSync(path26.join(latestScriptsDir, file), "utf-8");
28224
28501
  lines.push(`### \`${file}\` \u270F\uFE0F EDIT`);
28225
28502
  lines.push("```javascript");
28226
28503
  lines.push(content);
@@ -28236,7 +28513,7 @@ var DevServer = class _DevServer {
28236
28513
  lines.push("");
28237
28514
  for (const file of refFiles) {
28238
28515
  try {
28239
- const content = fs15.readFileSync(path25.join(latestScriptsDir, file), "utf-8");
28516
+ const content = fs15.readFileSync(path26.join(latestScriptsDir, file), "utf-8");
28240
28517
  lines.push(`### \`${file}\` \u{1F512}`);
28241
28518
  lines.push("```javascript");
28242
28519
  lines.push(content);
@@ -28269,10 +28546,10 @@ var DevServer = class _DevServer {
28269
28546
  lines.push("");
28270
28547
  }
28271
28548
  }
28272
- const docsDir = path25.join(providerDir, "../../docs");
28549
+ const docsDir = path26.join(providerDir, "../../docs");
28273
28550
  const loadGuide = (name) => {
28274
28551
  try {
28275
- const p = path25.join(docsDir, name);
28552
+ const p = path26.join(docsDir, name);
28276
28553
  if (fs15.existsSync(p)) return fs15.readFileSync(p, "utf-8");
28277
28554
  } catch {
28278
28555
  }
@@ -29624,6 +29901,7 @@ export {
29624
29901
  createGitWorkspaceMonitor,
29625
29902
  createInteractionId,
29626
29903
  createMesh,
29904
+ createWorktree,
29627
29905
  deleteMesh,
29628
29906
  detectAllVersions,
29629
29907
  detectCLIs,
@@ -29676,6 +29954,7 @@ export {
29676
29954
  launchWithCdp,
29677
29955
  listHostedCliRuntimes,
29678
29956
  listMeshes,
29957
+ listWorktrees,
29679
29958
  loadConfig,
29680
29959
  loadState,
29681
29960
  logCommand,
@@ -29695,6 +29974,7 @@ export {
29695
29974
  normalizeSessionModalFields,
29696
29975
  parsePorcelainV2Status,
29697
29976
  parseProviderSourceConfigUpdate,
29977
+ parseWorktreeListOutput,
29698
29978
  partitionSessionHostDiagnosticsSessions,
29699
29979
  partitionSessionHostRecords,
29700
29980
  prepareSessionChatTailUpdate,
@@ -29704,6 +29984,7 @@ export {
29704
29984
  recordDebugTrace,
29705
29985
  registerExtensionProviders,
29706
29986
  removeNode,
29987
+ removeWorktree,
29707
29988
  resetConfig,
29708
29989
  resetDebugRuntimeConfig,
29709
29990
  resetState,
@@ -29713,6 +29994,7 @@ export {
29713
29994
  resolveGitRepository,
29714
29995
  resolveSessionHostAppName,
29715
29996
  resolveSessionHostAppNameResolution,
29997
+ resolveWorktreePath,
29716
29998
  runAsyncBatch,
29717
29999
  runGit,
29718
30000
  saveConfig,