adhdev 0.8.49 → 0.8.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -4990,6 +4990,145 @@ var init_contracts = __esm({
4990
4990
  }
4991
4991
  });
4992
4992
 
4993
+ // ../../oss/packages/daemon-core/src/logging/debug-config.ts
4994
+ function normalizeCategories(categories) {
4995
+ if (!Array.isArray(categories)) return [];
4996
+ return categories.map((category) => String(category || "").trim()).filter(Boolean);
4997
+ }
4998
+ function resolveDebugRuntimeConfig(options = {}) {
4999
+ const dev = options.dev === true;
5000
+ return {
5001
+ logLevel: options.logLevel || (dev ? "debug" : DEFAULT_CONFIG2.logLevel),
5002
+ collectDebugTrace: typeof options.trace === "boolean" ? options.trace : dev,
5003
+ traceContent: options.traceContent === true,
5004
+ traceBufferSize: Number.isFinite(options.traceBufferSize) ? Math.max(10, Math.floor(options.traceBufferSize)) : dev ? DEV_TRACE_BUFFER_SIZE : DEFAULT_CONFIG2.traceBufferSize,
5005
+ traceCategories: normalizeCategories(options.traceCategories)
5006
+ };
5007
+ }
5008
+ function setDebugRuntimeConfig(config2) {
5009
+ currentConfig = {
5010
+ ...config2,
5011
+ traceCategories: normalizeCategories(config2.traceCategories),
5012
+ traceBufferSize: Math.max(10, Math.floor(config2.traceBufferSize || DEFAULT_CONFIG2.traceBufferSize))
5013
+ };
5014
+ }
5015
+ function getDebugRuntimeConfig() {
5016
+ return { ...currentConfig, traceCategories: [...currentConfig.traceCategories] };
5017
+ }
5018
+ function resetDebugRuntimeConfig() {
5019
+ currentConfig = { ...DEFAULT_CONFIG2 };
5020
+ }
5021
+ function shouldCollectTraceCategory(category) {
5022
+ const config2 = currentConfig;
5023
+ if (!config2.collectDebugTrace) return false;
5024
+ if (!category) return true;
5025
+ if (config2.traceCategories.length === 0) return true;
5026
+ return config2.traceCategories.includes(category);
5027
+ }
5028
+ var NORMAL_TRACE_BUFFER_SIZE, DEV_TRACE_BUFFER_SIZE, DEFAULT_CONFIG2, currentConfig;
5029
+ var init_debug_config = __esm({
5030
+ "../../oss/packages/daemon-core/src/logging/debug-config.ts"() {
5031
+ "use strict";
5032
+ NORMAL_TRACE_BUFFER_SIZE = 200;
5033
+ DEV_TRACE_BUFFER_SIZE = 1e3;
5034
+ DEFAULT_CONFIG2 = {
5035
+ logLevel: "info",
5036
+ collectDebugTrace: false,
5037
+ traceContent: false,
5038
+ traceBufferSize: NORMAL_TRACE_BUFFER_SIZE,
5039
+ traceCategories: []
5040
+ };
5041
+ currentConfig = { ...DEFAULT_CONFIG2 };
5042
+ }
5043
+ });
5044
+
5045
+ // ../../oss/packages/daemon-core/src/logging/debug-trace.ts
5046
+ function summarizeString(value) {
5047
+ return `[${value.length} chars]`;
5048
+ }
5049
+ function sanitizeTraceValue(value, traceContent) {
5050
+ if (traceContent) {
5051
+ if (Array.isArray(value)) return value.map((entry) => sanitizeTraceValue(entry, traceContent));
5052
+ if (value && typeof value === "object") {
5053
+ return Object.fromEntries(
5054
+ Object.entries(value).map(([key, nested]) => [key, sanitizeTraceValue(nested, traceContent)])
5055
+ );
5056
+ }
5057
+ return value;
5058
+ }
5059
+ if (typeof value === "string") return summarizeString(value);
5060
+ if (Array.isArray(value)) return value.map((entry) => sanitizeTraceValue(entry, traceContent));
5061
+ if (value && typeof value === "object") {
5062
+ return Object.fromEntries(
5063
+ Object.entries(value).map(([key, nested]) => [key, sanitizeTraceValue(nested, traceContent)])
5064
+ );
5065
+ }
5066
+ return value;
5067
+ }
5068
+ function sanitizeTracePayload(payload) {
5069
+ if (!payload) return {};
5070
+ const { traceContent } = getDebugRuntimeConfig();
5071
+ return sanitizeTraceValue(payload, traceContent);
5072
+ }
5073
+ function createEntry(event) {
5074
+ return {
5075
+ id: `trace_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
5076
+ ts: Date.now(),
5077
+ ...event,
5078
+ payload: sanitizeTracePayload(event.payload)
5079
+ };
5080
+ }
5081
+ function createDebugTraceStore(options) {
5082
+ const entries = [];
5083
+ const capacity = Math.max(1, Math.floor(options.capacity || 100));
5084
+ return {
5085
+ record(event) {
5086
+ if (!options.enabled) return null;
5087
+ const entry = createEntry(event);
5088
+ entries.push(entry);
5089
+ if (entries.length > capacity) {
5090
+ entries.splice(0, entries.length - capacity);
5091
+ }
5092
+ return entry;
5093
+ },
5094
+ list(query = {}) {
5095
+ const limit = Math.max(1, Math.floor(query.limit || 100));
5096
+ return entries.filter((entry) => !query.interactionId || entry.interactionId === query.interactionId).filter((entry) => !query.category || entry.category === query.category).slice(-limit).map((entry) => ({ ...entry, payload: entry.payload ? { ...entry.payload } : {} }));
5097
+ },
5098
+ clear() {
5099
+ entries.splice(0, entries.length);
5100
+ }
5101
+ };
5102
+ }
5103
+ function configureDebugTraceStore() {
5104
+ const config2 = getDebugRuntimeConfig();
5105
+ globalStore = createDebugTraceStore({
5106
+ enabled: config2.collectDebugTrace,
5107
+ capacity: config2.traceBufferSize
5108
+ });
5109
+ }
5110
+ function recordDebugTrace(event) {
5111
+ if (!shouldCollectTraceCategory(event.category)) return null;
5112
+ return globalStore.record(event);
5113
+ }
5114
+ function getRecentDebugTrace(query = {}) {
5115
+ return globalStore.list(query);
5116
+ }
5117
+ function clearDebugTrace() {
5118
+ globalStore.clear();
5119
+ }
5120
+ function createInteractionId(prefix = "ix") {
5121
+ return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
5122
+ }
5123
+ var globalStore;
5124
+ var init_debug_trace = __esm({
5125
+ "../../oss/packages/daemon-core/src/logging/debug-trace.ts"() {
5126
+ "use strict";
5127
+ init_debug_config();
5128
+ globalStore = createDebugTraceStore({ enabled: false, capacity: getDebugRuntimeConfig().traceBufferSize });
5129
+ }
5130
+ });
5131
+
4993
5132
  // ../../oss/packages/daemon-core/src/commands/chat-commands.ts
4994
5133
  function hashSignatureParts(parts) {
4995
5134
  let hash2 = 2166136261;
@@ -5055,6 +5194,20 @@ function getHistorySessionId(h, args) {
5055
5194
  const providerSessionId = typeof state?.providerSessionId === "string" ? state.providerSessionId.trim() : "";
5056
5195
  return providerSessionId || targetSessionId;
5057
5196
  }
5197
+ function getInteractionId(args) {
5198
+ return typeof args?._interactionId === "string" && args._interactionId.trim() ? args._interactionId.trim() : void 0;
5199
+ }
5200
+ function traceProviderEvent(args, category, stage, options) {
5201
+ recordDebugTrace({
5202
+ interactionId: getInteractionId(args),
5203
+ category,
5204
+ stage,
5205
+ level: options.level || "info",
5206
+ sessionId: typeof args?.targetSessionId === "string" ? args.targetSessionId : options.h.currentSession?.sessionId,
5207
+ providerType: options.provider?.type || options.h.currentProviderType || options.h.currentSession?.providerType,
5208
+ payload: options.payload
5209
+ });
5210
+ }
5058
5211
  function callLegacyTextScript(script, text) {
5059
5212
  if (typeof script !== "function") return null;
5060
5213
  return script(text);
@@ -5300,6 +5453,16 @@ async function handleReadChat(h, args) {
5300
5453
  }
5301
5454
  if (parsed && typeof parsed === "object") {
5302
5455
  _log(`Extension OK: ${parsed.messages?.length || 0} msgs`);
5456
+ traceProviderEvent(args, "provider", "extension.read_chat.success", {
5457
+ h,
5458
+ provider,
5459
+ payload: {
5460
+ method: "evaluateProviderScript",
5461
+ result: evalResult.result,
5462
+ parsed,
5463
+ messageCount: Array.isArray(parsed.messages) ? parsed.messages.length : 0
5464
+ }
5465
+ });
5303
5466
  h.historyWriter.appendNewMessages(
5304
5467
  provider?.type || "unknown_extension",
5305
5468
  toHistoryPersistedMessages(normalizeReadChatMessages(parsed)),
@@ -5312,6 +5475,12 @@ async function handleReadChat(h, args) {
5312
5475
  }
5313
5476
  } catch (e) {
5314
5477
  _log(`Extension error: ${e.message}`);
5478
+ traceProviderEvent(args, "provider", "extension.read_chat.error", {
5479
+ h,
5480
+ provider,
5481
+ level: "warn",
5482
+ payload: { method: "evaluateProviderScript", error: e.message }
5483
+ });
5315
5484
  }
5316
5485
  if (h.agentStream) {
5317
5486
  const cdp2 = h.getCdp();
@@ -5375,27 +5544,45 @@ async function handleReadChat(h, args) {
5375
5544
  const script = h.getProviderScript("readChat") || h.getProviderScript("read_chat");
5376
5545
  if (script) {
5377
5546
  try {
5378
- const result = await cdp.evaluate(script, 5e4);
5379
- let parsed = result;
5380
- if (typeof parsed === "string") {
5381
- try {
5382
- parsed = JSON.parse(parsed);
5383
- } catch {
5547
+ const evalResult = await h.evaluateProviderScript("readChat", void 0, 5e4);
5548
+ if (evalResult?.result) {
5549
+ let parsed = evalResult.result;
5550
+ if (typeof parsed === "string") {
5551
+ try {
5552
+ parsed = JSON.parse(parsed);
5553
+ } catch {
5554
+ }
5555
+ }
5556
+ if (parsed && typeof parsed === "object" && parsed.messages?.length > 0) {
5557
+ _log(`OK: ${parsed.messages?.length} msgs`);
5558
+ traceProviderEvent(args, "provider", "ide.read_chat.success", {
5559
+ h,
5560
+ provider,
5561
+ payload: {
5562
+ method: "evaluate",
5563
+ result: evalResult.result,
5564
+ parsed,
5565
+ messageCount: Array.isArray(parsed.messages) ? parsed.messages.length : 0
5566
+ }
5567
+ });
5568
+ h.historyWriter.appendNewMessages(
5569
+ provider?.type || getCurrentProviderType(h, "unknown_ide"),
5570
+ toHistoryPersistedMessages(normalizeReadChatMessages(parsed)),
5571
+ parsed.title,
5572
+ args?.targetSessionId,
5573
+ historySessionId
5574
+ );
5575
+ return buildReadChatCommandResult(parsed, args);
5384
5576
  }
5385
- }
5386
- if (parsed && typeof parsed === "object" && parsed.messages?.length > 0) {
5387
- _log(`OK: ${parsed.messages?.length} msgs`);
5388
- h.historyWriter.appendNewMessages(
5389
- provider?.type || getCurrentProviderType(h, "unknown_ide"),
5390
- toHistoryPersistedMessages(normalizeReadChatMessages(parsed)),
5391
- parsed.title,
5392
- args?.targetSessionId,
5393
- historySessionId
5394
- );
5395
- return buildReadChatCommandResult(parsed, args);
5396
5577
  }
5397
5578
  } catch (e) {
5398
5579
  LOG.info("Command", `[read_chat] Script error: ${e.message}`);
5580
+ traceProviderEvent(args, "provider", "ide.read_chat.error", {
5581
+ h,
5582
+ provider,
5583
+ level: "warn",
5584
+ payload: { method: "evaluate", error: e.message }
5585
+ });
5399
5586
  }
5400
5587
  }
5401
5588
  return buildReadChatCommandResult({ messages: [], status: "idle" }, args);
@@ -6043,6 +6230,7 @@ var init_chat_commands = __esm({
6043
6230
  init_contracts();
6044
6231
  init_chat_history();
6045
6232
  init_logger();
6233
+ init_debug_trace();
6046
6234
  RECENT_SEND_WINDOW_MS = 1200;
6047
6235
  recentSendByTarget = /* @__PURE__ */ new Map();
6048
6236
  }
@@ -32503,6 +32691,7 @@ function logCommand(entry) {
32503
32691
  ts: entry.ts,
32504
32692
  cmd: entry.cmd,
32505
32693
  src: entry.source,
32694
+ ...entry.interactionId ? { interactionId: entry.interactionId } : {},
32506
32695
  ...entry.args ? { args: maskArgs(entry.args) } : {},
32507
32696
  ...entry.success !== void 0 ? { ok: entry.success } : {},
32508
32697
  ...entry.error ? { err: entry.error } : {},
@@ -32524,6 +32713,7 @@ function getRecentCommands(count = 50) {
32524
32713
  ts: parsed.ts,
32525
32714
  cmd: parsed.cmd,
32526
32715
  source: parsed.src,
32716
+ interactionId: parsed.interactionId,
32527
32717
  args: parsed.args,
32528
32718
  success: parsed.ok,
32529
32719
  error: parsed.err,
@@ -33030,6 +33220,13 @@ function normalizeCommandSource(source) {
33030
33220
  return "unknown";
33031
33221
  }
33032
33222
  }
33223
+ function normalizeCommandArgsWithInteractionId(args) {
33224
+ const base = args && typeof args === "object" ? { ...args } : {};
33225
+ if (typeof base._interactionId !== "string" || !String(base._interactionId).trim()) {
33226
+ base._interactionId = createInteractionId();
33227
+ }
33228
+ return base;
33229
+ }
33033
33230
  function toHostedCliRuntimeDescriptor(record2) {
33034
33231
  if (!record2 || typeof record2 !== "object") return null;
33035
33232
  const runtimeId = typeof record2.sessionId === "string" ? record2.sessionId : "";
@@ -33067,6 +33264,7 @@ var init_router = __esm({
33067
33264
  init_logger();
33068
33265
  init_command_log();
33069
33266
  init_logger();
33267
+ init_debug_trace();
33070
33268
  init_builders();
33071
33269
  init_snapshot();
33072
33270
  init_snapshot();
@@ -33099,20 +33297,50 @@ var init_router = __esm({
33099
33297
  async execute(cmd, args, source = "unknown") {
33100
33298
  const cmdStart = Date.now();
33101
33299
  const logSource = normalizeCommandSource(source);
33300
+ const normalizedArgs = normalizeCommandArgsWithInteractionId(args);
33301
+ const interactionId = typeof normalizedArgs._interactionId === "string" ? normalizedArgs._interactionId : void 0;
33302
+ recordDebugTrace({
33303
+ interactionId,
33304
+ category: "command",
33305
+ stage: "received",
33306
+ level: "info",
33307
+ payload: { cmd, source: logSource }
33308
+ });
33102
33309
  try {
33103
- const daemonResult = await this.executeDaemonCommand(cmd, args);
33310
+ const daemonResult = await this.executeDaemonCommand(cmd, normalizedArgs);
33104
33311
  if (daemonResult) {
33105
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: daemonResult.success, durationMs: Date.now() - cmdStart });
33312
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: daemonResult.success, durationMs: Date.now() - cmdStart });
33313
+ recordDebugTrace({
33314
+ interactionId,
33315
+ category: "command",
33316
+ stage: "completed",
33317
+ level: daemonResult.success ? "info" : "warn",
33318
+ payload: { cmd, source: logSource, success: daemonResult.success, durationMs: Date.now() - cmdStart }
33319
+ });
33106
33320
  return daemonResult;
33107
33321
  }
33108
- const handlerResult = await this.deps.commandHandler.handle(cmd, args);
33109
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: handlerResult.success, durationMs: Date.now() - cmdStart });
33322
+ const handlerResult = await this.deps.commandHandler.handle(cmd, normalizedArgs);
33323
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: handlerResult.success, durationMs: Date.now() - cmdStart });
33324
+ recordDebugTrace({
33325
+ interactionId,
33326
+ category: "command",
33327
+ stage: "completed",
33328
+ level: handlerResult.success ? "info" : "warn",
33329
+ payload: { cmd, source: logSource, success: handlerResult.success, durationMs: Date.now() - cmdStart }
33330
+ });
33110
33331
  if (CHAT_COMMANDS.includes(cmd) && this.deps.onPostChatCommand) {
33111
33332
  this.deps.onPostChatCommand();
33112
33333
  }
33113
33334
  return handlerResult;
33114
33335
  } catch (e) {
33115
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: false, error: e.message, durationMs: Date.now() - cmdStart });
33336
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: false, error: e.message, durationMs: Date.now() - cmdStart });
33337
+ recordDebugTrace({
33338
+ interactionId,
33339
+ category: "command",
33340
+ stage: "failed",
33341
+ level: "error",
33342
+ payload: { cmd, source: logSource, error: e?.message || String(e), durationMs: Date.now() - cmdStart }
33343
+ });
33116
33344
  throw e;
33117
33345
  }
33118
33346
  }
@@ -33154,6 +33382,14 @@ var init_router = __esm({
33154
33382
  return { success: false, error: e.message };
33155
33383
  }
33156
33384
  }
33385
+ case "get_debug_trace": {
33386
+ const count = parseInt(args?.count) || parseInt(args?.limit) || 100;
33387
+ const sinceTs = Number(args?.since) || 0;
33388
+ const interactionId = typeof args?.interactionId === "string" ? args.interactionId : void 0;
33389
+ const category = typeof args?.category === "string" ? args.category : void 0;
33390
+ const trace = getRecentDebugTrace({ interactionId, category, limit: count }).filter((entry) => !sinceTs || entry.ts > sinceTs);
33391
+ return { success: true, trace, count: trace.length };
33392
+ }
33157
33393
  case "session_host_get_diagnostics": {
33158
33394
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
33159
33395
  const diagnostics = await this.deps.sessionHostControl.getDiagnostics({
@@ -40623,6 +40859,22 @@ var init_session_host_transport = __esm({
40623
40859
  }
40624
40860
  });
40625
40861
 
40862
+ // ../../oss/packages/daemon-core/src/session-host/app-name.ts
40863
+ function resolveSessionHostAppName(options = {}) {
40864
+ const env = options.env || process.env;
40865
+ const explicit = typeof env.ADHDEV_SESSION_HOST_NAME === "string" ? env.ADHDEV_SESSION_HOST_NAME.trim() : "";
40866
+ if (explicit) return explicit;
40867
+ return options.standalone ? DEFAULT_STANDALONE_SESSION_HOST_APP_NAME : DEFAULT_SESSION_HOST_APP_NAME;
40868
+ }
40869
+ var DEFAULT_SESSION_HOST_APP_NAME, DEFAULT_STANDALONE_SESSION_HOST_APP_NAME;
40870
+ var init_app_name = __esm({
40871
+ "../../oss/packages/daemon-core/src/session-host/app-name.ts"() {
40872
+ "use strict";
40873
+ DEFAULT_SESSION_HOST_APP_NAME = "adhdev";
40874
+ DEFAULT_STANDALONE_SESSION_HOST_APP_NAME = "adhdev-standalone";
40875
+ }
40876
+ });
40877
+
40626
40878
  // ../../oss/packages/daemon-core/src/session-host/runtime-support.ts
40627
40879
  async function canConnect(endpoint) {
40628
40880
  const client = new SessionHostClient({ endpoint });
@@ -41192,6 +41444,8 @@ __export(src_exports, {
41192
41444
  CliProviderInstance: () => CliProviderInstance,
41193
41445
  DAEMON_WS_PATH: () => DAEMON_WS_PATH,
41194
41446
  DEFAULT_DAEMON_PORT: () => DEFAULT_DAEMON_PORT,
41447
+ DEFAULT_SESSION_HOST_APP_NAME: () => DEFAULT_SESSION_HOST_APP_NAME,
41448
+ DEFAULT_STANDALONE_SESSION_HOST_APP_NAME: () => DEFAULT_STANDALONE_SESSION_HOST_APP_NAME,
41195
41449
  DaemonAgentStreamManager: () => DaemonAgentStreamManager,
41196
41450
  DaemonCdpInitializer: () => DaemonCdpInitializer,
41197
41451
  DaemonCdpManager: () => DaemonCdpManager,
@@ -41213,7 +41467,11 @@ __export(src_exports, {
41213
41467
  buildMachineInfo: () => buildMachineInfo,
41214
41468
  buildSessionEntries: () => buildSessionEntries,
41215
41469
  buildStatusSnapshot: () => buildStatusSnapshot,
41470
+ clearDebugTrace: () => clearDebugTrace,
41471
+ configureDebugTraceStore: () => configureDebugTraceStore,
41216
41472
  connectCdpManager: () => connectCdpManager,
41473
+ createDebugTraceStore: () => createDebugTraceStore,
41474
+ createInteractionId: () => createInteractionId,
41217
41475
  detectAllVersions: () => detectAllVersions,
41218
41476
  detectCLIs: () => detectCLIs,
41219
41477
  detectIDEs: () => detectIDEs,
@@ -41224,10 +41482,12 @@ __export(src_exports, {
41224
41482
  getAvailableIdeIds: () => getAvailableIdeIds,
41225
41483
  getCurrentDaemonLogPath: () => getCurrentDaemonLogPath,
41226
41484
  getDaemonLogDir: () => getDaemonLogDir,
41485
+ getDebugRuntimeConfig: () => getDebugRuntimeConfig,
41227
41486
  getHostMemorySnapshot: () => getHostMemorySnapshot,
41228
41487
  getLogLevel: () => getLogLevel,
41229
41488
  getRecentActivity: () => getRecentActivity,
41230
41489
  getRecentCommands: () => getRecentCommands,
41490
+ getRecentDebugTrace: () => getRecentDebugTrace,
41231
41491
  getRecentLogs: () => getRecentLogs,
41232
41492
  getSavedProviderSessions: () => getSavedProviderSessions,
41233
41493
  getWorkspaceState: () => getWorkspaceState,
@@ -41254,13 +41514,19 @@ __export(src_exports, {
41254
41514
  normalizeManagedStatus: () => normalizeManagedStatus,
41255
41515
  probeCdpPort: () => probeCdpPort,
41256
41516
  readChatHistory: () => readChatHistory,
41517
+ recordDebugTrace: () => recordDebugTrace,
41257
41518
  registerExtensionProviders: () => registerExtensionProviders,
41258
41519
  resetConfig: () => resetConfig,
41520
+ resetDebugRuntimeConfig: () => resetDebugRuntimeConfig,
41259
41521
  resetState: () => resetState,
41522
+ resolveDebugRuntimeConfig: () => resolveDebugRuntimeConfig,
41523
+ resolveSessionHostAppName: () => resolveSessionHostAppName,
41260
41524
  saveConfig: () => saveConfig,
41261
41525
  saveState: () => saveState,
41526
+ setDebugRuntimeConfig: () => setDebugRuntimeConfig,
41262
41527
  setLogLevel: () => setLogLevel,
41263
41528
  setupIdeInstance: () => setupIdeInstance,
41529
+ shouldCollectTraceCategory: () => shouldCollectTraceCategory,
41264
41530
  shutdownDaemonComponents: () => shutdownDaemonComponents,
41265
41531
  spawnDetachedDaemonUpgradeHelper: () => spawnDetachedDaemonUpgradeHelper,
41266
41532
  startDaemonDevSupport: () => startDaemonDevSupport,
@@ -41291,6 +41557,8 @@ var init_src = __esm({
41291
41557
  init_snapshot();
41292
41558
  init_normalize();
41293
41559
  init_logger();
41560
+ init_debug_config();
41561
+ init_debug_trace();
41294
41562
  init_command_log();
41295
41563
  init_cli_manager();
41296
41564
  init_launch();
@@ -41309,6 +41577,7 @@ var init_src = __esm({
41309
41577
  init_provider_cli_adapter();
41310
41578
  init_pty_transport();
41311
41579
  init_session_host_transport();
41580
+ init_app_name();
41312
41581
  init_runtime_support();
41313
41582
  init_installer();
41314
41583
  init_daemon_lifecycle();
@@ -49638,18 +49907,6 @@ function killPid2(pid) {
49638
49907
  }
49639
49908
  function getWindowsProcessCommandLine(pid) {
49640
49909
  const pidFilter = `ProcessId=${pid}`;
49641
- try {
49642
- const wmicOut = (0, import_child_process11.execFileSync)("wmic", [
49643
- "process",
49644
- "where",
49645
- pidFilter,
49646
- "get",
49647
- "CommandLine"
49648
- ], { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
49649
- const text = wmicOut.trim();
49650
- if (text) return text;
49651
- } catch {
49652
- }
49653
49910
  try {
49654
49911
  const psOut = (0, import_child_process11.execFileSync)("powershell.exe", [
49655
49912
  "-NoProfile",
@@ -49663,6 +49920,18 @@ function getWindowsProcessCommandLine(pid) {
49663
49920
  if (text) return text;
49664
49921
  } catch {
49665
49922
  }
49923
+ try {
49924
+ const wmicOut = (0, import_child_process11.execFileSync)("wmic", [
49925
+ "process",
49926
+ "where",
49927
+ pidFilter,
49928
+ "get",
49929
+ "CommandLine"
49930
+ ], { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
49931
+ const text = wmicOut.trim();
49932
+ if (text) return text;
49933
+ } catch {
49934
+ }
49666
49935
  return null;
49667
49936
  }
49668
49937
  function stopSessionHost() {
@@ -49671,7 +49940,7 @@ function stopSessionHost() {
49671
49940
  try {
49672
49941
  if (fs16.existsSync(pidFile)) {
49673
49942
  const pid = Number.parseInt(fs16.readFileSync(pidFile, "utf8").trim(), 10);
49674
- if (Number.isFinite(pid)) {
49943
+ if (Number.isFinite(pid) && pid !== process.pid) {
49675
49944
  stopped = killPid2(pid) || stopped;
49676
49945
  }
49677
49946
  }
@@ -49707,7 +49976,7 @@ function stopSessionHost() {
49707
49976
  const raw = (0, import_child_process11.execFileSync)("pgrep", ["-f", "session-host-daemon"], { encoding: "utf8" }).trim();
49708
49977
  for (const line of raw.split("\n")) {
49709
49978
  const pid = Number.parseInt(line.trim(), 10);
49710
- if (Number.isFinite(pid)) {
49979
+ if (Number.isFinite(pid) && pid !== process.pid && pid !== process.ppid) {
49711
49980
  stopped = killPid2(pid) || stopped;
49712
49981
  }
49713
49982
  }
@@ -50047,11 +50316,21 @@ function removeDaemonPid() {
50047
50316
  }
50048
50317
  function isDaemonRunning() {
50049
50318
  try {
50050
- const http3 = require("http");
50051
- const result = require("child_process").execSync(
50052
- `curl -s -o /dev/null -w "%{http_code}" --max-time 1 http://127.0.0.1:${DEFAULT_DAEMON_PORT}/health`,
50053
- { encoding: "utf-8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }
50054
- ).trim();
50319
+ const { execFileSync: execFileSync4 } = require("child_process");
50320
+ const probe = `
50321
+ const http = require('http');
50322
+ const req = http.get('http://127.0.0.1:${DEFAULT_DAEMON_PORT}/health', { timeout: 1500 }, (res) => {
50323
+ process.stdout.write(String(res.statusCode));
50324
+ res.resume();
50325
+ });
50326
+ req.on('error', () => process.stdout.write('0'));
50327
+ req.on('timeout', () => { req.destroy(); process.stdout.write('0'); });
50328
+ `;
50329
+ const result = execFileSync4(process.execPath, ["-e", probe], {
50330
+ encoding: "utf-8",
50331
+ timeout: 3e3,
50332
+ stdio: ["ignore", "pipe", "ignore"]
50333
+ }).trim();
50055
50334
  if (result === "200") return true;
50056
50335
  } catch {
50057
50336
  }
@@ -50060,12 +50339,46 @@ function isDaemonRunning() {
50060
50339
  if (!fs17.existsSync(pidFile)) return false;
50061
50340
  const pid = parseInt(fs17.readFileSync(pidFile, "utf-8").trim());
50062
50341
  process.kill(pid, 0);
50342
+ if (!isAdhdevProcess(pid)) {
50343
+ removeDaemonPid();
50344
+ return false;
50345
+ }
50063
50346
  return true;
50064
50347
  } catch {
50065
50348
  removeDaemonPid();
50066
50349
  return false;
50067
50350
  }
50068
50351
  }
