adhdev 0.5.7 → 0.5.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.
@@ -16558,10 +16558,10 @@ var require_dist = __commonJS({
16558
16558
  addCliHistory: () => addCliHistory,
16559
16559
  generateConnectionToken: () => generateConnectionToken,
16560
16560
  getConfigDir: () => getConfigDir,
16561
- isSetupComplete: () => isSetupComplete3,
16562
- loadConfig: () => loadConfig4,
16561
+ isSetupComplete: () => isSetupComplete2,
16562
+ loadConfig: () => loadConfig3,
16563
16563
  markSetupComplete: () => markSetupComplete2,
16564
- resetConfig: () => resetConfig2,
16564
+ resetConfig: () => resetConfig,
16565
16565
  saveConfig: () => saveConfig2,
16566
16566
  updateConfig: () => updateConfig2
16567
16567
  });
@@ -16575,7 +16575,7 @@ var require_dist = __commonJS({
16575
16575
  function getConfigPath() {
16576
16576
  return (0, import_path2.join)(getConfigDir(), "config.json");
16577
16577
  }
16578
- function loadConfig4() {
16578
+ function loadConfig3() {
16579
16579
  const configPath = getConfigPath();
16580
16580
  if (!(0, import_fs2.existsSync)(configPath)) {
16581
16581
  return { ...DEFAULT_CONFIG };
@@ -16614,7 +16614,7 @@ var require_dist = __commonJS({
16614
16614
  }
16615
16615
  }
16616
16616
  function updateConfig2(updates) {
16617
- const config2 = loadConfig4();
16617
+ const config2 = loadConfig3();
16618
16618
  const updated = { ...config2, ...updates };
16619
16619
  saveConfig2(updated);
16620
16620
  return updated;
@@ -16629,11 +16629,11 @@ var require_dist = __commonJS({
16629
16629
  setupDate: (/* @__PURE__ */ new Date()).toISOString()
16630
16630
  });
16631
16631
  }
16632
- function isSetupComplete3() {
16633
- const config2 = loadConfig4();
16632
+ function isSetupComplete2() {
16633
+ const config2 = loadConfig3();
16634
16634
  return config2.setupCompleted;
16635
16635
  }
16636
- function resetConfig2() {
16636
+ function resetConfig() {
16637
16637
  saveConfig2({ ...DEFAULT_CONFIG });
16638
16638
  }
16639
16639
  function generateConnectionToken() {
@@ -16645,7 +16645,7 @@ var require_dist = __commonJS({
16645
16645
  return token;
16646
16646
  }
16647
16647
  function addCliHistory(entry) {
16648
- const config2 = loadConfig4();
16648
+ const config2 = loadConfig3();
16649
16649
  const history = config2.cliHistory || [];
16650
16650
  const argsKey = (entry.cliArgs || []).join(" ");
16651
16651
  const filtered = history.filter((h) => {
@@ -16723,10 +16723,10 @@ var require_dist = __commonJS({
16723
16723
  addCliHistory: () => addCliHistory,
16724
16724
  connectCdpManager: () => connectCdpManager,
16725
16725
  detectAllVersions: () => detectAllVersions2,
16726
- detectCLIs: () => detectCLIs2,
16727
- detectIDEs: () => detectIDEs3,
16726
+ detectCLIs: () => detectCLIs,
16727
+ detectIDEs: () => detectIDEs2,
16728
16728
  getAIExtensions: () => getAIExtensions2,
16729
- getAvailableIdeIds: () => getAvailableIdeIds2,
16729
+ getAvailableIdeIds: () => getAvailableIdeIds,
16730
16730
  getHostMemorySnapshot: () => getHostMemorySnapshot,
16731
16731
  getLogLevel: () => getLogLevel,
16732
16732
  getRecentCommands: () => getRecentCommands,
@@ -16737,16 +16737,16 @@ var require_dist = __commonJS({
16737
16737
  installExtensions: () => installExtensions2,
16738
16738
  installGlobalInterceptor: () => installGlobalInterceptor,
16739
16739
  isExtensionInstalled: () => isExtensionInstalled,
16740
- isSetupComplete: () => isSetupComplete3,
16740
+ isSetupComplete: () => isSetupComplete2,
16741
16741
  launchIDE: () => launchIDE2,
16742
- launchWithCdp: () => launchWithCdp2,
16743
- loadConfig: () => loadConfig4,
16742
+ launchWithCdp: () => launchWithCdp,
16743
+ loadConfig: () => loadConfig3,
16744
16744
  logCommand: () => logCommand2,
16745
16745
  markSetupComplete: () => markSetupComplete2,
16746
16746
  probeCdpPort: () => probeCdpPort,
16747
16747
  readChatHistory: () => readChatHistory2,
16748
16748
  registerExtensionProviders: () => registerExtensionProviders,
16749
- resetConfig: () => resetConfig2,
16749
+ resetConfig: () => resetConfig,
16750
16750
  saveConfig: () => saveConfig2,
16751
16751
  setLogLevel: () => setLogLevel2,
16752
16752
  setupIdeInstance: () => setupIdeInstance,
@@ -16850,7 +16850,7 @@ var require_dist = __commonJS({
16850
16850
  }
16851
16851
  return null;
16852
16852
  }
16853
- async function detectIDEs3() {
16853
+ async function detectIDEs2() {
16854
16854
  const os15 = (0, import_os2.platform)();
16855
16855
  const results = [];
16856
16856
  for (const def of getMergedDefinitions()) {
@@ -16908,7 +16908,7 @@ var require_dist = __commonJS({
16908
16908
  child.on("error", () => resolve7(null));
16909
16909
  });
16910
16910
  }
16911
- async function detectCLIs2(providerLoader) {
16911
+ async function detectCLIs(providerLoader) {
16912
16912
  const platform8 = os22.platform();
16913
16913
  const whichCmd = platform8 === "win32" ? "where" : "which";
16914
16914
  const cliList = providerLoader ? providerLoader.getCliDetectionList() : [];
@@ -16937,7 +16937,7 @@ var require_dist = __commonJS({
16937
16937
  }
16938
16938
  async function detectCLI(cliId, providerLoader) {
16939
16939
  const resolvedId = providerLoader ? providerLoader.resolveAlias(cliId) : cliId;
16940
- const all = await detectCLIs2(providerLoader);
16940
+ const all = await detectCLIs(providerLoader);
16941
16941
  return all.find((c) => c.id === resolvedId && c.installed) || null;
16942
16942
  }
16943
16943
  var os32 = __toESM2(require("os"));
@@ -18406,9 +18406,9 @@ var require_dist = __commonJS({
18406
18406
  // meta
18407
18407
  instanceId;
18408
18408
  ideType = "";
18409
- constructor(provider2) {
18410
- this.type = provider2.type;
18411
- this.provider = provider2;
18409
+ constructor(provider) {
18410
+ this.type = provider.type;
18411
+ this.provider = provider;
18412
18412
  this.instanceId = crypto.randomUUID();
18413
18413
  this.monitor = new StatusMonitor();
18414
18414
  }
@@ -18655,13 +18655,12 @@ var require_dist = __commonJS({
18655
18655
  // IDE meta
18656
18656
  ideVersion = "";
18657
18657
  instanceId;
18658
- workspaceFolders = [];
18659
- activeFile = null;
18658
+ workspace = "";
18660
18659
  // ─── Child Extension Instances ────────────────────
18661
18660
  extensions = /* @__PURE__ */ new Map();
18662
- constructor(provider2, instanceKey) {
18663
- this.type = provider2.type;
18664
- this.provider = provider2;
18661
+ constructor(provider, instanceKey) {
18662
+ this.type = provider.type;
18663
+ this.provider = provider;
18665
18664
  this.instanceId = crypto22.randomUUID();
18666
18665
  this.monitor = new StatusMonitor();
18667
18666
  this.historyWriter = new ChatHistoryWriter();
@@ -18699,7 +18698,7 @@ var require_dist = __commonJS({
18699
18698
  }
18700
18699
  }
18701
18700
  getState() {
18702
- const cdp2 = this.context?.cdp;
18701
+ const cdp = this.context?.cdp;
18703
18702
  const extensionStates = [];
18704
18703
  for (const ext of this.extensions.values()) {
18705
18704
  extensionStates.push(ext.getState());
@@ -18717,10 +18716,9 @@ var require_dist = __commonJS({
18717
18716
  activeModal: this.cachedChat.activeModal || null,
18718
18717
  inputContent: this.cachedChat.inputContent || ""
18719
18718
  } : null,
18720
- workspaceFolders: this.workspaceFolders,
18721
- activeFile: this.activeFile,
18719
+ workspace: this.workspace || null,
18722
18720
  extensions: extensionStates,
18723
- cdpConnected: cdp2?.isConnected || false,
18721
+ cdpConnected: cdp?.isConnected || false,
18724
18722
  currentModel: this.cachedChat?.model || void 0,
18725
18723
  currentPlan: this.cachedChat?.mode || void 0,
18726
18724
  currentAutoApprove: this.cachedChat?.autoApprove || void 0,
@@ -18735,11 +18733,6 @@ var require_dist = __commonJS({
18735
18733
  } else if (event === "cdp_disconnected") {
18736
18734
  this.cachedChat = null;
18737
18735
  this.currentStatus = "idle";
18738
- } else if (event === "extension_data") {
18739
- if (data?.workspaceFolders) this.workspaceFolders = data.workspaceFolders;
18740
- if (data?.activeFile) this.activeFile = data.activeFile;
18741
- if (data?.ideVersion) this.ideVersion = data.ideVersion;
18742
- if (data?.instanceId) this.instanceId = data.instanceId;
18743
18736
  } else if (event === "stream_update") {
18744
18737
  const extType = data?.extensionType;
18745
18738
  if (extType && this.extensions.has(extType)) {
@@ -18759,17 +18752,17 @@ var require_dist = __commonJS({
18759
18752
  }
18760
18753
  // ─── Extension manage ─────────────────────────────
18761
18754
  /** Extension Instance add */
18762
- async addExtension(provider2, settings) {
18763
- if (this.extensions.has(provider2.type)) return;
18764
- const ext = new ExtensionProviderInstance(provider2);
18755
+ async addExtension(provider, settings) {
18756
+ if (this.extensions.has(provider.type)) return;
18757
+ const ext = new ExtensionProviderInstance(provider);
18765
18758
  await ext.init({
18766
18759
  cdp: this.context?.cdp,
18767
18760
  serverConn: this.context?.serverConn,
18768
18761
  settings: settings || {}
18769
18762
  });
18770
18763
  ext.onEvent("extension_connected", { ideType: this.type });
18771
- this.extensions.set(provider2.type, ext);
18772
- LOG5.info("IdeInstance", `[IdeInstance:${this.type}] Extension added: ${provider2.type}`);
18764
+ this.extensions.set(provider.type, ext);
18765
+ LOG5.info("IdeInstance", `[IdeInstance:${this.type}] Extension added: ${provider.type}`);
18773
18766
  }
18774
18767
  /** Extension Instance remove */
18775
18768
  removeExtension(type) {
@@ -18795,19 +18788,23 @@ var require_dist = __commonJS({
18795
18788
  getExtensionInstances() {
18796
18789
  return [...this.extensions.values()];
18797
18790
  }
18791
+ /** Set workspace from daemon launch context */
18792
+ setWorkspace(workspace) {
18793
+ this.workspace = workspace;
18794
+ }
18798
18795
  // ─── CDP readChat ───────────────────────────────
18799
18796
  async readChat() {
18800
- const { cdp: cdp2 } = this.context;
18801
- if (!cdp2?.isConnected) return;
18797
+ const { cdp } = this.context;
18798
+ if (!cdp?.isConnected) return;
18802
18799
  try {
18803
18800
  let raw = null;
18804
18801
  const webviewFn = this.provider.scripts?.webviewReadChat;
18805
- if (typeof webviewFn === "function" && cdp2.evaluateInWebviewFrame) {
18802
+ if (typeof webviewFn === "function" && cdp.evaluateInWebviewFrame) {
18806
18803
  const webviewScript = webviewFn();
18807
18804
  if (webviewScript) {
18808
18805
  const matchText = this.provider.webviewMatchText;
18809
18806
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
18810
- const webviewRaw = await cdp2.evaluateInWebviewFrame(webviewScript, matchFn);
18807
+ const webviewRaw = await cdp.evaluateInWebviewFrame(webviewScript, matchFn);
18811
18808
  if (webviewRaw) {
18812
18809
  raw = typeof webviewRaw === "string" ? (() => {
18813
18810
  try {
@@ -18822,7 +18819,7 @@ var require_dist = __commonJS({
18822
18819
  if (!raw) {
18823
18820
  const readChatScript = this.getReadChatScript();
18824
18821
  if (!readChatScript) return;
18825
- raw = await cdp2.evaluate(readChatScript, 3e4);
18822
+ raw = await cdp.evaluate(readChatScript, 3e4);
18826
18823
  if (typeof raw === "string") {
18827
18824
  try {
18828
18825
  raw = JSON.parse(raw);
@@ -18943,8 +18940,8 @@ var require_dist = __commonJS({
18943
18940
  return events;
18944
18941
  }
18945
18942
  // ─── external access ─────────────────────────────────
18946
- updateCdp(cdp2) {
18947
- if (this.context) this.context.cdp = cdp2;
18943
+ updateCdp(cdp) {
18944
+ if (this.context) this.context.cdp = cdp;
18948
18945
  }
18949
18946
  };
18950
18947
  function registerExtensionProviders(providerLoader, manager, ideType) {
@@ -18984,12 +18981,12 @@ var require_dist = __commonJS({
18984
18981
  return ideInstance;
18985
18982
  }
18986
18983
  async function connectCdpManager(port, ideType, logFn, providerLoader, targetId) {
18987
- const provider2 = providerLoader.getMeta(ideType);
18984
+ const provider = providerLoader.getMeta(ideType);
18988
18985
  const manager = new DaemonCdpManager2(
18989
18986
  port,
18990
18987
  logFn,
18991
18988
  targetId,
18992
- provider2?.targetFilter
18989
+ provider?.targetFilter
18993
18990
  );
18994
18991
  const connected = await manager.connect();
18995
18992
  return connected ? manager : null;
@@ -19192,12 +19189,12 @@ var require_dist = __commonJS({
19192
19189
  const targets = await DaemonCdpManager2.listAllTargets(port);
19193
19190
  if (targets.length === 0) {
19194
19191
  if (!await probeCdpPort(port)) return;
19195
- const provider2 = providerLoader.getMeta(ide);
19192
+ const provider = providerLoader.getMeta(ide);
19196
19193
  const manager = new DaemonCdpManager2(
19197
19194
  port,
19198
19195
  LOG5.forComponent(`CDP:${ide}`).asLogFn(),
19199
19196
  void 0,
19200
- provider2?.targetFilter
19197
+ provider?.targetFilter
19201
19198
  );
19202
19199
  const connected = await manager.connect();
19203
19200
  if (connected) {
@@ -19218,12 +19215,12 @@ var require_dist = __commonJS({
19218
19215
  managerKey = `${ide}_${workspaceName}`;
19219
19216
  }
19220
19217
  if (cdpManagers.has(managerKey)) continue;
19221
- const provider2 = providerLoader.getMeta(ide);
19218
+ const provider = providerLoader.getMeta(ide);
19222
19219
  const manager = new DaemonCdpManager2(
19223
19220
  port,
19224
19221
  LOG5.forComponent(`CDP:${managerKey}`).asLogFn(),
19225
19222
  target.id,
19226
- provider2?.targetFilter
19223
+ provider?.targetFilter
19227
19224
  );
19228
19225
  const connected = await manager.connect();
19229
19226
  if (connected) {
@@ -19283,8 +19280,8 @@ var require_dist = __commonJS({
19283
19280
  async function handleChatHistory(h, args) {
19284
19281
  const { agentType, offset, limit, instanceId } = args;
19285
19282
  try {
19286
- const provider2 = h.getProvider(agentType);
19287
- const agentStr = provider2?.type || agentType || h.currentIdeType || "";
19283
+ const provider = h.getProvider(agentType);
19284
+ const agentStr = provider?.type || agentType || h.currentIdeType || "";
19288
19285
  const result = readChatHistory2(agentStr, offset || 0, limit || 30, instanceId);
19289
19286
  return { success: true, ...result, agent: agentStr };
19290
19287
  } catch (e) {
@@ -19292,20 +19289,20 @@ var require_dist = __commonJS({
19292
19289
  }
19293
19290
  }
19294
19291
  async function handleReadChat(h, args) {
19295
- const provider2 = h.getProvider();
19292
+ const provider = h.getProvider();
19296
19293
  const _log = (msg) => LOG5.debug("Command", `[read_chat] ${msg}`);
19297
- if (provider2?.category === "cli" || provider2?.category === "acp") {
19298
- const adapter = h.getCliAdapter(provider2.type);
19294
+ if (provider?.category === "cli" || provider?.category === "acp") {
19295
+ const adapter = h.getCliAdapter(provider.type);
19299
19296
  if (adapter) {
19300
- _log(`${provider2.category} adapter: ${adapter.cliType}`);
19297
+ _log(`${provider.category} adapter: ${adapter.cliType}`);
19301
19298
  const status = adapter.getStatus?.();
19302
19299
  if (status) {
19303
19300
  return { success: true, messages: status.messages || [], status: status.status, activeModal: status.activeModal };
19304
19301
  }
19305
19302
  }
19306
- return { success: false, error: `${provider2.category} adapter not found` };
19303
+ return { success: false, error: `${provider.category} adapter not found` };
19307
19304
  }
19308
- if (provider2?.category === "extension") {
19305
+ if (provider?.category === "extension") {
19309
19306
  try {
19310
19307
  const evalResult = await h.evaluateProviderScript("readChat", void 0, 5e4);
19311
19308
  if (evalResult?.result) {
@@ -19319,7 +19316,7 @@ var require_dist = __commonJS({
19319
19316
  if (parsed && typeof parsed === "object") {
19320
19317
  _log(`Extension OK: ${parsed.messages?.length || 0} msgs`);
19321
19318
  h.historyWriter.appendNewMessages(
19322
- provider2.type || "unknown_extension",
19319
+ provider.type || "unknown_extension",
19323
19320
  parsed.messages || [],
19324
19321
  parsed.title,
19325
19322
  args?.instanceId
@@ -19331,10 +19328,10 @@ var require_dist = __commonJS({
19331
19328
  _log(`Extension error: ${e.message}`);
19332
19329
  }
19333
19330
  if (h.agentStream) {
19334
- const cdp22 = h.getCdp();
19335
- if (cdp22) {
19336
- const streams = await h.agentStream.collectAgentStreams(cdp22);
19337
- const stream = streams.find((s) => s.agentType === provider2.type);
19331
+ const cdp2 = h.getCdp();
19332
+ if (cdp2) {
19333
+ const streams = await h.agentStream.collectAgentStreams(cdp2);
19334
+ const stream = streams.find((s) => s.agentType === provider.type);
19338
19335
  if (stream) {
19339
19336
  h.historyWriter.appendNewMessages(
19340
19337
  stream.agentType,
@@ -19348,14 +19345,14 @@ var require_dist = __commonJS({
19348
19345
  }
19349
19346
  return { success: true, messages: [], status: "idle" };
19350
19347
  }
19351
- const cdp2 = h.getCdp();
19352
- if (!cdp2?.isConnected) return { success: false, error: "CDP not connected" };
19348
+ const cdp = h.getCdp();
19349
+ if (!cdp?.isConnected) return { success: false, error: "CDP not connected" };
19353
19350
  const webviewScript = h.getProviderScript("webviewReadChat") || h.getProviderScript("webview_read_chat");
19354
19351
  if (webviewScript) {
19355
19352
  try {
19356
- const matchText = provider2?.webviewMatchText;
19353
+ const matchText = provider?.webviewMatchText;
19357
19354
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19358
- const raw = await cdp2.evaluateInWebviewFrame(webviewScript, matchFn);
19355
+ const raw = await cdp.evaluateInWebviewFrame(webviewScript, matchFn);
19359
19356
  if (raw) {
19360
19357
  let parsed = raw;
19361
19358
  if (typeof parsed === "string") {
@@ -19367,7 +19364,7 @@ var require_dist = __commonJS({
19367
19364
  if (parsed && typeof parsed === "object") {
19368
19365
  _log(`Webview OK: ${parsed.messages?.length || 0} msgs`);
19369
19366
  h.historyWriter.appendNewMessages(
19370
- provider2?.type || h.currentIdeType || "unknown_webview",
19367
+ provider?.type || h.currentIdeType || "unknown_webview",
19371
19368
  parsed.messages || [],
19372
19369
  parsed.title,
19373
19370
  args?.instanceId
@@ -19383,7 +19380,7 @@ var require_dist = __commonJS({
19383
19380
  const script = h.getProviderScript("readChat") || h.getProviderScript("read_chat");
19384
19381
  if (script) {
19385
19382
  try {
19386
- const result = await cdp2.evaluate(script, 5e4);
19383
+ const result = await cdp.evaluate(script, 5e4);
19387
19384
  let parsed = result;
19388
19385
  if (typeof parsed === "string") {
19389
19386
  try {
@@ -19394,7 +19391,7 @@ var require_dist = __commonJS({
19394
19391
  if (parsed && typeof parsed === "object" && parsed.messages?.length > 0) {
19395
19392
  _log(`OK: ${parsed.messages?.length} msgs`);
19396
19393
  h.historyWriter.appendNewMessages(
19397
- provider2?.type || h.currentIdeType || "unknown_ide",
19394
+ provider?.type || h.currentIdeType || "unknown_ide",
19398
19395
  parsed.messages || [],
19399
19396
  parsed.title,
19400
19397
  args?.instanceId
@@ -19411,21 +19408,21 @@ var require_dist = __commonJS({
19411
19408
  const text = args?.text || args?.message;
19412
19409
  if (!text) return { success: false, error: "text required" };
19413
19410
  const _log = (msg) => LOG5.debug("Command", `[send_chat] ${msg}`);
19414
- const provider2 = h.getProvider();
19415
- if (provider2?.category === "cli" || provider2?.category === "acp") {
19416
- const adapter = h.getCliAdapter(provider2.type);
19411
+ const provider = h.getProvider();
19412
+ if (provider?.category === "cli" || provider?.category === "acp") {
19413
+ const adapter = h.getCliAdapter(provider.type);
19417
19414
  if (adapter) {
19418
- _log(`${provider2.category} adapter: ${adapter.cliType}`);
19415
+ _log(`${provider.category} adapter: ${adapter.cliType}`);
19419
19416
  try {
19420
19417
  await adapter.sendMessage(text);
19421
- return { success: true, sent: true, method: `${provider2.category}-adapter`, targetAgent: adapter.cliType };
19418
+ return { success: true, sent: true, method: `${provider.category}-adapter`, targetAgent: adapter.cliType };
19422
19419
  } catch (e) {
19423
- return { success: false, error: `${provider2.category} send failed: ${e.message}` };
19420
+ return { success: false, error: `${provider.category} send failed: ${e.message}` };
19424
19421
  }
19425
19422
  }
19426
19423
  }
19427
- if (provider2?.category === "extension") {
19428
- _log(`Extension: ${provider2.type}`);
19424
+ if (provider?.category === "extension") {
19425
+ _log(`Extension: ${provider.type}`);
19429
19426
  try {
19430
19427
  const evalResult = await h.evaluateProviderScript("sendMessage", { MESSAGE: text }, 3e4);
19431
19428
  if (evalResult?.result) {
@@ -19448,13 +19445,13 @@ var require_dist = __commonJS({
19448
19445
  _log(`Extension script error: ${e.message}`);
19449
19446
  }
19450
19447
  if (h.agentStream && h.getCdp()) {
19451
- const ok = await h.agentStream.sendToAgent(h.getCdp(), provider2.type, text, h.currentIdeType);
19448
+ const ok = await h.agentStream.sendToAgent(h.getCdp(), provider.type, text, h.currentIdeType);
19452
19449
  if (ok) {
19453
19450
  _log(`AgentStreamManager sent OK`);
19454
19451
  return { success: true, sent: true, method: "agent-stream" };
19455
19452
  }
19456
19453
  }
19457
- return { success: false, error: `Extension '${provider2.type}' send failed` };
19454
+ return { success: false, error: `Extension '${provider.type}' send failed` };
19458
19455
  }
19459
19456
  const targetCdp = h.getCdp();
19460
19457
  if (!targetCdp?.isConnected) {
@@ -19462,11 +19459,11 @@ var require_dist = __commonJS({
19462
19459
  return { success: false, error: `CDP for ${h.currentIdeType || "unknown"} not connected` };
19463
19460
  }
19464
19461
  _log(`Targeting IDE: ${h.currentIdeType}`);
19465
- if (provider2?.webviewMatchText && provider2?.scripts?.webviewSendMessage) {
19462
+ if (provider?.webviewMatchText && provider?.scripts?.webviewSendMessage) {
19466
19463
  try {
19467
- const webviewScript = provider2.scripts.webviewSendMessage(text);
19464
+ const webviewScript = provider.scripts.webviewSendMessage(text);
19468
19465
  if (webviewScript && targetCdp.evaluateInWebviewFrame) {
19469
- const matchText = provider2.webviewMatchText;
19466
+ const matchText = provider.webviewMatchText;
19470
19467
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19471
19468
  const wvResult = await targetCdp.evaluateInWebviewFrame(webviewScript, matchFn);
19472
19469
  let wvParsed = wvResult;
@@ -19486,11 +19483,11 @@ var require_dist = __commonJS({
19486
19483
  _log(`webviewSendMessage (priority) failed: ${e.message}, falling through`);
19487
19484
  }
19488
19485
  }
19489
- if (provider2?.inputMethod === "cdp-type-and-send" && provider2.inputSelector) {
19486
+ if (provider?.inputMethod === "cdp-type-and-send" && provider.inputSelector) {
19490
19487
  try {
19491
- const sent = await targetCdp.typeAndSend(provider2.inputSelector, text);
19488
+ const sent = await targetCdp.typeAndSend(provider.inputSelector, text);
19492
19489
  if (sent) {
19493
- _log(`typeAndSend(provider.inputSelector=${provider2.inputSelector}) success`);
19490
+ _log(`typeAndSend(provider.inputSelector=${provider.inputSelector}) success`);
19494
19491
  return { success: true, sent: true, method: "typeAndSend-provider" };
19495
19492
  }
19496
19493
  } catch (e) {
@@ -19523,11 +19520,11 @@ var require_dist = __commonJS({
19523
19520
  _log(`typeAndSend(script.selector) failed: ${e.message}`);
19524
19521
  }
19525
19522
  }
19526
- if (parsed?.needsTypeAndSend && provider2?.scripts?.webviewSendMessage) {
19523
+ if (parsed?.needsTypeAndSend && provider?.scripts?.webviewSendMessage) {
19527
19524
  try {
19528
- const webviewScript = provider2.scripts.webviewSendMessage(text);
19525
+ const webviewScript = provider.scripts.webviewSendMessage(text);
19529
19526
  if (webviewScript && targetCdp.evaluateInWebviewFrame) {
19530
- const matchText = provider2.webviewMatchText;
19527
+ const matchText = provider.webviewMatchText;
19531
19528
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19532
19529
  const wvResult = await targetCdp.evaluateInWebviewFrame(webviewScript, matchFn);
19533
19530
  let wvParsed = wvResult;
@@ -19566,10 +19563,10 @@ var require_dist = __commonJS({
19566
19563
  return { success: false, error: "No provider method could send the message" };
19567
19564
  }
19568
19565
  async function handleListChats(h, args) {
19569
- const provider2 = h.getProvider();
19570
- if (provider2?.category === "extension" && h.agentStream && h.getCdp()) {
19566
+ const provider = h.getProvider();
19567
+ if (provider?.category === "extension" && h.agentStream && h.getCdp()) {
19571
19568
  try {
19572
- const chats = await h.agentStream.listAgentChats(h.getCdp(), provider2.type);
19569
+ const chats = await h.agentStream.listAgentChats(h.getCdp(), provider.type);
19573
19570
  LOG5.info("Command", `[list_chats] Extension: ${chats.length} chats`);
19574
19571
  return { success: true, chats };
19575
19572
  } catch (e) {
@@ -19579,7 +19576,7 @@ var require_dist = __commonJS({
19579
19576
  try {
19580
19577
  const webviewScript = h.getProviderScript("webviewListSessions") || h.getProviderScript("webview_list_sessions");
19581
19578
  if (webviewScript) {
19582
- const matchText = provider2?.webviewMatchText;
19579
+ const matchText = provider?.webviewMatchText;
19583
19580
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19584
19581
  const raw = await h.getCdp()?.evaluateInWebviewFrame?.(webviewScript, matchFn);
19585
19582
  let parsed = raw;
@@ -19618,15 +19615,15 @@ var require_dist = __commonJS({
19618
19615
  return { success: false, error: "listSessions script not available for this provider" };
19619
19616
  }
19620
19617
  async function handleNewChat(h, args) {
19621
- const provider2 = h.getProvider();
19622
- if (provider2?.category === "extension" && h.agentStream && h.getCdp()) {
19623
- const ok = await h.agentStream.newAgentSession(h.getCdp(), provider2.type, h.currentIdeType);
19618
+ const provider = h.getProvider();
19619
+ if (provider?.category === "extension" && h.agentStream && h.getCdp()) {
19620
+ const ok = await h.agentStream.newAgentSession(h.getCdp(), provider.type, h.currentIdeType);
19624
19621
  return { success: ok };
19625
19622
  }
19626
19623
  try {
19627
19624
  const webviewScript = h.getProviderScript("webviewNewSession") || h.getProviderScript("webview_new_session");
19628
19625
  if (webviewScript) {
19629
- const matchText = provider2?.webviewMatchText;
19626
+ const matchText = provider?.webviewMatchText;
19630
19627
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19631
19628
  const raw = await h.getCdp()?.evaluateInWebviewFrame?.(webviewScript, matchFn);
19632
19629
  if (raw) return { success: true, result: raw };
@@ -19643,23 +19640,23 @@ var require_dist = __commonJS({
19643
19640
  return { success: false, error: "newSession script not available for this provider" };
19644
19641
  }
19645
19642
  async function handleSwitchChat(h, args) {
19646
- const provider2 = h.getProvider();
19643
+ const provider = h.getProvider();
19647
19644
  const ideType = h.currentIdeType;
19648
19645
  const sessionId = args?.sessionId || args?.id || args?.chatId;
19649
19646
  if (!sessionId) return { success: false, error: "sessionId required" };
19650
19647
  LOG5.info("Command", `[switch_chat] sessionId=${sessionId}, ideType=${ideType}`);
19651
- if (provider2?.category === "extension" && h.agentStream && h.getCdp()) {
19652
- const ok = await h.agentStream.switchAgentSession(h.getCdp(), provider2.type, sessionId);
19648
+ if (provider?.category === "extension" && h.agentStream && h.getCdp()) {
19649
+ const ok = await h.agentStream.switchAgentSession(h.getCdp(), provider.type, sessionId);
19653
19650
  return { success: ok, result: ok ? "switched" : "failed" };
19654
19651
  }
19655
- const cdp2 = h.getCdp(ideType);
19656
- if (!cdp2?.isConnected) return { success: false, error: "CDP not connected" };
19652
+ const cdp = h.getCdp(ideType);
19653
+ if (!cdp?.isConnected) return { success: false, error: "CDP not connected" };
19657
19654
  try {
19658
19655
  const webviewScript = h.getProviderScript("webviewSwitchSession", { SESSION_ID: JSON.stringify(sessionId) });
19659
19656
  if (webviewScript) {
19660
- const matchText = provider2?.webviewMatchText;
19657
+ const matchText = provider?.webviewMatchText;
19661
19658
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19662
- const raw = await cdp2.evaluateInWebviewFrame?.(webviewScript, matchFn);
19659
+ const raw = await cdp.evaluateInWebviewFrame?.(webviewScript, matchFn);
19663
19660
  if (raw) return { success: true, result: raw };
19664
19661
  }
19665
19662
  } catch (e) {
@@ -19668,7 +19665,7 @@ var require_dist = __commonJS({
19668
19665
  const script = h.getProviderScript("switchSession", { SESSION_ID: JSON.stringify(sessionId) }) || h.getProviderScript("switch_session", { SESSION_ID: JSON.stringify(sessionId) });
19669
19666
  if (!script) return { success: false, error: "switch_session script not available" };
19670
19667
  try {
19671
- const raw = await cdp2.evaluate(script, 15e3);
19668
+ const raw = await cdp.evaluate(script, 15e3);
19672
19669
  LOG5.info("Command", `[switch_chat] result: ${raw}`);
19673
19670
  let parsed = null;
19674
19671
  try {
@@ -19679,14 +19676,14 @@ var require_dist = __commonJS({
19679
19676
  const x = Math.round(parsed.clickX);
19680
19677
  const y = Math.round(parsed.clickY);
19681
19678
  LOG5.info("Command", `[switch_chat] CDP click at (${x}, ${y}) for "${parsed.title}"`);
19682
- await cdp2.send("Input.dispatchMouseEvent", {
19679
+ await cdp.send("Input.dispatchMouseEvent", {
19683
19680
  type: "mousePressed",
19684
19681
  x,
19685
19682
  y,
19686
19683
  button: "left",
19687
19684
  clickCount: 1
19688
19685
  });
19689
- await cdp2.send("Input.dispatchMouseEvent", {
19686
+ await cdp.send("Input.dispatchMouseEvent", {
19690
19687
  type: "mouseReleased",
19691
19688
  x,
19692
19689
  y,
@@ -19694,7 +19691,7 @@ var require_dist = __commonJS({
19694
19691
  clickCount: 1
19695
19692
  });
19696
19693
  await new Promise((r) => setTimeout(r, 2e3));
19697
- const wsResult = await cdp2.evaluate(`
19694
+ const wsResult = await cdp.evaluate(`
19698
19695
  (() => {
19699
19696
  const inp = Array.from(document.querySelectorAll('input[type="text"]'))
19700
19697
  .find(i => i.offsetWidth > 0 && (i.placeholder || '').includes('Select where'));
@@ -19710,14 +19707,14 @@ var require_dist = __commonJS({
19710
19707
  if (wsResult) {
19711
19708
  try {
19712
19709
  const ws = JSON.parse(wsResult);
19713
- await cdp2.send("Input.dispatchMouseEvent", {
19710
+ await cdp.send("Input.dispatchMouseEvent", {
19714
19711
  type: "mousePressed",
19715
19712
  x: ws.x,
19716
19713
  y: ws.y,
19717
19714
  button: "left",
19718
19715
  clickCount: 1
19719
19716
  });
19720
- await cdp2.send("Input.dispatchMouseEvent", {
19717
+ await cdp.send("Input.dispatchMouseEvent", {
19721
19718
  type: "mouseReleased",
19722
19719
  x: ws.x,
19723
19720
  y: ws.y,
@@ -19737,10 +19734,10 @@ var require_dist = __commonJS({
19737
19734
  }
19738
19735
  }
19739
19736
  async function handleSetMode(h, args) {
19740
- const provider2 = h.getProvider();
19737
+ const provider = h.getProvider();
19741
19738
  const mode = args?.mode || "agent";
19742
- if (provider2?.category === "acp") {
19743
- const adapter = h.getCliAdapter(provider2.type);
19739
+ if (provider?.category === "acp") {
19740
+ const adapter = h.getCliAdapter(provider.type);
19744
19741
  if (adapter) {
19745
19742
  const acpInstance = adapter._acpInstance;
19746
19743
  if (acpInstance && typeof acpInstance.onEvent === "function") {
@@ -19752,12 +19749,12 @@ var require_dist = __commonJS({
19752
19749
  }
19753
19750
  const webviewScript = h.getProviderScript("webviewSetMode", { MODE: JSON.stringify(mode) });
19754
19751
  if (webviewScript) {
19755
- const cdp2 = h.getCdp();
19756
- if (cdp2?.isConnected) {
19752
+ const cdp = h.getCdp();
19753
+ if (cdp?.isConnected) {
19757
19754
  try {
19758
- const matchText = provider2?.webviewMatchText;
19755
+ const matchText = provider?.webviewMatchText;
19759
19756
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19760
- const raw = await cdp2.evaluateInWebviewFrame?.(webviewScript, matchFn);
19757
+ const raw = await cdp.evaluateInWebviewFrame?.(webviewScript, matchFn);
19761
19758
  let result = raw;
19762
19759
  if (typeof raw === "string") {
19763
19760
  try {
@@ -19792,11 +19789,11 @@ var require_dist = __commonJS({
19792
19789
  return { success: false, error: `setMode '${mode}' not supported by this provider` };
19793
19790
  }
19794
19791
  async function handleChangeModel(h, args) {
19795
- const provider2 = h.getProvider();
19792
+ const provider = h.getProvider();
19796
19793
  const model = args?.model;
19797
- LOG5.info("Command", `[change_model] model=${model} provider=${provider2?.type} category=${provider2?.category} ideType=${h.currentIdeType} providerType=${h.currentProviderType}`);
19798
- if (provider2?.category === "acp") {
19799
- const adapter = h.getCliAdapter(provider2.type);
19794
+ LOG5.info("Command", `[change_model] model=${model} provider=${provider?.type} category=${provider?.category} ideType=${h.currentIdeType} providerType=${h.currentProviderType}`);
19795
+ if (provider?.category === "acp") {
19796
+ const adapter = h.getCliAdapter(provider.type);
19800
19797
  LOG5.info("Command", `[change_model] ACP adapter found: ${!!adapter}, type=${adapter?.cliType}, hasAcpInstance=${!!adapter?._acpInstance}`);
19801
19798
  if (adapter) {
19802
19799
  const acpInstance = adapter._acpInstance;
@@ -19810,12 +19807,12 @@ var require_dist = __commonJS({
19810
19807
  }
19811
19808
  const webviewScript = h.getProviderScript("webviewSetModel", { MODEL: JSON.stringify(model) });
19812
19809
  if (webviewScript) {
19813
- const cdp2 = h.getCdp();
19814
- if (cdp2?.isConnected) {
19810
+ const cdp = h.getCdp();
19811
+ if (cdp?.isConnected) {
19815
19812
  try {
19816
- const matchText = provider2?.webviewMatchText;
19813
+ const matchText = provider?.webviewMatchText;
19817
19814
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19818
- const raw = await cdp2.evaluateInWebviewFrame?.(webviewScript, matchFn);
19815
+ const raw = await cdp.evaluateInWebviewFrame?.(webviewScript, matchFn);
19819
19816
  let result = raw;
19820
19817
  if (typeof raw === "string") {
19821
19818
  try {
@@ -19853,28 +19850,28 @@ var require_dist = __commonJS({
19853
19850
  const configId = args?.configId;
19854
19851
  const value = args?.value;
19855
19852
  if (!configId || !value) return { success: false, error: "configId and value required" };
19856
- const provider2 = h.getProvider();
19857
- if (!provider2 || provider2.category !== "acp") {
19853
+ const provider = h.getProvider();
19854
+ if (!provider || provider.category !== "acp") {
19858
19855
  return { success: false, error: "set_thought_level only for ACP providers" };
19859
19856
  }
19860
- const adapter = h.getCliAdapter(provider2.type);
19857
+ const adapter = h.getCliAdapter(provider.type);
19861
19858
  const acpInstance = adapter?._acpInstance;
19862
19859
  if (!acpInstance) return { success: false, error: "ACP instance not found" };
19863
19860
  try {
19864
19861
  await acpInstance.setConfigOption(configId, value);
19865
- LOG5.info("Command", `[set_thought_level] ${configId}=${value} for ${provider2.type}`);
19862
+ LOG5.info("Command", `[set_thought_level] ${configId}=${value} for ${provider.type}`);
19866
19863
  return { success: true, configId, value };
19867
19864
  } catch (e) {
19868
19865
  return { success: false, error: e?.message };
19869
19866
  }
19870
19867
  }
19871
19868
  async function handleResolveAction(h, args) {
19872
- const provider2 = h.getProvider();
19869
+ const provider = h.getProvider();
19873
19870
  const action = args?.action || "approve";
19874
19871
  const button = args?.button || args?.buttonText || (action === "approve" ? "Accept" : action === "reject" ? "Reject" : "Accept");
19875
- LOG5.info("Command", `[resolveAction] action=${action} button="${button}" provider=${provider2?.type}`);
19876
- if (provider2?.category === "cli") {
19877
- const adapter = h.getCliAdapter(provider2.type);
19872
+ LOG5.info("Command", `[resolveAction] action=${action} button="${button}" provider=${provider?.type}`);
19873
+ if (provider?.category === "cli") {
19874
+ const adapter = h.getCliAdapter(provider.type);
19878
19875
  if (!adapter) return { success: false, error: "CLI adapter not running" };
19879
19876
  const status = adapter.getStatus?.();
19880
19877
  if (status?.status !== "waiting_approval") {
@@ -19906,24 +19903,24 @@ var require_dist = __commonJS({
19906
19903
  LOG5.info("Command", `[resolveAction] CLI PTY \u2192 buttonIndex=${buttonIndex} "${buttons[buttonIndex] ?? "?"}"`);
19907
19904
  return { success: true, buttonIndex, button: buttons[buttonIndex] ?? button };
19908
19905
  }
19909
- if (provider2?.category === "extension" && h.agentStream && h.getCdp()) {
19906
+ if (provider?.category === "extension" && h.agentStream && h.getCdp()) {
19910
19907
  const ok = await h.agentStream.resolveAgentAction(
19911
19908
  h.getCdp(),
19912
- provider2.type,
19909
+ provider.type,
19913
19910
  action,
19914
19911
  h.currentIdeType
19915
19912
  );
19916
19913
  return { success: ok };
19917
19914
  }
19918
- if (provider2?.scripts?.webviewResolveAction || provider2?.scripts?.webview_resolve_action) {
19915
+ if (provider?.scripts?.webviewResolveAction || provider?.scripts?.webview_resolve_action) {
19919
19916
  const script = h.getProviderScript("webviewResolveAction", { action, button, buttonText: button }) || h.getProviderScript("webview_resolve_action", { action, button, buttonText: button });
19920
19917
  if (script) {
19921
- const cdp2 = h.getCdp();
19922
- if (cdp2?.isConnected) {
19918
+ const cdp = h.getCdp();
19919
+ if (cdp?.isConnected) {
19923
19920
  try {
19924
- const matchText = provider2?.webviewMatchText;
19921
+ const matchText = provider?.webviewMatchText;
19925
19922
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
19926
- const raw = await cdp2.evaluateInWebviewFrame?.(script, matchFn);
19923
+ const raw = await cdp.evaluateInWebviewFrame?.(script, matchFn);
19927
19924
  let result = raw;
19928
19925
  if (typeof raw === "string") {
19929
19926
  try {
@@ -19943,13 +19940,13 @@ var require_dist = __commonJS({
19943
19940
  }
19944
19941
  }
19945
19942
  }
19946
- if (provider2?.scripts?.resolveAction) {
19947
- const script = provider2.scripts.resolveAction({ action, button, buttonText: button });
19943
+ if (provider?.scripts?.resolveAction) {
19944
+ const script = provider.scripts.resolveAction({ action, button, buttonText: button });
19948
19945
  if (script) {
19949
- const cdp2 = h.getCdp();
19950
- if (!cdp2?.isConnected) return { success: false, error: "CDP not connected" };
19946
+ const cdp = h.getCdp();
19947
+ if (!cdp?.isConnected) return { success: false, error: "CDP not connected" };
19951
19948
  try {
19952
- const raw = await cdp2.evaluate(script, 3e4);
19949
+ const raw = await cdp.evaluate(script, 3e4);
19953
19950
  let result = raw;
19954
19951
  if (typeof raw === "string") {
19955
19952
  try {
@@ -19965,14 +19962,14 @@ var require_dist = __commonJS({
19965
19962
  if (result?.found && result.x != null && result.y != null) {
19966
19963
  const x = result.x;
19967
19964
  const y = result.y;
19968
- await cdp2.send("Input.dispatchMouseEvent", {
19965
+ await cdp.send("Input.dispatchMouseEvent", {
19969
19966
  type: "mousePressed",
19970
19967
  x,
19971
19968
  y,
19972
19969
  button: "left",
19973
19970
  clickCount: 1
19974
19971
  });
19975
- await cdp2.send("Input.dispatchMouseEvent", {
19972
+ await cdp.send("Input.dispatchMouseEvent", {
19976
19973
  type: "mouseReleased",
19977
19974
  x,
19978
19975
  y,
@@ -20376,25 +20373,25 @@ var require_dist = __commonJS({
20376
20373
  if (!agentType) return { success: false, error: "agentType is required" };
20377
20374
  const loader = h.ctx.providerLoader;
20378
20375
  if (!loader) return { success: false, error: "ProviderLoader not initialized" };
20379
- const provider2 = loader.resolve(agentType);
20380
- if (!provider2) return { success: false, error: `Provider not found: ${agentType}` };
20376
+ const provider = loader.resolve(agentType);
20377
+ if (!provider) return { success: false, error: `Provider not found: ${agentType}` };
20381
20378
  const webviewScriptName = `webview${scriptName.charAt(0).toUpperCase() + scriptName.slice(1)}`;
20382
- const hasWebviewScript = provider2.category === "ide" && !!provider2.scripts?.[webviewScriptName];
20379
+ const hasWebviewScript = provider.category === "ide" && !!provider.scripts?.[webviewScriptName];
20383
20380
  const actualScriptName = hasWebviewScript ? webviewScriptName : scriptName;
20384
- if (!provider2.scripts?.[actualScriptName]) {
20381
+ if (!provider.scripts?.[actualScriptName]) {
20385
20382
  return { success: false, error: `Script '${actualScriptName}' not available for ${agentType}` };
20386
20383
  }
20387
- const scriptFn = provider2.scripts[actualScriptName];
20384
+ const scriptFn = provider.scripts[actualScriptName];
20388
20385
  const scriptCode = scriptFn(args);
20389
20386
  if (!scriptCode) return { success: false, error: `Script '${actualScriptName}' returned null` };
20390
- const cdpKey = provider2.category === "ide" ? h.currentIdeType || agentType : h.currentIdeType || ideType;
20391
- LOG5.info("Command", `[ExtScript] provider=${provider2.type} category=${provider2.category} cdpKey=${cdpKey}`);
20392
- const cdp2 = h.getCdp(cdpKey);
20393
- if (!cdp2?.isConnected) return { success: false, error: `No CDP connection for ${cdpKey || "any"}` };
20387
+ const cdpKey = provider.category === "ide" ? h.currentIdeType || agentType : h.currentIdeType || ideType;
20388
+ LOG5.info("Command", `[ExtScript] provider=${provider.type} category=${provider.category} cdpKey=${cdpKey}`);
20389
+ const cdp = h.getCdp(cdpKey);
20390
+ if (!cdp?.isConnected) return { success: false, error: `No CDP connection for ${cdpKey || "any"}` };
20394
20391
  try {
20395
20392
  let result;
20396
- if (provider2.category === "extension") {
20397
- const sessions = cdp2.getAgentSessions();
20393
+ if (provider.category === "extension") {
20394
+ const sessions = cdp.getAgentSessions();
20398
20395
  let targetSessionId = null;
20399
20396
  for (const [sessionId, target] of sessions) {
20400
20397
  if (target.agentType === agentType) {
@@ -20405,13 +20402,13 @@ var require_dist = __commonJS({
20405
20402
  if (!targetSessionId) {
20406
20403
  return { success: false, error: `No active session found for ${agentType}` };
20407
20404
  }
20408
- result = await cdp2.evaluateInSession(targetSessionId, scriptCode);
20409
- } else if (hasWebviewScript && cdp2.evaluateInWebviewFrame) {
20410
- const matchText = provider2.webviewMatchText;
20405
+ result = await cdp.evaluateInSession(targetSessionId, scriptCode);
20406
+ } else if (hasWebviewScript && cdp.evaluateInWebviewFrame) {
20407
+ const matchText = provider.webviewMatchText;
20411
20408
  const matchFn = matchText ? (body) => body.includes(matchText) : void 0;
20412
- result = await cdp2.evaluateInWebviewFrame(scriptCode, matchFn);
20409
+ result = await cdp.evaluateInWebviewFrame(scriptCode, matchFn);
20413
20410
  } else {
20414
- result = await cdp2.evaluate(scriptCode, 3e4);
20411
+ result = await cdp.evaluate(scriptCode, 3e4);
20415
20412
  }
20416
20413
  if (typeof result === "string") {
20417
20414
  try {
@@ -20431,7 +20428,7 @@ var require_dist = __commonJS({
20431
20428
  const loader = h.ctx.providerLoader;
20432
20429
  if (!loader) return { success: false, error: "ProviderLoader not initialized" };
20433
20430
  const allExtProviders = loader.getByCategory?.("extension") || [];
20434
- const config2 = loadConfig4();
20431
+ const config2 = loadConfig3();
20435
20432
  if (ideType) {
20436
20433
  const extensions = allExtProviders.map((p) => ({
20437
20434
  type: p.type,
@@ -20471,7 +20468,7 @@ var require_dist = __commonJS({
20471
20468
  init_config();
20472
20469
  init_workspaces();
20473
20470
  function handleWorkspaceList() {
20474
- const config2 = loadConfig4();
20471
+ const config2 = loadConfig3();
20475
20472
  const state = getWorkspaceState(config2);
20476
20473
  return {
20477
20474
  success: true,
@@ -20486,7 +20483,7 @@ var require_dist = __commonJS({
20486
20483
  const rawPath = (args?.path || args?.dir || "").trim();
20487
20484
  const label = (args?.label || "").trim() || void 0;
20488
20485
  if (!rawPath) return { success: false, error: "path required" };
20489
- const config2 = loadConfig4();
20486
+ const config2 = loadConfig3();
20490
20487
  const result = addWorkspaceEntry(config2, rawPath, label);
20491
20488
  if ("error" in result) return { success: false, error: result.error };
20492
20489
  let cfg = appendWorkspaceActivity(result.config, result.entry.path, {});
@@ -20497,7 +20494,7 @@ var require_dist = __commonJS({
20497
20494
  function handleWorkspaceRemove(args) {
20498
20495
  const id = (args?.id || "").trim();
20499
20496
  if (!id) return { success: false, error: "id required" };
20500
- const config2 = loadConfig4();
20497
+ const config2 = loadConfig3();
20501
20498
  const removed = (config2.workspaces || []).find((w) => w.id === id);
20502
20499
  const result = removeWorkspaceEntry(config2, id);
20503
20500
  if ("error" in result) return { success: false, error: result.error };
@@ -20512,7 +20509,7 @@ var require_dist = __commonJS({
20512
20509
  function handleWorkspaceSetDefault(args) {
20513
20510
  const clear = args?.clear === true || args?.id === null || args?.id === "";
20514
20511
  if (clear) {
20515
- const config22 = loadConfig4();
20512
+ const config22 = loadConfig3();
20516
20513
  const result2 = setDefaultWorkspaceId(config22, null);
20517
20514
  if ("error" in result2) return { success: false, error: result2.error };
20518
20515
  saveConfig2(result2.config);
@@ -20528,7 +20525,7 @@ var require_dist = __commonJS({
20528
20525
  if (!pathArg && !idArg) {
20529
20526
  return { success: false, error: "id or path required (or clear: true)" };
20530
20527
  }
20531
- let config2 = loadConfig4();
20528
+ let config2 = loadConfig3();
20532
20529
  let nextId;
20533
20530
  if (pathArg) {
20534
20531
  let w = findWorkspaceByPath(config2, pathArg);
@@ -20607,9 +20604,9 @@ var require_dist = __commonJS({
20607
20604
  }
20608
20605
  /** Get a provider script by name from ProviderLoader. */
20609
20606
  getProviderScript(scriptName, params, ideType) {
20610
- const provider2 = this.getProvider(ideType);
20611
- if (provider2?.scripts) {
20612
- const fn = provider2.scripts[scriptName];
20607
+ const provider = this.getProvider(ideType);
20608
+ if (provider?.scripts) {
20609
+ const fn = provider.scripts[scriptName];
20613
20610
  if (typeof fn === "function") {
20614
20611
  const firstVal = params ? Object.values(params)[0] : void 0;
20615
20612
  const script = firstVal ? fn(firstVal) : fn();
@@ -20624,24 +20621,24 @@ var require_dist = __commonJS({
20624
20621
  * Extension → cdp.evaluateInSession(sessionId, script) (webview)
20625
20622
  */
20626
20623
  async evaluateProviderScript(scriptName, params, timeout = 3e4) {
20627
- const provider2 = this.getProvider();
20624
+ const provider = this.getProvider();
20628
20625
  const script = this.getProviderScript(scriptName, params);
20629
20626
  if (!script) return null;
20630
- const cdp2 = this.getCdp();
20631
- if (!cdp2?.isConnected) return null;
20632
- if (provider2?.category === "extension") {
20633
- let sessionId = this.getExtensionSessionId(provider2);
20627
+ const cdp = this.getCdp();
20628
+ if (!cdp?.isConnected) return null;
20629
+ if (provider?.category === "extension") {
20630
+ let sessionId = this.getExtensionSessionId(provider);
20634
20631
  if (!sessionId && this._agentStream) {
20635
- await this._agentStream.switchActiveAgent(cdp2, provider2.type);
20636
- await this._agentStream.syncAgentSessions(cdp2);
20637
- sessionId = this.getExtensionSessionId(provider2);
20632
+ await this._agentStream.switchActiveAgent(cdp, provider.type);
20633
+ await this._agentStream.syncAgentSessions(cdp);
20634
+ sessionId = this.getExtensionSessionId(provider);
20638
20635
  }
20639
20636
  if (!sessionId) return null;
20640
- const result2 = await cdp2.evaluateInSession(sessionId, script, timeout);
20637
+ const result2 = await cdp.evaluateInSession(sessionId, script, timeout);
20641
20638
  return { result: result2, category: "extension" };
20642
20639
  }
20643
- const result = await cdp2.evaluate(script, timeout);
20644
- return { result, category: provider2?.category || "ide" };
20640
+ const result = await cdp.evaluate(script, timeout);
20641
+ return { result, category: provider?.category || "ide" };
20645
20642
  }
20646
20643
  /** CLI adapter search */
20647
20644
  getCliAdapter(type) {
@@ -20655,9 +20652,9 @@ var require_dist = __commonJS({
20655
20652
  return null;
20656
20653
  }
20657
20654
  // ─── Private helpers ──────────────────────────────
20658
- getExtensionSessionId(provider2) {
20659
- if (provider2.category !== "extension" || !this._agentStream) return null;
20660
- const managed = this._agentStream.getManagedAgent(provider2.type);
20655
+ getExtensionSessionId(provider) {
20656
+ if (provider.category !== "extension" || !this._agentStream) return null;
20657
+ const managed = this._agentStream.getManagedAgent(provider.type);
20661
20658
  return managed?.sessionId || null;
20662
20659
  }
20663
20660
  /** Extract ideType from _targetInstance */
@@ -20785,7 +20782,7 @@ var require_dist = __commonJS({
20785
20782
  case "get_recent_workspaces":
20786
20783
  return this.handleGetRecentWorkspaces(args);
20787
20784
  case "get_cli_history": {
20788
- const config2 = loadConfig4();
20785
+ const config2 = loadConfig3();
20789
20786
  return { success: true, history: config2.cliHistory || [] };
20790
20787
  }
20791
20788
  case "workspace_list":
@@ -20847,7 +20844,7 @@ var require_dist = __commonJS({
20847
20844
  }
20848
20845
  // ─── Misc (kept in handler — too small to extract) ───────
20849
20846
  async handleGetRecentWorkspaces(_args) {
20850
- const config2 = loadConfig4();
20847
+ const config2 = loadConfig3();
20851
20848
  const cliRecent = config2.recentCliWorkspaces || [];
20852
20849
  const ws = getWorkspaceState(config2);
20853
20850
  return {
@@ -21507,9 +21504,9 @@ var require_dist = __commonJS({
21507
21504
  * Get public settings schema for a provider (for dashboard UI rendering)
21508
21505
  */
21509
21506
  getPublicSettings(type) {
21510
- const provider2 = this.providers.get(type);
21511
- if (!provider2?.settings) return [];
21512
- return Object.entries(provider2.settings).filter(([, def]) => def.public === true).map(([key, def]) => ({ key, ...def }));
21507
+ const provider = this.providers.get(type);
21508
+ if (!provider?.settings) return [];
21509
+ return Object.entries(provider.settings).filter(([, def]) => def.public === true).map(([key, def]) => ({ key, ...def }));
21513
21510
  }
21514
21511
  /**
21515
21512
  * Get public settings schema for all providers
@@ -21526,8 +21523,8 @@ var require_dist = __commonJS({
21526
21523
  * Resolved setting value for a provider (default + user override)
21527
21524
  */
21528
21525
  getSettingValue(type, key) {
21529
- const provider2 = this.providers.get(type);
21530
- const schemaDef = provider2?.settings?.[key];
21526
+ const provider = this.providers.get(type);
21527
+ const schemaDef = provider?.settings?.[key];
21531
21528
  const defaultVal = schemaDef ? schemaDef.default : void 0;
21532
21529
  try {
21533
21530
  const { loadConfig: loadConfig22 } = (init_config(), __toCommonJS2(config_exports));
@@ -21542,10 +21539,10 @@ var require_dist = __commonJS({
21542
21539
  * All resolved settings for a provider (default + user override)
21543
21540
  */
21544
21541
  getSettings(type) {
21545
- const provider2 = this.providers.get(type);
21546
- if (!provider2?.settings) return {};
21542
+ const provider = this.providers.get(type);
21543
+ if (!provider?.settings) return {};
21547
21544
  const result = {};
21548
- for (const [key, def] of Object.entries(provider2.settings)) {
21545
+ for (const [key, def] of Object.entries(provider.settings)) {
21549
21546
  result[key] = this.getSettingValue(type, key);
21550
21547
  }
21551
21548
  return result;
@@ -21554,8 +21551,8 @@ var require_dist = __commonJS({
21554
21551
  * Save provider setting value (writes to config.json)
21555
21552
  */
21556
21553
  setSetting(type, key, value) {
21557
- const provider2 = this.providers.get(type);
21558
- const schemaDef = provider2?.settings?.[key];
21554
+ const provider = this.providers.get(type);
21555
+ const schemaDef = provider?.settings?.[key];
21559
21556
  if (!schemaDef) return false;
21560
21557
  if (!schemaDef.public) return false;
21561
21558
  if (schemaDef.type === "boolean" && typeof value !== "boolean") return false;
@@ -21585,9 +21582,9 @@ var require_dist = __commonJS({
21585
21582
  * Checks builtinDir, upstreamDir, userDir in order.
21586
21583
  */
21587
21584
  findProviderDir(type) {
21588
- const provider2 = this.providers.get(type);
21589
- if (!provider2) return null;
21590
- const cat = provider2.category;
21585
+ const provider = this.providers.get(type);
21586
+ if (!provider) return null;
21587
+ const cat = provider.category;
21591
21588
  const searchRoots = [this.userDir, this.upstreamDir, ...this.builtinDirs];
21592
21589
  for (const root of searchRoots) {
21593
21590
  if (!fs5.existsSync(root)) continue;
@@ -21951,10 +21948,10 @@ var require_dist = __commonJS({
21951
21948
  }
21952
21949
  return void 0;
21953
21950
  }
21954
- async function launchWithCdp2(options = {}) {
21951
+ async function launchWithCdp(options = {}) {
21955
21952
  const platform8 = os8.platform();
21956
21953
  let targetIde;
21957
- const ides = await detectIDEs3();
21954
+ const ides = await detectIDEs2();
21958
21955
  if (options.ideId) {
21959
21956
  targetIde = ides.find((i) => i.id === options.ideId && i.installed);
21960
21957
  if (!targetIde) {
@@ -22093,7 +22090,7 @@ var require_dist = __commonJS({
22093
22090
  if (workspace) args.push(workspace);
22094
22091
  (0, import_child_process4.spawn)(cli, args, { detached: true, stdio: "ignore" }).unref();
22095
22092
  }
22096
- function getAvailableIdeIds2() {
22093
+ function getAvailableIdeIds() {
22097
22094
  return getProviderLoader().getAvailableIdeTypes();
22098
22095
  }
22099
22096
  init_config();
@@ -22348,7 +22345,7 @@ var require_dist = __commonJS({
22348
22345
  workspaceId: args?.workspaceId,
22349
22346
  useDefaultWorkspace: args?.useDefaultWorkspace
22350
22347
  },
22351
- loadConfig4()
22348
+ loadConfig3()
22352
22349
  );
22353
22350
  const launchArgs = {
22354
22351
  ideId: ideKey,
@@ -22356,11 +22353,11 @@ var require_dist = __commonJS({
22356
22353
  newWindow: args?.newWindow
22357
22354
  };
22358
22355
  LOG5.info("LaunchIDE", `target=${ideKey || "auto"}`);
22359
- const result = await launchWithCdp2(launchArgs);
22356
+ const result = await launchWithCdp(launchArgs);
22360
22357
  if (result.success && result.port && result.ideId && !this.deps.cdpManagers.has(result.ideId)) {
22361
22358
  const logFn = this.deps.getCdpLogFn ? this.deps.getCdpLogFn(result.ideId) : LOG5.forComponent(`CDP:${result.ideId}`).asLogFn();
22362
- const provider2 = this.deps.providerLoader.getMeta(result.ideId);
22363
- const manager = new DaemonCdpManager2(result.port, logFn, void 0, provider2?.targetFilter);
22359
+ const provider = this.deps.providerLoader.getMeta(result.ideId);
22360
+ const manager = new DaemonCdpManager2(result.port, logFn, void 0, provider?.targetFilter);
22364
22361
  const connected = await manager.connect();
22365
22362
  if (connected) {
22366
22363
  registerExtensionProviders(this.deps.providerLoader, manager, result.ideId);
@@ -22373,7 +22370,7 @@ var require_dist = __commonJS({
22373
22370
  this.deps.onIdeConnected?.();
22374
22371
  if (result.success && resolvedWorkspace) {
22375
22372
  try {
22376
- saveConfig2(appendWorkspaceActivity(loadConfig4(), resolvedWorkspace, {
22373
+ saveConfig2(appendWorkspaceActivity(loadConfig3(), resolvedWorkspace, {
22377
22374
  kind: "ide",
22378
22375
  agentType: result.ideId
22379
22376
  }));
@@ -22384,7 +22381,7 @@ var require_dist = __commonJS({
22384
22381
  }
22385
22382
  // ─── IDE detection ───
22386
22383
  case "detect_ides": {
22387
- this.deps.detectedIdes.value = await detectIDEs3();
22384
+ this.deps.detectedIdes.value = await detectIDEs2();
22388
22385
  return { success: true, ides: this.deps.detectedIdes.value };
22389
22386
  }
22390
22387
  // ─── Machine Settings ───
@@ -22400,10 +22397,10 @@ var require_dist = __commonJS({
22400
22397
  * IDE stop: CDP disconnect + remove from InstanceManager + clean instanceIdMap
22401
22398
  */
22402
22399
  async stopIde(ideType) {
22403
- const cdp2 = this.deps.cdpManagers.get(ideType);
22404
- if (cdp2) {
22400
+ const cdp = this.deps.cdpManagers.get(ideType);
22401
+ if (cdp) {
22405
22402
  try {
22406
- cdp2.disconnect();
22403
+ cdp.disconnect();
22407
22404
  } catch {
22408
22405
  }
22409
22406
  this.deps.cdpManagers.delete(ideType);
@@ -22516,7 +22513,7 @@ var require_dist = __commonJS({
22516
22513
  const acpStates = allStates.filter((s) => s.category === "acp");
22517
22514
  const ideSummary = ideStates.map((s) => {
22518
22515
  const msgs = s.activeChat?.messages?.length || 0;
22519
- const exts = (s.extensions || []).length;
22516
+ const exts = s.extensions.length;
22520
22517
  return `${s.type}(${s.status},${msgs}msg,${exts}ext${s.currentModel ? ",model=" + s.currentModel : ""})`;
22521
22518
  }).join(", ");
22522
22519
  const cliSummary = cliStates.map((s) => `${s.type}(${s.status})`).join(", ");
@@ -22536,13 +22533,12 @@ var require_dist = __commonJS({
22536
22533
  ideType: s.type,
22537
22534
  ideVersion: "",
22538
22535
  instanceId: s.instanceId,
22539
- workspaceFolders: s.workspaceFolders || [],
22540
- activeFile: s.activeFile || null,
22536
+ workspace: s.workspace || null,
22541
22537
  terminals: 0,
22542
22538
  aiAgents: [],
22543
22539
  activeChat: s.activeChat,
22544
22540
  chats: [],
22545
- agentStreams: (s.extensions || []).map((ext) => ({
22541
+ agentStreams: s.extensions.map((ext) => ({
22546
22542
  agentType: ext.type,
22547
22543
  agentName: ext.name,
22548
22544
  extensionId: ext.type,
@@ -22551,7 +22547,7 @@ var require_dist = __commonJS({
22551
22547
  inputContent: ext.activeChat?.inputContent || "",
22552
22548
  activeModal: ext.activeChat?.activeModal || null
22553
22549
  })),
22554
- cdpConnected: s.cdpConnected || false,
22550
+ cdpConnected: s.cdpConnected,
22555
22551
  currentModel: s.currentModel,
22556
22552
  currentPlan: s.currentPlan,
22557
22553
  currentAutoApprove: s.currentAutoApprove
@@ -22562,8 +22558,8 @@ var require_dist = __commonJS({
22562
22558
  cliType: s.type,
22563
22559
  cliName: s.name,
22564
22560
  status: s.status,
22565
- mode: s.mode || "terminal",
22566
- workingDir: s.workingDir || "",
22561
+ mode: s.mode,
22562
+ workspace: s.workspace || "",
22567
22563
  activeChat: s.activeChat
22568
22564
  }));
22569
22565
  const managedAcps = acpStates.map((s) => ({
@@ -22571,19 +22567,22 @@ var require_dist = __commonJS({
22571
22567
  acpType: s.type,
22572
22568
  acpName: s.name,
22573
22569
  status: s.status,
22574
- mode: "chat",
22575
- workingDir: s.workingDir || "",
22570
+ mode: s.mode,
22571
+ workspace: s.workspace || "",
22576
22572
  activeChat: s.activeChat,
22577
22573
  currentModel: s.currentModel,
22578
22574
  currentPlan: s.currentPlan,
22579
22575
  acpConfigOptions: s.acpConfigOptions,
22580
- acpModes: s.acpModes
22576
+ acpModes: s.acpModes,
22577
+ errorMessage: s.errorMessage,
22578
+ errorReason: s.errorReason
22581
22579
  }));
22582
- const cfg = loadConfig4();
22580
+ const cfg = loadConfig3();
22583
22581
  const wsState = getWorkspaceState(cfg);
22584
22582
  const memSnap = getHostMemorySnapshot();
22585
22583
  const payload = {
22586
22584
  daemonMode: true,
22585
+ version: this.deps.daemonVersion || "unknown",
22587
22586
  machineNickname: cfg.machineNickname || null,
22588
22587
  workspaces: wsState.workspaces,
22589
22588
  defaultWorkspaceId: wsState.defaultWorkspaceId,
@@ -22685,7 +22684,7 @@ var require_dist = __commonJS({
22685
22684
  var os12 = __toESM2(require("os"));
22686
22685
  var path10 = __toESM2(require("path"));
22687
22686
  var crypto4 = __toESM2(require("crypto"));
22688
- var import_chalk4 = __toESM2(require("chalk"));
22687
+ var import_chalk7 = __toESM2(require("chalk"));
22689
22688
  var os11 = __toESM2(require("os"));
22690
22689
  var path9 = __toESM2(require("path"));
22691
22690
  var import_child_process5 = require("child_process");
@@ -22786,12 +22785,14 @@ var require_dist = __commonJS({
22786
22785
  /Type your message/i,
22787
22786
  /^>\s*$/m,
22788
22787
  // '>' alone on its own line
22789
- /[›➤]\s*$/,
22790
- /for shortcuts/i,
22791
- /\?\s*for help/i,
22788
+ /[›❯]\s*[\r\n]/,
22789
+ // prompt char followed by line ending (ANSI-stripped may not have $ at end)
22790
+ /[›❯]\s*$/m,
22791
+ // prompt char at end of line (multiline)
22792
+ /for\s*shortcuts/i,
22793
+ // Claude Code prompt (ANSI strip may remove spaces → 'forshortcuts')
22794
+ /\?\s*for\s*help/i,
22792
22795
  /Press enter/i
22793
- // NOTE: removed /^[\s\u2500-\u257f]*>\s*$/m — the box-drawing char range is too wide and
22794
- // can match dialog-clearing ANSI output, causing false prompt detection in approval state.
22795
22796
  ];
22796
22797
  var FALLBACK_GENERATING = [
22797
22798
  /[\u2800-\u28ff]/,
@@ -22803,13 +22804,18 @@ var require_dist = __commonJS({
22803
22804
  // Specific Claude Code status
22804
22805
  ];
22805
22806
  var FALLBACK_APPROVAL = [
22806
- /Allow\s+once/i,
22807
- /Always\s+allow/i,
22807
+ /Allow\s*once/i,
22808
+ // ANSI strip may remove spaces
22809
+ /Always\s*allow/i,
22808
22810
  /\(y\/n\)/i,
22809
22811
  /\[Y\/n\]/i,
22810
- /Run\s+this\s+command/i
22811
- // NOTE: removed /Do you want to (?:run|execute|allow)/i — too broad, matches AI explanation
22812
- // text like "Do you want to allow this feature?" causing false approval notifications.
22812
+ /Run\s*this\s*command/i,
22813
+ /Allow\s*tool/i,
22814
+ // Claude Code v2 approval
22815
+ /Yes,?\s*don'?t\s*ask/i,
22816
+ // "Yes, don't ask again" (Claude Code)
22817
+ /Deny/i
22818
+ // Deny button presence = approval dialog
22813
22819
  ];
22814
22820
  function defaultCleanOutput(raw, _lastUserInput) {
22815
22821
  return stripAnsi(raw).trim();
@@ -22828,13 +22834,13 @@ var require_dist = __commonJS({
22828
22834
  };
22829
22835
  }
22830
22836
  var ProviderCliAdapter = class {
22831
- constructor(provider2, workingDir, extraArgs = []) {
22837
+ constructor(provider, workingDir, extraArgs = []) {
22832
22838
  this.extraArgs = extraArgs;
22833
- this.provider = normalizeCliProviderForRuntime(provider2);
22834
- this.cliType = provider2.type;
22835
- this.cliName = provider2.name;
22839
+ this.provider = normalizeCliProviderForRuntime(provider);
22840
+ this.cliType = provider.type;
22841
+ this.cliName = provider.name;
22836
22842
  this.workingDir = workingDir.startsWith("~") ? workingDir.replace(/^~/, os11.homedir()) : workingDir;
22837
- const t = provider2.timeouts || {};
22843
+ const t = provider.timeouts || {};
22838
22844
  this.timeouts = {
22839
22845
  ptyFlush: t.ptyFlush ?? 50,
22840
22846
  dialogAccept: t.dialogAccept ?? 300,
@@ -22844,6 +22850,8 @@ var require_dist = __commonJS({
22844
22850
  maxResponse: t.maxResponse ?? 3e5,
22845
22851
  shutdownGrace: t.shutdownGrace ?? 1e3
22846
22852
  };
22853
+ const rawKeys = provider.approvalKeys;
22854
+ this.approvalKeys = rawKeys && typeof rawKeys === "object" ? rawKeys : {};
22847
22855
  }
22848
22856
  cliType;
22849
22857
  cliName;
@@ -22875,8 +22883,20 @@ var require_dist = __commonJS({
22875
22883
  approvalExitTimeout = null;
22876
22884
  // Resize redraw suppression
22877
22885
  resizeSuppressUntil = 0;
22886
+ // Debug: status transition history
22887
+ statusHistory = [];
22888
+ setStatus(status, trigger) {
22889
+ const prev = this.currentStatus;
22890
+ if (prev === status) return;
22891
+ this.currentStatus = status;
22892
+ this.statusHistory.push({ status, at: Date.now(), trigger });
22893
+ if (this.statusHistory.length > 50) this.statusHistory.shift();
22894
+ LOG5.info("CLI", `[${this.cliType}] status: ${prev} \u2192 ${status}${trigger ? ` (${trigger})` : ""}`);
22895
+ }
22878
22896
  // Resolved timeouts (provider defaults + overrides)
22879
22897
  timeouts;
22898
+ // Provider approval key mapping (e.g. { 0: '1', 1: '2', 2: '3' }) — loaded from provider.json
22899
+ approvalKeys;
22880
22900
  // ─── Lifecycle ─────────────────────────────────
22881
22901
  setServerConn(serverConn) {
22882
22902
  this.serverConn = serverConn;
@@ -22956,11 +22976,11 @@ var require_dist = __commonJS({
22956
22976
  this.ptyProcess.onExit(({ exitCode }) => {
22957
22977
  LOG5.info("CLI", `[${this.cliType}] Exit code ${exitCode}`);
22958
22978
  this.ptyProcess = null;
22959
- this.currentStatus = "stopped";
22979
+ this.setStatus("stopped", "pty_exit");
22960
22980
  this.ready = false;
22961
22981
  this.onStatusChange?.();
22962
22982
  });
22963
- this.currentStatus = "starting";
22983
+ this.setStatus("starting", "spawn");
22964
22984
  this.onStatusChange?.();
22965
22985
  }
22966
22986
  // ─── Output state machine ────────────────────────────
@@ -22978,9 +22998,13 @@ var require_dist = __commonJS({
22978
22998
  this.recentOutputBuffer = (this.recentOutputBuffer + cleanData).slice(-1e3);
22979
22999
  if (!this.ready) {
22980
23000
  this.startupBuffer += cleanData;
23001
+ LOG5.info("CLI", `[${this.cliType}] startup chunk (${cleanData.length} chars): ${cleanData.slice(0, 200).replace(/\n/g, "\\n")}`);
22981
23002
  const dialogPatterns = [
22982
23003
  /Do you want to connect/i,
22983
- /Do you trust the files/i
23004
+ /Do you trust the files/i,
23005
+ /Quick safety check/i,
23006
+ /Is this a project/i,
23007
+ /Enter to confirm/i
22984
23008
  ];
22985
23009
  if (dialogPatterns.some((p) => p.test(this.startupBuffer))) {
22986
23010
  setTimeout(() => this.ptyProcess?.write("\r"), this.timeouts.dialogAccept);
@@ -22989,7 +23013,7 @@ var require_dist = __commonJS({
22989
23013
  }
22990
23014
  if (patterns.prompt.some((p) => p.test(this.startupBuffer))) {
22991
23015
  this.ready = true;
22992
- this.currentStatus = "idle";
23016
+ this.setStatus("idle", "prompt_matched");
22993
23017
  LOG5.info("CLI", `[${this.cliType}] \u2713 Ready`);
22994
23018
  this.onStatusChange?.();
22995
23019
  }
@@ -23000,12 +23024,12 @@ var require_dist = __commonJS({
23000
23024
  if (this.lastApprovalResolvedAt && Date.now() - this.lastApprovalResolvedAt < this.timeouts.approvalCooldown) return;
23001
23025
  const ctxLines = this.recentOutputBuffer.split("\n").map((l) => l.trim()).filter((l) => l && !/^[─═╭╮╰╯│]+$/.test(l));
23002
23026
  this.isWaitingForResponse = true;
23003
- this.currentStatus = "waiting_approval";
23027
+ this.setStatus("waiting_approval", "approval_pattern");
23004
23028
  this.recentOutputBuffer = "";
23005
23029
  this.approvalTransitionBuffer = "";
23006
23030
  this.activeModal = {
23007
23031
  message: ctxLines.slice(-5).join(" ").slice(0, 200) || "Approval required",
23008
- buttons: ["Allow once", "Always allow", "Deny"]
23032
+ buttons: this.cliType === "claude-cli" ? ["Yes (y)", "Always allow (a)", "Deny (Esc)"] : ["Allow once", "Always allow", "Deny"]
23009
23033
  };
23010
23034
  if (this.idleTimeout) clearTimeout(this.idleTimeout);
23011
23035
  if (this.approvalExitTimeout) clearTimeout(this.approvalExitTimeout);
@@ -23017,7 +23041,7 @@ var require_dist = __commonJS({
23017
23041
  this.recentOutputBuffer = "";
23018
23042
  this.approvalTransitionBuffer = "";
23019
23043
  this.approvalExitTimeout = null;
23020
- this.currentStatus = this.isWaitingForResponse ? "generating" : "idle";
23044
+ this.setStatus(this.isWaitingForResponse ? "generating" : "idle", "approval_cleared");
23021
23045
  this.onStatusChange?.();
23022
23046
  }
23023
23047
  }, 6e4);
@@ -23033,7 +23057,7 @@ var require_dist = __commonJS({
23033
23057
  clearTimeout(this.approvalExitTimeout);
23034
23058
  this.approvalExitTimeout = null;
23035
23059
  }
23036
- this.currentStatus = "generating";
23060
+ this.setStatus("generating", "approval_gen_resume");
23037
23061
  this.activeModal = null;
23038
23062
  this.recentOutputBuffer = "";
23039
23063
  this.approvalTransitionBuffer = "";
@@ -23056,7 +23080,7 @@ var require_dist = __commonJS({
23056
23080
  if (patterns.generating.some((p) => p.test(cleanData))) {
23057
23081
  this.isWaitingForResponse = true;
23058
23082
  this.responseBuffer = "";
23059
- this.currentStatus = "generating";
23083
+ this.setStatus("generating", "autonomous_gen");
23060
23084
  this.onStatusChange?.();
23061
23085
  }
23062
23086
  }
@@ -23065,7 +23089,7 @@ var require_dist = __commonJS({
23065
23089
  if (this.idleTimeout) clearTimeout(this.idleTimeout);
23066
23090
  const stillGenerating = patterns.generating.some((p) => p.test(cleanData));
23067
23091
  if (stillGenerating) {
23068
- this.currentStatus = "generating";
23092
+ this.setStatus("generating", "still_generating");
23069
23093
  this.idleTimeout = setTimeout(() => {
23070
23094
  if (this.isWaitingForResponse) this.finishResponse();
23071
23095
  }, this.timeouts.generatingIdle);
@@ -23112,7 +23136,7 @@ var require_dist = __commonJS({
23112
23136
  this.responseBuffer = "";
23113
23137
  this.isWaitingForResponse = false;
23114
23138
  this.activeModal = null;
23115
- this.currentStatus = "idle";
23139
+ this.setStatus("idle", "response_finished");
23116
23140
  this.onStatusChange?.();
23117
23141
  }
23118
23142
  // ─── Public API (CliAdapter interface) ──────────
@@ -23131,7 +23155,7 @@ var require_dist = __commonJS({
23131
23155
  this.messages.push({ role: "user", content: text, timestamp: Date.now() });
23132
23156
  this.isWaitingForResponse = true;
23133
23157
  this.responseBuffer = "";
23134
- this.currentStatus = "generating";
23158
+ this.setStatus("generating", "sendMessage");
23135
23159
  this.onStatusChange?.();
23136
23160
  this.ptyProcess.write(text + "\r");
23137
23161
  this.responseTimeout = setTimeout(() => {
@@ -23159,7 +23183,7 @@ var require_dist = __commonJS({
23159
23183
  } catch {
23160
23184
  }
23161
23185
  this.ptyProcess = null;
23162
- this.currentStatus = "stopped";
23186
+ this.setStatus("stopped", "stop_cmd");
23163
23187
  this.ready = false;
23164
23188
  this.onStatusChange?.();
23165
23189
  }, this.timeouts.shutdownGrace);
@@ -23185,9 +23209,13 @@ var require_dist = __commonJS({
23185
23209
  */
23186
23210
  resolveModal(buttonIndex) {
23187
23211
  if (!this.ptyProcess || this.currentStatus !== "waiting_approval") return;
23188
- const DOWN = "\x1B[B";
23189
- const keys = DOWN.repeat(Math.max(0, buttonIndex)) + "\r";
23190
- this.ptyProcess.write(keys);
23212
+ if (buttonIndex in this.approvalKeys) {
23213
+ this.ptyProcess.write(this.approvalKeys[buttonIndex]);
23214
+ } else {
23215
+ const DOWN = "\x1B[B";
23216
+ const keys = DOWN.repeat(Math.max(0, buttonIndex)) + "\r";
23217
+ this.ptyProcess.write(keys);
23218
+ }
23191
23219
  }
23192
23220
  resize(cols, rows) {
23193
23221
  if (this.ptyProcess) {
@@ -23198,18 +23226,56 @@ var require_dist = __commonJS({
23198
23226
  }
23199
23227
  }
23200
23228
  }
23229
+ /**
23230
+ * Full debug state — exposes all internal buffers, status, and patterns for debugging.
23231
+ * Used by DevServer /api/cli/debug endpoint.
23232
+ */
23233
+ getDebugState() {
23234
+ return {
23235
+ type: this.cliType,
23236
+ name: this.cliName,
23237
+ status: this.currentStatus,
23238
+ ready: this.ready,
23239
+ workingDir: this.workingDir,
23240
+ messages: this.messages.slice(-20),
23241
+ messageCount: this.messages.length,
23242
+ // Buffers
23243
+ startupBuffer: this.startupBuffer.slice(-500),
23244
+ recentOutputBuffer: this.recentOutputBuffer.slice(-500),
23245
+ responseBuffer: this.responseBuffer.slice(-500),
23246
+ approvalTransitionBuffer: this.approvalTransitionBuffer.slice(-500),
23247
+ // State
23248
+ isWaitingForResponse: this.isWaitingForResponse,
23249
+ activeModal: this.activeModal,
23250
+ lastApprovalResolvedAt: this.lastApprovalResolvedAt,
23251
+ resizeSuppressUntil: this.resizeSuppressUntil,
23252
+ // Provider patterns (serialized)
23253
+ patterns: {
23254
+ prompt: this.provider.patterns.prompt.map((p) => p.toString()),
23255
+ generating: this.provider.patterns.generating.map((p) => p.toString()),
23256
+ approval: this.provider.patterns.approval.map((p) => p.toString()),
23257
+ ready: this.provider.patterns.ready.map((p) => p.toString())
23258
+ },
23259
+ // Status history
23260
+ statusHistory: this.statusHistory.slice(-30),
23261
+ // Timeouts config
23262
+ timeouts: this.timeouts,
23263
+ // PTY alive
23264
+ ptyAlive: !!this.ptyProcess
23265
+ };
23266
+ }
23201
23267
  };
23202
23268
  init_config();
23203
23269
  init_workspaces();
23204
23270
  var crypto3 = __toESM2(require("crypto"));
23205
23271
  var CliProviderInstance = class {
23206
- constructor(provider2, workingDir, cliArgs = [], instanceId) {
23207
- this.provider = provider2;
23272
+ constructor(provider, workingDir, cliArgs = [], instanceId) {
23273
+ this.provider = provider;
23208
23274
  this.workingDir = workingDir;
23209
23275
  this.cliArgs = cliArgs;
23210
- this.type = provider2.type;
23276
+ this.type = provider.type;
23211
23277
  this.instanceId = instanceId || crypto3.randomUUID();
23212
- this.adapter = new ProviderCliAdapter(provider2, workingDir, cliArgs);
23278
+ this.adapter = new ProviderCliAdapter(provider, workingDir, cliArgs);
23213
23279
  this.monitor = new StatusMonitor();
23214
23280
  this.historyWriter = new ChatHistoryWriter();
23215
23281
  }
@@ -23222,6 +23288,8 @@ var require_dist = __commonJS({
23222
23288
  generatingStartedAt = 0;
23223
23289
  settings = {};
23224
23290
  monitor;
23291
+ generatingDebounceTimer = null;
23292
+ generatingDebouncePending = null;
23225
23293
  historyWriter;
23226
23294
  instanceId;
23227
23295
  // ─── Lifecycle ─────────────────────────────────
@@ -23288,7 +23356,7 @@ var require_dist = __commonJS({
23288
23356
  activeModal: adapterStatus.activeModal,
23289
23357
  inputContent: ""
23290
23358
  },
23291
- workingDir: this.workingDir,
23359
+ workspace: this.workingDir,
23292
23360
  instanceId: this.instanceId,
23293
23361
  lastUpdated: Date.now(),
23294
23362
  settings: this.settings,
@@ -23317,8 +23385,24 @@ var require_dist = __commonJS({
23317
23385
  LOG5.info("CLI", `[${this.type}] status: ${this.lastStatus} \u2192 ${newStatus}`);
23318
23386
  if (this.lastStatus === "idle" && newStatus === "generating") {
23319
23387
  this.generatingStartedAt = now;
23320
- this.pushEvent({ event: "agent:generating_started", chatTitle, timestamp: now });
23388
+ if (this.generatingDebounceTimer) clearTimeout(this.generatingDebounceTimer);
23389
+ this.generatingDebouncePending = { chatTitle, timestamp: now };
23390
+ this.generatingDebounceTimer = setTimeout(() => {
23391
+ if (this.generatingDebouncePending) {
23392
+ this.pushEvent({ event: "agent:generating_started", ...this.generatingDebouncePending });
23393
+ this.generatingDebouncePending = null;
23394
+ }
23395
+ this.generatingDebounceTimer = null;
23396
+ }, 1e3);
23321
23397
  } else if (newStatus === "waiting_approval") {
23398
+ if (this.generatingDebouncePending) {
23399
+ if (this.generatingDebounceTimer) {
23400
+ clearTimeout(this.generatingDebounceTimer);
23401
+ this.generatingDebounceTimer = null;
23402
+ }
23403
+ this.pushEvent({ event: "agent:generating_started", ...this.generatingDebouncePending });
23404
+ this.generatingDebouncePending = null;
23405
+ }
23322
23406
  if (!this.generatingStartedAt) this.generatingStartedAt = now;
23323
23407
  const modal = adapterStatus.activeModal;
23324
23408
  LOG5.info("CLI", `[${this.type}] approval modal: "${modal?.message?.slice(0, 80) ?? "none"}"`);
@@ -23331,10 +23415,24 @@ var require_dist = __commonJS({
23331
23415
  });
23332
23416
  } else if (newStatus === "idle" && (this.lastStatus === "generating" || this.lastStatus === "waiting_approval")) {
23333
23417
  const duration3 = this.generatingStartedAt ? Math.round((now - this.generatingStartedAt) / 1e3) : 0;
23334
- LOG5.info("CLI", `[${this.type}] completed in ${duration3}s`);
23335
- this.pushEvent({ event: "agent:generating_completed", chatTitle, duration: duration3, timestamp: now });
23418
+ if (this.generatingDebouncePending) {
23419
+ LOG5.info("CLI", `[${this.type}] suppressed short generating (${now - this.generatingStartedAt}ms)`);
23420
+ if (this.generatingDebounceTimer) {
23421
+ clearTimeout(this.generatingDebounceTimer);
23422
+ this.generatingDebounceTimer = null;
23423
+ }
23424
+ this.generatingDebouncePending = null;
23425
+ } else {
23426
+ LOG5.info("CLI", `[${this.type}] completed in ${duration3}s`);
23427
+ this.pushEvent({ event: "agent:generating_completed", chatTitle, duration: duration3, timestamp: now });
23428
+ }
23336
23429
  this.generatingStartedAt = 0;
23337
23430
  } else if (newStatus === "stopped") {
23431
+ if (this.generatingDebounceTimer) {
23432
+ clearTimeout(this.generatingDebounceTimer);
23433
+ this.generatingDebounceTimer = null;
23434
+ }
23435
+ this.generatingDebouncePending = null;
23338
23436
  this.pushEvent({ event: "agent:stopped", chatTitle, timestamp: now });
23339
23437
  }
23340
23438
  this.lastStatus = newStatus;
@@ -23373,10 +23471,10 @@ var require_dist = __commonJS({
23373
23471
  return content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
23374
23472
  }
23375
23473
  var AcpProviderInstance = class {
23376
- constructor(provider2, workingDir, cliArgs = []) {
23474
+ constructor(provider, workingDir, cliArgs = []) {
23377
23475
  this.cliArgs = cliArgs;
23378
- this.type = provider2.type;
23379
- this.provider = provider2;
23476
+ this.type = provider.type;
23477
+ this.provider = provider;
23380
23478
  this.workingDir = workingDir;
23381
23479
  this.instanceId = crypto.randomUUID();
23382
23480
  this.monitor = new StatusMonitor();
@@ -23479,7 +23577,7 @@ var require_dist = __commonJS({
23479
23577
  } : null,
23480
23578
  inputContent: ""
23481
23579
  },
23482
- workingDir: this.workingDir,
23580
+ workspace: this.workingDir,
23483
23581
  currentModel: this.currentModel,
23484
23582
  currentPlan: this.currentMode,
23485
23583
  instanceId: this.instanceId,
@@ -23490,8 +23588,8 @@ var require_dist = __commonJS({
23490
23588
  acpConfigOptions: this.configOptions,
23491
23589
  acpModes: this.availableModes,
23492
23590
  // Error details for dashboard display
23493
- errorMessage: this.errorMessage,
23494
- errorReason: this.errorReason
23591
+ errorMessage: this.errorMessage || void 0,
23592
+ errorReason: this.errorReason || void 0
23495
23593
  };
23496
23594
  }
23497
23595
  onEvent(event, data) {
@@ -23974,29 +24072,27 @@ var require_dist = __commonJS({
23974
24072
  handleSessionUpdate(params) {
23975
24073
  if (!params) return;
23976
24074
  const update = params.update;
23977
- this.log.debug(`[${this.type}] sessionUpdate: ${update.sessionUpdate} | keys=${Object.keys(update).join(",")}`);
24075
+ this.log.debug(`[${this.type}] sessionUpdate: ${update.sessionUpdate}`);
23978
24076
  switch (update.sessionUpdate) {
23979
24077
  case "agent_message_chunk": {
23980
24078
  const content = update.content;
23981
- if (content?.type === "text" && content.text) {
24079
+ if (content.type === "text") {
23982
24080
  this.partialContent += content.text;
23983
- } else if (content?.type === "image") {
24081
+ } else if (content.type === "image") {
23984
24082
  this.partialBlocks.push({
23985
24083
  type: "image",
23986
- data: content.data || "",
23987
- mimeType: content.mimeType || "image/png",
23988
- uri: content.uri
24084
+ data: content.data,
24085
+ mimeType: content.mimeType
23989
24086
  });
23990
- } else if (content?.type === "resource_link") {
24087
+ } else if (content.type === "resource_link") {
23991
24088
  this.partialBlocks.push({
23992
24089
  type: "resource_link",
23993
- uri: content.uri || "",
24090
+ uri: content.uri,
23994
24091
  name: content.name || "resource",
23995
- title: content.title,
23996
- mimeType: content.mimeType,
23997
- size: content.size
24092
+ title: content.title ?? void 0,
24093
+ mimeType: content.mimeType ?? void 0
23998
24094
  });
23999
- } else if (content?.type === "resource") {
24095
+ } else if (content.type === "resource") {
24000
24096
  this.partialBlocks.push({
24001
24097
  type: "resource",
24002
24098
  resource: content.resource
@@ -24264,27 +24360,27 @@ var require_dist = __commonJS({
24264
24360
  persistRecentDir(cliType, dir) {
24265
24361
  try {
24266
24362
  const normalizedType = this.providerLoader.resolveAlias(cliType);
24267
- const provider2 = this.providerLoader.getByAlias(cliType);
24268
- const actKind = provider2?.category === "acp" ? "acp" : "cli";
24269
- let next = loadConfig4();
24270
- console.log(import_chalk4.default.cyan(` \u{1F4C2} Saving recent workspace: ${dir}`));
24363
+ const provider = this.providerLoader.getByAlias(cliType);
24364
+ const actKind = provider?.category === "acp" ? "acp" : "cli";
24365
+ let next = loadConfig3();
24366
+ console.log(import_chalk7.default.cyan(` \u{1F4C2} Saving recent workspace: ${dir}`));
24271
24367
  const recent = next.recentCliWorkspaces || [];
24272
24368
  if (!recent.includes(dir)) {
24273
24369
  next = { ...next, recentCliWorkspaces: [dir, ...recent].slice(0, 10) };
24274
24370
  }
24275
24371
  next = appendWorkspaceActivity(next, dir, { kind: actKind, agentType: normalizedType });
24276
24372
  saveConfig2(next);
24277
- console.log(import_chalk4.default.green(` \u2713 Recent workspace saved: ${dir}`));
24373
+ console.log(import_chalk7.default.green(` \u2713 Recent workspace saved: ${dir}`));
24278
24374
  } catch (e) {
24279
- console.error(import_chalk4.default.red(` \u2717 Failed to save recent workspace: ${e}`));
24375
+ console.error(import_chalk7.default.red(` \u2717 Failed to save recent workspace: ${e}`));
24280
24376
  }
24281
24377
  }
24282
24378
  createAdapter(cliType, workingDir, cliArgs) {
24283
24379
  const normalizedType = this.providerLoader.resolveAlias(cliType);
24284
- const provider2 = this.providerLoader.getMeta(normalizedType);
24285
- if (provider2 && provider2.category === "cli" && provider2.patterns && provider2.spawn) {
24286
- console.log(import_chalk4.default.cyan(` \u{1F4E6} Using provider: ${provider2.name} (${provider2.type})`));
24287
- return new ProviderCliAdapter(provider2, workingDir, cliArgs);
24380
+ const provider = this.providerLoader.getMeta(normalizedType);
24381
+ if (provider && provider.category === "cli" && provider.patterns && provider.spawn) {
24382
+ console.log(import_chalk7.default.cyan(` \u{1F4E6} Using provider: ${provider.name} (${provider.type})`));
24383
+ return new ProviderCliAdapter(provider, workingDir, cliArgs);
24288
24384
  }
24289
24385
  throw new Error(`No CLI provider found for '${cliType}'. Create a provider.js in providers/cli/${cliType}/`);
24290
24386
  }
@@ -24294,28 +24390,28 @@ var require_dist = __commonJS({
24294
24390
  if (!trimmed) throw new Error("working directory required");
24295
24391
  const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os12.homedir()) : path10.resolve(trimmed);
24296
24392
  const normalizedType = this.providerLoader.resolveAlias(cliType);
24297
- const provider2 = this.providerLoader.getByAlias(cliType);
24393
+ const provider = this.providerLoader.getByAlias(cliType);
24298
24394
  const key = crypto4.randomUUID();
24299
- if (provider2 && provider2.category === "acp") {
24395
+ if (provider && provider.category === "acp") {
24300
24396
  const instanceManager2 = this.deps.getInstanceManager();
24301
24397
  if (!instanceManager2) throw new Error("InstanceManager not available");
24302
- const spawnCmd = provider2.spawn?.command;
24398
+ const spawnCmd = provider.spawn?.command;
24303
24399
  if (spawnCmd) {
24304
24400
  try {
24305
24401
  const { execSync: execSync7 } = require("child_process");
24306
24402
  execSync7(`which ${spawnCmd}`, { stdio: "ignore" });
24307
24403
  } catch {
24308
- const installInfo = provider2.install || `Install: check ${provider2.displayName || provider2.name} documentation`;
24404
+ const installInfo = provider.install || `Install: check ${provider.displayName || provider.name} documentation`;
24309
24405
  throw new Error(
24310
- `${provider2.displayName || provider2.name} is not installed.
24406
+ `${provider.displayName || provider.name} is not installed.
24311
24407
  Command '${spawnCmd}' not found in PATH.
24312
24408
 
24313
24409
  ${installInfo}`
24314
24410
  );
24315
24411
  }
24316
24412
  }
24317
- console.log(import_chalk4.default.cyan(` \u{1F50C} Starting ACP agent: ${provider2.name} (${provider2.type}) in ${resolvedDir}`));
24318
- const acpInstance = new AcpProviderInstance(provider2, resolvedDir, cliArgs);
24413
+ console.log(import_chalk7.default.cyan(` \u{1F50C} Starting ACP agent: ${provider.name} (${provider.type}) in ${resolvedDir}`));
24414
+ const acpInstance = new AcpProviderInstance(provider, resolvedDir, cliArgs);
24319
24415
  await instanceManager2.addInstance(key, acpInstance, {
24320
24416
  settings: this.providerLoader.getSettings(normalizedType)
24321
24417
  });
@@ -24344,11 +24440,11 @@ ${installInfo}`
24344
24440
  setOnPtyData: () => {
24345
24441
  }
24346
24442
  });
24347
- console.log(import_chalk4.default.green(` \u2713 ACP agent started: ${provider2.name} in ${resolvedDir}`));
24443
+ console.log(import_chalk7.default.green(` \u2713 ACP agent started: ${provider.name} in ${resolvedDir}`));
24348
24444
  if (initialModel) {
24349
24445
  try {
24350
24446
  await acpInstance.setConfigOption("model", initialModel);
24351
- console.log(import_chalk4.default.green(` \u{1F916} Initial model set: ${initialModel}`));
24447
+ console.log(import_chalk7.default.green(` \u{1F916} Initial model set: ${initialModel}`));
24352
24448
  } catch (e) {
24353
24449
  LOG5.warn("CLI", `[ACP] Initial model set failed: ${e?.message}`);
24354
24450
  }
@@ -24363,13 +24459,13 @@ ${installInfo}`
24363
24459
  }
24364
24460
  const cliInfo = await detectCLI(cliType, this.providerLoader);
24365
24461
  if (!cliInfo) throw new Error(`${cliType} not found`);
24366
- console.log(import_chalk4.default.yellow(` \u26A1 Starting CLI ${cliType} in ${resolvedDir}...`));
24367
- if (provider2) {
24368
- console.log(import_chalk4.default.cyan(` \u{1F4E6} Using provider: ${provider2.name} (${provider2.type})`));
24462
+ console.log(import_chalk7.default.yellow(` \u26A1 Starting CLI ${cliType} in ${resolvedDir}...`));
24463
+ if (provider) {
24464
+ console.log(import_chalk7.default.cyan(` \u{1F4E6} Using provider: ${provider.name} (${provider.type})`));
24369
24465
  }
24370
24466
  const instanceManager = this.deps.getInstanceManager();
24371
- if (provider2 && instanceManager) {
24372
- const cliInstance = new CliProviderInstance(provider2, resolvedDir, cliArgs, key);
24467
+ if (provider && instanceManager) {
24468
+ const cliInstance = new CliProviderInstance(provider, resolvedDir, cliArgs, key);
24373
24469
  try {
24374
24470
  await instanceManager.addInstance(key, cliInstance, {
24375
24471
  serverConn: this.deps.getServerConn(),
@@ -24384,7 +24480,7 @@ ${installInfo}`
24384
24480
  throw new Error(`Failed to start ${cliInfo.displayName}: ${spawnErr?.message}`);
24385
24481
  }
24386
24482
  this.adapters.set(key, cliInstance.getAdapter());
24387
- console.log(import_chalk4.default.green(` \u2713 CLI started: ${cliInfo.displayName} v${cliInfo.version || "unknown"} in ${resolvedDir}`));
24483
+ console.log(import_chalk7.default.green(` \u2713 CLI started: ${cliInfo.displayName} v${cliInfo.version || "unknown"} in ${resolvedDir}`));
24388
24484
  const checkStopped = setInterval(() => {
24389
24485
  try {
24390
24486
  const adapter = this.adapters.get(key);
@@ -24440,7 +24536,7 @@ ${installInfo}`
24440
24536
  });
24441
24537
  }
24442
24538
  this.adapters.set(key, adapter);
24443
- console.log(import_chalk4.default.green(` \u2713 CLI started: ${cliInfo.displayName} v${cliInfo.version || "unknown"} in ${resolvedDir}`));
24539
+ console.log(import_chalk7.default.green(` \u2713 CLI started: ${cliInfo.displayName} v${cliInfo.version || "unknown"} in ${resolvedDir}`));
24444
24540
  }
24445
24541
  try {
24446
24542
  addCliHistory({ cliType, dir: resolvedDir, cliArgs });
@@ -24510,7 +24606,7 @@ ${installInfo}`
24510
24606
  switch (cmd) {
24511
24607
  case "launch_cli": {
24512
24608
  const cliType = args?.cliType;
24513
- const config2 = loadConfig4();
24609
+ const config2 = loadConfig3();
24514
24610
  const resolved = resolveLaunchDirectory(
24515
24611
  {
24516
24612
  dir: args?.dir,
@@ -24551,13 +24647,13 @@ ${installInfo}`
24551
24647
  if (found) {
24552
24648
  await this.stopSession(found.key);
24553
24649
  } else {
24554
- console.log(import_chalk4.default.yellow(` \u26A0 No adapter found for ${cliType}`));
24650
+ console.log(import_chalk7.default.yellow(` \u26A0 No adapter found for ${cliType}`));
24555
24651
  }
24556
24652
  return { success: true, cliType, dir, stopped: true };
24557
24653
  }
24558
24654
  case "restart_session": {
24559
24655
  const cliType = args?.cliType || args?.agentType || args?.ideType;
24560
- const cfg = loadConfig4();
24656
+ const cfg = loadConfig3();
24561
24657
  const rdir = resolveLaunchDirectory(
24562
24658
  {
24563
24659
  dir: args?.dir,
@@ -24622,12 +24718,12 @@ ${installInfo}`
24622
24718
  extensionIdPattern;
24623
24719
  provider;
24624
24720
  lastSuccessState = null;
24625
- constructor(provider2) {
24626
- this.provider = provider2;
24627
- this.agentType = provider2.type;
24628
- this.agentName = provider2.displayName || provider2.name;
24629
- this.extensionId = provider2.extensionId || provider2.type;
24630
- this.extensionIdPattern = provider2.extensionIdPattern || new RegExp(`extensionId=${this.extensionId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i");
24721
+ constructor(provider) {
24722
+ this.provider = provider;
24723
+ this.agentType = provider.type;
24724
+ this.agentName = provider.displayName || provider.name;
24725
+ this.extensionId = provider.extensionId || provider.type;
24726
+ this.extensionIdPattern = provider.extensionIdPattern || new RegExp(`extensionId=${this.extensionId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`, "i");
24631
24727
  }
24632
24728
  callScript(name, ...args) {
24633
24729
  const fn = this.provider.scripts?.[name];
@@ -24758,13 +24854,13 @@ ${installInfo}`
24758
24854
  /** Panel focus based on provider.js focusPanel or extensionId (currently no-op) */
24759
24855
  async ensureAgentPanelOpen(agentType, targetIdeType) {
24760
24856
  }
24761
- async switchActiveAgent(cdp2, agentType) {
24857
+ async switchActiveAgent(cdp, agentType) {
24762
24858
  if (this._activeAgentType === agentType) return;
24763
24859
  if (this._activeAgentType) {
24764
24860
  const prev = this.managed.get(this._activeAgentType);
24765
24861
  if (prev) {
24766
24862
  try {
24767
- await cdp2.detachAgent(prev.sessionId);
24863
+ await cdp.detachAgent(prev.sessionId);
24768
24864
  } catch {
24769
24865
  }
24770
24866
  this.managed.delete(this._activeAgentType);
@@ -24776,7 +24872,7 @@ ${installInfo}`
24776
24872
  this.logFn(`[AgentStream] Active agent: ${agentType || "none"}`);
24777
24873
  }
24778
24874
  /** Agent webview discovery + session connection */
24779
- async syncAgentSessions(cdp2) {
24875
+ async syncAgentSessions(cdp) {
24780
24876
  if (!this.enabled || !this._activeAgentType) return;
24781
24877
  const now = Date.now();
24782
24878
  if (this.managed.has(this._activeAgentType) && now - this.lastDiscoveryTime < this.discoveryIntervalMs) {
@@ -24784,12 +24880,12 @@ ${installInfo}`
24784
24880
  }
24785
24881
  this.lastDiscoveryTime = now;
24786
24882
  try {
24787
- const targets = await cdp2.discoverAgentWebviews();
24883
+ const targets = await cdp.discoverAgentWebviews();
24788
24884
  const activeTarget = targets.find((t) => t.agentType === this._activeAgentType);
24789
24885
  if (activeTarget && !this.managed.has(this._activeAgentType)) {
24790
24886
  const adapter = this.allAdapters.find((a) => a.agentType === this._activeAgentType);
24791
24887
  if (adapter) {
24792
- const sessionId = await cdp2.attachToAgent(activeTarget);
24888
+ const sessionId = await cdp.attachToAgent(activeTarget);
24793
24889
  if (sessionId) {
24794
24890
  this.managed.set(this._activeAgentType, {
24795
24891
  adapter,
@@ -24805,7 +24901,7 @@ ${installInfo}`
24805
24901
  }
24806
24902
  for (const [type, agent] of this.managed) {
24807
24903
  if (type !== this._activeAgentType) {
24808
- await cdp2.detachAgent(agent.sessionId);
24904
+ await cdp.detachAgent(agent.sessionId);
24809
24905
  this.managed.delete(type);
24810
24906
  }
24811
24907
  }
@@ -24815,7 +24911,7 @@ ${installInfo}`
24815
24911
  }
24816
24912
  }
24817
24913
  /** Collect active agent status */
24818
- async collectAgentStreams(cdp2) {
24914
+ async collectAgentStreams(cdp) {
24819
24915
  if (!this.enabled) return [];
24820
24916
  const results = [];
24821
24917
  if (this._activeAgentType && this.managed.has(this._activeAgentType)) {
@@ -24827,7 +24923,7 @@ ${installInfo}`
24827
24923
  results.push(agent.lastState);
24828
24924
  } else {
24829
24925
  try {
24830
- const evaluate = (expr, timeout) => cdp2.evaluateInSession(agent.sessionId, expr, timeout);
24926
+ const evaluate = (expr, timeout) => cdp.evaluateInSession(agent.sessionId, expr, timeout);
24831
24927
  const state = await agent.adapter.readChat(evaluate);
24832
24928
  agent.lastState = state;
24833
24929
  agent.lastError = null;
@@ -24849,7 +24945,7 @@ ${installInfo}`
24849
24945
  });
24850
24946
  if (errorMsg.includes("timeout") || errorMsg.includes("not connected") || errorMsg.includes("Session")) {
24851
24947
  try {
24852
- await cdp2.detachAgent(agent.sessionId);
24948
+ await cdp.detachAgent(agent.sessionId);
24853
24949
  } catch {
24854
24950
  }
24855
24951
  this.managed.delete(type);
@@ -24860,12 +24956,12 @@ ${installInfo}`
24860
24956
  }
24861
24957
  return results;
24862
24958
  }
24863
- async sendToAgent(cdp2, agentType, text, targetIdeType) {
24959
+ async sendToAgent(cdp, agentType, text, targetIdeType) {
24864
24960
  await this.ensureAgentPanelOpen(agentType, targetIdeType);
24865
24961
  const agent = this.managed.get(agentType);
24866
24962
  if (!agent) return false;
24867
24963
  try {
24868
- const evaluate = (expr, timeout) => cdp2.evaluateInSession(agent.sessionId, expr, timeout);
24964
+ const evaluate = (expr, timeout) => cdp.evaluateInSession(agent.sessionId, expr, timeout);
24869
24965
  await agent.adapter.sendMessage(evaluate, text);
24870
24966
  return true;
24871
24967
  } catch (e) {
@@ -24873,24 +24969,24 @@ ${installInfo}`
24873
24969
  return false;
24874
24970
  }
24875
24971
  }
24876
- async resolveAgentAction(cdp2, agentType, action, targetIdeType) {
24972
+ async resolveAgentAction(cdp, agentType, action, targetIdeType) {
24877
24973
  await this.ensureAgentPanelOpen(agentType, targetIdeType);
24878
24974
  const agent = this.managed.get(agentType);
24879
24975
  if (!agent) return false;
24880
24976
  try {
24881
- const evaluate = (expr, timeout) => cdp2.evaluateInSession(agent.sessionId, expr, timeout);
24977
+ const evaluate = (expr, timeout) => cdp.evaluateInSession(agent.sessionId, expr, timeout);
24882
24978
  return await agent.adapter.resolveAction(evaluate, action);
24883
24979
  } catch (e) {
24884
24980
  this.logFn(`[AgentStream] resolveAction(${agentType}) error: ${e.message}`);
24885
24981
  return false;
24886
24982
  }
24887
24983
  }
24888
- async newAgentSession(cdp2, agentType, targetIdeType) {
24984
+ async newAgentSession(cdp, agentType, targetIdeType) {
24889
24985
  await this.ensureAgentPanelOpen(agentType, targetIdeType);
24890
24986
  const agent = this.managed.get(agentType);
24891
24987
  if (!agent) return false;
24892
24988
  try {
24893
- const evaluate = (expr, timeout) => cdp2.evaluateInSession(agent.sessionId, expr, timeout);
24989
+ const evaluate = (expr, timeout) => cdp.evaluateInSession(agent.sessionId, expr, timeout);
24894
24990
  await agent.adapter.newSession(evaluate);
24895
24991
  return true;
24896
24992
  } catch (e) {
@@ -24898,45 +24994,45 @@ ${installInfo}`
24898
24994
  return false;
24899
24995
  }
24900
24996
  }
24901
- async listAgentChats(cdp2, agentType) {
24997
+ async listAgentChats(cdp, agentType) {
24902
24998
  let agent = this.managed.get(agentType);
24903
24999
  if (!agent) {
24904
25000
  this.logFn(`[AgentStream] listChats: ${agentType} not managed, trying on-demand activation`);
24905
- await this.switchActiveAgent(cdp2, agentType);
24906
- await this.syncAgentSessions(cdp2);
25001
+ await this.switchActiveAgent(cdp, agentType);
25002
+ await this.syncAgentSessions(cdp);
24907
25003
  agent = this.managed.get(agentType);
24908
25004
  }
24909
25005
  if (!agent || typeof agent.adapter.listChats !== "function") return [];
24910
25006
  try {
24911
- const evaluate = (expr, timeout) => cdp2.evaluateInSession(agent.sessionId, expr, timeout);
25007
+ const evaluate = (expr, timeout) => cdp.evaluateInSession(agent.sessionId, expr, timeout);
24912
25008
  return await agent.adapter.listChats(evaluate);
24913
25009
  } catch (e) {
24914
25010
  this.logFn(`[AgentStream] listChats(${agentType}) error: ${e.message}`);
24915
25011
  return [];
24916
25012
  }
24917
25013
  }
24918
- async switchAgentSession(cdp2, agentType, sessionId) {
25014
+ async switchAgentSession(cdp, agentType, sessionId) {
24919
25015
  let agent = this.managed.get(agentType);
24920
25016
  if (!agent) {
24921
25017
  this.logFn(`[AgentStream] switchSession: ${agentType} not managed, trying on-demand activation`);
24922
- await this.switchActiveAgent(cdp2, agentType);
24923
- await this.syncAgentSessions(cdp2);
25018
+ await this.switchActiveAgent(cdp, agentType);
25019
+ await this.syncAgentSessions(cdp);
24924
25020
  agent = this.managed.get(agentType);
24925
25021
  }
24926
25022
  if (!agent || typeof agent.adapter.switchSession !== "function") return false;
24927
25023
  try {
24928
- const evaluate = (expr, timeout) => cdp2.evaluateInSession(agent.sessionId, expr, timeout);
25024
+ const evaluate = (expr, timeout) => cdp.evaluateInSession(agent.sessionId, expr, timeout);
24929
25025
  return await agent.adapter.switchSession(evaluate, sessionId);
24930
25026
  } catch (e) {
24931
25027
  this.logFn(`[AgentStream] switchSession(${agentType}) error: ${e.message}`);
24932
25028
  return false;
24933
25029
  }
24934
25030
  }
24935
- async focusAgentEditor(cdp2, agentType) {
25031
+ async focusAgentEditor(cdp, agentType) {
24936
25032
  const agent = this.managed.get(agentType);
24937
25033
  if (!agent || typeof agent.adapter.focusEditor !== "function") return false;
24938
25034
  try {
24939
- const evaluate = (expr, timeout) => cdp2.evaluateInSession(agent.sessionId, expr, timeout);
25035
+ const evaluate = (expr, timeout) => cdp.evaluateInSession(agent.sessionId, expr, timeout);
24940
25036
  await agent.adapter.focusEditor(evaluate);
24941
25037
  return true;
24942
25038
  } catch (e) {
@@ -24950,10 +25046,10 @@ ${installInfo}`
24950
25046
  getManagedAgent(agentType) {
24951
25047
  return this.managed.get(agentType);
24952
25048
  }
24953
- async dispose(cdp2) {
25049
+ async dispose(cdp) {
24954
25050
  for (const [, agent] of this.managed) {
24955
25051
  try {
24956
- await cdp2.detachAgent(agent.sessionId);
25052
+ await cdp.detachAgent(agent.sessionId);
24957
25053
  } catch {
24958
25054
  }
24959
25055
  }
@@ -25000,8 +25096,8 @@ ${installInfo}`
25000
25096
  cdpManagers
25001
25097
  } = this.deps;
25002
25098
  if (!agentStreamManager || cdpManagers.size === 0) return;
25003
- for (const [ideType, cdp2] of cdpManagers) {
25004
- registerExtensionProviders(providerLoader, cdp2, ideType);
25099
+ for (const [ideType, cdp] of cdpManagers) {
25100
+ registerExtensionProviders(providerLoader, cdp, ideType);
25005
25101
  const ideInstance = instanceManager.getInstance(`ide:${ideType}`);
25006
25102
  if (ideInstance?.getExtensionTypes && ideInstance?.addExtension && ideInstance?.removeExtension) {
25007
25103
  const currentExtTypes = new Set(ideInstance.getExtensionTypes());
@@ -25027,11 +25123,11 @@ ${installInfo}`
25027
25123
  }
25028
25124
  }
25029
25125
  if (this._activeIdeType) {
25030
- const cdp2 = cdpManagers.get(this._activeIdeType);
25031
- if (cdp2?.isConnected) {
25126
+ const cdp = cdpManagers.get(this._activeIdeType);
25127
+ if (cdp?.isConnected) {
25032
25128
  try {
25033
- await agentStreamManager.syncAgentSessions(cdp2);
25034
- const streams = await agentStreamManager.collectAgentStreams(cdp2);
25129
+ await agentStreamManager.syncAgentSessions(cdp);
25130
+ const streams = await agentStreamManager.collectAgentStreams(cdp);
25035
25131
  this.deps.onStreamsUpdated?.(this._activeIdeType, streams);
25036
25132
  } catch {
25037
25133
  }
@@ -25040,16 +25136,16 @@ ${installInfo}`
25040
25136
  this._activeIdeType = null;
25041
25137
  }
25042
25138
  if (!agentStreamManager.activeAgentType) {
25043
- for (const [ideType, cdp2] of cdpManagers) {
25044
- if (!cdp2.isConnected) continue;
25139
+ for (const [ideType, cdp] of cdpManagers) {
25140
+ if (!cdp.isConnected) continue;
25045
25141
  try {
25046
- const discovered = await cdp2.discoverAgentWebviews();
25142
+ const discovered = await cdp.discoverAgentWebviews();
25047
25143
  if (discovered.length > 0) {
25048
25144
  this._activeIdeType = ideType;
25049
- await agentStreamManager.switchActiveAgent(cdp2, discovered[0].agentType);
25145
+ await agentStreamManager.switchActiveAgent(cdp, discovered[0].agentType);
25050
25146
  LOG5.info("AgentStream", `Auto-activated: ${discovered[0].agentType} (${ideType})`);
25051
- await agentStreamManager.syncAgentSessions(cdp2);
25052
- const streams = await agentStreamManager.collectAgentStreams(cdp2);
25147
+ await agentStreamManager.syncAgentSessions(cdp);
25148
+ const streams = await agentStreamManager.collectAgentStreams(cdp);
25053
25149
  this.deps.onStreamsUpdated?.(ideType, streams);
25054
25150
  return;
25055
25151
  }
@@ -25321,26 +25417,26 @@ ${installInfo}`
25321
25417
  async function detectAllVersions2(loader, archive) {
25322
25418
  const results = [];
25323
25419
  const currentOs = (0, import_os3.platform)();
25324
- for (const provider2 of loader.getAll()) {
25420
+ for (const provider of loader.getAll()) {
25325
25421
  const info = {
25326
- type: provider2.type,
25327
- name: provider2.name,
25328
- category: provider2.category,
25422
+ type: provider.type,
25423
+ name: provider.name,
25424
+ category: provider.category,
25329
25425
  installed: false,
25330
25426
  version: null,
25331
25427
  path: null,
25332
25428
  binary: null,
25333
25429
  detectedAt: (/* @__PURE__ */ new Date()).toISOString()
25334
25430
  };
25335
- const versionCommand = provider2.versionCommand;
25336
- if (provider2.category === "ide") {
25337
- const osPaths = provider2.paths?.[currentOs] || [];
25431
+ const versionCommand = provider.versionCommand;
25432
+ if (provider.category === "ide") {
25433
+ const osPaths = provider.paths?.[currentOs] || [];
25338
25434
  const appPath = checkPathExists2(osPaths);
25339
- const cliBin = provider2.cli ? findBinary2(provider2.cli) : null;
25435
+ const cliBin = provider.cli ? findBinary2(provider.cli) : null;
25340
25436
  let resolvedBin = cliBin;
25341
25437
  if (!resolvedBin && appPath && currentOs === "darwin") {
25342
- const bundled = path11.join(appPath, "Contents", "Resources", "app", "bin", provider2.cli || "");
25343
- if (provider2.cli && fs8.existsSync(bundled)) resolvedBin = bundled;
25438
+ const bundled = path11.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
25439
+ if (provider.cli && fs8.existsSync(bundled)) resolvedBin = bundled;
25344
25440
  }
25345
25441
  info.installed = !!(appPath || resolvedBin);
25346
25442
  info.path = appPath || null;
@@ -25351,23 +25447,23 @@ ${installInfo}`
25351
25447
  if (!info.version && appPath) {
25352
25448
  info.version = getMacAppVersion(appPath);
25353
25449
  }
25354
- } else if (provider2.category === "cli" || provider2.category === "acp") {
25355
- const bin = provider2.binary || provider2.spawn?.command || provider2.cli || provider2.type;
25450
+ } else if (provider.category === "cli" || provider.category === "acp") {
25451
+ const bin = provider.binary || provider.spawn?.command || provider.cli || provider.type;
25356
25452
  const binPath = findBinary2(bin);
25357
25453
  info.installed = !!binPath;
25358
25454
  info.binary = binPath || null;
25359
25455
  if (binPath) {
25360
25456
  info.version = getVersion(binPath, versionCommand);
25361
25457
  }
25362
- } else if (provider2.category === "extension") {
25458
+ } else if (provider.category === "extension") {
25363
25459
  info.installed = false;
25364
25460
  info.version = null;
25365
25461
  }
25366
25462
  if (info.version && archive) {
25367
- archive.record(provider2.type, info.version);
25463
+ archive.record(provider.type, info.version);
25368
25464
  }
25369
25465
  if (info.version && info.installed) {
25370
- const testedVersions = provider2.testedVersions || [];
25466
+ const testedVersions = provider.testedVersions || [];
25371
25467
  if (testedVersions.length > 0 && !testedVersions.includes(info.version)) {
25372
25468
  info.warning = `Version ${info.version} is not in testedVersions [${testedVersions.join(", ")}]. Scripts may not work correctly.`;
25373
25469
  }
@@ -25709,6 +25805,8 @@ async (params) => {
25709
25805
  server = null;
25710
25806
  providerLoader;
25711
25807
  cdpManagers;
25808
+ instanceManager;
25809
+ cliManager;
25712
25810
  logFn;
25713
25811
  sseClients = [];
25714
25812
  watchScriptPath = null;
@@ -25718,9 +25816,13 @@ async (params) => {
25718
25816
  autoImplProcess = null;
25719
25817
  autoImplSSEClients = [];
25720
25818
  autoImplStatus = { running: false, type: null, progress: [] };
25819
+ // CLI debug SSE
25820
+ cliSSEClients = [];
25721
25821
  constructor(options) {
25722
25822
  this.providerLoader = options.providerLoader;
25723
25823
  this.cdpManagers = options.cdpManagers;
25824
+ this.instanceManager = options.instanceManager || null;
25825
+ this.cliManager = options.cliManager || null;
25724
25826
  this.logFn = options.logFn || LOG5.forComponent("DevServer").asLogFn();
25725
25827
  }
25726
25828
  log(msg) {
@@ -25747,6 +25849,15 @@ async (params) => {
25747
25849
  { method: "POST", pattern: "/api/watch/stop", handler: (q, s) => this.handleWatchStop(q, s) },
25748
25850
  { method: "GET", pattern: "/api/watch/events", handler: (q, s) => this.handleSSE(q, s) },
25749
25851
  { method: "POST", pattern: "/api/scaffold", handler: (q, s) => this.handleScaffold(q, s) },
25852
+ // CLI Debug routes
25853
+ { method: "GET", pattern: "/api/cli/status", handler: (q, s) => this.handleCliStatus(q, s) },
25854
+ { method: "POST", pattern: "/api/cli/launch", handler: (q, s) => this.handleCliLaunch(q, s) },
25855
+ { method: "POST", pattern: "/api/cli/send", handler: (q, s) => this.handleCliSend(q, s) },
25856
+ { method: "POST", pattern: "/api/cli/resolve", handler: (q, s) => this.handleCliResolve(q, s) },
25857
+ { method: "POST", pattern: "/api/cli/raw", handler: (q, s) => this.handleCliRaw(q, s) },
25858
+ { method: "POST", pattern: "/api/cli/stop", handler: (q, s) => this.handleCliStop(q, s) },
25859
+ { method: "GET", pattern: "/api/cli/events", handler: (q, s) => this.handleCliSSE(q, s) },
25860
+ { method: "GET", pattern: /^\/api\/cli\/debug\/([^/]+)$/, handler: (q, s, p) => this.handleCliDebug(p[0], q, s) },
25750
25861
  // Dynamic routes (provider :type param)
25751
25862
  { method: "POST", pattern: /^\/api\/providers\/([^/]+)\/script$/, handler: (q, s, p) => this.handleRunScript(p[0], q, s) },
25752
25863
  { method: "GET", pattern: /^\/api\/providers\/([^/]+)\/files$/, handler: (q, s, p) => this.handleListFiles(p[0], q, s) },
@@ -25862,12 +25973,12 @@ async (params) => {
25862
25973
  this.json(res, 200, { providers, count: providers.length });
25863
25974
  }
25864
25975
  async handleProviderConfig(type, _req, res) {
25865
- const provider2 = this.providerLoader.resolve(type);
25866
- if (!provider2) {
25976
+ const provider = this.providerLoader.resolve(type);
25977
+ if (!provider) {
25867
25978
  this.json(res, 404, { error: `Provider not found: ${type}` });
25868
25979
  return;
25869
25980
  }
25870
- const config2 = { ...provider2 };
25981
+ const config2 = { ...provider };
25871
25982
  if (config2.scripts) {
25872
25983
  config2.scriptNames = Object.keys(config2.scripts).filter((k) => typeof config2.scripts[k] === "function");
25873
25984
  delete config2.scripts;
@@ -25875,12 +25986,12 @@ async (params) => {
25875
25986
  this.json(res, 200, { type, config: config2 });
25876
25987
  }
25877
25988
  async handleSpawnTest(type, req, res) {
25878
- const provider2 = this.providerLoader.resolve(type);
25879
- if (!provider2) {
25989
+ const provider = this.providerLoader.resolve(type);
25990
+ if (!provider) {
25880
25991
  this.json(res, 404, { error: `Provider not found: ${type}` });
25881
25992
  return;
25882
25993
  }
25883
- const spawn3 = provider2.spawn;
25994
+ const spawn3 = provider.spawn;
25884
25995
  if (!spawn3) {
25885
25996
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
25886
25997
  return;
@@ -25940,18 +26051,18 @@ async (params) => {
25940
26051
  async handleRunScript(type, req, res) {
25941
26052
  const body = await this.readBody(req);
25942
26053
  const { script: scriptName, params, ideType: scriptIdeType } = body;
25943
- const provider2 = this.providerLoader.resolve(type);
25944
- if (!provider2) {
26054
+ const provider = this.providerLoader.resolve(type);
26055
+ if (!provider) {
25945
26056
  this.json(res, 404, { error: `Provider '${type}' not found` });
25946
26057
  return;
25947
26058
  }
25948
- const fn = provider2.scripts?.[scriptName];
26059
+ const fn = provider.scripts?.[scriptName];
25949
26060
  if (typeof fn !== "function") {
25950
- this.json(res, 400, { error: `Script '${scriptName}' not found in provider '${type}'`, available: provider2.scripts ? Object.keys(provider2.scripts) : [] });
26061
+ this.json(res, 400, { error: `Script '${scriptName}' not found in provider '${type}'`, available: provider.scripts ? Object.keys(provider.scripts) : [] });
25951
26062
  return;
25952
26063
  }
25953
- const cdp2 = this.getCdp(scriptIdeType);
25954
- if (!cdp2) {
26064
+ const cdp = this.getCdp(scriptIdeType);
26065
+ if (!cdp) {
25955
26066
  this.json(res, 503, { error: "No CDP connection available" });
25956
26067
  return;
25957
26068
  }
@@ -25964,11 +26075,11 @@ async (params) => {
25964
26075
  const isWebviewScript = scriptName.toLowerCase().includes("webview");
25965
26076
  let raw;
25966
26077
  if (isWebviewScript) {
25967
- const matchText = provider2.webviewMatchText;
26078
+ const matchText = provider.webviewMatchText;
25968
26079
  const matchFn = matchText ? (body2) => body2.includes(matchText) : void 0;
25969
- raw = await cdp2.evaluateInWebviewFrame(scriptCode, matchFn);
26080
+ raw = await cdp.evaluateInWebviewFrame(scriptCode, matchFn);
25970
26081
  } else {
25971
- raw = await cdp2.evaluate(scriptCode, 3e4);
26082
+ raw = await cdp.evaluate(scriptCode, 3e4);
25972
26083
  }
25973
26084
  let result = raw;
25974
26085
  if (typeof raw === "string") {
@@ -25989,13 +26100,13 @@ async (params) => {
25989
26100
  this.json(res, 400, { error: "expression required" });
25990
26101
  return;
25991
26102
  }
25992
- const cdp2 = ideType ? this.cdpManagers.get(ideType) : this.getAnyCdp();
25993
- if (!cdp2?.isConnected) {
26103
+ const cdp = ideType ? this.cdpManagers.get(ideType) : this.getAnyCdp();
26104
+ if (!cdp?.isConnected) {
25994
26105
  this.json(res, 503, { error: "No CDP connection available" });
25995
26106
  return;
25996
26107
  }
25997
26108
  try {
25998
- const raw = await cdp2.evaluate(expression, timeout || 3e4);
26109
+ const raw = await cdp.evaluate(expression, timeout || 3e4);
25999
26110
  let result = raw;
26000
26111
  if (typeof raw === "string") {
26001
26112
  try {
@@ -26015,8 +26126,8 @@ async (params) => {
26015
26126
  this.json(res, 400, { error: "selector required" });
26016
26127
  return;
26017
26128
  }
26018
- const cdp2 = this.getCdp(ideType);
26019
- if (!cdp2) {
26129
+ const cdp = this.getCdp(ideType);
26130
+ if (!cdp) {
26020
26131
  this.json(res, 503, { error: "No CDP connection available" });
26021
26132
  return;
26022
26133
  }
@@ -26041,7 +26152,7 @@ async (params) => {
26041
26152
  } catch (e) { return JSON.stringify({ error: e.message }); }
26042
26153
  })()`;
26043
26154
  try {
26044
- const raw = await cdp2.evaluate(expr, 1e4);
26155
+ const raw = await cdp.evaluate(expr, 1e4);
26045
26156
  const result = typeof raw === "string" ? JSON.parse(raw) : raw;
26046
26157
  this.json(res, 200, result);
26047
26158
  } catch (e) {
@@ -26051,15 +26162,15 @@ async (params) => {
26051
26162
  async handleScreenshot(req, res) {
26052
26163
  const url2 = new URL(req.url || "/", "http://localhost");
26053
26164
  const ideType = url2.searchParams.get("ideType") || void 0;
26054
- const cdp2 = this.getCdp(ideType);
26055
- if (!cdp2) {
26165
+ const cdp = this.getCdp(ideType);
26166
+ if (!cdp) {
26056
26167
  this.json(res, 503, { error: "No CDP connection available" });
26057
26168
  return;
26058
26169
  }
26059
26170
  try {
26060
26171
  let vpW = 0, vpH = 0;
26061
26172
  try {
26062
- const metrics = await cdp2.send("Page.getLayoutMetrics", {}, 3e3);
26173
+ const metrics = await cdp.send("Page.getLayoutMetrics", {}, 3e3);
26063
26174
  const vp = metrics?.cssVisualViewport || metrics?.visualViewport;
26064
26175
  if (vp) {
26065
26176
  vpW = Math.round(vp.clientWidth || vp.width || 0);
@@ -26067,7 +26178,7 @@ async (params) => {
26067
26178
  }
26068
26179
  } catch {
26069
26180
  }
26070
- const buf = await cdp2.captureScreenshot();
26181
+ const buf = await cdp.captureScreenshot();
26071
26182
  if (buf) {
26072
26183
  res.writeHead(200, {
26073
26184
  "Content-Type": "image/webp",
@@ -26098,8 +26209,8 @@ async (params) => {
26098
26209
  category: p.category
26099
26210
  }));
26100
26211
  const cdpStatus = {};
26101
- for (const [key, cdp2] of this.cdpManagers.entries()) {
26102
- cdpStatus[key] = { connected: cdp2.isConnected };
26212
+ for (const [key, cdp] of this.cdpManagers.entries()) {
26213
+ cdpStatus[key] = { connected: cdp.isConnected };
26103
26214
  }
26104
26215
  this.json(res, 200, {
26105
26216
  devMode: true,
@@ -26219,25 +26330,25 @@ async (params) => {
26219
26330
  this.sendSSE({ type: "watch_started", provider: type, script: this.watchScriptName });
26220
26331
  const runWatch = async () => {
26221
26332
  if (!this.watchScriptPath) return;
26222
- const provider2 = this.providerLoader.resolve(this.watchScriptPath);
26223
- if (!provider2) {
26333
+ const provider = this.providerLoader.resolve(this.watchScriptPath);
26334
+ if (!provider) {
26224
26335
  this.sendSSE({ type: "watch_error", error: `Provider '${this.watchScriptPath}' not found` });
26225
26336
  return;
26226
26337
  }
26227
- const fn = provider2.scripts?.[this.watchScriptName];
26338
+ const fn = provider.scripts?.[this.watchScriptName];
26228
26339
  if (typeof fn !== "function") {
26229
26340
  this.sendSSE({ type: "watch_error", error: `Script '${this.watchScriptName}' not found` });
26230
26341
  return;
26231
26342
  }
26232
- const cdp2 = this.getAnyCdp();
26233
- if (!cdp2) {
26343
+ const cdp = this.getAnyCdp();
26344
+ if (!cdp) {
26234
26345
  this.sendSSE({ type: "watch_error", error: "No CDP connection" });
26235
26346
  return;
26236
26347
  }
26237
26348
  try {
26238
26349
  const script = fn();
26239
26350
  const start = Date.now();
26240
- const raw = await cdp2.evaluate(script, 15e3);
26351
+ const raw = await cdp.evaluate(script, 15e3);
26241
26352
  const elapsed = Date.now() - start;
26242
26353
  let result = raw;
26243
26354
  if (typeof raw === "string") {
@@ -26268,9 +26379,9 @@ async (params) => {
26268
26379
  // ─── Provider File Explorer ───
26269
26380
  /** Find the provider directory on disk */
26270
26381
  findProviderDir(type) {
26271
- const provider2 = this.providerLoader.getMeta(type);
26272
- if (!provider2) return null;
26273
- const cat = provider2.category;
26382
+ const provider = this.providerLoader.getMeta(type);
26383
+ if (!provider) return null;
26384
+ const cat = provider.category;
26274
26385
  const builtinDir = this.providerLoader.builtinDir || path12.resolve(__dirname, "../providers/_builtin");
26275
26386
  const userDir = path12.join(os14.homedir(), ".adhdev", "providers");
26276
26387
  const directCandidates = [
@@ -26568,12 +26679,12 @@ async (params) => {
26568
26679
  this.json(res, 400, { error: "message required" });
26569
26680
  return;
26570
26681
  }
26571
- const provider2 = this.providerLoader.getMeta(type);
26572
- if (!provider2) {
26682
+ const provider = this.providerLoader.getMeta(type);
26683
+ if (!provider) {
26573
26684
  this.json(res, 404, { error: `Provider not found: ${type}` });
26574
26685
  return;
26575
26686
  }
26576
- const spawn3 = provider2.spawn;
26687
+ const spawn3 = provider.spawn;
26577
26688
  if (!spawn3) {
26578
26689
  this.json(res, 400, { error: `Provider ${type} has no spawn config` });
26579
26690
  return;
@@ -26626,8 +26737,8 @@ async (params) => {
26626
26737
  }
26627
26738
  async handleCdpTargets(_req, res) {
26628
26739
  const targets = [];
26629
- for (const [ide, cdp2] of this.cdpManagers.entries()) {
26630
- targets.push({ ide, connected: cdp2.isConnected, port: cdp2.getPort() });
26740
+ for (const [ide, cdp] of this.cdpManagers.entries()) {
26741
+ targets.push({ ide, connected: cdp.isConnected, port: cdp.getPort() });
26631
26742
  }
26632
26743
  this.json(res, 200, { targets });
26633
26744
  }
@@ -26703,8 +26814,8 @@ async (params) => {
26703
26814
  async handleDomInspect(req, res) {
26704
26815
  const body = await this.readBody(req);
26705
26816
  const { x, y, selector, ideType } = body;
26706
- const cdp2 = this.getCdp(ideType);
26707
- if (!cdp2) {
26817
+ const cdp = this.getCdp(ideType);
26818
+ if (!cdp) {
26708
26819
  this.json(res, 503, { error: "No CDP connection" });
26709
26820
  return;
26710
26821
  }
@@ -26757,7 +26868,7 @@ async (params) => {
26757
26868
  return JSON.stringify({ element: info, ancestors: ancestors.reverse(), children });
26758
26869
  })()`;
26759
26870
  try {
26760
- const raw = await cdp2.evaluate(inspectScript, 1e4);
26871
+ const raw = await cdp.evaluate(inspectScript, 1e4);
26761
26872
  let result = raw;
26762
26873
  if (typeof raw === "string") {
26763
26874
  try {
@@ -26773,8 +26884,8 @@ async (params) => {
26773
26884
  async handleDomChildren(req, res) {
26774
26885
  const body = await this.readBody(req);
26775
26886
  const { selector, ideType } = body;
26776
- const cdp2 = this.getCdp(ideType);
26777
- if (!cdp2) {
26887
+ const cdp = this.getCdp(ideType);
26888
+ if (!cdp) {
26778
26889
  this.json(res, 503, { error: "No CDP connection" });
26779
26890
  return;
26780
26891
  }
@@ -26812,7 +26923,7 @@ async (params) => {
26812
26923
  return JSON.stringify({ selector: ${JSON.stringify(selector)}, childCount: el.children?.length||0, children });
26813
26924
  })()`;
26814
26925
  try {
26815
- const raw = await cdp2.evaluate(script, 1e4);
26926
+ const raw = await cdp.evaluate(script, 1e4);
26816
26927
  let result = raw;
26817
26928
  if (typeof raw === "string") {
26818
26929
  try {
@@ -26828,8 +26939,8 @@ async (params) => {
26828
26939
  async handleDomAnalyze(req, res) {
26829
26940
  const body = await this.readBody(req);
26830
26941
  const { ideType, selector, x, y } = body;
26831
- const cdp2 = this.getCdp(ideType);
26832
- if (!cdp2) {
26942
+ const cdp = this.getCdp(ideType);
26943
+ if (!cdp) {
26833
26944
  this.json(res, 503, { error: "No CDP connection" });
26834
26945
  return;
26835
26946
  }
@@ -26951,7 +27062,7 @@ async (params) => {
26951
27062
  return JSON.stringify(result);
26952
27063
  })()`;
26953
27064
  try {
26954
- const raw = await cdp2.evaluate(analyzeScript, 15e3);
27065
+ const raw = await cdp.evaluate(analyzeScript, 15e3);
26955
27066
  let result = raw;
26956
27067
  if (typeof raw === "string") {
26957
27068
  try {
@@ -26971,8 +27082,8 @@ async (params) => {
26971
27082
  this.json(res, 400, { error: "include[] is required" });
26972
27083
  return;
26973
27084
  }
26974
- const cdp2 = this.getCdp(ideType);
26975
- if (!cdp2) {
27085
+ const cdp = this.getCdp(ideType);
27086
+ if (!cdp) {
26976
27087
  this.json(res, 503, { error: "No CDP connection" });
26977
27088
  return;
26978
27089
  }
@@ -27160,7 +27271,7 @@ async (params) => {
27160
27271
  });
27161
27272
  })()`;
27162
27273
  try {
27163
- const raw = await cdp2.evaluate(script, 1e4);
27274
+ const raw = await cdp.evaluate(script, 1e4);
27164
27275
  let result = raw;
27165
27276
  if (typeof raw === "string") {
27166
27277
  try {
@@ -27180,8 +27291,8 @@ async (params) => {
27180
27291
  this.json(res, 400, { error: "text is required" });
27181
27292
  return;
27182
27293
  }
27183
- const cdp2 = this.getCdp(ideType);
27184
- if (!cdp2) {
27294
+ const cdp = this.getCdp(ideType);
27295
+ if (!cdp) {
27185
27296
  this.json(res, 503, { error: "No CDP connection" });
27186
27297
  return;
27187
27298
  }
@@ -27286,7 +27397,7 @@ async (params) => {
27286
27397
  return JSON.stringify({ query: ${JSON.stringify(text)}, matches, total: matches.length });
27287
27398
  })()`;
27288
27399
  try {
27289
- const raw = await cdp2.evaluate(script, 1e4);
27400
+ const raw = await cdp.evaluate(script, 1e4);
27290
27401
  let result = raw;
27291
27402
  if (typeof raw === "string") {
27292
27403
  try {
@@ -27303,20 +27414,20 @@ async (params) => {
27303
27414
  async handleDomContext(type, req, res) {
27304
27415
  const body = await this.readBody(req);
27305
27416
  const { ideType } = body;
27306
- const provider2 = this.providerLoader.resolve(type);
27307
- if (!provider2) {
27417
+ const provider = this.providerLoader.resolve(type);
27418
+ if (!provider) {
27308
27419
  this.json(res, 404, { error: `Provider not found: ${type}` });
27309
27420
  return;
27310
27421
  }
27311
- const cdp2 = this.getCdp(ideType || type);
27312
- if (!cdp2) {
27422
+ const cdp = this.getCdp(ideType || type);
27423
+ if (!cdp) {
27313
27424
  this.json(res, 503, { error: "No CDP connection available. Target IDE must be running with CDP enabled." });
27314
27425
  return;
27315
27426
  }
27316
27427
  try {
27317
27428
  let screenshot = null;
27318
27429
  try {
27319
- const buf = await cdp2.captureScreenshot();
27430
+ const buf = await cdp.captureScreenshot();
27320
27431
  if (buf) screenshot = buf.toString("base64");
27321
27432
  } catch {
27322
27433
  }
@@ -27417,7 +27528,7 @@ async (params) => {
27417
27528
 
27418
27529
  return JSON.stringify(result);
27419
27530
  })()`;
27420
- const raw = await cdp2.evaluate(domScript, 15e3);
27531
+ const raw = await cdp.evaluate(domScript, 15e3);
27421
27532
  let domSnapshot = {};
27422
27533
  if (typeof raw === "string") {
27423
27534
  try {
@@ -27429,8 +27540,8 @@ async (params) => {
27429
27540
  this.json(res, 200, {
27430
27541
  screenshot: screenshot ? `base64:${screenshot}` : null,
27431
27542
  domSnapshot,
27432
- pageTitle: await cdp2.evaluate("document.title", 3e3).catch(() => ""),
27433
- pageUrl: await cdp2.evaluate("window.location.href", 3e3).catch(() => ""),
27543
+ pageTitle: await cdp.evaluate("document.title", 3e3).catch(() => ""),
27544
+ pageUrl: await cdp.evaluate("window.location.href", 3e3).catch(() => ""),
27434
27545
  providerType: type,
27435
27546
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
27436
27547
  });
@@ -27450,8 +27561,8 @@ async (params) => {
27450
27561
  this.json(res, 409, { error: "Auto-implement already in progress", type: this.autoImplStatus.type });
27451
27562
  return;
27452
27563
  }
27453
- const provider2 = this.providerLoader.resolve(type);
27454
- if (!provider2) {
27564
+ const provider = this.providerLoader.resolve(type);
27565
+ if (!provider) {
27455
27566
  this.json(res, 404, { error: `Provider not found: ${type}` });
27456
27567
  return;
27457
27568
  }
@@ -27463,8 +27574,8 @@ async (params) => {
27463
27574
  try {
27464
27575
  this.sendAutoImplSSE({ event: "progress", data: { function: "_init", status: "analyzing", message: "DOM \uAD6C\uC870 \uC218\uC9D1 \uC911..." } });
27465
27576
  let domContext = null;
27466
- const cdp2 = this.getCdp(type);
27467
- if (cdp2) {
27577
+ const cdp = this.getCdp(type);
27578
+ if (cdp) {
27468
27579
  try {
27469
27580
  const domScript = `(() => {
27470
27581
  function fp(el) {
@@ -27499,7 +27610,7 @@ async (params) => {
27499
27610
  }));
27500
27611
  return JSON.stringify(r);
27501
27612
  })()`;
27502
- const raw = await cdp2.evaluate(domScript, 1e4);
27613
+ const raw = await cdp.evaluate(domScript, 1e4);
27503
27614
  domContext = typeof raw === "string" ? JSON.parse(raw) : raw;
27504
27615
  } catch (e) {
27505
27616
  this.log(`DOM context collection failed (non-fatal): ${e.message}`);
@@ -27532,7 +27643,7 @@ async (params) => {
27532
27643
  }
27533
27644
  }
27534
27645
  }
27535
- const prompt = this.buildAutoImplPrompt(type, provider2, providerDir, functions, domContext, referenceScripts);
27646
+ const prompt = this.buildAutoImplPrompt(type, provider, providerDir, functions, domContext, referenceScripts);
27536
27647
  const tmpDir = path12.join(os14.tmpdir(), "adhdev-autoimpl");
27537
27648
  if (!fs9.existsSync(tmpDir)) fs9.mkdirSync(tmpDir, { recursive: true });
27538
27649
  const promptFile = path12.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
@@ -27779,12 +27890,12 @@ async (params) => {
27779
27890
  this.json(res, 500, { error: `Auto-implement failed: ${e.message}` });
27780
27891
  }
27781
27892
  }
27782
- buildAutoImplPrompt(type, provider2, providerDir, functions, domContext, referenceScripts) {
27893
+ buildAutoImplPrompt(type, provider, providerDir, functions, domContext, referenceScripts) {
27783
27894
  const lines = [];
27784
27895
  lines.push("You are implementing browser automation scripts for an IDE provider.");
27785
27896
  lines.push("Be concise. Do NOT explain your reasoning. Just edit files directly.");
27786
27897
  lines.push("");
27787
- lines.push(`# Target: ${provider2.name || type} (${type})`);
27898
+ lines.push(`# Target: ${provider.name || type} (${type})`);
27788
27899
  lines.push(`Provider directory: \`${providerDir}\``);
27789
27900
  lines.push("");
27790
27901
  lines.push("## Current Target Files");
@@ -27985,11 +28096,11 @@ data: ${JSON.stringify(msg.data)}
27985
28096
  /** Get CDP manager — matching IDE when ideType specified, first connected one otherwise */
27986
28097
  getCdp(ideType) {
27987
28098
  if (ideType) {
27988
- const cdp2 = this.cdpManagers.get(ideType);
27989
- if (cdp2?.isConnected) return cdp2;
28099
+ const cdp = this.cdpManagers.get(ideType);
28100
+ if (cdp?.isConnected) return cdp;
27990
28101
  }
27991
- for (const cdp2 of this.cdpManagers.values()) {
27992
- if (cdp2.isConnected) return cdp2;
28102
+ for (const cdp of this.cdpManagers.values()) {
28103
+ if (cdp.isConnected) return cdp;
27993
28104
  }
27994
28105
  return null;
27995
28106
  }
@@ -28013,6 +28124,251 @@ data: ${JSON.stringify(msg.data)}
28013
28124
  });
28014
28125
  });
28015
28126
  }
28127
+ // ─── CLI Debug Handlers ──────────────────────────────
28128
+ /** GET /api/cli/status — list all running CLI/ACP instances with state */
28129
+ async handleCliStatus(_req, res) {
28130
+ if (!this.instanceManager) {
28131
+ this.json(res, 503, { error: "InstanceManager not available (daemon not fully initialized)" });
28132
+ return;
28133
+ }
28134
+ const allStates = this.instanceManager.collectAllStates();
28135
+ const cliStates = allStates.filter((s) => s.category === "cli" || s.category === "acp");
28136
+ const result = cliStates.map((s) => ({
28137
+ instanceId: s.instanceId,
28138
+ type: s.type,
28139
+ name: s.name,
28140
+ category: s.category,
28141
+ status: s.status,
28142
+ mode: s.mode,
28143
+ workspace: s.workspace,
28144
+ messageCount: s.activeChat?.messages?.length || 0,
28145
+ lastMessage: s.activeChat?.messages?.slice(-1)[0] || null,
28146
+ activeModal: s.activeChat?.activeModal || null,
28147
+ pendingEvents: s.pendingEvents || [],
28148
+ currentModel: s.currentModel,
28149
+ settings: s.settings
28150
+ }));
28151
+ this.json(res, 200, { instances: result, count: result.length });
28152
+ }
28153
+ /** POST /api/cli/launch — launch a CLI agent { type, workingDir?, args? } */
28154
+ async handleCliLaunch(req, res) {
28155
+ if (!this.cliManager) {
28156
+ this.json(res, 503, { error: "CliManager not available" });
28157
+ return;
28158
+ }
28159
+ const body = await this.readBody(req);
28160
+ const { type, workingDir, args } = body;
28161
+ if (!type) {
28162
+ this.json(res, 400, { error: "type required (e.g. claude-cli, gemini-cli)" });
28163
+ return;
28164
+ }
28165
+ try {
28166
+ await this.cliManager.startSession(type, workingDir || process.cwd(), args || []);
28167
+ this.json(res, 200, { launched: true, type, workspace: workingDir || process.cwd() });
28168
+ } catch (e) {
28169
+ this.json(res, 500, { error: `Launch failed: ${e.message}` });
28170
+ }
28171
+ }
28172
+ /** POST /api/cli/send — send message to a running CLI { type, text } */
28173
+ async handleCliSend(req, res) {
28174
+ if (!this.instanceManager) {
28175
+ this.json(res, 503, { error: "InstanceManager not available" });
28176
+ return;
28177
+ }
28178
+ const body = await this.readBody(req);
28179
+ const { type, text, instanceId } = body;
28180
+ if (!text) {
28181
+ this.json(res, 400, { error: "text required" });
28182
+ return;
28183
+ }
28184
+ const allStates = this.instanceManager.collectAllStates();
28185
+ const target = allStates.find(
28186
+ (s) => (s.category === "cli" || s.category === "acp") && (instanceId ? s.instanceId === instanceId : s.type === type)
28187
+ );
28188
+ if (!target) {
28189
+ this.json(res, 404, { error: `No running instance found for: ${type || instanceId}` });
28190
+ return;
28191
+ }
28192
+ try {
28193
+ this.instanceManager.sendEvent(target.instanceId, "send_message", { text });
28194
+ this.json(res, 200, { sent: true, type: target.type, instanceId: target.instanceId });
28195
+ } catch (e) {
28196
+ this.json(res, 500, { error: `Send failed: ${e.message}` });
28197
+ }
28198
+ }
28199
+ /** POST /api/cli/stop — stop a running CLI { type } */
28200
+ async handleCliStop(req, res) {
28201
+ if (!this.instanceManager) {
28202
+ this.json(res, 503, { error: "InstanceManager not available" });
28203
+ return;
28204
+ }
28205
+ const body = await this.readBody(req);
28206
+ const { type, instanceId } = body;
28207
+ const allStates = this.instanceManager.collectAllStates();
28208
+ const target = allStates.find(
28209
+ (s) => (s.category === "cli" || s.category === "acp") && (instanceId ? s.instanceId === instanceId : s.type === type)
28210
+ );
28211
+ if (!target) {
28212
+ this.json(res, 404, { error: `No running instance found for: ${type || instanceId}` });
28213
+ return;
28214
+ }
28215
+ try {
28216
+ this.instanceManager.removeInstance(target.instanceId);
28217
+ this.json(res, 200, { stopped: true, type: target.type, instanceId: target.instanceId });
28218
+ } catch (e) {
28219
+ this.json(res, 500, { error: `Stop failed: ${e.message}` });
28220
+ }
28221
+ }
28222
+ /** GET /api/cli/events — SSE stream of CLI status events */
28223
+ handleCliSSE(_req, res) {
28224
+ res.writeHead(200, {
28225
+ "Content-Type": "text/event-stream",
28226
+ "Cache-Control": "no-cache",
28227
+ "Connection": "keep-alive",
28228
+ "Access-Control-Allow-Origin": "*"
28229
+ });
28230
+ res.write('data: {"type":"connected"}\n\n');
28231
+ this.cliSSEClients.push(res);
28232
+ if (this.cliSSEClients.length === 1 && this.instanceManager) {
28233
+ this.instanceManager.onEvent((event) => {
28234
+ this.sendCliSSE(event);
28235
+ });
28236
+ }
28237
+ if (this.instanceManager) {
28238
+ const allStates = this.instanceManager.collectAllStates();
28239
+ const cliStates = allStates.filter((s) => s.category === "cli" || s.category === "acp");
28240
+ for (const s of cliStates) {
28241
+ this.sendCliSSE({ event: "snapshot", providerType: s.type, status: s.status, instanceId: s.instanceId });
28242
+ }
28243
+ }
28244
+ _req.on("close", () => {
28245
+ this.cliSSEClients = this.cliSSEClients.filter((c) => c !== res);
28246
+ });
28247
+ }
28248
+ sendCliSSE(data) {
28249
+ const msg = `data: ${JSON.stringify({ ...data, timestamp: Date.now() })}
28250
+
28251
+ `;
28252
+ for (const client of this.cliSSEClients) {
28253
+ try {
28254
+ client.write(msg);
28255
+ } catch {
28256
+ }
28257
+ }
28258
+ }
28259
+ /** GET /api/cli/debug/:type — full internal debug state of a CLI adapter */
28260
+ async handleCliDebug(type, _req, res) {
28261
+ if (!this.instanceManager) {
28262
+ this.json(res, 503, { error: "InstanceManager not available" });
28263
+ return;
28264
+ }
28265
+ const allStates = this.instanceManager.collectAllStates();
28266
+ const target = allStates.find(
28267
+ (s) => (s.category === "cli" || s.category === "acp") && s.type === type
28268
+ );
28269
+ if (!target) {
28270
+ this.json(res, 404, { error: `No running instance for: ${type}`, available: allStates.filter((s) => s.category === "cli" || s.category === "acp").map((s) => s.type) });
28271
+ return;
28272
+ }
28273
+ const instance = this.instanceManager.getInstance(target.instanceId);
28274
+ if (!instance) {
28275
+ this.json(res, 404, { error: `Instance not found: ${target.instanceId}` });
28276
+ return;
28277
+ }
28278
+ try {
28279
+ const adapter = instance.getAdapter?.() || instance.adapter;
28280
+ if (adapter && typeof adapter.getDebugState === "function") {
28281
+ const debugState = adapter.getDebugState();
28282
+ this.json(res, 200, {
28283
+ instanceId: target.instanceId,
28284
+ providerState: {
28285
+ type: target.type,
28286
+ name: target.name,
28287
+ status: target.status,
28288
+ mode: "mode" in target ? target.mode : void 0
28289
+ },
28290
+ debug: debugState
28291
+ });
28292
+ } else {
28293
+ this.json(res, 200, {
28294
+ instanceId: target.instanceId,
28295
+ providerState: target,
28296
+ debug: null,
28297
+ message: "No debug state available (adapter.getDebugState not found)"
28298
+ });
28299
+ }
28300
+ } catch (e) {
28301
+ this.json(res, 500, { error: `Debug state failed: ${e.message}` });
28302
+ }
28303
+ }
28304
+ /** POST /api/cli/resolve — resolve an approval modal { type, buttonIndex } */
28305
+ async handleCliResolve(req, res) {
28306
+ const body = await this.readBody(req);
28307
+ const { type, buttonIndex, instanceId } = body;
28308
+ if (buttonIndex === void 0 || buttonIndex === null) {
28309
+ this.json(res, 400, { error: "buttonIndex required (0=Yes, 1=Always, 2=Deny)" });
28310
+ return;
28311
+ }
28312
+ if (!this.cliManager) {
28313
+ this.json(res, 503, { error: "CliManager not available" });
28314
+ return;
28315
+ }
28316
+ let adapter = null;
28317
+ for (const [, a] of this.cliManager.adapters) {
28318
+ if (type && a.cliType === type) {
28319
+ adapter = a;
28320
+ break;
28321
+ }
28322
+ }
28323
+ if (!adapter) {
28324
+ this.json(res, 404, { error: `No running adapter for: ${type || instanceId}` });
28325
+ return;
28326
+ }
28327
+ try {
28328
+ if (typeof adapter.resolveModal === "function") {
28329
+ adapter.resolveModal(buttonIndex);
28330
+ this.json(res, 200, { resolved: true, type, buttonIndex });
28331
+ } else {
28332
+ this.json(res, 400, { error: "resolveModal not available on this adapter" });
28333
+ }
28334
+ } catch (e) {
28335
+ this.json(res, 500, { error: `Resolve failed: ${e.message}` });
28336
+ }
28337
+ }
28338
+ /** POST /api/cli/raw — send raw keystrokes to PTY { type, keys } */
28339
+ async handleCliRaw(req, res) {
28340
+ const body = await this.readBody(req);
28341
+ const { type, keys, instanceId } = body;
28342
+ if (!keys) {
28343
+ this.json(res, 400, { error: "keys required (raw string to send to PTY)" });
28344
+ return;
28345
+ }
28346
+ if (!this.cliManager) {
28347
+ this.json(res, 503, { error: "CliManager not available" });
28348
+ return;
28349
+ }
28350
+ let adapter = null;
28351
+ for (const [, a] of this.cliManager.adapters) {
28352
+ if (type && a.cliType === type) {
28353
+ adapter = a;
28354
+ break;
28355
+ }
28356
+ }
28357
+ if (!adapter) {
28358
+ this.json(res, 404, { error: `No running adapter for: ${type || instanceId}` });
28359
+ return;
28360
+ }
28361
+ try {
28362
+ if (typeof adapter.writeRaw === "function") {
28363
+ adapter.writeRaw(keys);
28364
+ this.json(res, 200, { sent: true, type, keysLength: keys.length });
28365
+ } else {
28366
+ this.json(res, 400, { error: "writeRaw not available on this adapter" });
28367
+ }
28368
+ } catch (e) {
28369
+ this.json(res, 500, { error: `Raw send failed: ${e.message}` });
28370
+ }
28371
+ }
28016
28372
  };
28017
28373
  var import_child_process8 = require("child_process");
28018
28374
  var EXTENSION_CATALOG = [
@@ -28208,7 +28564,7 @@ data: ${JSON.stringify(msg.data)}
28208
28564
  getInstanceManager: () => instanceManager
28209
28565
  }, providerLoader);
28210
28566
  LOG5.info("Init", "Detecting IDEs...");
28211
- detectedIdesRef.value = await detectIDEs3();
28567
+ detectedIdesRef.value = await detectIDEs2();
28212
28568
  const installed = detectedIdesRef.value.filter((i) => i.installed);
28213
28569
  LOG5.info("Init", `Found ${installed.length} IDE(s): ${installed.map((i) => i.id).join(", ") || "none"}`);
28214
28570
  const cdpSetupContext = {
@@ -28220,7 +28576,7 @@ data: ${JSON.stringify(msg.data)}
28220
28576
  const cdpInitializer = new DaemonCdpInitializer({
28221
28577
  providerLoader,
28222
28578
  cdpManagers,
28223
- enabledIdes: config2.enabledIdes || loadConfig4().enabledIdes || void 0,
28579
+ enabledIdes: config2.enabledIdes || loadConfig3().enabledIdes || void 0,
28224
28580
  onConnected: async (ideType, manager, managerKey) => {
28225
28581
  await setupIdeInstance(cdpSetupContext, { ideType, manager, managerKey });
28226
28582
  await config2.onCdpManagerSetup?.(ideType, manager, managerKey);
@@ -28357,7 +28713,8 @@ var init_server_connection = __esm({
28357
28713
  this.ws = new import_ws.default(fullUrl, {
28358
28714
  headers: {
28359
28715
  "X-ADHDev-Token": this.options.token,
28360
- "X-ADHDev-IDE": JSON.stringify(this.options.cliInfo)
28716
+ "X-ADHDev-IDE": JSON.stringify(this.options.cliInfo),
28717
+ "X-ADHDev-Version": this.options.daemonVersion || "unknown"
28361
28718
  }
28362
28719
  });
28363
28720
  this.ws.on("open", () => this.onOpen());
@@ -28455,6 +28812,19 @@ var init_server_connection = __esm({
28455
28812
  import_daemon_core.LOG.error("Server", `Auth failed: ${message.payload.reason}`);
28456
28813
  this.setState("error");
28457
28814
  return;
28815
+ } else if (message.type === "version_mismatch") {
28816
+ const p = message.payload;
28817
+ import_daemon_core.LOG.info("Server", `
28818
+ \u{1F504} Update available: v${p.current} \u2192 v${p.latest}`);
28819
+ import_daemon_core.LOG.info("Server", ` Run: adhdev daemon:upgrade
28820
+ `);
28821
+ } else if (message.type === "force_update_required") {
28822
+ const p = message.payload;
28823
+ import_daemon_core.LOG.error("Server", `
28824
+ \u26D4 Daemon v${this.options.daemonVersion} is no longer compatible.`);
28825
+ import_daemon_core.LOG.error("Server", ` Minimum required: v${p.minVersion}`);
28826
+ import_daemon_core.LOG.error("Server", ` Run: adhdev daemon:upgrade
28827
+ `);
28458
28828
  }
28459
28829
  const handlers = this.messageHandlers.get(message.type);
28460
28830
  if (handlers) {
@@ -29376,7 +29746,7 @@ var init_screenshot_controller = __esm({
29376
29746
  if (!this.deps.isRunning()) return;
29377
29747
  const active = this.deps.isScreenshotActive();
29378
29748
  const ssIdeType = this.deps.getScreenshotIdeType();
29379
- const cdp2 = this.deps.getCdp(ssIdeType);
29749
+ const cdp = this.deps.getCdp(ssIdeType);
29380
29750
  const isRelay = this.deps.isUsingRelay();
29381
29751
  const profile = isRelay ? this.profileRelay : this.profileDirect;
29382
29752
  this.checkBudgetReset();
@@ -29392,7 +29762,7 @@ var init_screenshot_controller = __esm({
29392
29762
  import_daemon_core3.LOG.info("Screenshot", `Daily budget exhausted: ${usedMin}/${this.dailyBudgetMinutes}min \u2014 pausing until midnight UTC`);
29393
29763
  }
29394
29764
  }
29395
- if (!active || !cdp2 || this.budgetExhausted) {
29765
+ if (!active || !cdp || this.budgetExhausted) {
29396
29766
  this.staticFrameCount = 0;
29397
29767
  this.currentInterval = profile.maxInterval;
29398
29768
  if (!active) this.lastActiveTimestamp = 0;
@@ -29401,7 +29771,7 @@ var init_screenshot_controller = __esm({
29401
29771
  }
29402
29772
  this.debugCount++;
29403
29773
  try {
29404
- const buf = await cdp2.captureScreenshot({ quality: profile.quality });
29774
+ const buf = await cdp.captureScreenshot({ quality: profile.quality });
29405
29775
  if (buf) {
29406
29776
  const hash2 = _ScreenshotController.fnvHash(buf);
29407
29777
  const sizeMatch = buf.length === this.lastSize;
@@ -29631,6 +30001,7 @@ var init_adhdev_daemon = __esm({
29631
30001
  this.serverConn = new ServerConnection({
29632
30002
  serverUrl: options.serverUrl || config2.serverUrl,
29633
30003
  token: config2.connectionToken,
30004
+ daemonVersion: pkgVersion,
29634
30005
  cliInfo: {
29635
30006
  type: "adhdev-daemon",
29636
30007
  version: pkgVersion,
@@ -29716,6 +30087,7 @@ var init_adhdev_daemon = __esm({
29716
30087
  adapters: this.components.cliManager.adapters,
29717
30088
  detectedIdes: this.components.detectedIdes.value,
29718
30089
  ideType: this.ideType,
30090
+ daemonVersion: pkgVersion,
29719
30091
  instanceManager: this.components.instanceManager
29720
30092
  });
29721
30093
  this.statusReporter.startReporting();
@@ -29726,7 +30098,12 @@ var init_adhdev_daemon = __esm({
29726
30098
  process.on("SIGINT", () => this.stop());
29727
30099
  process.on("SIGTERM", () => this.stop());
29728
30100
  if (options.dev) {
29729
- const devServer = new import_daemon_core4.DevServer({ providerLoader: this.components.providerLoader, cdpManagers: this.components.cdpManagers });
30101
+ const devServer = new import_daemon_core4.DevServer({
30102
+ providerLoader: this.components.providerLoader,
30103
+ cdpManagers: this.components.cdpManagers,
30104
+ instanceManager: this.components.instanceManager,
30105
+ cliManager: this.components.cliManager
30106
+ });
29730
30107
  await devServer.start();
29731
30108
  }
29732
30109
  this.printBanner(options, config2.serverUrl);
@@ -29977,24 +30354,11 @@ var init_adhdev_daemon = __esm({
29977
30354
  }
29978
30355
  });
29979
30356
 
29980
- // src/cli-entrypoint.ts
29981
- var import_commander = require("commander");
29982
- var import_chalk3 = __toESM(require("chalk"));
29983
-
29984
30357
  // src/wizard.ts
29985
- var import_chalk2 = __toESM(require("chalk"));
29986
- var import_inquirer = __toESM(require("inquirer"));
29987
- var import_ora = __toESM(require("ora"));
29988
- var import_open = __toESM(require("open"));
29989
- var import_daemon_core5 = __toESM(require_dist());
29990
- var SERVER_URL = process.env.ADHDEV_SERVER_URL || "https://api.adhf.dev";
29991
- var LOGO = `
29992
- ${import_chalk2.default.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}
29993
- ${import_chalk2.default.cyan("\u2551")} ${import_chalk2.default.bold.white("\u{1F9A6} ADHDev Setup Wizard")} ${import_chalk2.default.cyan("\u2551")}
29994
- ${import_chalk2.default.cyan("\u2551")} ${import_chalk2.default.gray("Agent Dashboard Hub for Dev")} ${import_chalk2.default.cyan("\u2551")}
29995
- ${import_chalk2.default.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}
29996
- `;
29997
- var DIVIDER = import_chalk2.default.gray("\u2500".repeat(44));
30358
+ var wizard_exports = {};
30359
+ __export(wizard_exports, {
30360
+ runWizard: () => runWizard
30361
+ });
29998
30362
  async function runWizard(options = {}) {
29999
30363
  const loader = new import_daemon_core5.ProviderLoader({ logFn: () => {
30000
30364
  } });
@@ -30069,54 +30433,56 @@ async function quickSetup() {
30069
30433
  console.log(import_chalk2.default.bold("\n\u{1F680} Quick Setup\n"));
30070
30434
  const spinner = (0, import_ora.default)("Detecting installed IDEs...").start();
30071
30435
  const ides = await (0, import_daemon_core5.detectIDEs)();
30072
- const installedIDEs = ides.filter((i) => i.installed && i.cliCommand);
30436
+ const installedIDEs = ides.filter((i) => i.installed);
30073
30437
  spinner.stop();
30438
+ let selectedIDEs = [];
30074
30439
  if (installedIDEs.length === 0) {
30075
- console.log(import_chalk2.default.red("\u2717 No supported IDE with CLI found."));
30440
+ console.log(import_chalk2.default.yellow("\u26A0 No supported IDEs auto-detected."));
30441
+ console.log(import_chalk2.default.gray(" This is fine \u2014 the daemon will detect IDEs at runtime via CDP."));
30076
30442
  console.log(import_chalk2.default.gray(" Supported: VS Code, Cursor, Antigravity, Windsurf, VSCodium"));
30077
- return;
30078
- }
30079
- console.log(import_chalk2.default.green(`Found ${installedIDEs.length} IDE(s):
30443
+ console.log();
30444
+ } else {
30445
+ console.log(import_chalk2.default.green(`Found ${installedIDEs.length} IDE(s):
30080
30446
  `));
30081
- installedIDEs.forEach((ide) => {
30082
- const version2 = ide.version ? import_chalk2.default.gray(` v${ide.version}`) : "";
30083
- console.log(` ${import_chalk2.default.green("\u2713")} ${ide.icon} ${import_chalk2.default.bold(ide.displayName)}${version2}`);
30084
- });
30085
- console.log();
30086
- let selectedIDEs;
30087
- if (installedIDEs.length === 1) {
30088
- selectedIDEs = installedIDEs;
30089
- console.log(import_chalk2.default.gray(` Auto-selected: ${installedIDEs[0].displayName}
30447
+ installedIDEs.forEach((ide) => {
30448
+ const version2 = ide.version ? import_chalk2.default.gray(` v${ide.version}`) : "";
30449
+ console.log(` ${import_chalk2.default.green("\u2713")} ${ide.icon} ${import_chalk2.default.bold(ide.displayName)}${version2}`);
30450
+ });
30451
+ console.log();
30452
+ if (installedIDEs.length === 1) {
30453
+ selectedIDEs = installedIDEs;
30454
+ console.log(import_chalk2.default.gray(` Auto-selected: ${installedIDEs[0].displayName}
30090
30455
  `));
30091
- } else {
30092
- const { selectedIdeIds } = await import_inquirer.default.prompt([
30093
- {
30094
- type: "checkbox",
30095
- name: "selectedIdeIds",
30096
- message: "Select IDEs to set up (Space to toggle, Enter to confirm):",
30097
- choices: installedIDEs.map((ide) => ({
30098
- name: `${ide.icon} ${ide.displayName}${ide.version ? import_chalk2.default.gray(` v${ide.version}`) : ""}`,
30099
- value: ide.id,
30100
- checked: true
30101
- // All selected by default
30102
- })),
30103
- validate: (input) => input.length > 0 ? true : "Select at least one IDE"
30104
- }
30105
- ]);
30106
- selectedIDEs = installedIDEs.filter((i) => selectedIdeIds.includes(i.id));
30456
+ } else {
30457
+ const { selectedIdeIds } = await import_inquirer.default.prompt([
30458
+ {
30459
+ type: "checkbox",
30460
+ name: "selectedIdeIds",
30461
+ message: "Select IDEs to set up (Space to toggle, Enter to confirm):",
30462
+ choices: installedIDEs.map((ide) => ({
30463
+ name: `${ide.icon} ${ide.displayName}${ide.version ? import_chalk2.default.gray(` v${ide.version}`) : ""}`,
30464
+ value: ide.id,
30465
+ checked: true
30466
+ // All selected by default
30467
+ })),
30468
+ validate: (input) => input.length > 0 ? true : "Select at least one IDE"
30469
+ }
30470
+ ]);
30471
+ selectedIDEs = installedIDEs.filter((i) => selectedIdeIds.includes(i.id));
30472
+ }
30107
30473
  }
30108
30474
  console.log(DIVIDER);
30109
30475
  const loginResult = await loginFlow();
30110
30476
  if (!loginResult) {
30111
30477
  console.log(import_chalk2.default.yellow("\u26A0 Setup completed without login. You can login later with `adhdev setup`."));
30112
30478
  }
30113
- if (loginResult?.connectionToken) {
30479
+ if (loginResult?.connectionToken && selectedIDEs.length > 0) {
30114
30480
  for (const ide of selectedIDEs) {
30115
30481
  await injectTokenToIDE(ide, loginResult.connectionToken);
30116
30482
  }
30117
30483
  }
30118
30484
  const ideIds = selectedIDEs.map((i) => i.id);
30119
- (0, import_daemon_core5.markSetupComplete)(ideIds, ["adhdev"]);
30485
+ (0, import_daemon_core5.markSetupComplete)(ideIds.length > 0 ? ideIds : ["daemon-only"], ["adhdev"]);
30120
30486
  if (loginResult) {
30121
30487
  (0, import_daemon_core5.updateConfig)({
30122
30488
  connectionToken: loginResult.connectionToken,
@@ -30126,10 +30492,14 @@ async function quickSetup() {
30126
30492
  }
30127
30493
  console.log(DIVIDER);
30128
30494
  console.log(import_chalk2.default.bold("\n\u{1F389} Setup Complete!\n"));
30129
- if (selectedIDEs.length === 1) {
30130
- console.log(` ${import_chalk2.default.bold("IDE:")} ${selectedIDEs[0].icon} ${selectedIDEs[0].displayName}`);
30495
+ if (selectedIDEs.length > 0) {
30496
+ if (selectedIDEs.length === 1) {
30497
+ console.log(` ${import_chalk2.default.bold("IDE:")} ${selectedIDEs[0].icon} ${selectedIDEs[0].displayName}`);
30498
+ } else {
30499
+ console.log(` ${import_chalk2.default.bold("IDEs:")} ${selectedIDEs.map((i) => `${i.icon} ${i.displayName}`).join(", ")}`);
30500
+ }
30131
30501
  } else {
30132
- console.log(` ${import_chalk2.default.bold("IDEs:")} ${selectedIDEs.map((i) => `${i.icon} ${i.displayName}`).join(", ")}`);
30502
+ console.log(` ${import_chalk2.default.bold("IDEs:")} ${import_chalk2.default.gray("None detected (daemon will auto-detect at runtime)")}`);
30133
30503
  }
30134
30504
  console.log(` ${import_chalk2.default.bold("User:")} ${loginResult?.email || "not logged in"}`);
30135
30505
  console.log(` ${import_chalk2.default.bold("Status:")} ${import_chalk2.default.green("Ready to connect")}`);
@@ -30152,7 +30522,26 @@ async function customSetup() {
30152
30522
  const installedIDEs = ides.filter((i) => i.installed);
30153
30523
  spinner.stop();
30154
30524
  if (installedIDEs.length === 0) {
30155
- console.log(import_chalk2.default.yellow("\u26A0 No supported IDEs found."));
30525
+ console.log(import_chalk2.default.yellow("\u26A0 No supported IDEs auto-detected."));
30526
+ console.log(import_chalk2.default.gray(" The daemon will detect IDEs at runtime via CDP."));
30527
+ console.log();
30528
+ console.log(DIVIDER);
30529
+ const loginResult2 = await loginFlow();
30530
+ (0, import_daemon_core5.markSetupComplete)(["daemon-only"], ["adhdev"]);
30531
+ if (loginResult2) {
30532
+ (0, import_daemon_core5.updateConfig)({
30533
+ connectionToken: loginResult2.connectionToken,
30534
+ userEmail: loginResult2.email,
30535
+ userName: loginResult2.name
30536
+ });
30537
+ }
30538
+ console.log(DIVIDER);
30539
+ console.log(import_chalk2.default.bold("\n\u{1F389} Setup Complete!\n"));
30540
+ console.log(` ${import_chalk2.default.bold("IDEs:")} ${import_chalk2.default.gray("None detected (daemon will auto-detect at runtime)")}`);
30541
+ console.log(` ${import_chalk2.default.bold("User:")} ${loginResult2?.email || "not logged in"}`);
30542
+ console.log(` ${import_chalk2.default.bold("Status:")} ${import_chalk2.default.green("Ready to connect")}`);
30543
+ console.log();
30544
+ await startDaemonFlow();
30156
30545
  return;
30157
30546
  }
30158
30547
  console.log(import_chalk2.default.green(`Found ${installedIDEs.length} IDE(s):
@@ -30484,418 +30873,352 @@ async function installCliOnly() {
30484
30873
  console.log();
30485
30874
  }
30486
30875
  }
30876
+ var import_chalk2, import_inquirer, import_ora, import_open, import_daemon_core5, SERVER_URL, LOGO, DIVIDER;
30877
+ var init_wizard = __esm({
30878
+ "src/wizard.ts"() {
30879
+ "use strict";
30880
+ import_chalk2 = __toESM(require("chalk"));
30881
+ import_inquirer = __toESM(require("inquirer"));
30882
+ import_ora = __toESM(require("ora"));
30883
+ import_open = __toESM(require("open"));
30884
+ import_daemon_core5 = __toESM(require_dist());
30885
+ SERVER_URL = process.env.ADHDEV_SERVER_URL || "https://api.adhf.dev";
30886
+ LOGO = `
30887
+ ${import_chalk2.default.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}
30888
+ ${import_chalk2.default.cyan("\u2551")} ${import_chalk2.default.bold.white("\u{1F9A6} ADHDev Setup Wizard")} ${import_chalk2.default.cyan("\u2551")}
30889
+ ${import_chalk2.default.cyan("\u2551")} ${import_chalk2.default.gray("Agent Dashboard Hub for Dev")} ${import_chalk2.default.cyan("\u2551")}
30890
+ ${import_chalk2.default.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}
30891
+ `;
30892
+ DIVIDER = import_chalk2.default.gray("\u2500".repeat(44));
30893
+ }
30894
+ });
30487
30895
 
30488
- // src/cli-entrypoint.ts
30489
- var import_daemon_core6 = __toESM(require_dist());
30896
+ // src/cli/index.ts
30897
+ var import_commander = require("commander");
30898
+ var import_chalk6 = __toESM(require("chalk"));
30490
30899
  var import_fs = require("fs");
30491
30900
  var import_path = require("path");
30492
- var pkgVersion2 = "unknown";
30493
- try {
30494
- const possiblePaths = [
30495
- (0, import_path.join)(__dirname, "..", "package.json"),
30496
- (0, import_path.join)(__dirname, "package.json")
30497
- ];
30498
- for (const p of possiblePaths) {
30499
- try {
30500
- const data = JSON.parse((0, import_fs.readFileSync)(p, "utf-8"));
30501
- if (data.version) {
30502
- pkgVersion2 = data.version;
30503
- break;
30504
- }
30505
- } catch {
30506
- }
30507
- }
30508
- } catch {
30509
- }
30510
- var _cliProviderLoader = new import_daemon_core6.ProviderLoader({ logFn: () => {
30511
- } });
30512
- _cliProviderLoader.loadAll();
30513
- _cliProviderLoader.registerToDetector();
30514
- var program = new import_commander.Command();
30515
- program.name("adhdev").description("\u{1F9A6} ADHDev \u2014 Agent Dashboard Hub for Dev").version(pkgVersion2);
30516
- program.command("setup").description("Run the interactive setup wizard (detect IDEs, login)").option("-f, --force", "Force re-run setup even if already configured").action(async (options) => {
30517
- await runWizard({ force: options.force });
30518
- });
30519
- program.command("launch [target]").description("Launch IDE with CDP or start CLI agent (e.g. cursor, gemini, claude)").option("-w, --workspace <path>", "Workspace directory to open").option("-n, --new-window", "Open in a new window").option("-d, --dir <path>", "Working directory for CLI agent", process.cwd()).action(async (targetArg, options) => {
30520
- const resolvedType = targetArg ? _cliProviderLoader.resolveAlias(targetArg.toLowerCase()) : null;
30521
- const resolvedProvider = resolvedType ? _cliProviderLoader.get(resolvedType) : null;
30522
- const cliType = resolvedProvider && (resolvedProvider.category === "cli" || resolvedProvider.category === "acp") ? resolvedType : null;
30523
- if (cliType) {
30524
- const workingDir = options.dir || options.workspace || process.cwd();
30525
- const ora3 = await import("ora");
30526
- const spinner2 = ora3.default(`Launching ${targetArg}...`).start();
30527
- try {
30528
- const { isDaemonRunning: isDaemonRunning2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
30529
- if (isDaemonRunning2()) {
30530
- const result = await sendDaemonCommand("launch_cli", {
30531
- cliType,
30532
- dir: require("path").resolve(workingDir)
30533
- });
30534
- spinner2.stop();
30535
- if (result?.error) {
30536
- console.log(import_chalk3.default.red(`
30537
- \u2717 ${result.error}
30901
+ var import_daemon_core6 = __toESM(require_dist());
30902
+
30903
+ // src/cli/setup-commands.ts
30904
+ var import_chalk3 = __toESM(require("chalk"));
30905
+ function registerSetupCommands(program2, providerLoader) {
30906
+ program2.command("setup").description("Run the interactive setup wizard (detect IDEs, login)").option("-f, --force", "Force re-run setup even if already configured").action(async (options) => {
30907
+ const { runWizard: runWizard2 } = await Promise.resolve().then(() => (init_wizard(), wizard_exports));
30908
+ await runWizard2({ force: options.force });
30909
+ });
30910
+ program2.command("launch [target]").description("Launch IDE with CDP or start CLI agent (e.g. cursor, gemini, claude)").option("-w, --workspace <path>", "Workspace directory to open").option("-n, --new-window", "Open in a new window").option("-d, --dir <path>", "Working directory for CLI agent", process.cwd()).action(async (targetArg, options) => {
30911
+ const {
30912
+ detectIDEs: detectIDEs2,
30913
+ detectCLIs,
30914
+ launchWithCdp
30915
+ } = await Promise.resolve().then(() => __toESM(require_dist()));
30916
+ const resolvedType = targetArg ? providerLoader.resolveAlias(targetArg.toLowerCase()) : null;
30917
+ const resolvedProvider = resolvedType ? providerLoader.get(resolvedType) : null;
30918
+ const cliType = resolvedProvider && (resolvedProvider.category === "cli" || resolvedProvider.category === "acp") ? resolvedType : null;
30919
+ if (cliType) {
30920
+ const workingDir = options.dir || options.workspace || process.cwd();
30921
+ const ora3 = await import("ora");
30922
+ const spinner2 = ora3.default(`Launching ${targetArg}...`).start();
30923
+ try {
30924
+ const { isDaemonRunning: isDaemonRunning2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
30925
+ if (isDaemonRunning2()) {
30926
+ const devServerPort = 19280;
30927
+ const body = JSON.stringify({
30928
+ type: cliType,
30929
+ workingDir: require("path").resolve(workingDir)
30930
+ });
30931
+ const res = await fetch(`http://127.0.0.1:${devServerPort}/api/cli/launch`, {
30932
+ method: "POST",
30933
+ headers: { "Content-Type": "application/json" },
30934
+ body
30935
+ });
30936
+ const result = await res.json();
30937
+ spinner2.stop();
30938
+ if (!result?.launched) {
30939
+ console.log(import_chalk3.default.red(`
30940
+ \u2717 ${result?.error || "Launch failed"}
30941
+ `));
30942
+ process.exit(1);
30943
+ }
30944
+ console.log();
30945
+ console.log(import_chalk3.default.bold(` \u{1F680} CLI Agent Launched
30946
+ `));
30947
+ console.log(` ${import_chalk3.default.bold("Agent:")} ${targetArg} (${cliType})`);
30948
+ console.log(` ${import_chalk3.default.bold("Dir:")} ${workingDir}`);
30949
+ console.log(` ${import_chalk3.default.bold("Mode:")} via running daemon`);
30950
+ console.log();
30951
+ console.log(import_chalk3.default.gray(" Open dashboard: https://adhf.dev/dashboard"));
30952
+ console.log();
30953
+ } else {
30954
+ spinner2.stop();
30955
+ console.log(import_chalk3.default.yellow(`
30956
+ \u26A0 Daemon not running. Start with 'adhdev daemon' first.
30538
30957
  `));
30958
+ console.log(import_chalk3.default.gray(" Then run: adhdev launch " + targetArg));
30539
30959
  process.exit(1);
30540
30960
  }
30541
- console.log();
30542
- console.log(import_chalk3.default.bold(` \u{1F680} CLI Agent Launched
30543
- `));
30544
- console.log(` ${import_chalk3.default.bold("Agent:")} ${targetArg} (${cliType})`);
30545
- console.log(` ${import_chalk3.default.bold("Dir:")} ${workingDir}`);
30546
- console.log(` ${import_chalk3.default.bold("Mode:")} via running daemon`);
30547
- console.log();
30548
- console.log(import_chalk3.default.gray(" Open dashboard: https://adhf.dev/dashboard"));
30549
- console.log();
30550
- } else {
30961
+ } catch (e) {
30551
30962
  spinner2.stop();
30552
- console.log(import_chalk3.default.yellow(`
30553
- \u26A0 Daemon not running. Starting daemon with ${targetArg}...
30963
+ console.log(import_chalk3.default.red(`
30964
+ \u2717 Launch failed: ${e?.message || e}
30554
30965
  `));
30555
- const { AdhdevDaemon: AdhdevDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
30556
- const daemon = new AdhdevDaemon2();
30557
- await daemon.start({
30558
- localPort: 19222,
30559
- foreground: true
30560
- });
30561
- setTimeout(async () => {
30562
- try {
30563
- const result = await sendDaemonCommand("launch_cli", {
30564
- cliType,
30565
- dir: require("path").resolve(workingDir)
30566
- });
30567
- if (result?.success) {
30568
- console.log(import_chalk3.default.green(` \u2713 CLI ${targetArg} started`));
30569
- }
30570
- } catch (e) {
30571
- console.log(import_chalk3.default.yellow(` \u26A0 CLI auto-start failed: ${e?.message}. Use dashboard to start.`));
30572
- }
30573
- }, 3e3);
30966
+ if (e?.cause?.code === "ECONNREFUSED") {
30967
+ console.log(import_chalk3.default.gray(" Is the daemon running with --dev? (adhdev daemon --dev)"));
30968
+ }
30969
+ process.exit(1);
30574
30970
  }
30575
- } catch (e) {
30576
- spinner2.stop();
30971
+ return;
30972
+ }
30973
+ let targetIdeId = targetArg;
30974
+ if (!targetIdeId) {
30975
+ const ides = await detectIDEs2();
30976
+ const installed = ides.filter((i) => i.installed && i.cliCommand);
30977
+ if (installed.length === 0) {
30978
+ console.log(import_chalk3.default.red("\n\u2717 No supported IDE found.\n"));
30979
+ process.exit(1);
30980
+ }
30981
+ if (installed.length === 1) {
30982
+ targetIdeId = installed[0].id;
30983
+ } else {
30984
+ const inquirer2 = await import("inquirer");
30985
+ const { selectedIde } = await inquirer2.default.prompt([
30986
+ {
30987
+ type: "list",
30988
+ name: "selectedIde",
30989
+ message: "Which IDE to launch with CDP?",
30990
+ choices: installed.map((ide) => ({
30991
+ name: `${ide.icon} ${ide.displayName}${ide.version ? import_chalk3.default.gray(` v${ide.version}`) : ""}`,
30992
+ value: ide.id
30993
+ }))
30994
+ }
30995
+ ]);
30996
+ targetIdeId = selectedIde;
30997
+ }
30998
+ }
30999
+ const ora2 = await import("ora");
31000
+ const spinner = ora2.default("Detecting IDE...").start();
31001
+ try {
31002
+ const result = await launchWithCdp({
31003
+ ideId: targetIdeId,
31004
+ workspace: options.workspace,
31005
+ newWindow: options.newWindow
31006
+ });
31007
+ spinner.stop();
31008
+ if (!result.success) {
31009
+ console.log(import_chalk3.default.red(`
31010
+ \u2717 ${result.error}
31011
+ `));
31012
+ console.log(import_chalk3.default.gray(" Available IDEs:"));
31013
+ const ides = await detectIDEs2();
31014
+ ides.forEach((ide) => {
31015
+ if (ide.installed) {
31016
+ console.log(` ${import_chalk3.default.green("\u2713")} ${ide.icon} ${import_chalk3.default.bold(ide.id)} \u2014 ${ide.displayName}`);
31017
+ }
31018
+ });
31019
+ console.log(import_chalk3.default.gray("\n Available CLI Agents:"));
31020
+ const clis = await detectCLIs(providerLoader);
31021
+ clis.forEach((cli) => {
31022
+ if (cli.installed) {
31023
+ console.log(` ${import_chalk3.default.green("\u2713")} ${cli.icon} ${import_chalk3.default.bold(cli.id)} \u2014 ${cli.displayName}`);
31024
+ }
31025
+ });
31026
+ console.log(import_chalk3.default.gray(`
31027
+ Usage: adhdev launch <ide-or-cli>
31028
+ `));
31029
+ process.exit(1);
31030
+ }
31031
+ console.log();
31032
+ console.log(import_chalk3.default.bold(" \u{1F680} IDE Launched with CDP\n"));
31033
+ console.log(` ${import_chalk3.default.bold("IDE:")} ${result.ideName}`);
31034
+ console.log(` ${import_chalk3.default.bold("CDP:")} ${import_chalk3.default.cyan(`ws://127.0.0.1:${result.port}`)}`);
31035
+ switch (result.action) {
31036
+ case "reused":
31037
+ console.log(` ${import_chalk3.default.bold("Action:")} ${import_chalk3.default.yellow("CDP already active \u2014 reusing existing session")}`);
31038
+ break;
31039
+ case "restarted":
31040
+ console.log(` ${import_chalk3.default.bold("Action:")} ${import_chalk3.default.green("\u2713 Killed existing process \u2192 Restarted with CDP")}`);
31041
+ break;
31042
+ case "started":
31043
+ console.log(` ${import_chalk3.default.bold("Action:")} ${import_chalk3.default.green("\u2713 Started fresh with CDP")}`);
31044
+ break;
31045
+ }
31046
+ console.log();
31047
+ console.log(import_chalk3.default.gray(" Daemon will auto-detect and connect via CDP."));
31048
+ console.log(import_chalk3.default.gray(` Test: curl http://127.0.0.1:${result.port}/json/version
31049
+ `));
31050
+ } catch (e) {
31051
+ spinner.stop();
30577
31052
  console.log(import_chalk3.default.red(`
30578
31053
  \u2717 Launch failed: ${e?.message || e}
30579
31054
  `));
30580
31055
  process.exit(1);
30581
31056
  }
30582
- return;
30583
- }
30584
- let targetIdeId = targetArg;
30585
- if (!targetIdeId) {
30586
- const ides = await (0, import_daemon_core6.detectIDEs)();
30587
- const installed = ides.filter((i) => i.installed && i.cliCommand);
30588
- if (installed.length === 0) {
30589
- console.log(import_chalk3.default.red("\n\u2717 No supported IDE found.\n"));
30590
- process.exit(1);
31057
+ });
31058
+ program2.command("status").description("Show current ADHDev setup status").action(async () => {
31059
+ const { loadConfig: loadConfig3, detectIDEs: detectIDEs2, detectCLIs } = await Promise.resolve().then(() => __toESM(require_dist()));
31060
+ const config2 = loadConfig3();
31061
+ console.log(import_chalk3.default.bold("\n\u{1F9A6} ADHDev Status\n"));
31062
+ if (!config2.setupCompleted) {
31063
+ console.log(import_chalk3.default.yellow(" Status: Not configured"));
31064
+ console.log(import_chalk3.default.gray(" Run `adhdev setup` to get started.\n"));
31065
+ return;
30591
31066
  }
30592
- if (installed.length === 1) {
30593
- targetIdeId = installed[0].id;
30594
- } else {
30595
- const inquirer2 = await import("inquirer");
30596
- const { selectedIde } = await inquirer2.default.prompt([
30597
- {
30598
- type: "list",
30599
- name: "selectedIde",
30600
- message: "Which IDE to launch with CDP?",
30601
- choices: installed.map((ide) => ({
30602
- name: `${ide.icon} ${ide.displayName}${ide.version ? import_chalk3.default.gray(` v${ide.version}`) : ""}`,
30603
- value: ide.id
30604
- }))
31067
+ const ideList = config2.configuredIdes?.length ? config2.configuredIdes : config2.selectedIde ? [config2.selectedIde] : [];
31068
+ console.log(` ${import_chalk3.default.bold("Status:")} ${import_chalk3.default.green("\u2713 Configured")}`);
31069
+ if (ideList.length > 0) {
31070
+ const ides = await detectIDEs2();
31071
+ console.log(` ${import_chalk3.default.bold("IDEs:")}`);
31072
+ for (const ideId of ideList) {
31073
+ const ide = ides.find((i) => i.id === ideId);
31074
+ if (ide?.installed) {
31075
+ const ver = ide.version ? import_chalk3.default.gray(` v${ide.version}`) : "";
31076
+ console.log(` ${import_chalk3.default.green("\u2713")} ${ide.icon} ${ide.displayName}${ver}`);
31077
+ } else {
31078
+ console.log(` ${import_chalk3.default.yellow("?")} ${ideId}`);
30605
31079
  }
30606
- ]);
30607
- targetIdeId = selectedIde;
31080
+ }
30608
31081
  }
30609
- }
30610
- const ora2 = await import("ora");
30611
- const spinner = ora2.default("Detecting IDE...").start();
30612
- try {
30613
- const result = await (0, import_daemon_core6.launchWithCdp)({
30614
- ideId: targetIdeId,
30615
- workspace: options.workspace,
30616
- newWindow: options.newWindow
31082
+ const clis = await detectCLIs(providerLoader);
31083
+ const installedClis = clis.filter((c) => c.installed);
31084
+ if (installedClis.length > 0) {
31085
+ console.log(` ${import_chalk3.default.bold("CLI Agents:")}`);
31086
+ installedClis.forEach((cli) => {
31087
+ const ver = cli.version ? import_chalk3.default.gray(` v${cli.version}`) : "";
31088
+ console.log(` ${import_chalk3.default.green("\u2713")} ${cli.icon} ${cli.displayName}${ver}`);
31089
+ });
31090
+ }
31091
+ console.log(` ${import_chalk3.default.bold("Extensions:")} ${config2.installedExtensions.length} installed`);
31092
+ config2.installedExtensions.forEach((ext) => {
31093
+ console.log(import_chalk3.default.gray(` \u2022 ${ext}`));
30617
31094
  });
30618
- spinner.stop();
30619
- if (!result.success) {
30620
- console.log(import_chalk3.default.red(`
30621
- \u2717 ${result.error}
30622
- `));
30623
- console.log(import_chalk3.default.gray(" Available IDEs:"));
30624
- const ides = await (0, import_daemon_core6.detectIDEs)();
30625
- ides.forEach((ide) => {
30626
- if (ide.installed) {
30627
- console.log(` ${import_chalk3.default.green("\u2713")} ${ide.icon} ${import_chalk3.default.bold(ide.id)} \u2014 ${ide.displayName}`);
31095
+ console.log(` ${import_chalk3.default.bold("User:")} ${config2.userEmail || import_chalk3.default.gray("not logged in")}`);
31096
+ console.log(` ${import_chalk3.default.bold("Auto-connect:")} ${config2.autoConnect ? import_chalk3.default.green("enabled") : import_chalk3.default.gray("disabled")}`);
31097
+ console.log(` ${import_chalk3.default.bold("Server:")} ${config2.serverUrl}`);
31098
+ console.log(` ${import_chalk3.default.bold("Setup date:")} ${config2.setupDate || "unknown"}`);
31099
+ console.log();
31100
+ });
31101
+ program2.command("detect").description("Detect installed IDEs, CLI agents, and ACP agents").action(async () => {
31102
+ const { detectIDEs: detectIDEs2, detectCLIs } = await Promise.resolve().then(() => __toESM(require_dist()));
31103
+ console.log(import_chalk3.default.bold("\n\u{1F50D} Detecting installed IDEs...\n"));
31104
+ const ides = await detectIDEs2();
31105
+ ides.forEach((ide) => {
31106
+ if (ide.installed) {
31107
+ const version2 = ide.version ? import_chalk3.default.gray(` v${ide.version}`) : "";
31108
+ console.log(` ${import_chalk3.default.green("\u2713")} ${ide.icon} ${import_chalk3.default.bold(ide.displayName)}${version2}`);
31109
+ if (ide.cliCommand) {
31110
+ console.log(import_chalk3.default.gray(` CLI: ${ide.cliCommand}`));
31111
+ }
31112
+ if (ide.path) {
31113
+ console.log(import_chalk3.default.gray(` Path: ${ide.path}`));
30628
31114
  }
30629
- });
30630
- console.log(import_chalk3.default.gray("\n Available CLI Agents:"));
30631
- const clis = await (0, import_daemon_core6.detectCLIs)(_cliProviderLoader);
30632
- clis.forEach((cli) => {
31115
+ } else {
31116
+ console.log(` ${import_chalk3.default.gray("\u2717")} ${ide.icon} ${import_chalk3.default.gray(ide.displayName)} \u2014 not found`);
31117
+ }
31118
+ });
31119
+ console.log(import_chalk3.default.bold("\n\u{1F50D} Detecting CLI & ACP Agents...\n"));
31120
+ const clis = await detectCLIs(providerLoader);
31121
+ const cliAgents = clis.filter((c) => c.category === "cli");
31122
+ const acpAgents = clis.filter((c) => c.category === "acp");
31123
+ const installedCli = cliAgents.filter((c) => c.installed);
31124
+ const installedAcp = acpAgents.filter((c) => c.installed);
31125
+ if (cliAgents.length > 0) {
31126
+ console.log(` ${import_chalk3.default.bold("\u2328\uFE0F CLI Agents")} (${installedCli.length}/${cliAgents.length})`);
31127
+ cliAgents.forEach((cli) => {
30633
31128
  if (cli.installed) {
30634
- console.log(` ${import_chalk3.default.green("\u2713")} ${cli.icon} ${import_chalk3.default.bold(cli.id)} \u2014 ${cli.displayName}`);
31129
+ const version2 = cli.version ? import_chalk3.default.gray(` v${cli.version}`) : "";
31130
+ console.log(` ${import_chalk3.default.green("\u2713")} ${cli.icon} ${import_chalk3.default.bold(cli.displayName)}${version2}`);
31131
+ console.log(import_chalk3.default.gray(` Path: ${cli.path}`));
31132
+ } else {
31133
+ console.log(` ${import_chalk3.default.gray("\u2717")} ${cli.icon} ${import_chalk3.default.gray(cli.displayName)} \u2014 not found`);
30635
31134
  }
30636
31135
  });
30637
- console.log(import_chalk3.default.gray(`
30638
- Usage: adhdev launch <ide-or-cli>
30639
- `));
30640
- process.exit(1);
30641
31136
  }
30642
- console.log();
30643
- console.log(import_chalk3.default.bold(" \u{1F680} IDE Launched with CDP\n"));
30644
- console.log(` ${import_chalk3.default.bold("IDE:")} ${result.ideName}`);
30645
- console.log(` ${import_chalk3.default.bold("CDP:")} ${import_chalk3.default.cyan(`ws://127.0.0.1:${result.port}`)}`);
30646
- switch (result.action) {
30647
- case "reused":
30648
- console.log(` ${import_chalk3.default.bold("Action:")} ${import_chalk3.default.yellow("CDP already active \u2014 reusing existing session")}`);
30649
- break;
30650
- case "restarted":
30651
- console.log(` ${import_chalk3.default.bold("Action:")} ${import_chalk3.default.green("\u2713 Killed existing process \u2192 Restarted with CDP")}`);
30652
- break;
30653
- case "started":
30654
- console.log(` ${import_chalk3.default.bold("Action:")} ${import_chalk3.default.green("\u2713 Started fresh with CDP")}`);
30655
- break;
30656
- }
30657
- console.log();
30658
- console.log(import_chalk3.default.gray(" Daemon will auto-detect and connect via CDP."));
30659
- console.log(import_chalk3.default.gray(` Test: curl http://127.0.0.1:${result.port}/json/version
30660
- `));
30661
- } catch (e) {
30662
- spinner.stop();
30663
- console.log(import_chalk3.default.red(`
30664
- \u2717 Launch failed: ${e?.message || e}
30665
- `));
30666
- process.exit(1);
30667
- }
30668
- });
30669
- program.command("status").description("Show current ADHDev setup status").action(async () => {
30670
- const config2 = (0, import_daemon_core6.loadConfig)();
30671
- console.log(import_chalk3.default.bold("\n\u{1F9A6} ADHDev Status\n"));
30672
- if (!config2.setupCompleted) {
30673
- console.log(import_chalk3.default.yellow(" Status: Not configured"));
30674
- console.log(import_chalk3.default.gray(" Run `adhdev setup` to get started.\n"));
30675
- return;
30676
- }
30677
- const ideList = config2.configuredIdes?.length ? config2.configuredIdes : config2.selectedIde ? [config2.selectedIde] : [];
30678
- console.log(` ${import_chalk3.default.bold("Status:")} ${import_chalk3.default.green("\u2713 Configured")}`);
30679
- if (ideList.length > 0) {
30680
- const ides = await (0, import_daemon_core6.detectIDEs)();
30681
- console.log(` ${import_chalk3.default.bold("IDEs:")}`);
30682
- for (const ideId of ideList) {
30683
- const ide = ides.find((i) => i.id === ideId);
30684
- if (ide?.installed) {
30685
- const ver = ide.version ? import_chalk3.default.gray(` v${ide.version}`) : "";
30686
- console.log(` ${import_chalk3.default.green("\u2713")} ${ide.icon} ${ide.displayName}${ver}`);
30687
- } else {
30688
- console.log(` ${import_chalk3.default.yellow("?")} ${ideId}`);
31137
+ if (acpAgents.length > 0) {
31138
+ console.log(`
31139
+ ${import_chalk3.default.bold("\u{1F50C} ACP Agents")} (${installedAcp.length}/${acpAgents.length})`);
31140
+ acpAgents.filter((c) => c.installed).forEach((cli) => {
31141
+ const version2 = cli.version ? import_chalk3.default.gray(` v${cli.version}`) : "";
31142
+ console.log(` ${import_chalk3.default.green("\u2713")} ${cli.icon} ${import_chalk3.default.bold(cli.displayName)}${version2}`);
31143
+ console.log(import_chalk3.default.gray(` Path: ${cli.path}`));
31144
+ });
31145
+ const notInstalledAcp = acpAgents.filter((c) => !c.installed);
31146
+ if (notInstalledAcp.length > 0) {
31147
+ console.log(import_chalk3.default.gray(` ... ${notInstalledAcp.length} more available (not installed)`));
30689
31148
  }
30690
31149
  }
30691
- }
30692
- const clis = await (0, import_daemon_core6.detectCLIs)(_cliProviderLoader);
30693
- const installedClis = clis.filter((c) => c.installed);
30694
- if (installedClis.length > 0) {
30695
- console.log(` ${import_chalk3.default.bold("CLI Agents:")}`);
30696
- installedClis.forEach((cli) => {
30697
- const ver = cli.version ? import_chalk3.default.gray(` v${cli.version}`) : "";
30698
- console.log(` ${import_chalk3.default.green("\u2713")} ${cli.icon} ${cli.displayName}${ver}`);
30699
- });
30700
- }
30701
- console.log(` ${import_chalk3.default.bold("Extensions:")} ${config2.installedExtensions.length} installed`);
30702
- config2.installedExtensions.forEach((ext) => {
30703
- console.log(import_chalk3.default.gray(` \u2022 ${ext}`));
31150
+ console.log();
30704
31151
  });
30705
- console.log(` ${import_chalk3.default.bold("User:")} ${config2.userEmail || import_chalk3.default.gray("not logged in")}`);
30706
- console.log(` ${import_chalk3.default.bold("Auto-connect:")} ${config2.autoConnect ? import_chalk3.default.green("enabled") : import_chalk3.default.gray("disabled")}`);
30707
- console.log(` ${import_chalk3.default.bold("Server:")} ${config2.serverUrl}`);
30708
- console.log(` ${import_chalk3.default.bold("Setup date:")} ${config2.setupDate || "unknown"}`);
30709
- console.log();
30710
- });
30711
- program.command("detect").description("Detect installed IDEs, CLI agents, and ACP agents").action(async () => {
30712
- console.log(import_chalk3.default.bold("\n\u{1F50D} Detecting installed IDEs...\n"));
30713
- const ides = await (0, import_daemon_core6.detectIDEs)();
30714
- ides.forEach((ide) => {
30715
- if (ide.installed) {
30716
- const version2 = ide.version ? import_chalk3.default.gray(` v${ide.version}`) : "";
30717
- console.log(` ${import_chalk3.default.green("\u2713")} ${ide.icon} ${import_chalk3.default.bold(ide.displayName)}${version2}`);
30718
- if (ide.cliCommand) {
30719
- console.log(import_chalk3.default.gray(` CLI: ${ide.cliCommand}`));
30720
- }
30721
- if (ide.path) {
30722
- console.log(import_chalk3.default.gray(` Path: ${ide.path}`));
31152
+ program2.command("reset").description("Reset ADHDev configuration").action(async () => {
31153
+ const { resetConfig } = await Promise.resolve().then(() => __toESM(require_dist()));
31154
+ const inquirer2 = await import("inquirer");
31155
+ const { confirm } = await inquirer2.default.prompt([
31156
+ {
31157
+ type: "confirm",
31158
+ name: "confirm",
31159
+ message: "Are you sure you want to reset ADHDev configuration?",
31160
+ default: false
30723
31161
  }
30724
- } else {
30725
- console.log(` ${import_chalk3.default.gray("\u2717")} ${ide.icon} ${import_chalk3.default.gray(ide.displayName)} \u2014 not found`);
31162
+ ]);
31163
+ if (confirm) {
31164
+ resetConfig();
31165
+ console.log(import_chalk3.default.green("\n\u2713 Configuration reset successfully."));
31166
+ console.log(import_chalk3.default.gray(" Run `adhdev setup` to reconfigure.\n"));
30726
31167
  }
30727
31168
  });
30728
- console.log(import_chalk3.default.bold("\n\u{1F50D} Detecting CLI & ACP Agents...\n"));
30729
- const clis = await (0, import_daemon_core6.detectCLIs)(_cliProviderLoader);
30730
- const cliAgents = clis.filter((c) => c.category === "cli");
30731
- const acpAgents = clis.filter((c) => c.category === "acp");
30732
- const installedCli = cliAgents.filter((c) => c.installed);
30733
- const installedAcp = acpAgents.filter((c) => c.installed);
30734
- if (cliAgents.length > 0) {
30735
- console.log(` ${import_chalk3.default.bold("\u2328\uFE0F CLI Agents")} (${installedCli.length}/${cliAgents.length})`);
30736
- cliAgents.forEach((cli) => {
30737
- if (cli.installed) {
30738
- const version2 = cli.version ? import_chalk3.default.gray(` v${cli.version}`) : "";
30739
- console.log(` ${import_chalk3.default.green("\u2713")} ${cli.icon} ${import_chalk3.default.bold(cli.displayName)}${version2}`);
30740
- console.log(import_chalk3.default.gray(` Path: ${cli.path}`));
30741
- } else {
30742
- console.log(` ${import_chalk3.default.gray("\u2717")} ${cli.icon} ${import_chalk3.default.gray(cli.displayName)} \u2014 not found`);
30743
- }
30744
- });
30745
- }
30746
- if (acpAgents.length > 0) {
30747
- console.log(`
30748
- ${import_chalk3.default.bold("\u{1F50C} ACP Agents")} (${installedAcp.length}/${acpAgents.length})`);
30749
- acpAgents.filter((c) => c.installed).forEach((cli) => {
30750
- const version2 = cli.version ? import_chalk3.default.gray(` v${cli.version}`) : "";
30751
- console.log(` ${import_chalk3.default.green("\u2713")} ${cli.icon} ${import_chalk3.default.bold(cli.displayName)}${version2}`);
30752
- console.log(import_chalk3.default.gray(` Path: ${cli.path}`));
31169
+ }
31170
+
31171
+ // src/cli/daemon-commands.ts
31172
+ var import_chalk4 = __toESM(require("chalk"));
31173
+ function registerDaemonCommands(program2, pkgVersion3) {
31174
+ program2.command("daemon").description("\u{1F680} Start ADHDev Daemon \u2014 unified hub for IDE monitoring, agent management, and remote control").option("-p, --port <port>", "Local WS server port", "19222").option("--server <url>", "Override server URL for testing").option("--dev", "Enable Dev Mode \u2014 HTTP API on :19280 for script debugging").action(async (options) => {
31175
+ const { AdhdevDaemon: AdhdevDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
31176
+ const daemon = new AdhdevDaemon2();
31177
+ await daemon.start({
31178
+ localPort: parseInt(options.port) || 19222,
31179
+ serverUrl: options.server,
31180
+ foreground: true,
31181
+ dev: options.dev || false
30753
31182
  });
30754
- const notInstalledAcp = acpAgents.filter((c) => !c.installed);
30755
- if (notInstalledAcp.length > 0) {
30756
- console.log(import_chalk3.default.gray(` ... ${notInstalledAcp.length} more available (not installed)`));
30757
- }
30758
- }
30759
- console.log();
30760
- });
30761
- program.command("reset").description("Reset ADHDev configuration").action(async () => {
30762
- const inquirer2 = await import("inquirer");
30763
- const { confirm } = await inquirer2.default.prompt([
30764
- {
30765
- type: "confirm",
30766
- name: "confirm",
30767
- message: "Are you sure you want to reset ADHDev configuration?",
30768
- default: false
30769
- }
30770
- ]);
30771
- if (confirm) {
30772
- (0, import_daemon_core6.resetConfig)();
30773
- console.log(import_chalk3.default.green("\n\u2713 Configuration reset successfully."));
30774
- console.log(import_chalk3.default.gray(" Run `adhdev setup` to reconfigure.\n"));
30775
- }
30776
- });
30777
- program.command("daemon").description("\u{1F680} Start ADHDev Daemon \u2014 unified hub for IDE monitoring, agent management, and remote control").option("-p, --port <port>", "Local WS server port", "19222").option("--server <url>", "Override server URL for testing").option("--dev", "Enable Dev Mode \u2014 HTTP API on :19280 for script debugging").action(async (options) => {
30778
- const { AdhdevDaemon: AdhdevDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
30779
- const daemon = new AdhdevDaemon2();
30780
- await daemon.start({
30781
- localPort: parseInt(options.port) || 19222,
30782
- serverUrl: options.server,
30783
- foreground: true,
30784
- dev: options.dev || false
30785
31183
  });
30786
- });
30787
- program.command("daemon:status").description("Check ADHDev Daemon status").action(async () => {
30788
- const { isDaemonRunning: isDaemonRunning2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
30789
- if (isDaemonRunning2()) {
30790
- console.log(import_chalk3.default.green(`
31184
+ program2.command("daemon:status").description("Check ADHDev Daemon status").action(async () => {
31185
+ const { isDaemonRunning: isDaemonRunning2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
31186
+ if (isDaemonRunning2()) {
31187
+ console.log(import_chalk4.default.green(`
30791
31188
  \u2713 ADHDev Daemon is running.
30792
31189
  `));
30793
- } else {
30794
- console.log(import_chalk3.default.gray(`
31190
+ } else {
31191
+ console.log(import_chalk4.default.gray(`
30795
31192
  \u2717 ADHDev Daemon is not running.`));
30796
- console.log(import_chalk3.default.gray(` Start with: adhdev daemon
31193
+ console.log(import_chalk4.default.gray(` Start with: adhdev daemon
30797
31194
  `));
30798
- }
30799
- });
30800
- program.command("daemon:stop").description("Stop ADHDev Daemon").action(async () => {
30801
- const { stopDaemon: stopDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
30802
- if (stopDaemon2()) {
30803
- console.log(import_chalk3.default.green(`
31195
+ }
31196
+ });
31197
+ program2.command("daemon:stop").description("Stop ADHDev Daemon").action(async () => {
31198
+ const { stopDaemon: stopDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
31199
+ if (stopDaemon2()) {
31200
+ console.log(import_chalk4.default.green(`
30804
31201
  \u2713 ADHDev Daemon stopped.
30805
31202
  `));
30806
- } else {
30807
- console.log(import_chalk3.default.gray(`
31203
+ } else {
31204
+ console.log(import_chalk4.default.gray(`
30808
31205
  \u2717 No running daemon found.
30809
31206
  `));
30810
- }
30811
- });
30812
- program.command("daemon:restart").description("Restart ADHDev Daemon (stop \u2192 start)").option("-p, --port <port>", "Local WS server port", "19222").option("--server <url>", "Override server URL").option("--dev", "Enable Dev Mode").action(async (options) => {
30813
- const { stopDaemon: stopDaemon2, isDaemonRunning: isDaemonRunning2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
30814
- const { spawn } = await import("child_process");
30815
- if (isDaemonRunning2()) {
30816
- console.log(import_chalk3.default.yellow("\n Stopping existing daemon..."));
30817
- stopDaemon2();
30818
- await new Promise((r) => setTimeout(r, 2e3));
30819
- }
30820
- console.log(import_chalk3.default.cyan(" Starting new daemon..."));
30821
- const args = ["daemon", "-p", options.port || "19222"];
30822
- if (options.server) args.push("--server", options.server);
30823
- if (options.dev) args.push("--dev");
30824
- const child = spawn(process.execPath, [process.argv[1], ...args], {
30825
- detached: true,
30826
- stdio: "ignore",
30827
- env: { ...process.env }
30828
- });
30829
- child.unref();
30830
- await new Promise((r) => setTimeout(r, 3e3));
30831
- if (isDaemonRunning2()) {
30832
- console.log(import_chalk3.default.green(` \u2713 ADHDev Daemon restarted (PID: ${child.pid})
30833
- `));
30834
- } else {
30835
- console.log(import_chalk3.default.red(` \u2717 Daemon failed to start. Check logs: ~/.adhdev/daemon.log
30836
- `));
30837
- process.exit(1);
30838
- }
30839
- });
30840
- program.command("daemon:upgrade").description("Upgrade ADHDev to latest version and restart daemon").option("--no-restart", "Upgrade only, skip daemon restart").action(async (options) => {
30841
- const { isDaemonRunning: isDaemonRunning2, stopDaemon: stopDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
30842
- const { execSync, spawn } = await import("child_process");
30843
- const fsMod = await import("fs");
30844
- const pathMod = await import("path");
30845
- console.log(import_chalk3.default.bold("\n \u{1F504} ADHDev Upgrade\n"));
30846
- const adhdevPath = process.argv[1];
30847
- const realPath = fsMod.realpathSync(adhdevPath);
30848
- const isLinked = realPath.includes(".openclaw") || realPath.includes("/src/");
30849
- const currentVersion = pkgVersion2;
30850
- console.log(` ${import_chalk3.default.bold("Current:")} v${currentVersion}`);
30851
- console.log(` ${import_chalk3.default.bold("Install:")} ${isLinked ? "npm link (dev)" : "npm global"}`);
30852
- if (isLinked) {
30853
- const projectRoot = pathMod.resolve(pathMod.dirname(realPath), "..");
30854
- const launcherDir = pathMod.join(projectRoot);
30855
- console.log(` ${import_chalk3.default.bold("Path:")} ${launcherDir}`);
30856
- console.log(import_chalk3.default.cyan("\n Pulling latest..."));
30857
- try {
30858
- let gitRoot = launcherDir;
30859
- while (!fsMod.existsSync(pathMod.join(gitRoot, ".git")) && gitRoot !== "/") {
30860
- gitRoot = pathMod.dirname(gitRoot);
30861
- }
30862
- execSync("git pull --rebase", { cwd: gitRoot, stdio: "inherit" });
30863
- console.log(import_chalk3.default.cyan("\n Building..."));
30864
- execSync("npm run build", { cwd: launcherDir, stdio: "inherit" });
30865
- execSync("npm link", { cwd: launcherDir, stdio: "inherit" });
30866
- console.log(import_chalk3.default.green("\n \u2713 Build complete"));
30867
- } catch (e) {
30868
- console.log(import_chalk3.default.red(`
30869
- \u2717 Build failed: ${e?.message}
30870
- `));
30871
- process.exit(1);
30872
31207
  }
30873
- } else {
30874
- console.log(import_chalk3.default.cyan("\n Checking for updates..."));
30875
- try {
30876
- const latest = execSync("npm view adhdev version", { encoding: "utf-8" }).trim();
30877
- console.log(` ${import_chalk3.default.bold("Latest:")} v${latest}`);
30878
- if (latest === currentVersion) {
30879
- console.log(import_chalk3.default.green("\n \u2713 Already on latest version.\n"));
30880
- if (!options.restart) return;
30881
- } else {
30882
- console.log(import_chalk3.default.cyan(`
30883
- Upgrading v${currentVersion} \u2192 v${latest}...`));
30884
- execSync("npm install -g adhdev@latest", { stdio: "inherit" });
30885
- console.log(import_chalk3.default.green("\n \u2713 Upgrade complete"));
30886
- }
30887
- } catch (e) {
30888
- console.log(import_chalk3.default.red(`
30889
- \u2717 Upgrade failed: ${e?.message}
30890
- `));
30891
- process.exit(1);
30892
- }
30893
- }
30894
- if (options.restart !== false && isDaemonRunning2()) {
30895
- console.log(import_chalk3.default.yellow("\n Restarting daemon..."));
30896
- stopDaemon2();
30897
- await new Promise((r) => setTimeout(r, 2e3));
30898
- const child = spawn(process.execPath, [process.argv[1], "daemon", "-p", "19222"], {
31208
+ });
31209
+ program2.command("daemon:restart").description("Restart ADHDev Daemon (stop \u2192 start)").option("-p, --port <port>", "Local WS server port", "19222").option("--server <url>", "Override server URL").option("--dev", "Enable Dev Mode").action(async (options) => {
31210
+ const { stopDaemon: stopDaemon2, isDaemonRunning: isDaemonRunning2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
31211
+ const { spawn } = await import("child_process");
31212
+ if (isDaemonRunning2()) {
31213
+ console.log(import_chalk4.default.yellow("\n Stopping existing daemon..."));
31214
+ stopDaemon2();
31215
+ await new Promise((r) => setTimeout(r, 2e3));
31216
+ }
31217
+ console.log(import_chalk4.default.cyan(" Starting new daemon..."));
31218
+ const args = ["daemon", "-p", options.port || "19222"];
31219
+ if (options.server) args.push("--server", options.server);
31220
+ if (options.dev) args.push("--dev");
31221
+ const child = spawn(process.execPath, [process.argv[1], ...args], {
30899
31222
  detached: true,
30900
31223
  stdio: "ignore",
30901
31224
  env: { ...process.env }
@@ -30903,18 +31226,102 @@ program.command("daemon:upgrade").description("Upgrade ADHDev to latest version
30903
31226
  child.unref();
30904
31227
  await new Promise((r) => setTimeout(r, 3e3));
30905
31228
  if (isDaemonRunning2()) {
30906
- console.log(import_chalk3.default.green(` \u2713 Daemon restarted with new version
31229
+ console.log(import_chalk4.default.green(` \u2713 ADHDev Daemon restarted (PID: ${child.pid})
31230
+ `));
31231
+ } else {
31232
+ console.log(import_chalk4.default.red(` \u2717 Daemon failed to start. Check logs: ~/.adhdev/daemon.log
31233
+ `));
31234
+ process.exit(1);
31235
+ }
31236
+ });
31237
+ program2.command("daemon:upgrade").description("Upgrade ADHDev to latest version and restart daemon").option("--no-restart", "Upgrade only, skip daemon restart").action(async (options) => {
31238
+ const { isDaemonRunning: isDaemonRunning2, stopDaemon: stopDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
31239
+ const { execSync, spawn } = await import("child_process");
31240
+ const fsMod = await import("fs");
31241
+ const pathMod = await import("path");
31242
+ console.log(import_chalk4.default.bold("\n \u{1F504} ADHDev Upgrade\n"));
31243
+ const adhdevPath = process.argv[1];
31244
+ const realPath = fsMod.realpathSync(adhdevPath);
31245
+ const isLinked = realPath.includes(".openclaw") || realPath.includes("/src/");
31246
+ const currentVersion = pkgVersion3;
31247
+ console.log(` ${import_chalk4.default.bold("Current:")} v${currentVersion}`);
31248
+ console.log(` ${import_chalk4.default.bold("Install:")} ${isLinked ? "npm link (dev)" : "npm global"}`);
31249
+ if (isLinked) {
31250
+ const projectRoot = pathMod.resolve(pathMod.dirname(realPath), "..");
31251
+ const launcherDir = pathMod.join(projectRoot);
31252
+ console.log(` ${import_chalk4.default.bold("Path:")} ${launcherDir}`);
31253
+ console.log(import_chalk4.default.cyan("\n Pulling latest..."));
31254
+ try {
31255
+ let gitRoot = launcherDir;
31256
+ while (!fsMod.existsSync(pathMod.join(gitRoot, ".git")) && gitRoot !== "/") {
31257
+ gitRoot = pathMod.dirname(gitRoot);
31258
+ }
31259
+ execSync("git pull --rebase", { cwd: gitRoot, stdio: "inherit" });
31260
+ console.log(import_chalk4.default.cyan("\n Building..."));
31261
+ execSync("npm run build", { cwd: launcherDir, stdio: "inherit" });
31262
+ execSync("npm link", { cwd: launcherDir, stdio: "inherit" });
31263
+ console.log(import_chalk4.default.green("\n \u2713 Build complete"));
31264
+ } catch (e) {
31265
+ console.log(import_chalk4.default.red(`
31266
+ \u2717 Build failed: ${e?.message}
30907
31267
  `));
31268
+ process.exit(1);
31269
+ }
30908
31270
  } else {
30909
- console.log(import_chalk3.default.yellow(` \u26A0 Daemon not detected. Start manually: adhdev daemon
31271
+ console.log(import_chalk4.default.cyan("\n Checking for updates..."));
31272
+ try {
31273
+ const latest = execSync("npm view adhdev version", { encoding: "utf-8" }).trim();
31274
+ console.log(` ${import_chalk4.default.bold("Latest:")} v${latest}`);
31275
+ if (latest === currentVersion) {
31276
+ console.log(import_chalk4.default.green("\n \u2713 Already on latest version.\n"));
31277
+ if (!options.restart) return;
31278
+ } else {
31279
+ console.log(import_chalk4.default.cyan(`
31280
+ Upgrading v${currentVersion} \u2192 v${latest}...`));
31281
+ execSync("npm install -g adhdev@latest", { stdio: "inherit" });
31282
+ console.log(import_chalk4.default.green("\n \u2713 Upgrade complete"));
31283
+ }
31284
+ } catch (e) {
31285
+ console.log(import_chalk4.default.red(`
31286
+ \u2717 Upgrade failed: ${e?.message}
30910
31287
  `));
31288
+ process.exit(1);
31289
+ }
30911
31290
  }
30912
- } else if (options.restart !== false) {
30913
- console.log(import_chalk3.default.gray("\n Daemon was not running. Start with: adhdev daemon\n"));
30914
- } else {
30915
- console.log(import_chalk3.default.green("\n \u2713 Upgrade complete (daemon not restarted)\n"));
30916
- }
30917
- });
31291
+ if (options.restart !== false && isDaemonRunning2()) {
31292
+ console.log(import_chalk4.default.yellow("\n Restarting daemon..."));
31293
+ stopDaemon2();
31294
+ await new Promise((r) => setTimeout(r, 2e3));
31295
+ const child = spawn(process.execPath, [process.argv[1], "daemon", "-p", "19222"], {
31296
+ detached: true,
31297
+ stdio: "ignore",
31298
+ env: { ...process.env }
31299
+ });
31300
+ child.unref();
31301
+ await new Promise((r) => setTimeout(r, 3e3));
31302
+ if (isDaemonRunning2()) {
31303
+ console.log(import_chalk4.default.green(` \u2713 Daemon restarted with new version
31304
+ `));
31305
+ } else {
31306
+ console.log(import_chalk4.default.yellow(` \u26A0 Daemon not detected. Start manually: adhdev daemon
31307
+ `));
31308
+ }
31309
+ } else if (options.restart !== false) {
31310
+ console.log(import_chalk4.default.gray("\n Daemon was not running. Start with: adhdev daemon\n"));
31311
+ } else {
31312
+ console.log(import_chalk4.default.green("\n \u2713 Upgrade complete (daemon not restarted)\n"));
31313
+ }
31314
+ });
31315
+ program2.command("update").description("\u{1F504} Update ADHDev to latest version and restart daemon (alias for daemon:upgrade)").option("--no-restart", "Upgrade only, skip daemon restart").action(async (options) => {
31316
+ process.argv = [process.argv[0], process.argv[1], "daemon:upgrade", ...options.restart === false ? ["--no-restart"] : []];
31317
+ await program2.parseAsync(process.argv);
31318
+ });
31319
+ }
31320
+
31321
+ // src/cli/provider-commands.ts
31322
+ var import_chalk5 = __toESM(require("chalk"));
31323
+
31324
+ // src/cli/cdp-utils.ts
30918
31325
  async function sendDaemonCommand(cmd, args = {}, port = 19222) {
30919
31326
  const WebSocket2 = (await import("ws")).default;
30920
31327
  const { DAEMON_WS_PATH } = await Promise.resolve().then(() => __toESM(require_dist()));
@@ -31021,138 +31428,141 @@ async function directCdpEval(expression, port = 9222) {
31021
31428
  });
31022
31429
  });
31023
31430
  }
31024
- var provider = program.command("provider").description("\u{1F50C} Provider management \u2014 list, test, reload providers");
31025
- provider.command("list").description("List all loaded providers").option("-j, --json", "Output raw JSON").action(async (options) => {
31026
- try {
31027
- const { ProviderLoader: ProviderLoader3 } = await Promise.resolve().then(() => __toESM(require_dist()));
31028
- const loader = new ProviderLoader3();
31029
- loader.loadAll();
31030
- const providers = loader.getAll();
31031
- if (options.json) {
31032
- console.log(JSON.stringify(providers.map((p) => ({
31033
- type: p.type,
31034
- name: p.name,
31035
- category: p.category,
31036
- scripts: p.scripts ? Object.keys(p.scripts).filter((k) => typeof p.scripts[k] === "function") : [],
31037
- extensionId: p.extensionId || null,
31038
- inputMethod: p.inputMethod || null
31039
- })), null, 2));
31040
- return;
31041
- }
31042
- console.log(import_chalk3.default.bold("\n\u{1F50C} ADHDev Providers\n"));
31043
- const categories = ["ide", "extension", "cli", "acp"];
31044
- for (const cat of categories) {
31045
- const catProviders = providers.filter((p) => p.category === cat);
31046
- if (catProviders.length === 0) continue;
31047
- const icons = { ide: "\u{1F4BB}", extension: "\u{1F9E9}", cli: "\u2328\uFE0F ", acp: "\u{1F50C}" };
31048
- console.log(` ${icons[cat] || ""} ${import_chalk3.default.bold(cat.toUpperCase())} (${catProviders.length})`);
31049
- for (const p of catProviders) {
31050
- const scripts = p.scripts ? Object.keys(p.scripts).filter((k) => typeof p.scripts[k] === "function") : [];
31051
- console.log(` ${import_chalk3.default.green("\u2713")} ${import_chalk3.default.bold(p.type)} \u2014 ${p.name}`);
31052
- console.log(import_chalk3.default.gray(` scripts: ${scripts.join(", ")}`));
31053
- if (p.extensionId) console.log(import_chalk3.default.gray(` extensionId: ${p.extensionId}`));
31054
- if (p.inputMethod) console.log(import_chalk3.default.gray(` inputMethod: ${p.inputMethod}`));
31431
+
31432
+ // src/cli/provider-commands.ts
31433
+ function registerProviderCommands(program2) {
31434
+ const provider = program2.command("provider").description("\u{1F50C} Provider management \u2014 list, test, reload providers");
31435
+ provider.command("list").description("List all loaded providers").option("-j, --json", "Output raw JSON").action(async (options) => {
31436
+ try {
31437
+ const { ProviderLoader: ProviderLoader3 } = await Promise.resolve().then(() => __toESM(require_dist()));
31438
+ const loader = new ProviderLoader3();
31439
+ loader.loadAll();
31440
+ const providers = loader.getAll();
31441
+ if (options.json) {
31442
+ console.log(JSON.stringify(providers.map((p) => ({
31443
+ type: p.type,
31444
+ name: p.name,
31445
+ category: p.category,
31446
+ scripts: p.scripts ? Object.keys(p.scripts).filter((k) => typeof p.scripts[k] === "function") : [],
31447
+ extensionId: p.extensionId || null,
31448
+ inputMethod: p.inputMethod || null
31449
+ })), null, 2));
31450
+ return;
31055
31451
  }
31056
- console.log();
31057
- }
31058
- } catch (e) {
31059
- console.error(import_chalk3.default.red(`
31452
+ console.log(import_chalk5.default.bold("\n\u{1F50C} ADHDev Providers\n"));
31453
+ const categories = ["ide", "extension", "cli", "acp"];
31454
+ for (const cat of categories) {
31455
+ const catProviders = providers.filter((p) => p.category === cat);
31456
+ if (catProviders.length === 0) continue;
31457
+ const icons = { ide: "\u{1F4BB}", extension: "\u{1F9E9}", cli: "\u2328\uFE0F ", acp: "\u{1F50C}" };
31458
+ console.log(` ${icons[cat] || ""} ${import_chalk5.default.bold(cat.toUpperCase())} (${catProviders.length})`);
31459
+ for (const p of catProviders) {
31460
+ const scripts = p.scripts ? Object.keys(p.scripts).filter((k) => typeof p.scripts[k] === "function") : [];
31461
+ console.log(` ${import_chalk5.default.green("\u2713")} ${import_chalk5.default.bold(p.type)} \u2014 ${p.name}`);
31462
+ console.log(import_chalk5.default.gray(` scripts: ${scripts.join(", ")}`));
31463
+ if (p.extensionId) console.log(import_chalk5.default.gray(` extensionId: ${p.extensionId}`));
31464
+ if (p.inputMethod) console.log(import_chalk5.default.gray(` inputMethod: ${p.inputMethod}`));
31465
+ }
31466
+ console.log();
31467
+ }
31468
+ } catch (e) {
31469
+ console.error(import_chalk5.default.red(`
31060
31470
  \u2717 ${e.message}
31061
31471
  `));
31062
- process.exit(1);
31063
- }
31064
- });
31065
- provider.command("reload").description("Hot-reload all providers (requires daemon --dev)").action(async () => {
31066
- try {
31067
- const http = await import("http");
31068
- const result = await new Promise((resolve, reject) => {
31069
- const req = http.request({
31070
- hostname: "127.0.0.1",
31071
- port: 19280,
31072
- path: "/api/providers/reload",
31073
- method: "POST",
31074
- headers: { "Content-Type": "application/json", "Content-Length": "2" }
31075
- }, (res) => {
31076
- let data = "";
31077
- res.on("data", (c) => data += c);
31078
- res.on("end", () => {
31079
- try {
31080
- resolve(JSON.parse(data));
31081
- } catch {
31082
- resolve({ raw: data });
31083
- }
31472
+ process.exit(1);
31473
+ }
31474
+ });
31475
+ provider.command("reload").description("Hot-reload all providers (requires daemon --dev)").action(async () => {
31476
+ try {
31477
+ const http = await import("http");
31478
+ const result = await new Promise((resolve, reject) => {
31479
+ const req = http.request({
31480
+ hostname: "127.0.0.1",
31481
+ port: 19280,
31482
+ path: "/api/providers/reload",
31483
+ method: "POST",
31484
+ headers: { "Content-Type": "application/json", "Content-Length": "2" }
31485
+ }, (res) => {
31486
+ let data = "";
31487
+ res.on("data", (c) => data += c);
31488
+ res.on("end", () => {
31489
+ try {
31490
+ resolve(JSON.parse(data));
31491
+ } catch {
31492
+ resolve({ raw: data });
31493
+ }
31494
+ });
31084
31495
  });
31496
+ req.on("error", () => reject(new Error("DevServer not reachable. Run: adhdev daemon --dev")));
31497
+ req.write("{}");
31498
+ req.end();
31085
31499
  });
31086
- req.on("error", () => reject(new Error("DevServer not reachable. Run: adhdev daemon --dev")));
31087
- req.write("{}");
31088
- req.end();
31089
- });
31090
- if (result.reloaded) {
31091
- console.log(import_chalk3.default.green(`
31500
+ if (result.reloaded) {
31501
+ console.log(import_chalk5.default.green(`
31092
31502
  \u2713 Providers reloaded: ${result.providers?.length || 0} loaded
31093
31503
  `));
31094
- for (const p of result.providers || []) {
31095
- console.log(` ${import_chalk3.default.green("\u2713")} ${p.type} (${p.category}) \u2014 ${p.name}`);
31096
- }
31097
- console.log();
31098
- } else {
31099
- console.log(import_chalk3.default.red(`
31504
+ for (const p of result.providers || []) {
31505
+ console.log(` ${import_chalk5.default.green("\u2713")} ${p.type} (${p.category}) \u2014 ${p.name}`);
31506
+ }
31507
+ console.log();
31508
+ } else {
31509
+ console.log(import_chalk5.default.red(`
31100
31510
  \u2717 Reload failed: ${result.error || "unknown"}
31101
31511
  `));
31102
- }
31103
- } catch (e) {
31104
- console.error(import_chalk3.default.red(`
31512
+ }
31513
+ } catch (e) {
31514
+ console.error(import_chalk5.default.red(`
31105
31515
  \u2717 ${e.message}
31106
31516
  `));
31107
- process.exit(1);
31108
- }
31109
- });
31110
- provider.command("create <type>").description("Scaffold a new provider.js from template").option("-n, --name <name>", "Display name").option("-c, --category <cat>", "Category: ide, extension, cli", "ide").option("--builtin", "Create in builtin directory (default: ~/.adhdev/providers/)").action(async (type, options) => {
31111
- try {
31112
- const name = options.name || type.split("-").map((s) => s[0].toUpperCase() + s.slice(1)).join(" ");
31113
- const category = options.category;
31114
- const location = options.builtin ? "builtin" : "user";
31115
- const http = await import("http");
31116
- const result = await new Promise((resolve, reject) => {
31117
- const postData = JSON.stringify({ type, name, category, location });
31118
- const req = http.request({
31119
- hostname: "127.0.0.1",
31120
- port: 19280,
31121
- path: "/api/scaffold",
31122
- method: "POST",
31123
- headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) }
31124
- }, (res) => {
31125
- let data = "";
31126
- res.on("data", (c) => data += c);
31127
- res.on("end", () => {
31128
- try {
31129
- resolve(JSON.parse(data));
31130
- } catch {
31131
- resolve({ raw: data });
31132
- }
31517
+ process.exit(1);
31518
+ }
31519
+ });
31520
+ provider.command("create <type>").description("Scaffold a new provider.js from template").option("-n, --name <name>", "Display name").option("-c, --category <cat>", "Category: ide, extension, cli", "ide").option("--builtin", "Create in builtin directory (default: ~/.adhdev/providers/)").action(async (type, options) => {
31521
+ try {
31522
+ const name = options.name || type.split("-").map((s) => s[0].toUpperCase() + s.slice(1)).join(" ");
31523
+ const category = options.category;
31524
+ const location = options.builtin ? "builtin" : "user";
31525
+ const http = await import("http");
31526
+ const result = await new Promise((resolve, reject) => {
31527
+ const postData = JSON.stringify({ type, name, category, location });
31528
+ const req = http.request({
31529
+ hostname: "127.0.0.1",
31530
+ port: 19280,
31531
+ path: "/api/scaffold",
31532
+ method: "POST",
31533
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) }
31534
+ }, (res) => {
31535
+ let data = "";
31536
+ res.on("data", (c) => data += c);
31537
+ res.on("end", () => {
31538
+ try {
31539
+ resolve(JSON.parse(data));
31540
+ } catch {
31541
+ resolve({ raw: data });
31542
+ }
31543
+ });
31133
31544
  });
31134
- });
31135
- req.on("error", () => {
31136
- reject(new Error("DevServer not reachable"));
31137
- });
31138
- req.write(postData);
31139
- req.end();
31140
- }).catch(async () => {
31141
- const pathMod = await import("path");
31142
- const fsMod = await import("fs");
31143
- const osMod = await import("os");
31144
- let targetDir;
31145
- if (location === "builtin") {
31146
- targetDir = pathMod.resolve(__dirname, "../providers/_builtin", category, type);
31147
- } else {
31148
- targetDir = pathMod.join(osMod.homedir(), ".adhdev", "providers", type);
31149
- }
31150
- const targetFile = pathMod.join(targetDir, "provider.js");
31151
- if (fsMod.existsSync(targetFile)) {
31152
- return { error: `Provider already exists at ${targetFile}`, path: targetFile };
31153
- }
31154
- const isExtension = category === "extension";
31155
- const template = `/**
31545
+ req.on("error", () => {
31546
+ reject(new Error("DevServer not reachable"));
31547
+ });
31548
+ req.write(postData);
31549
+ req.end();
31550
+ }).catch(async () => {
31551
+ const pathMod = await import("path");
31552
+ const fsMod = await import("fs");
31553
+ const osMod = await import("os");
31554
+ let targetDir;
31555
+ if (location === "builtin") {
31556
+ targetDir = pathMod.resolve(__dirname, "../../providers/_builtin", category, type);
31557
+ } else {
31558
+ targetDir = pathMod.join(osMod.homedir(), ".adhdev", "providers", type);
31559
+ }
31560
+ const targetFile = pathMod.join(targetDir, "provider.js");
31561
+ if (fsMod.existsSync(targetFile)) {
31562
+ return { error: `Provider already exists at ${targetFile}`, path: targetFile };
31563
+ }
31564
+ const isExtension = category === "extension";
31565
+ const template = `/**
31156
31566
  * ${name} \u2014 Provider
31157
31567
  */
31158
31568
  module.exports = {
@@ -31170,151 +31580,153 @@ ${isExtension ? ` extensionId: 'publisher.${type}',
31170
31580
  },
31171
31581
  };
31172
31582
  `;
31173
- fsMod.mkdirSync(targetDir, { recursive: true });
31174
- fsMod.writeFileSync(targetFile, template, "utf-8");
31175
- return { created: true, path: targetFile, type, name, category };
31176
- });
31177
- if (result.error) {
31178
- console.log(import_chalk3.default.red(`
31583
+ fsMod.mkdirSync(targetDir, { recursive: true });
31584
+ fsMod.writeFileSync(targetFile, template, "utf-8");
31585
+ return { created: true, path: targetFile, type, name, category };
31586
+ });
31587
+ if (result.error) {
31588
+ console.log(import_chalk5.default.red(`
31179
31589
  \u2717 ${result.error}
31180
31590
  `));
31181
- if (result.path) console.log(import_chalk3.default.gray(` Path: ${result.path}
31591
+ if (result.path) console.log(import_chalk5.default.gray(` Path: ${result.path}
31182
31592
  `));
31183
- process.exit(1);
31184
- }
31185
- console.log(import_chalk3.default.green(`
31593
+ process.exit(1);
31594
+ }
31595
+ console.log(import_chalk5.default.green(`
31186
31596
  \u2713 Provider scaffolded!
31187
31597
  `));
31188
- console.log(` ${import_chalk3.default.bold("Type:")} ${result.type}`);
31189
- console.log(` ${import_chalk3.default.bold("Name:")} ${result.name}`);
31190
- console.log(` ${import_chalk3.default.bold("Category:")} ${result.category}`);
31191
- console.log(` ${import_chalk3.default.bold("Path:")} ${import_chalk3.default.cyan(result.path)}`);
31192
- console.log();
31193
- console.log(import_chalk3.default.gray(" Next steps:"));
31194
- console.log(import_chalk3.default.gray(` 1. Edit ${result.path}`));
31195
- console.log(import_chalk3.default.gray(" 2. Run: adhdev provider reload"));
31196
- console.log(import_chalk3.default.gray(` 3. Test: adhdev provider test ${type}`));
31197
- console.log(import_chalk3.default.gray(" 4. Open DevConsole: http://127.0.0.1:19280"));
31198
- console.log();
31199
- } catch (e) {
31200
- console.error(import_chalk3.default.red(`
31598
+ console.log(` ${import_chalk5.default.bold("Type:")} ${result.type}`);
31599
+ console.log(` ${import_chalk5.default.bold("Name:")} ${result.name}`);
31600
+ console.log(` ${import_chalk5.default.bold("Category:")} ${result.category}`);
31601
+ console.log(` ${import_chalk5.default.bold("Path:")} ${import_chalk5.default.cyan(result.path)}`);
31602
+ console.log();
31603
+ console.log(import_chalk5.default.gray(" Next steps:"));
31604
+ console.log(import_chalk5.default.gray(` 1. Edit ${result.path}`));
31605
+ console.log(import_chalk5.default.gray(" 2. Run: adhdev provider reload"));
31606
+ console.log(import_chalk5.default.gray(` 3. Test: adhdev provider test ${type}`));
31607
+ console.log(import_chalk5.default.gray(" 4. Open DevConsole: http://127.0.0.1:19280"));
31608
+ console.log();
31609
+ } catch (e) {
31610
+ console.error(import_chalk5.default.red(`
31201
31611
  \u2717 ${e.message}
31202
31612
  `));
31203
- process.exit(1);
31204
- }
31205
- });
31206
- provider.command("run <type> <script>").description("Run a specific provider script (requires daemon --dev)").option("-p, --param <value>", "Parameter value (for sendMessage, switchSession, etc.)").option("-j, --json", "Output raw JSON").action(async (type, script, options) => {
31207
- try {
31208
- const http = await import("http");
31209
- const postData = JSON.stringify({
31210
- script,
31211
- params: options.param ? { text: options.param, sessionId: options.param, buttonText: options.param } : {}
31212
- });
31213
- const result = await new Promise((resolve, reject) => {
31214
- const req = http.request({
31215
- hostname: "127.0.0.1",
31216
- port: 19280,
31217
- path: `/api/providers/${type}/script`,
31218
- method: "POST",
31219
- headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) }
31220
- }, (res) => {
31221
- let data = "";
31222
- res.on("data", (c) => data += c);
31223
- res.on("end", () => {
31224
- try {
31225
- resolve(JSON.parse(data));
31226
- } catch {
31227
- resolve({ raw: data });
31228
- }
31613
+ process.exit(1);
31614
+ }
31615
+ });
31616
+ provider.command("run <type> <script>").description("Run a specific provider script (requires daemon --dev)").option("-p, --param <value>", "Parameter value (for sendMessage, switchSession, etc.)").option("-j, --json", "Output raw JSON").action(async (type, script, options) => {
31617
+ try {
31618
+ const http = await import("http");
31619
+ const postData = JSON.stringify({
31620
+ script,
31621
+ params: options.param ? { text: options.param, sessionId: options.param, buttonText: options.param } : {}
31622
+ });
31623
+ const result = await new Promise((resolve, reject) => {
31624
+ const req = http.request({
31625
+ hostname: "127.0.0.1",
31626
+ port: 19280,
31627
+ path: `/api/providers/${type}/script`,
31628
+ method: "POST",
31629
+ headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) }
31630
+ }, (res) => {
31631
+ let data = "";
31632
+ res.on("data", (c) => data += c);
31633
+ res.on("end", () => {
31634
+ try {
31635
+ resolve(JSON.parse(data));
31636
+ } catch {
31637
+ resolve({ raw: data });
31638
+ }
31639
+ });
31229
31640
  });
31641
+ req.on("error", () => reject(new Error("DevServer not reachable. Run: adhdev daemon --dev")));
31642
+ req.write(postData);
31643
+ req.end();
31230
31644
  });
31231
- req.on("error", () => reject(new Error("DevServer not reachable. Run: adhdev daemon --dev")));
31232
- req.write(postData);
31233
- req.end();
31234
- });
31235
- if (options.json) {
31236
- console.log(JSON.stringify(result, null, 2));
31237
- return;
31238
- }
31239
- if (result.error) {
31240
- console.log(import_chalk3.default.red(`
31645
+ if (options.json) {
31646
+ console.log(JSON.stringify(result, null, 2));
31647
+ return;
31648
+ }
31649
+ if (result.error) {
31650
+ console.log(import_chalk5.default.red(`
31241
31651
  \u2717 ${result.error}
31242
31652
  `));
31243
- if (result.available) console.log(import_chalk3.default.gray(` Available scripts: ${result.available.join(", ")}
31653
+ if (result.available) console.log(import_chalk5.default.gray(` Available scripts: ${result.available.join(", ")}
31244
31654
  `));
31245
- process.exit(1);
31246
- }
31247
- console.log(import_chalk3.default.bold(`
31248
- \u25B6 ${import_chalk3.default.cyan(type)} \u2192 ${import_chalk3.default.yellow(script)}
31655
+ process.exit(1);
31656
+ }
31657
+ console.log(import_chalk5.default.bold(`
31658
+ \u25B6 ${import_chalk5.default.cyan(type)} \u2192 ${import_chalk5.default.yellow(script)}
31249
31659
  `));
31250
- const output = result.result !== void 0 ? result.result : result;
31251
- console.log(typeof output === "string" ? output : JSON.stringify(output, null, 2));
31252
- console.log();
31253
- } catch (e) {
31254
- console.error(import_chalk3.default.red(`
31660
+ const output = result.result !== void 0 ? result.result : result;
31661
+ console.log(typeof output === "string" ? output : JSON.stringify(output, null, 2));
31662
+ console.log();
31663
+ } catch (e) {
31664
+ console.error(import_chalk5.default.red(`
31255
31665
  \u2717 ${e.message}
31256
31666
  `));
31257
- process.exit(1);
31258
- }
31259
- });
31260
- provider.command("source <type>").description("View source code of a provider").action(async (type) => {
31261
- try {
31262
- const http = await import("http");
31263
- const result = await new Promise((resolve, reject) => {
31264
- http.get(`http://127.0.0.1:19280/api/providers/${type}/source`, (res) => {
31265
- let data = "";
31266
- res.on("data", (c) => data += c);
31267
- res.on("end", () => {
31268
- try {
31269
- resolve(JSON.parse(data));
31270
- } catch {
31271
- resolve({ raw: data });
31272
- }
31667
+ process.exit(1);
31668
+ }
31669
+ });
31670
+ provider.command("source <type>").description("View source code of a provider").action(async (type) => {
31671
+ try {
31672
+ const http = await import("http");
31673
+ const result = await new Promise((resolve, reject) => {
31674
+ http.get(`http://127.0.0.1:19280/api/providers/${type}/source`, (res) => {
31675
+ let data = "";
31676
+ res.on("data", (c) => data += c);
31677
+ res.on("end", () => {
31678
+ try {
31679
+ resolve(JSON.parse(data));
31680
+ } catch {
31681
+ resolve({ raw: data });
31682
+ }
31683
+ });
31684
+ }).on("error", () => {
31685
+ reject(new Error("Use --offline or start daemon --dev"));
31273
31686
  });
31274
- }).on("error", () => {
31275
- reject(new Error("Use --offline or start daemon --dev"));
31276
- });
31277
- }).catch(async () => {
31278
- const pathMod = await import("path");
31279
- const fsMod = await import("fs");
31280
- const osMod = await import("os");
31281
- const possiblePaths = [
31282
- pathMod.join(osMod.homedir(), ".adhdev", "providers", type, "provider.js"),
31283
- pathMod.resolve(__dirname, "../providers/_builtin/ide", type, "provider.js"),
31284
- pathMod.resolve(__dirname, "../providers/_builtin/extension", type, "provider.js")
31285
- ];
31286
- for (const p of possiblePaths) {
31287
- if (fsMod.existsSync(p)) {
31288
- return { type, path: p, source: fsMod.readFileSync(p, "utf-8") };
31687
+ }).catch(async () => {
31688
+ const pathMod = await import("path");
31689
+ const fsMod = await import("fs");
31690
+ const osMod = await import("os");
31691
+ const possiblePaths = [
31692
+ pathMod.join(osMod.homedir(), ".adhdev", "providers", type, "provider.js"),
31693
+ pathMod.resolve(__dirname, "../../providers/_builtin/ide", type, "provider.js"),
31694
+ pathMod.resolve(__dirname, "../../providers/_builtin/extension", type, "provider.js")
31695
+ ];
31696
+ for (const p of possiblePaths) {
31697
+ if (fsMod.existsSync(p)) {
31698
+ return { type, path: p, source: fsMod.readFileSync(p, "utf-8") };
31699
+ }
31289
31700
  }
31290
- }
31291
- return { error: `Provider '${type}' not found` };
31292
- });
31293
- if (result.error) {
31294
- console.log(import_chalk3.default.red(`
31701
+ return { error: `Provider '${type}' not found` };
31702
+ });
31703
+ if (result.error) {
31704
+ console.log(import_chalk5.default.red(`
31295
31705
  \u2717 ${result.error}
31296
31706
  `));
31297
- process.exit(1);
31298
- }
31299
- console.log(import_chalk3.default.bold(`
31707
+ process.exit(1);
31708
+ }
31709
+ console.log(import_chalk5.default.bold(`
31300
31710
  \u{1F4C4} ${type} \u2014 ${result.path}
31301
31711
  `));
31302
- console.log(result.source);
31303
- } catch (e) {
31304
- console.error(import_chalk3.default.red(`
31712
+ console.log(result.source);
31713
+ } catch (e) {
31714
+ console.error(import_chalk5.default.red(`
31305
31715
  \u2717 ${e.message}
31306
31716
  `));
31307
- process.exit(1);
31308
- }
31309
- });
31310
- var cdp = program.command("cdp").description("\u{1F50D} CDP debugging tools \u2014 analyze IDE DOM for script development");
31311
- cdp.command("debug").description("Analyze IDE AI panel \u2014 find inputs, buttons, textareas, iframes").option("-p, --port <port>", "CDP port (direct mode)", "9222").option("-d, --daemon", "Use running daemon instead of direct CDP").option("--session <id>", "Agent webview session ID").option("-j, --json", "Output raw JSON").action(async (options) => {
31312
- try {
31313
- let result;
31314
- if (options.daemon) {
31315
- result = await sendDaemonCommand("cdp_dom_debug", { sessionId: options.session });
31316
- } else {
31317
- const expression = `(() => {
31717
+ process.exit(1);
31718
+ }
31719
+ });
31720
+ }
31721
+ function registerCdpCommands(program2) {
31722
+ const cdp = program2.command("cdp").description("\u{1F50D} CDP debugging tools \u2014 analyze IDE DOM for script development");
31723
+ cdp.command("debug").description("Analyze IDE AI panel \u2014 find inputs, buttons, textareas, iframes").option("-p, --port <port>", "CDP port (direct mode)", "9222").option("-d, --daemon", "Use running daemon instead of direct CDP").option("--session <id>", "Agent webview session ID").option("-j, --json", "Output raw JSON").action(async (options) => {
31724
+ try {
31725
+ let result;
31726
+ if (options.daemon) {
31727
+ result = await sendDaemonCommand("cdp_dom_debug", { sessionId: options.session });
31728
+ } else {
31729
+ const expression = `(() => {
31318
31730
  const result = { url: location.href, title: document.title, viewport: { w: window.innerWidth, h: window.innerHeight }, inputs: [], textareas: [], editables: [], buttons: [], iframes: [], textboxes: [] };
31319
31731
  document.querySelectorAll('input[type="text"], input:not([type])').forEach((el, i) => { if (i >= 10) return; result.inputs.push({ id: el.id||null, class: (el.className||'').toString().slice(0,150), placeholder: el.getAttribute('placeholder')||null, visible: el.offsetParent!==null, rect: (() => { try { const r=el.getBoundingClientRect(); return {x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)}; } catch{return null;} })() }); });
31320
31732
  document.querySelectorAll('textarea').forEach((el, i) => { if (i >= 10) return; result.textareas.push({ id: el.id||null, class: (el.className||'').toString().slice(0,150), placeholder: el.getAttribute('placeholder')||null, rows: el.rows, visible: el.offsetParent!==null }); });
@@ -31325,213 +31737,245 @@ cdp.command("debug").description("Analyze IDE AI panel \u2014 find inputs, butto
31325
31737
  document.querySelectorAll('iframe, webview').forEach((el, i) => { if (i >= 20) return; result.iframes.push({ tag: el.tagName?.toLowerCase(), src: el.getAttribute('src')?.slice(0,200)||null, title: el.getAttribute('title')||null }); });
31326
31738
  return JSON.stringify(result);
31327
31739
  })()`;
31328
- const raw = await directCdpEval(expression, parseInt(options.port));
31329
- result = typeof raw === "string" ? JSON.parse(raw) : raw;
31330
- }
31331
- if (options.json) {
31332
- console.log(JSON.stringify(result, null, 2));
31333
- return;
31334
- }
31335
- console.log(import_chalk3.default.bold("\n\u{1F50D} CDP DOM Debug\n"));
31336
- console.log(` ${import_chalk3.default.bold("URL:")} ${result.url || "N/A"}`);
31337
- console.log(` ${import_chalk3.default.bold("Title:")} ${result.title || "N/A"}`);
31338
- if (result.viewport) console.log(` ${import_chalk3.default.bold("Viewport:")} ${result.viewport.w}\xD7${result.viewport.h}`);
31339
- const sections = [
31340
- { key: "inputs", label: "\u{1F4DD} Inputs", fields: ["id", "placeholder", "class"] },
31341
- { key: "textareas", label: "\u{1F4DD} Textareas", fields: ["id", "placeholder", "rows"] },
31342
- { key: "editables", label: "\u270F\uFE0F ContentEditable", fields: ["tag", "role", "class", "text"] },
31343
- { key: "textboxes", label: '\u{1F4E6} role="textbox"', fields: ["tag", "class", "text"] },
31344
- { key: "buttons", label: "\u{1F518} Buttons", fields: ["text", "disabled"] },
31345
- { key: "iframes", label: "\u{1F5BC} Iframes/Webviews", fields: ["tag", "src", "title"] }
31346
- ];
31347
- for (const { key, label, fields } of sections) {
31348
- const items = result[key] || [];
31349
- if (items.length === 0) continue;
31350
- console.log(`
31351
- ${import_chalk3.default.bold(label)} (${items.length})`);
31352
- for (const item of items) {
31353
- const vis = item.visible === false ? import_chalk3.default.red(" [hidden]") : "";
31354
- const parts = fields.map((f) => item[f] ? `${f}=${import_chalk3.default.cyan(String(item[f]).slice(0, 60))}` : null).filter(Boolean);
31355
- console.log(` ${import_chalk3.default.gray("\u2022")} ${parts.join(" ")}${vis}`);
31740
+ const raw = await directCdpEval(expression, parseInt(options.port));
31741
+ result = typeof raw === "string" ? JSON.parse(raw) : raw;
31356
31742
  }
31357
- }
31358
- console.log();
31359
- } catch (e) {
31360
- console.error(import_chalk3.default.red(`
31743
+ if (options.json) {
31744
+ console.log(JSON.stringify(result, null, 2));
31745
+ return;
31746
+ }
31747
+ console.log(import_chalk5.default.bold("\n\u{1F50D} CDP DOM Debug\n"));
31748
+ console.log(` ${import_chalk5.default.bold("URL:")} ${result.url || "N/A"}`);
31749
+ console.log(` ${import_chalk5.default.bold("Title:")} ${result.title || "N/A"}`);
31750
+ if (result.viewport) console.log(` ${import_chalk5.default.bold("Viewport:")} ${result.viewport.w}\xD7${result.viewport.h}`);
31751
+ const sections = [
31752
+ { key: "inputs", label: "\u{1F4DD} Inputs", fields: ["id", "placeholder", "class"] },
31753
+ { key: "textareas", label: "\u{1F4DD} Textareas", fields: ["id", "placeholder", "rows"] },
31754
+ { key: "editables", label: "\u270F\uFE0F ContentEditable", fields: ["tag", "role", "class", "text"] },
31755
+ { key: "textboxes", label: '\u{1F4E6} role="textbox"', fields: ["tag", "class", "text"] },
31756
+ { key: "buttons", label: "\u{1F518} Buttons", fields: ["text", "disabled"] },
31757
+ { key: "iframes", label: "\u{1F5BC} Iframes/Webviews", fields: ["tag", "src", "title"] }
31758
+ ];
31759
+ for (const { key, label, fields } of sections) {
31760
+ const items = result[key] || [];
31761
+ if (items.length === 0) continue;
31762
+ console.log(`
31763
+ ${import_chalk5.default.bold(label)} (${items.length})`);
31764
+ for (const item of items) {
31765
+ const vis = item.visible === false ? import_chalk5.default.red(" [hidden]") : "";
31766
+ const parts = fields.map((f) => item[f] ? `${f}=${import_chalk5.default.cyan(String(item[f]).slice(0, 60))}` : null).filter(Boolean);
31767
+ console.log(` ${import_chalk5.default.gray("\u2022")} ${parts.join(" ")}${vis}`);
31768
+ }
31769
+ }
31770
+ console.log();
31771
+ } catch (e) {
31772
+ console.error(import_chalk5.default.red(`
31361
31773
  \u2717 ${e.message}
31362
31774
  `));
31363
- process.exit(1);
31364
- }
31365
- });
31366
- cdp.command("dump [selector]").description("Dump DOM tree (default: body)").option("-p, --port <port>", "CDP port (direct mode)", "9222").option("-d, --daemon", "Use running daemon").option("-f, --format <fmt>", "Format: html, tree, summary", "tree").option("--depth <n>", "Max depth", "6").option("--session <id>", "Agent webview session ID").option("-o, --output <file>", "Save to file").action(async (selector, options) => {
31367
- try {
31368
- const sel = selector || "body";
31369
- const depth = parseInt(options.depth) || 6;
31370
- let result;
31371
- if (options.daemon) {
31372
- const resp = await sendDaemonCommand("cdp_dom_dump", {
31373
- selector: sel,
31374
- format: options.format,
31375
- depth,
31376
- sessionId: options.session
31377
- });
31378
- result = resp?.result || resp;
31379
- } else {
31380
- let expr;
31381
- if (options.format === "tree") {
31382
- expr = `(() => { const root = document.querySelector('${sel.replace(/'/g, "\\'")}'); if (!root) return 'Not found: ${sel}'; function tree(el, indent, d, maxD) { if (d > maxD) return indent + '...\\n'; let line = indent + '<' + (el.tagName?.toLowerCase()||'?'); if (el.id) line += ' #' + el.id; if (el.className && typeof el.className === 'string') { const cls = el.className.trim().split(' ').filter(c=>c).slice(0,3).join('.'); if(cls) line += ' .' + cls; } const role = el.getAttribute?.('role'); if(role) line += ' [role=' + role + ']'; line += '> (' + (el.children?.length||0) + ')\\n'; let r = line; if (el.children?.length > 0 && d < maxD) { for (let i = 0; i < Math.min(el.children.length, 30); i++) { r += tree(el.children[i], indent + ' ', d+1, maxD); } if (el.children.length > 30) r += indent + ' ... +' + (el.children.length-30) + ' more\\n'; } return r; } return tree(root, '', 0, ${depth}); })()`;
31383
- } else if (options.format === "summary") {
31384
- expr = `(() => { const root = document.querySelector('${sel.replace(/'/g, "\\'")}'); if (!root) return JSON.stringify({error:'Not found'}); function s(el, d, maxD) { if (d > maxD) return {tag:'...',note:'max depth'}; const n = {tag:el.tagName?.toLowerCase(),id:el.id||undefined,class:el.className&&typeof el.className==='string'?el.className.split(' ').filter(c=>c).slice(0,5).join(' '):undefined,role:el.getAttribute?.('role')||undefined,childCount:el.children?.length||0}; if (el.children?.length > 0 && d < maxD) { n.children = Array.from(el.children).slice(0,30).map(c=>s(c,d+1,maxD)); } return n; } return JSON.stringify(s(root,0,${depth})); })()`;
31775
+ process.exit(1);
31776
+ }
31777
+ });
31778
+ cdp.command("dump [selector]").description("Dump DOM tree (default: body)").option("-p, --port <port>", "CDP port (direct mode)", "9222").option("-d, --daemon", "Use running daemon").option("-f, --format <fmt>", "Format: html, tree, summary", "tree").option("--depth <n>", "Max depth", "6").option("--session <id>", "Agent webview session ID").option("-o, --output <file>", "Save to file").action(async (selector, options) => {
31779
+ try {
31780
+ const sel = selector || "body";
31781
+ const depth = parseInt(options.depth) || 6;
31782
+ let result;
31783
+ if (options.daemon) {
31784
+ const resp = await sendDaemonCommand("cdp_dom_dump", {
31785
+ selector: sel,
31786
+ format: options.format,
31787
+ depth,
31788
+ sessionId: options.session
31789
+ });
31790
+ result = resp?.result || resp;
31385
31791
  } else {
31386
- expr = `(() => { const root = document.querySelector('${sel.replace(/'/g, "\\'")}'); if (!root) return 'Not found: ${sel}'; let html = root.outerHTML; if (html.length > 200000) html = html.slice(0, 200000) + '\\n<!-- TRUNCATED -->'; return html; })()`;
31387
- }
31388
- result = await directCdpEval(expr, parseInt(options.port));
31389
- if (options.format === "summary" && typeof result === "string") {
31390
- try {
31391
- result = JSON.parse(result);
31392
- } catch {
31792
+ let expr;
31793
+ if (options.format === "tree") {
31794
+ expr = `(() => { const root = document.querySelector('${sel.replace(/'/g, "\\'")}'); if (!root) return 'Not found: ${sel}'; function tree(el, indent, d, maxD) { if (d > maxD) return indent + '...\\n'; let line = indent + '<' + (el.tagName?.toLowerCase()||'?'); if (el.id) line += ' #' + el.id; if (el.className && typeof el.className === 'string') { const cls = el.className.trim().split(' ').filter(c=>c).slice(0,3).join('.'); if(cls) line += ' .' + cls; } const role = el.getAttribute?.('role'); if(role) line += ' [role=' + role + ']'; line += '> (' + (el.children?.length||0) + ')\\n'; let r = line; if (el.children?.length > 0 && d < maxD) { for (let i = 0; i < Math.min(el.children.length, 30); i++) { r += tree(el.children[i], indent + ' ', d+1, maxD); } if (el.children.length > 30) r += indent + ' ... +' + (el.children.length-30) + ' more\\n'; } return r; } return tree(root, '', 0, ${depth}); })()`;
31795
+ } else if (options.format === "summary") {
31796
+ expr = `(() => { const root = document.querySelector('${sel.replace(/'/g, "\\'")}'); if (!root) return JSON.stringify({error:'Not found'}); function s(el, d, maxD) { if (d > maxD) return {tag:'...',note:'max depth'}; const n = {tag:el.tagName?.toLowerCase(),id:el.id||undefined,class:el.className&&typeof el.className==='string'?el.className.split(' ').filter(c=>c).slice(0,5).join(' '):undefined,role:el.getAttribute?.('role')||undefined,childCount:el.children?.length||0}; if (el.children?.length > 0 && d < maxD) { n.children = Array.from(el.children).slice(0,30).map(c=>s(c,d+1,maxD)); } return n; } return JSON.stringify(s(root,0,${depth})); })()`;
31797
+ } else {
31798
+ expr = `(() => { const root = document.querySelector('${sel.replace(/'/g, "\\'")}'); if (!root) return 'Not found: ${sel}'; let html = root.outerHTML; if (html.length > 200000) html = html.slice(0, 200000) + '\\n<!-- TRUNCATED -->'; return html; })()`;
31799
+ }
31800
+ result = await directCdpEval(expr, parseInt(options.port));
31801
+ if (options.format === "summary" && typeof result === "string") {
31802
+ try {
31803
+ result = JSON.parse(result);
31804
+ } catch {
31805
+ }
31393
31806
  }
31394
31807
  }
31395
- }
31396
- const output = typeof result === "string" ? result : JSON.stringify(result, null, 2);
31397
- if (options.output) {
31398
- const fs3 = await import("fs");
31399
- fs3.writeFileSync(options.output, output, "utf-8");
31400
- console.log(import_chalk3.default.green(`
31808
+ const output = typeof result === "string" ? result : JSON.stringify(result, null, 2);
31809
+ if (options.output) {
31810
+ const fs3 = await import("fs");
31811
+ fs3.writeFileSync(options.output, output, "utf-8");
31812
+ console.log(import_chalk5.default.green(`
31401
31813
  \u2713 Saved to ${options.output} (${output.length} chars)
31402
31814
  `));
31403
- } else {
31404
- console.log(output);
31405
- }
31406
- } catch (e) {
31407
- console.error(import_chalk3.default.red(`
31815
+ } else {
31816
+ console.log(output);
31817
+ }
31818
+ } catch (e) {
31819
+ console.error(import_chalk5.default.red(`
31408
31820
  \u2717 ${e.message}
31409
31821
  `));
31410
- process.exit(1);
31411
- }
31412
- });
31413
- cdp.command("query <selector>").description("Test a CSS selector \u2014 count matches, show elements").option("-p, --port <port>", "CDP port (direct mode)", "9222").option("-d, --daemon", "Use running daemon").option("-l, --limit <n>", "Max results", "10").option("--session <id>", "Agent webview session ID").option("-j, --json", "Output raw JSON").action(async (selector, options) => {
31414
- try {
31415
- const limit = parseInt(options.limit) || 10;
31416
- let result;
31417
- if (options.daemon) {
31418
- result = await sendDaemonCommand("cdp_dom_query", {
31419
- selector,
31420
- limit,
31421
- sessionId: options.session
31422
- });
31423
- } else {
31424
- const expr = `(() => { try { const els = document.querySelectorAll('${selector.replace(/'/g, "\\'")}'); const results = []; for (let i = 0; i < Math.min(els.length, ${limit}); i++) { const el = els[i]; results.push({ index: i, tag: el.tagName?.toLowerCase(), id: el.id||null, class: el.className&&typeof el.className==='string'?el.className.trim().slice(0,200):null, role: el.getAttribute?.('role')||null, text: (el.textContent||'').trim().slice(0,100), visible: el.offsetParent!==null||el.offsetWidth>0, rect: (()=>{try{const r=el.getBoundingClientRect();return{x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};}catch{return null;}})() }); } return JSON.stringify({ total: els.length, results }); } catch(e) { return JSON.stringify({ error: e.message }); } })()`;
31425
- const raw = await directCdpEval(expr, parseInt(options.port));
31426
- result = typeof raw === "string" ? JSON.parse(raw) : raw;
31427
- }
31428
- if (options.json) {
31429
- console.log(JSON.stringify(result, null, 2));
31430
- return;
31822
+ process.exit(1);
31431
31823
  }
31432
- const total = result.total || 0;
31433
- console.log(import_chalk3.default.bold(`
31434
- \u{1F50D} Selector: ${import_chalk3.default.cyan(selector)}`));
31435
- console.log(` Matches: ${total === 0 ? import_chalk3.default.red("0") : import_chalk3.default.green(total)}
31824
+ });
31825
+ cdp.command("query <selector>").description("Test a CSS selector \u2014 count matches, show elements").option("-p, --port <port>", "CDP port (direct mode)", "9222").option("-d, --daemon", "Use running daemon").option("-l, --limit <n>", "Max results", "10").option("--session <id>", "Agent webview session ID").option("-j, --json", "Output raw JSON").action(async (selector, options) => {
31826
+ try {
31827
+ const limit = parseInt(options.limit) || 10;
31828
+ let result;
31829
+ if (options.daemon) {
31830
+ result = await sendDaemonCommand("cdp_dom_query", {
31831
+ selector,
31832
+ limit,
31833
+ sessionId: options.session
31834
+ });
31835
+ } else {
31836
+ const expr = `(() => { try { const els = document.querySelectorAll('${selector.replace(/'/g, "\\'")}'); const results = []; for (let i = 0; i < Math.min(els.length, ${limit}); i++) { const el = els[i]; results.push({ index: i, tag: el.tagName?.toLowerCase(), id: el.id||null, class: el.className&&typeof el.className==='string'?el.className.trim().slice(0,200):null, role: el.getAttribute?.('role')||null, text: (el.textContent||'').trim().slice(0,100), visible: el.offsetParent!==null||el.offsetWidth>0, rect: (()=>{try{const r=el.getBoundingClientRect();return{x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};}catch{return null;}})() }); } return JSON.stringify({ total: els.length, results }); } catch(e) { return JSON.stringify({ error: e.message }); } })()`;
31837
+ const raw = await directCdpEval(expr, parseInt(options.port));
31838
+ result = typeof raw === "string" ? JSON.parse(raw) : raw;
31839
+ }
31840
+ if (options.json) {
31841
+ console.log(JSON.stringify(result, null, 2));
31842
+ return;
31843
+ }
31844
+ const total = result.total || 0;
31845
+ console.log(import_chalk5.default.bold(`
31846
+ \u{1F50D} Selector: ${import_chalk5.default.cyan(selector)}`));
31847
+ console.log(` Matches: ${total === 0 ? import_chalk5.default.red("0") : import_chalk5.default.green(total)}
31436
31848
  `);
31437
- for (const item of result.results || []) {
31438
- const vis = item.visible === false ? import_chalk3.default.red(" [hidden]") : import_chalk3.default.green(" [visible]");
31439
- const rect = item.rect ? import_chalk3.default.gray(` ${item.rect.x},${item.rect.y} ${item.rect.w}\xD7${item.rect.h}`) : "";
31440
- console.log(` ${import_chalk3.default.yellow(`[${item.index}]`)} <${import_chalk3.default.bold(item.tag)}>${vis}${rect}`);
31441
- if (item.id) console.log(` id: ${import_chalk3.default.cyan(item.id)}`);
31442
- if (item.class) console.log(` class: ${import_chalk3.default.gray(item.class.slice(0, 80))}`);
31443
- if (item.text) console.log(` text: "${import_chalk3.default.white(item.text.slice(0, 80))}"`);
31444
- if (item.role) console.log(` role: ${import_chalk3.default.magenta(item.role)}`);
31445
- }
31446
- console.log();
31447
- } catch (e) {
31448
- console.error(import_chalk3.default.red(`
31849
+ for (const item of result.results || []) {
31850
+ const vis = item.visible === false ? import_chalk5.default.red(" [hidden]") : import_chalk5.default.green(" [visible]");
31851
+ const rect = item.rect ? import_chalk5.default.gray(` ${item.rect.x},${item.rect.y} ${item.rect.w}\xD7${item.rect.h}`) : "";
31852
+ console.log(` ${import_chalk5.default.yellow(`[${item.index}]`)} <${import_chalk5.default.bold(item.tag)}>${vis}${rect}`);
31853
+ if (item.id) console.log(` id: ${import_chalk5.default.cyan(item.id)}`);
31854
+ if (item.class) console.log(` class: ${import_chalk5.default.gray(item.class.slice(0, 80))}`);
31855
+ if (item.text) console.log(` text: "${import_chalk5.default.white(item.text.slice(0, 80))}"`);
31856
+ if (item.role) console.log(` role: ${import_chalk5.default.magenta(item.role)}`);
31857
+ }
31858
+ console.log();
31859
+ } catch (e) {
31860
+ console.error(import_chalk5.default.red(`
31449
31861
  \u2717 ${e.message}
31450
31862
  `));
31451
- process.exit(1);
31452
- }
31453
- });
31454
- cdp.command("eval <expression>").description("Execute JavaScript expression via CDP").option("-p, --port <port>", "CDP port", "9222").option("-d, --daemon", "Use running daemon").action(async (expression, options) => {
31455
- try {
31456
- let result;
31457
- if (options.daemon) {
31458
- const resp = await sendDaemonCommand("cdp_eval", { expression });
31459
- result = resp?.result !== void 0 ? resp.result : resp;
31460
- } else {
31461
- result = await directCdpEval(expression, parseInt(options.port));
31863
+ process.exit(1);
31462
31864
  }
31463
- const output = typeof result === "string" ? result : JSON.stringify(result, null, 2);
31464
- console.log(output);
31465
- } catch (e) {
31466
- console.error(import_chalk3.default.red(`
31865
+ });
31866
+ cdp.command("eval <expression>").description("Execute JavaScript expression via CDP").option("-p, --port <port>", "CDP port", "9222").option("-d, --daemon", "Use running daemon").action(async (expression, options) => {
31867
+ try {
31868
+ let result;
31869
+ if (options.daemon) {
31870
+ const resp = await sendDaemonCommand("cdp_eval", { expression });
31871
+ result = resp?.result !== void 0 ? resp.result : resp;
31872
+ } else {
31873
+ result = await directCdpEval(expression, parseInt(options.port));
31874
+ }
31875
+ const output = typeof result === "string" ? result : JSON.stringify(result, null, 2);
31876
+ console.log(output);
31877
+ } catch (e) {
31878
+ console.error(import_chalk5.default.red(`
31467
31879
  \u2717 ${e.message}
31468
31880
  `));
31469
- process.exit(1);
31470
- }
31471
- });
31472
- cdp.command("screenshot").description("Capture IDE screenshot").option("-p, --port <port>", "CDP port", "9222").option("-o, --output <file>", "Output file path", "/tmp/cdp_screenshot.jpg").action(async (options) => {
31473
- try {
31474
- const http = await import("http");
31475
- const targets = await new Promise((resolve, reject) => {
31476
- http.get(`http://127.0.0.1:${options.port}/json`, (res) => {
31477
- let data = "";
31478
- res.on("data", (c) => data += c);
31479
- res.on("end", () => {
31480
- try {
31481
- resolve(JSON.parse(data));
31482
- } catch {
31483
- reject(new Error("Invalid JSON"));
31484
- }
31485
- });
31486
- }).on("error", (e) => reject(e));
31487
- });
31488
- const isNonMain = (title) => !title || /extension-output|ADHDev CDP|Debug Console|Output\s*$|Launchpad/i.test(title);
31489
- const pages = targets.filter((t) => (t.type === "page" || t.type === "Page") && t.webSocketDebuggerUrl);
31490
- const mainPages = pages.filter((t) => !isNonMain(t.title || ""));
31491
- const target = (mainPages.length > 0 ? mainPages[0] : pages[0]) || targets[0];
31492
- if (!target?.webSocketDebuggerUrl) throw new Error("No CDP target");
31493
- const WebSocket2 = (await import("ws")).default;
31494
- const ws = new WebSocket2(target.webSocketDebuggerUrl);
31495
- await new Promise((resolve, reject) => {
31496
- ws.on("open", () => {
31497
- ws.send(JSON.stringify({ id: 1, method: "Page.captureScreenshot", params: { format: "jpeg", quality: 50 } }));
31881
+ process.exit(1);
31882
+ }
31883
+ });
31884
+ cdp.command("screenshot").description("Capture IDE screenshot").option("-p, --port <port>", "CDP port", "9222").option("-o, --output <file>", "Output file path", "/tmp/cdp_screenshot.jpg").action(async (options) => {
31885
+ try {
31886
+ const http = await import("http");
31887
+ const targets = await new Promise((resolve, reject) => {
31888
+ http.get(`http://127.0.0.1:${options.port}/json`, (res) => {
31889
+ let data = "";
31890
+ res.on("data", (c) => data += c);
31891
+ res.on("end", () => {
31892
+ try {
31893
+ resolve(JSON.parse(data));
31894
+ } catch {
31895
+ reject(new Error("Invalid JSON"));
31896
+ }
31897
+ });
31898
+ }).on("error", (e) => reject(e));
31498
31899
  });
31499
- ws.on("message", async (data) => {
31500
- const msg = JSON.parse(data.toString());
31501
- if (msg.id === 1 && msg.result?.data) {
31502
- const fs3 = await import("fs");
31503
- fs3.writeFileSync(options.output, Buffer.from(msg.result.data, "base64"));
31504
- console.log(import_chalk3.default.green(`
31900
+ const isNonMain = (title) => !title || /extension-output|ADHDev CDP|Debug Console|Output\s*$|Launchpad/i.test(title);
31901
+ const pages = targets.filter((t) => (t.type === "page" || t.type === "Page") && t.webSocketDebuggerUrl);
31902
+ const mainPages = pages.filter((t) => !isNonMain(t.title || ""));
31903
+ const target = (mainPages.length > 0 ? mainPages[0] : pages[0]) || targets[0];
31904
+ if (!target?.webSocketDebuggerUrl) throw new Error("No CDP target");
31905
+ const WebSocket2 = (await import("ws")).default;
31906
+ const ws = new WebSocket2(target.webSocketDebuggerUrl);
31907
+ await new Promise((resolve, reject) => {
31908
+ ws.on("open", () => {
31909
+ ws.send(JSON.stringify({ id: 1, method: "Page.captureScreenshot", params: { format: "jpeg", quality: 50 } }));
31910
+ });
31911
+ ws.on("message", async (data) => {
31912
+ const msg = JSON.parse(data.toString());
31913
+ if (msg.id === 1 && msg.result?.data) {
31914
+ const fs3 = await import("fs");
31915
+ fs3.writeFileSync(options.output, Buffer.from(msg.result.data, "base64"));
31916
+ console.log(import_chalk5.default.green(`
31505
31917
  \u2713 Screenshot saved to ${options.output}
31506
31918
  `));
31507
- ws.close();
31508
- resolve();
31509
- }
31919
+ ws.close();
31920
+ resolve();
31921
+ }
31922
+ });
31923
+ ws.on("error", (e) => reject(e));
31510
31924
  });
31511
- ws.on("error", (e) => reject(e));
31512
- });
31513
- } catch (e) {
31514
- console.error(import_chalk3.default.red(`
31925
+ } catch (e) {
31926
+ console.error(import_chalk5.default.red(`
31515
31927
  \u2717 ${e.message}
31516
31928
  `));
31517
- process.exit(1);
31929
+ process.exit(1);
31930
+ }
31931
+ });
31932
+ }
31933
+
31934
+ // src/cli/index.ts
31935
+ var pkgVersion2 = "unknown";
31936
+ try {
31937
+ const possiblePaths = [
31938
+ (0, import_path.join)(__dirname, "..", "..", "package.json"),
31939
+ (0, import_path.join)(__dirname, "..", "package.json"),
31940
+ (0, import_path.join)(__dirname, "package.json")
31941
+ ];
31942
+ for (const p of possiblePaths) {
31943
+ try {
31944
+ const data = JSON.parse((0, import_fs.readFileSync)(p, "utf-8"));
31945
+ if (data.version) {
31946
+ pkgVersion2 = data.version;
31947
+ break;
31948
+ }
31949
+ } catch {
31950
+ }
31518
31951
  }
31519
- });
31952
+ } catch {
31953
+ }
31954
+ var _cliProviderLoader = new import_daemon_core6.ProviderLoader({ logFn: () => {
31955
+ } });
31956
+ _cliProviderLoader.loadAll();
31957
+ _cliProviderLoader.registerToDetector();
31958
+ var program = new import_commander.Command();
31959
+ program.name("adhdev").description("\u{1F9A6} ADHDev \u2014 Agent Dashboard Hub for Dev").version(pkgVersion2);
31960
+ registerSetupCommands(program, _cliProviderLoader);
31961
+ registerDaemonCommands(program, pkgVersion2);
31962
+ registerProviderCommands(program);
31963
+ registerCdpCommands(program);
31520
31964
  if (process.argv.length <= 2) {
31521
31965
  program.outputHelp();
31522
31966
  console.log();
31523
- console.log(import_chalk3.default.gray(" Quick start:"));
31524
- console.log(import_chalk3.default.gray(" adhdev daemon \u2014 Start unified daemon (Required)"));
31525
- console.log(import_chalk3.default.gray(" adhdev launch cursor \u2014 Launch IDE with CDP (e.g. cursor, windsurf)"));
31526
- console.log(import_chalk3.default.gray(" adhdev launch claude \u2014 Launch CLI agent (e.g. gemini, claude)"));
31527
- console.log(import_chalk3.default.gray(" adhdev setup \u2014 First-time setup & configuration"));
31528
- console.log(import_chalk3.default.gray(" adhdev status \u2014 Check current setup"));
31967
+ console.log(import_chalk6.default.gray(" Quick start:"));
31968
+ console.log(import_chalk6.default.gray(" adhdev daemon \u2014 Start unified daemon (Required)"));
31969
+ console.log(import_chalk6.default.gray(" adhdev launch cursor \u2014 Launch IDE with CDP (e.g. cursor, windsurf)"));
31970
+ console.log(import_chalk6.default.gray(" adhdev launch claude \u2014 Launch CLI agent (e.g. gemini, claude)"));
31971
+ console.log(import_chalk6.default.gray(" adhdev setup \u2014 First-time setup & configuration"));
31972
+ console.log(import_chalk6.default.gray(" adhdev status \u2014 Check current setup"));
31529
31973
  console.log();
31530
31974
  } else {
31531
31975
  program.parseAsync(process.argv).catch((err) => {
31532
- console.error(import_chalk3.default.red(`
31976
+ console.error(import_chalk6.default.red(`
31533
31977
  \u2717 ${err.message}`));
31534
31978
  process.exit(1);
31535
31979
  });
31536
31980
  }
31537
- //# sourceMappingURL=cli-entrypoint.js.map
31981
+ //# sourceMappingURL=index.js.map