50352
+ function isAdhdevProcess(pid) {
50353
+ try {
50354
+ if (process.platform === "win32") {
50355
+ const { execFileSync: execFileSync4 } = require("child_process");
50356
+ try {
50357
+ const psOut = execFileSync4("powershell.exe", [
50358
+ "-NoProfile",
50359
+ "-NonInteractive",
50360
+ "-ExecutionPolicy",
50361
+ "Bypass",
50362
+ "-Command",
50363
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`
50364
+ ], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] }).trim();
50365
+ return /adhdev|daemon/i.test(psOut);
50366
+ } catch {
50367
+ return true;
50368
+ }
50369
+ } else {
50370
+ const { execFileSync: execFileSync4 } = require("child_process");
50371
+ const cmdline = execFileSync4("ps", ["-o", "command=", "-p", String(pid)], {
50372
+ encoding: "utf-8",
50373
+ timeout: 2e3,
50374
+ stdio: ["ignore", "pipe", "ignore"]
50375
+ }).trim();
50376
+ return /adhdev|daemon/i.test(cmdline);
50377
+ }
50378
+ } catch {
50379
+ return true;
50380
+ }
50381
+ }
50069
50382
  function getDaemonPid() {
50070
50383
  const pidFile = getDaemonPidFile();
50071
50384
  try {
@@ -50107,7 +50420,7 @@ var init_adhdev_daemon = __esm({
50107
50420
  import_ws3 = require("ws");
50108
50421
  import_chalk2 = __toESM(require("chalk"));
50109
50422
  init_version();
50110
- pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.49" });
50423
+ pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.50" });
50111
50424
  ACTIVE_CHAT_POLL_STATUSES = /* @__PURE__ */ new Set([
50112
50425
  "generating",
50113
50426
  "waiting_approval",
@@ -50134,6 +50447,8 @@ var init_adhdev_daemon = __esm({
50134
50447
  ideType = "unknown";
50135
50448
  pendingMandatoryUpdate = null;
50136
50449
  mandatoryUpgradeInFlight = false;
50450
+ debugConfig = resolveDebugRuntimeConfig();
50451
+ recentInteractionIdsBySession = /* @__PURE__ */ new Map();
50137
50452
  static MANDATORY_UPDATE_BLOCKED_COMMANDS = /* @__PURE__ */ new Set([
50138
50453
  "launch_ide",
50139
50454
  "launch_cli",
@@ -50144,6 +50459,36 @@ var init_adhdev_daemon = __esm({
50144
50459
  constructor() {
50145
50460
  this.localPort = 19222;
50146
50461
  }
50462
+ applyDebugRuntime(options) {
50463
+ this.debugConfig = resolveDebugRuntimeConfig({
50464
+ dev: options.dev,
50465
+ logLevel: options.logLevel,
50466
+ trace: options.trace,
50467
+ traceContent: options.traceContent,
50468
+ traceBufferSize: options.traceBufferSize,
50469
+ traceCategories: options.traceCategories
50470
+ });
50471
+ setDebugRuntimeConfig(this.debugConfig);
50472
+ configureDebugTraceStore();
50473
+ setLogLevel(this.debugConfig.logLevel);
50474
+ LOG.info("Daemon", `Debug runtime configured: level=${this.debugConfig.logLevel} trace=${this.debugConfig.collectDebugTrace ? "on" : "off"} traceContent=${this.debugConfig.traceContent ? "on" : "off"} traceBuffer=${this.debugConfig.traceBufferSize}`);
50475
+ }
50476
+ ensureInteractionContext(args) {
50477
+ const normalized = args && typeof args === "object" ? { ...args } : {};
50478
+ if (typeof normalized._interactionId !== "string" || !String(normalized._interactionId).trim()) {
50479
+ normalized._interactionId = createInteractionId();
50480
+ }
50481
+ const interactionId = String(normalized._interactionId);
50482
+ const targetSessionId = typeof normalized.targetSessionId === "string" ? normalized.targetSessionId : "";
50483
+ if (targetSessionId) {
50484
+ this.recentInteractionIdsBySession.set(targetSessionId, interactionId);
50485
+ }
50486
+ return normalized;
50487
+ }
50488
+ getSessionInteractionId(sessionId) {
50489
+ if (!sessionId) return void 0;
50490
+ return this.recentInteractionIdsBySession.get(sessionId);
50491
+ }
50147
50492
  getCliPresentationMode(sessionId) {
50148
50493
  if (!sessionId || !this.components) return null;
50149
50494
  const instance = this.components.instanceManager.getInstance(sessionId);
@@ -50258,11 +50603,27 @@ var init_adhdev_daemon = __esm({
50258
50603
  return null;
50259
50604
  }
50260
50605
  subscription.lastDeliveredSignature = deliverySignature;
50606
+ const interactionId = this.getSessionInteractionId(subscription.params.targetSessionId);
50607
+ recordDebugTrace({
50608
+ interactionId,
50609
+ category: "topic",
50610
+ stage: "session.chat_tail_published",
50611
+ level: "info",
50612
+ sessionId: subscription.params.targetSessionId,
50613
+ payload: {
50614
+ syncMode,
50615
+ totalMessages: Number(result.totalMessages || 0),
50616
+ replaceFrom: Number(result.replaceFrom || 0),
50617
+ hasModal: !!activeModal,
50618
+ hasTitle: typeof result.title === "string"
50619
+ }
50620
+ });
50261
50621
  return {
50262
50622
  topic: "session.chat_tail",
50263
50623
  key: subscription.key,
50264
50624
  sessionId: subscription.params.targetSessionId,
50265
50625
  ...subscription.params.historySessionId ? { historySessionId: subscription.params.historySessionId } : {},
50626
+ ...interactionId ? { interactionId } : {},
50266
50627
  seq: subscription.seq,
50267
50628
  timestamp: Date.now(),
50268
50629
  messages: Array.isArray(result.messages) ? result.messages : [],
@@ -50408,6 +50769,20 @@ var init_adhdev_daemon = __esm({
50408
50769
  subscription.lastDeliveredSignature = deliverySignature;
50409
50770
  subscription.seq += 1;
50410
50771
  subscription.lastSentAt = now;
50772
+ const interactionId = this.getSessionInteractionId(subscription.params.targetSessionId);
50773
+ recordDebugTrace({
50774
+ interactionId,
50775
+ category: "topic",
50776
+ stage: "session.modal_published",
50777
+ level: "info",
50778
+ sessionId: subscription.params.targetSessionId,
50779
+ payload: {
50780
+ status,
50781
+ hasTitle: !!title,
50782
+ modalMessage: modalMessage ? modalMessage.slice(0, 140) : void 0,
50783
+ modalButtonCount: modalButtons.length
50784
+ }
50785
+ });
50411
50786
  return {
50412
50787
  topic: "session.modal",
50413
50788
  key: subscription.key,
@@ -50416,6 +50791,7 @@ var init_adhdev_daemon = __esm({
50416
50791
  ...title ? { title } : {},
50417
50792
  ...modalMessage ? { modalMessage } : {},
50418
50793
  ...modalButtons.length > 0 ? { modalButtons } : {},
50794
+ ...interactionId ? { interactionId } : {},
50419
50795
  seq: subscription.seq,
50420
50796
  timestamp: now
50421
50797
  };
@@ -50461,6 +50837,7 @@ var init_adhdev_daemon = __esm({
50461
50837
  }
50462
50838
  async start(options = {}) {
50463
50839
  installGlobalInterceptor();
50840
+ this.applyDebugRuntime(options);
50464
50841
  process.on("uncaughtException", (err) => {
50465
50842
  LOG.error("Daemon", `Uncaught exception: ${err?.message}
50466
50843
  ${err?.stack || ""}`);
@@ -50487,6 +50864,7 @@ ${err?.stack || ""}`);
50487
50864
  console.log(import_chalk2.default.gray(" Run `adhdev setup` first.\n"));
50488
50865
  process.exit(1);
50489
50866
  }
50867
+ await this.startLocalIpcServer();
50490
50868
  const sessionHostEndpoint = await ensureSessionHostReady2();
50491
50869
  this.sessionHostEndpoint = sessionHostEndpoint;
50492
50870
  this.sessionHostController = new SessionHostController(
@@ -50549,7 +50927,6 @@ ${err?.stack || ""}`);
50549
50927
  }
50550
50928
  });
50551
50929
  await this.components.cliManager.restoreHostedSessions();
50552
- await this.startLocalIpcServer();
50553
50930
  this.components.providerLoader.fetchLatest().then(({ updated }) => {
50554
50931
  if (updated) {
50555
50932
  this.components.providerLoader.reload();
@@ -50763,7 +51140,9 @@ ${err?.stack || ""}`);
50763
51140
  });
50764
51141
  }
50765
51142
  async handleCommand(msg, cmd, args) {
50766
- LOG.info("Command", `${cmd}${args?.targetSessionId ? ` \u2192 session:${String(args.targetSessionId).split("_")[0]}` : ""}`);
51143
+ const normalizedArgs = this.ensureInteractionContext(args);
51144
+ const interactionId = String(normalizedArgs._interactionId);
51145
+ LOG.info("Command", `${cmd}${normalizedArgs?.targetSessionId ? ` \u2192 session:${String(normalizedArgs.targetSessionId).split("_")[0]}` : ""} [${interactionId}]`);
50767
51146
  const cmdStart = Date.now();
50768
51147
  const source = msg.ipcWs ? "ext" : typeof msg.source === "string" && msg.source.trim() ? msg.source : "ws";
50769
51148
  try {
@@ -50773,18 +51152,20 @@ ${err?.stack || ""}`);
50773
51152
  code: "DAEMON_UPDATE_REQUIRED",
50774
51153
  required: true,
50775
51154
  latest: this.pendingMandatoryUpdate.targetVersion,
50776
- reason: this.pendingMandatoryUpdate.reason
51155
+ reason: this.pendingMandatoryUpdate.reason,
51156
+ interactionId
50777
51157
  });
50778
51158
  return;
50779
51159
  }
50780
51160
  if (source === "api" && !loadConfig().allowServerApiProxy) {
50781
51161
  this.sendResult(msg, false, {
50782
51162
  error: "Server API relay is disabled on this daemon. Enable it explicitly with `adhdev daemon:api enable`.",
50783
- code: "SERVER_API_DISABLED"
51163
+ code: "SERVER_API_DISABLED",
51164
+ interactionId
50784
51165
  });
50785
51166
  return;
50786
51167
  }
50787
- const result = await this.components.router.execute(cmd, args, source);
51168
+ const result = await this.components.router.execute(cmd, normalizedArgs, source);
50788
51169
  if (cmd.startsWith("workspace_")) this.statusReporter?.throttledReport();
50789
51170
  if (cmd === "get_status_metadata" || cmd.startsWith("workspace_") || cmd.startsWith("session_host_")) {
50790
51171
  void this.flushP2PDaemonMetadataSubscriptions();
@@ -50795,24 +51176,34 @@ ${err?.stack || ""}`);
50795
51176
  if (cmd === "resolve_action" || cmd === "send_chat" || cmd === "read_chat") {
50796
51177
  void this.flushP2PSessionModalSubscriptions();
50797
51178
  }
50798
- this.sendResult(msg, result.success, result);
51179
+ this.sendResult(msg, result.success, { ...result, interactionId });
51180
+ recordDebugTrace({
51181
+ interactionId,
51182
+ category: "command",
51183
+ stage: "result_sent",
51184
+ level: result.success ? "info" : "warn",
51185
+ sessionId: typeof normalizedArgs.targetSessionId === "string" ? normalizedArgs.targetSessionId : void 0,
51186
+ payload: { cmd, source, durationMs: Date.now() - cmdStart, success: result.success }
51187
+ });
50799
51188
  } catch (e) {
50800
51189
  console.error(import_chalk2.default.red(` \u2717 Command failed: ${e.message}`));
50801
- this.sendResult(msg, false, { error: e.message });
51190
+ this.sendResult(msg, false, { error: e.message, interactionId });
50802
51191
  }
50803
51192
  }
50804
51193
  /** P2P command processing — P2P-only commands + unified router */
50805
51194
  async handleP2PCommand(cmdType, data) {
51195
+ const normalizedData = this.ensureInteractionContext(data);
51196
+ const interactionId = String(normalizedData._interactionId);
50806
51197
  const cmdStart = Date.now();
50807
51198
  try {
50808
51199
  switch (cmdType) {
50809
51200
  case "get_runtime_snapshot": {
50810
- const sessionId = typeof data.sessionId === "string" ? data.sessionId : "";
50811
- if (!sessionId) return { success: false, error: "sessionId is required" };
51201
+ const sessionId = typeof normalizedData.sessionId === "string" ? normalizedData.sessionId : "";
51202
+ if (!sessionId) return { success: false, error: "sessionId is required", interactionId };
50812
51203
  if (!this.isCliSession(sessionId)) {
50813
- return { success: false, error: "CLI session runtime unavailable", code: "CLI_RUNTIME_UNAVAILABLE" };
51204
+ return { success: false, error: "CLI session runtime unavailable", code: "CLI_RUNTIME_UNAVAILABLE", interactionId };
50814
51205
  }
50815
- if (!this.sessionHostEndpoint) return { success: false, error: "Session host unavailable" };
51206
+ if (!this.sessionHostEndpoint) return { success: false, error: "Session host unavailable", interactionId };
50816
51207
  const client = new SessionHostClient({ endpoint: this.sessionHostEndpoint });
50817
51208
  try {
50818
51209
  await client.connect();
@@ -50821,31 +51212,30 @@ ${err?.stack || ""}`);
50821
51212
  payload: { sessionId }
50822
51213
  });
50823
51214
  if (!snapshot.success || !snapshot.result) {
50824
- return { success: false, error: snapshot.error || "Runtime snapshot unavailable" };
51215
+ return { success: false, error: snapshot.error || "Runtime snapshot unavailable", interactionId };
50825
51216
  }
50826
- return { success: true, result: snapshot.result };
51217
+ return { success: true, result: snapshot.result, interactionId };
50827
51218
  } finally {
50828
51219
  await client.close().catch(() => {
50829
51220
  });
50830
51221
  }
50831
51222
  }
50832
51223
  case "set_machine_nickname": {
50833
- const nickname = data.nickname?.trim() || null;
51224
+ const nickname = normalizedData.nickname?.trim() || null;
50834
51225
  const config2 = loadConfig();
50835
51226
  config2.machineNickname = nickname;
50836
51227
  saveConfig(config2);
50837
51228
  void this.flushP2PDaemonMetadataSubscriptions();
50838
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd: cmdType, source: "p2p", args: { nickname }, success: true, durationMs: Date.now() - cmdStart });
50839
- return { success: true, nickname };
51229
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd: cmdType, source: "p2p", interactionId, args: { nickname }, success: true, durationMs: Date.now() - cmdStart });
51230
+ return { success: true, nickname, interactionId };
50840
51231
  }
50841
51232
  case "get_command_history": {
50842
- const { getRecentCommands: getRecentCommands2 } = require("./logging/command-log");
50843
- const count = parseInt(data.count) || 50;
50844
- const history = getRecentCommands2(count);
50845
- return { success: true, history };
51233
+ const count = parseInt(normalizedData.count) || 50;
51234
+ const history = getRecentCommands(count);
51235
+ return { success: true, history, interactionId };
50846
51236
  }
50847
51237
  }
50848
- const routed = await this.components.router.execute(cmdType, data, "p2p");
51238
+ const routed = await this.components.router.execute(cmdType, normalizedData, "p2p");
50849
51239
  if (cmdType.startsWith("workspace_")) this.statusReporter?.throttledReport();
50850
51240
  if (cmdType === "get_status_metadata" || cmdType.startsWith("workspace_") || cmdType.startsWith("session_host_")) {
50851
51241
  void this.flushP2PDaemonMetadataSubscriptions();
@@ -50856,10 +51246,10 @@ ${err?.stack || ""}`);
50856
51246
  if (cmdType === "resolve_action" || cmdType === "send_chat" || cmdType === "read_chat") {
50857
51247
  void this.flushP2PSessionModalSubscriptions();
50858
51248
  }
50859
- return routed;
51249
+ return { ...routed, interactionId };
50860
51250
  } catch (e) {
50861
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd: cmdType, source: "p2p", success: false, error: e.message, durationMs: Date.now() - cmdStart });
50862
- return { success: false, error: e.message };
51251
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd: cmdType, source: "p2p", interactionId, success: false, error: e.message, durationMs: Date.now() - cmdStart });
51252
+ return { success: false, error: e.message, interactionId };
50863
51253
  }
50864
51254
  }
50865
51255
  async startLocalIpcServer() {
@@ -52892,18 +53282,23 @@ function summarizeLatestTransition(diagnostics) {
52892
53282
  return `${latest.action} ${status}${lifecycle}${detail} @ ${at}`;
52893
53283
  }
52894
53284
  function registerDaemonCommands(program2, pkgVersion3) {
52895
- 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) => {
53285
+ 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 + structured trace collection").option("--log-level <level>", "Console log level (debug|info|warn|error)").option("--trace", "Enable structured debug trace collection").option("--trace-content", "Include richer content snapshots in debug traces").option("--trace-buffer-size <count>", "Structured trace ring buffer size").action(async (options) => {
52896
53286
  const { AdhdevDaemon: AdhdevDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
52897
53287
  const daemon = new AdhdevDaemon2();
52898
53288
  await daemon.start({
52899
53289
  localPort: parseInt(options.port) || 19222,
52900
53290
  serverUrl: options.server,
52901
53291
  foreground: true,
52902
- dev: options.dev || false
53292
+ dev: options.dev || false,
53293
+ logLevel: options.logLevel,
53294
+ trace: options.trace || false,
53295
+ traceContent: options.traceContent || false,
53296
+ traceBufferSize: options.traceBufferSize ? parseInt(options.traceBufferSize, 10) || void 0 : void 0
52903
53297
  });
52904
53298
  });
52905
53299
  program2.command("standalone").description("\u{1F5A5}\uFE0F Start ADHDev Standalone Server (Local Dashboard & Embedded Daemon)").option("-p, --port <port>", "Local HTTP/WS server port", "3847").option("--host <host>", "Bind to specific host (use 0.0.0.0 for LAN access)").option("--no-open", "Prevent opening browser automatically").option("--token <token>", "Require token authentication").option("--dev", "Enable Dev Mode").action(async (options) => {
52906
53300
  const { spawn: spawn5, execSync: execSync8 } = await import("child_process");
53301
+ const { DEFAULT_STANDALONE_SESSION_HOST_APP_NAME: DEFAULT_STANDALONE_SESSION_HOST_APP_NAME2, resolveSessionHostAppName: resolveSessionHostAppName2 } = await Promise.resolve().then(() => (init_src(), src_exports));
52907
53302
  console.log(import_chalk5.default.cyan("\n Starting ADHDev Standalone Server..."));
52908
53303
  const args = [];
52909
53304
  if (options.port) args.push("--port", options.port);
@@ -52911,6 +53306,11 @@ function registerDaemonCommands(program2, pkgVersion3) {
52911
53306
  if (options.open === false) args.push("--no-open");
52912
53307
  if (options.token) args.push("--token", options.token);
52913
53308
  if (options.dev) args.push("--dev");
53309
+ const sessionHostName = resolveSessionHostAppName2({ standalone: true, env: process.env });
53310
+ const standaloneEnv = {
53311
+ ...process.env,
53312
+ ADHDEV_SESSION_HOST_NAME: process.env.ADHDEV_SESSION_HOST_NAME || sessionHostName
53313
+ };
52914
53314
  let bin = "npx";
52915
53315
  const npxArgs = ["-y", "@adhdev/daemon-standalone@latest", ...args];
52916
53316
  try {
@@ -52920,10 +53320,12 @@ function registerDaemonCommands(program2, pkgVersion3) {
52920
53320
  console.log(import_chalk5.default.gray(" Standalone server package not found locally."));
52921
53321
  console.log(import_chalk5.default.gray(" Downloading and running via npx (this may take a moment)..."));
52922
53322
  }
53323
+ console.log(import_chalk5.default.gray(` Session host namespace: ${sessionHostName}${sessionHostName === DEFAULT_STANDALONE_SESSION_HOST_APP_NAME2 ? " (default isolated standalone namespace)" : " (from ADHDEV_SESSION_HOST_NAME)"}`));
52923
53324
  const spawnArgs = bin === "npx" ? npxArgs : args;
52924
53325
  const child = spawn5(bin, spawnArgs, {
52925
53326
  stdio: "inherit",
52926
- shell: process.platform === "win32"
53327
+ shell: process.platform === "win32",
53328
+ env: standaloneEnv
52927
53329
  });
52928
53330
  child.on("error", (err) => {
52929
53331
  console.error(import_chalk5.default.red(`
@@ -54900,6 +55302,9 @@ function rotateLogs() {
54900
55302
  }
54901
55303
  function buildPlist(nodeExe, cliExe) {
54902
55304
  const brewPrefix = import_node_fs3.default.existsSync("/opt/homebrew/bin") ? "/opt/homebrew/bin" : "/usr/local/bin";
55305
+ const nodeDir = import_node_path2.default.dirname(nodeExe);
55306
+ const pathEntries = /* @__PURE__ */ new Set([nodeDir, brewPrefix, "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"]);
55307
+ const pathValue = [...pathEntries].join(":");
54903
55308
  return `<?xml version="1.0" encoding="UTF-8"?>
54904
55309
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
54905
55310
  <plist version="1.0">
@@ -54920,7 +55325,7 @@ function buildPlist(nodeExe, cliExe) {
54920
55325
  <false/>
54921
55326
  </dict>
54922
55327
  <key>ThrottleInterval</key>
54923
- <integer>10</integer>
55328
+ <integer>30</integer>
54924
55329
  <key>StandardOutPath</key>
54925
55330
  <string>${LOG_OUT}</string>
54926
55331
  <key>StandardErrorPath</key>
@@ -54928,7 +55333,7 @@ function buildPlist(nodeExe, cliExe) {
54928
55333
  <key>EnvironmentVariables</key>
54929
55334
  <dict>
54930
55335
  <key>PATH</key>
54931
- <string>${brewPrefix}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
55336
+ <string>${pathValue}</string>
54932
55337
  </dict>
54933
55338
  </dict>
54934
55339
  </plist>`;
@@ -54968,19 +55373,23 @@ function uninstallDarwin() {
54968
55373
  function isInstalledDarwin() {
54969
55374
  return import_node_fs3.default.existsSync(getDarwinPlistPath());
54970
55375
  }
54971
- function buildVbs(cliExe) {
55376
+ function buildVbs(nodeExe, cliExe) {
55377
+ const logFile = import_node_path2.default.join(ADHDEV_DIR, "daemon-service.log").replace(/\\/g, "\\\\");
55378
+ const escapedNodeExe = nodeExe.replace(/\\/g, "\\\\");
55379
+ const escapedCliExe = cliExe.replace(/\\/g, "\\\\");
54972
55380
  return `' ADHDev Daemon Auto-Start (generated by adhdev service install)
54973
55381
  Set WshShell = CreateObject("WScript.Shell")
54974
- WshShell.Run "cmd.exe /c ""node"" ""${cliExe.replace(/\\/g, "\\\\")}"" daemon", 0, False
55382
+ WshShell.Run "cmd.exe /c """"${escapedNodeExe}"""" """"${escapedCliExe}"""" daemon >> """"${logFile}"""" 2>&1", 0, False
54975
55383
  `;
54976
55384
  }
54977
- function installWindows(cliExe) {
55385
+ function installWindows(nodeExe, cliExe) {
54978
55386
  const vbsPath = getWindowsVbsPath();
54979
55387
  ensureDir(ADHDEV_DIR);
54980
55388
  ensureDir(import_node_path2.default.dirname(vbsPath));
54981
- import_node_fs3.default.writeFileSync(vbsPath, buildVbs(cliExe), "utf-8");
55389
+ import_node_fs3.default.writeFileSync(vbsPath, buildVbs(nodeExe, cliExe), "utf-8");
54982
55390
  console.log(import_chalk8.default.gray(` Startup script: ${vbsPath}`));
54983
55391
  console.log(import_chalk8.default.green("\n \u2713 Registered in Startup folder \u2014 daemon will start on login (hidden)."));
55392
+ console.log(import_chalk8.default.gray(` Logs: ${import_node_path2.default.join(ADHDEV_DIR, "daemon-service.log")}`));
54984
55393
  console.log(import_chalk8.default.gray(" To start now without rebooting, run: adhdev daemon"));
54985
55394
  }
54986
55395
  function uninstallWindows() {
@@ -55009,7 +55418,7 @@ function registerServiceCommands(program2) {
55009
55418
  if (platform12 === "darwin") {
55010
55419
  installDarwin(nodeExe, cliExe);
55011
55420
  } else if (platform12 === "win32") {
55012
- installWindows(cliExe);
55421
+ installWindows(nodeExe, cliExe);
55013
55422
  } else {
55014
55423
  console.log(import_chalk8.default.yellow("\n \u26A0 Auto-start service install is not supported on this platform."));
55015
55424
  console.log(import_chalk8.default.gray(" On Linux, create a systemd user unit manually:"));