adhdev 0.8.49 → 0.8.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/cli/index.js +514 -80
  2. package/dist/cli/index.js.map +1 -1
  3. package/dist/index.js +485 -70
  4. package/dist/index.js.map +1 -1
  5. package/package.json +3 -2
  6. package/vendor/terminal-mux-cli/index.d.mts +1 -0
  7. package/vendor/terminal-mux-cli/index.d.ts +1 -0
  8. package/vendor/terminal-mux-cli/index.js +2056 -0
  9. package/vendor/terminal-mux-cli/index.mjs +2048 -0
  10. package/vendor/terminal-mux-cli/node_modules/@adhdev/session-host-core/index.d.mts +427 -0
  11. package/vendor/terminal-mux-cli/node_modules/@adhdev/session-host-core/index.d.ts +427 -0
  12. package/vendor/terminal-mux-cli/node_modules/@adhdev/session-host-core/index.js +617 -0
  13. package/vendor/terminal-mux-cli/node_modules/@adhdev/session-host-core/index.js.map +1 -0
  14. package/vendor/terminal-mux-cli/node_modules/@adhdev/session-host-core/index.mjs +573 -0
  15. package/vendor/terminal-mux-cli/node_modules/@adhdev/session-host-core/index.mjs.map +1 -0
  16. package/vendor/terminal-mux-cli/node_modules/@adhdev/session-host-core/package.json +7 -0
  17. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/api.d.mts +16 -0
  18. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/api.d.ts +16 -0
  19. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/api.js +206 -0
  20. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/api.mjs +17 -0
  21. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/chunk-7RNMRPVZ.mjs +183 -0
  22. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/chunk-R4EFW6W3.mjs +46 -0
  23. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/chunk-XZWWVN5W.mjs +164 -0
  24. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/control-socket.d.mts +35 -0
  25. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/control-socket.d.ts +35 -0
  26. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/control-socket.js +219 -0
  27. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/control-socket.mjs +13 -0
  28. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/index.d.mts +5 -0
  29. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/index.d.ts +5 -0
  30. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/index.js +427 -0
  31. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/index.mjs +34 -0
  32. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/package.json +33 -0
  33. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/storage.d.mts +49 -0
  34. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/storage.d.ts +49 -0
  35. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/storage.js +222 -0
  36. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-control/storage.mjs +16 -0
  37. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-core/index.d.mts +162 -0
  38. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-core/index.d.ts +162 -0
  39. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-core/index.js +985 -0
  40. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-core/index.mjs +948 -0
  41. package/vendor/terminal-mux-cli/node_modules/@adhdev/terminal-mux-core/package.json +7 -0
package/dist/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
  }
@@ -27994,6 +28182,19 @@ var init_acp_provider_instance = __esm({
27994
28182
  }
27995
28183
  });
27996
28184
 
28185
+ // ../../oss/packages/daemon-core/src/commands/hosted-runtime-restore.ts
28186
+ function shouldRestoreHostedRuntime(record2, managerTag) {
28187
+ if (!managerTag) return true;
28188
+ const managedBy = typeof record2.managedBy === "string" ? record2.managedBy.trim() : "";
28189
+ if (!managedBy) return true;
28190
+ return managedBy === managerTag;
28191
+ }
28192
+ var init_hosted_runtime_restore = __esm({
28193
+ "../../oss/packages/daemon-core/src/commands/hosted-runtime-restore.ts"() {
28194
+ "use strict";
28195
+ }
28196
+ });
28197
+
27997
28198
  // ../../oss/packages/daemon-core/src/commands/cli-manager.ts
27998
28199
  function colorize(color, text) {
27999
28200
  const fn = chalkApi?.[color];
@@ -28124,6 +28325,7 @@ var init_cli_manager = __esm({
28124
28325
  init_cli_provider_instance();
28125
28326
  init_acp_provider_instance();
28126
28327
  init_logger();
28328
+ init_hosted_runtime_restore();
28127
28329
  chalkModule = import_chalk.default;
28128
28330
  chalkApi = typeof chalkModule.yellow === "function" ? chalkModule : chalkModule.default || null;
28129
28331
  DaemonCliManager = class {
@@ -28508,8 +28710,16 @@ Run 'adhdev doctor' for detailed diagnostics.`
28508
28710
  const sessions = records || await this.deps.listHostedCliRuntimes?.() || [];
28509
28711
  let restored = 0;
28510
28712
  const restoredBindings = /* @__PURE__ */ new Set();
28713
+ const managerTag = this.deps.hostedRuntimeManagerTag;
28511
28714
  for (const record2 of sessions) {
28512
28715
  if (!record2?.runtimeId || !record2?.cliType || !record2?.workspace) continue;
28716
+ if (!shouldRestoreHostedRuntime(record2, managerTag)) {
28717
+ LOG.info(
28718
+ "CLI",
28719
+ `\u21B7 Skipping hosted runtime restore owned by ${record2.managedBy}: ${record2.runtimeKey || record2.runtimeId}`
28720
+ );
28721
+ continue;
28722
+ }
28513
28723
  if (this.adapters.has(record2.runtimeId) || instanceManager.getInstance(record2.runtimeId)) continue;
28514
28724
  const normalizedType = this.providerLoader.resolveAlias(record2.cliType);
28515
28725
  const providerMeta = this.providerLoader.getMeta(normalizedType);
@@ -32136,6 +32346,7 @@ function logCommand(entry) {
32136
32346
  ts: entry.ts,
32137
32347
  cmd: entry.cmd,
32138
32348
  src: entry.source,
32349
+ ...entry.interactionId ? { interactionId: entry.interactionId } : {},
32139
32350
  ...entry.args ? { args: maskArgs(entry.args) } : {},
32140
32351
  ...entry.success !== void 0 ? { ok: entry.success } : {},
32141
32352
  ...entry.error ? { err: entry.error } : {},
@@ -32157,6 +32368,7 @@ function getRecentCommands(count = 50) {
32157
32368
  ts: parsed.ts,
32158
32369
  cmd: parsed.cmd,
32159
32370
  source: parsed.src,
32371
+ interactionId: parsed.interactionId,
32160
32372
  args: parsed.args,
32161
32373
  success: parsed.ok,
32162
32374
  error: parsed.err,
@@ -32663,6 +32875,13 @@ function normalizeCommandSource(source) {
32663
32875
  return "unknown";
32664
32876
  }
32665
32877
  }
32878
+ function normalizeCommandArgsWithInteractionId(args) {
32879
+ const base = args && typeof args === "object" ? { ...args } : {};
32880
+ if (typeof base._interactionId !== "string" || !String(base._interactionId).trim()) {
32881
+ base._interactionId = createInteractionId();
32882
+ }
32883
+ return base;
32884
+ }
32666
32885
  function toHostedCliRuntimeDescriptor(record2) {
32667
32886
  if (!record2 || typeof record2 !== "object") return null;
32668
32887
  const runtimeId = typeof record2.sessionId === "string" ? record2.sessionId : "";
@@ -32700,6 +32919,7 @@ var init_router = __esm({
32700
32919
  init_logger();
32701
32920
  init_command_log();
32702
32921
  init_logger();
32922
+ init_debug_trace();
32703
32923
  init_builders();
32704
32924
  init_snapshot();
32705
32925
  init_snapshot();
@@ -32732,20 +32952,50 @@ var init_router = __esm({
32732
32952
  async execute(cmd, args, source = "unknown") {
32733
32953
  const cmdStart = Date.now();
32734
32954
  const logSource = normalizeCommandSource(source);
32955
+ const normalizedArgs = normalizeCommandArgsWithInteractionId(args);
32956
+ const interactionId = typeof normalizedArgs._interactionId === "string" ? normalizedArgs._interactionId : void 0;
32957
+ recordDebugTrace({
32958
+ interactionId,
32959
+ category: "command",
32960
+ stage: "received",
32961
+ level: "info",
32962
+ payload: { cmd, source: logSource }
32963
+ });
32735
32964
  try {
32736
- const daemonResult = await this.executeDaemonCommand(cmd, args);
32965
+ const daemonResult = await this.executeDaemonCommand(cmd, normalizedArgs);
32737
32966
  if (daemonResult) {
32738
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: daemonResult.success, durationMs: Date.now() - cmdStart });
32967
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: daemonResult.success, durationMs: Date.now() - cmdStart });
32968
+ recordDebugTrace({
32969
+ interactionId,
32970
+ category: "command",
32971
+ stage: "completed",
32972
+ level: daemonResult.success ? "info" : "warn",
32973
+ payload: { cmd, source: logSource, success: daemonResult.success, durationMs: Date.now() - cmdStart }
32974
+ });
32739
32975
  return daemonResult;
32740
32976
  }
32741
- const handlerResult = await this.deps.commandHandler.handle(cmd, args);
32742
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: handlerResult.success, durationMs: Date.now() - cmdStart });
32977
+ const handlerResult = await this.deps.commandHandler.handle(cmd, normalizedArgs);
32978
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: handlerResult.success, durationMs: Date.now() - cmdStart });
32979
+ recordDebugTrace({
32980
+ interactionId,
32981
+ category: "command",
32982
+ stage: "completed",
32983
+ level: handlerResult.success ? "info" : "warn",
32984
+ payload: { cmd, source: logSource, success: handlerResult.success, durationMs: Date.now() - cmdStart }
32985
+ });
32743
32986
  if (CHAT_COMMANDS.includes(cmd) && this.deps.onPostChatCommand) {
32744
32987
  this.deps.onPostChatCommand();
32745
32988
  }
32746
32989
  return handlerResult;
32747
32990
  } catch (e) {
32748
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: false, error: e.message, durationMs: Date.now() - cmdStart });
32991
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: false, error: e.message, durationMs: Date.now() - cmdStart });
32992
+ recordDebugTrace({
32993
+ interactionId,
32994
+ category: "command",
32995
+ stage: "failed",
32996
+ level: "error",
32997
+ payload: { cmd, source: logSource, error: e?.message || String(e), durationMs: Date.now() - cmdStart }
32998
+ });
32749
32999
  throw e;
32750
33000
  }
32751
33001
  }
@@ -32787,6 +33037,14 @@ var init_router = __esm({
32787
33037
  return { success: false, error: e.message };
32788
33038
  }
32789
33039
  }
33040
+ case "get_debug_trace": {
33041
+ const count = parseInt(args?.count) || parseInt(args?.limit) || 100;
33042
+ const sinceTs = Number(args?.since) || 0;
33043
+ const interactionId = typeof args?.interactionId === "string" ? args.interactionId : void 0;
33044
+ const category = typeof args?.category === "string" ? args.category : void 0;
33045
+ const trace = getRecentDebugTrace({ interactionId, category, limit: count }).filter((entry) => !sinceTs || entry.ts > sinceTs);
33046
+ return { success: true, trace, count: trace.length };
33047
+ }
32790
33048
  case "session_host_get_diagnostics": {
32791
33049
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
32792
33050
  const diagnostics = await this.deps.sessionHostControl.getDiagnostics({
@@ -40256,6 +40514,22 @@ var init_session_host_transport = __esm({
40256
40514
  }
40257
40515
  });
40258
40516
 
40517
+ // ../../oss/packages/daemon-core/src/session-host/app-name.ts
40518
+ function resolveSessionHostAppName(options = {}) {
40519
+ const env = options.env || process.env;
40520
+ const explicit = typeof env.ADHDEV_SESSION_HOST_NAME === "string" ? env.ADHDEV_SESSION_HOST_NAME.trim() : "";
40521
+ if (explicit) return explicit;
40522
+ return options.standalone ? DEFAULT_STANDALONE_SESSION_HOST_APP_NAME : DEFAULT_SESSION_HOST_APP_NAME;
40523
+ }
40524
+ var DEFAULT_SESSION_HOST_APP_NAME, DEFAULT_STANDALONE_SESSION_HOST_APP_NAME;
40525
+ var init_app_name = __esm({
40526
+ "../../oss/packages/daemon-core/src/session-host/app-name.ts"() {
40527
+ "use strict";
40528
+ DEFAULT_SESSION_HOST_APP_NAME = "adhdev";
40529
+ DEFAULT_STANDALONE_SESSION_HOST_APP_NAME = "adhdev-standalone";
40530
+ }
40531
+ });
40532
+
40259
40533
  // ../../oss/packages/daemon-core/src/session-host/runtime-support.ts
40260
40534
  async function canConnect(endpoint) {
40261
40535
  const client = new SessionHostClient({ endpoint });
@@ -40302,7 +40576,8 @@ async function listHostedCliRuntimes(endpoint) {
40302
40576
  cliType: record2.providerType,
40303
40577
  workspace: record2.workspace,
40304
40578
  cliArgs: Array.isArray(record2.meta?.cliArgs) ? record2.meta.cliArgs : [],
40305
- providerSessionId: typeof record2.meta?.providerSessionId === "string" ? String(record2.meta.providerSessionId) : void 0
40579
+ providerSessionId: typeof record2.meta?.providerSessionId === "string" ? String(record2.meta.providerSessionId) : void 0,
40580
+ managedBy: typeof record2.meta?.managedBy === "string" ? String(record2.meta.managedBy) : void 0
40306
40581
  }));
40307
40582
  } finally {
40308
40583
  await client.close().catch(() => {
@@ -40825,6 +41100,8 @@ __export(src_exports, {
40825
41100
  CliProviderInstance: () => CliProviderInstance,
40826
41101
  DAEMON_WS_PATH: () => DAEMON_WS_PATH,
40827
41102
  DEFAULT_DAEMON_PORT: () => DEFAULT_DAEMON_PORT,
41103
+ DEFAULT_SESSION_HOST_APP_NAME: () => DEFAULT_SESSION_HOST_APP_NAME,
41104
+ DEFAULT_STANDALONE_SESSION_HOST_APP_NAME: () => DEFAULT_STANDALONE_SESSION_HOST_APP_NAME,
40828
41105
  DaemonAgentStreamManager: () => DaemonAgentStreamManager,
40829
41106
  DaemonCdpInitializer: () => DaemonCdpInitializer,
40830
41107
  DaemonCdpManager: () => DaemonCdpManager,
@@ -40846,7 +41123,11 @@ __export(src_exports, {
40846
41123
  buildMachineInfo: () => buildMachineInfo,
40847
41124
  buildSessionEntries: () => buildSessionEntries,
40848
41125
  buildStatusSnapshot: () => buildStatusSnapshot,
41126
+ clearDebugTrace: () => clearDebugTrace,
41127
+ configureDebugTraceStore: () => configureDebugTraceStore,
40849
41128
  connectCdpManager: () => connectCdpManager,
41129
+ createDebugTraceStore: () => createDebugTraceStore,
41130
+ createInteractionId: () => createInteractionId,
40850
41131
  detectAllVersions: () => detectAllVersions,
40851
41132
  detectCLIs: () => detectCLIs,
40852
41133
  detectIDEs: () => detectIDEs,
@@ -40857,10 +41138,12 @@ __export(src_exports, {
40857
41138
  getAvailableIdeIds: () => getAvailableIdeIds,
40858
41139
  getCurrentDaemonLogPath: () => getCurrentDaemonLogPath,
40859
41140
  getDaemonLogDir: () => getDaemonLogDir,
41141
+ getDebugRuntimeConfig: () => getDebugRuntimeConfig,
40860
41142
  getHostMemorySnapshot: () => getHostMemorySnapshot,
40861
41143
  getLogLevel: () => getLogLevel,
40862
41144
  getRecentActivity: () => getRecentActivity,
40863
41145
  getRecentCommands: () => getRecentCommands,
41146
+ getRecentDebugTrace: () => getRecentDebugTrace,
40864
41147
  getRecentLogs: () => getRecentLogs,
40865
41148
  getSavedProviderSessions: () => getSavedProviderSessions,
40866
41149
  getWorkspaceState: () => getWorkspaceState,
@@ -40887,13 +41170,19 @@ __export(src_exports, {
40887
41170
  normalizeManagedStatus: () => normalizeManagedStatus,
40888
41171
  probeCdpPort: () => probeCdpPort,
40889
41172
  readChatHistory: () => readChatHistory,
41173
+ recordDebugTrace: () => recordDebugTrace,
40890
41174
  registerExtensionProviders: () => registerExtensionProviders,
40891
41175
  resetConfig: () => resetConfig,
41176
+ resetDebugRuntimeConfig: () => resetDebugRuntimeConfig,
40892
41177
  resetState: () => resetState,
41178
+ resolveDebugRuntimeConfig: () => resolveDebugRuntimeConfig,
41179
+ resolveSessionHostAppName: () => resolveSessionHostAppName,
40893
41180
  saveConfig: () => saveConfig,
40894
41181
  saveState: () => saveState,
41182
+ setDebugRuntimeConfig: () => setDebugRuntimeConfig,
40895
41183
  setLogLevel: () => setLogLevel,
40896
41184
  setupIdeInstance: () => setupIdeInstance,
41185
+ shouldCollectTraceCategory: () => shouldCollectTraceCategory,
40897
41186
  shutdownDaemonComponents: () => shutdownDaemonComponents,
40898
41187
  spawnDetachedDaemonUpgradeHelper: () => spawnDetachedDaemonUpgradeHelper,
40899
41188
  startDaemonDevSupport: () => startDaemonDevSupport,
@@ -40924,6 +41213,8 @@ var init_src = __esm({
40924
41213
  init_snapshot();
40925
41214
  init_normalize();
40926
41215
  init_logger();
41216
+ init_debug_config();
41217
+ init_debug_trace();
40927
41218
  init_command_log();
40928
41219
  init_cli_manager();
40929
41220
  init_launch();
@@ -40942,6 +41233,7 @@ var init_src = __esm({
40942
41233
  init_provider_cli_adapter();
40943
41234
  init_pty_transport();
40944
41235
  init_session_host_transport();
41236
+ init_app_name();
40945
41237
  init_runtime_support();
40946
41238
  init_installer();
40947
41239
  init_daemon_lifecycle();
@@ -49116,18 +49408,6 @@ function killPid2(pid) {
49116
49408
  }
49117
49409
  function getWindowsProcessCommandLine(pid) {
49118
49410
  const pidFilter = `ProcessId=${pid}`;
49119
- try {
49120
- const wmicOut = (0, import_child_process11.execFileSync)("wmic", [
49121
- "process",
49122
- "where",
49123
- pidFilter,
49124
- "get",
49125
- "CommandLine"
49126
- ], { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
49127
- const text = wmicOut.trim();
49128
- if (text) return text;
49129
- } catch {
49130
- }
49131
49411
  try {
49132
49412
  const psOut = (0, import_child_process11.execFileSync)("powershell.exe", [
49133
49413
  "-NoProfile",
@@ -49141,6 +49421,18 @@ function getWindowsProcessCommandLine(pid) {
49141
49421
  if (text) return text;
49142
49422
  } catch {
49143
49423
  }
49424
+ try {
49425
+ const wmicOut = (0, import_child_process11.execFileSync)("wmic", [
49426
+ "process",
49427
+ "where",
49428
+ pidFilter,
49429
+ "get",
49430
+ "CommandLine"
49431
+ ], { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
49432
+ const text = wmicOut.trim();
49433
+ if (text) return text;
49434
+ } catch {
49435
+ }
49144
49436
  return null;
49145
49437
  }
49146
49438
  function stopSessionHost() {
@@ -49149,7 +49441,7 @@ function stopSessionHost() {
49149
49441
  try {
49150
49442
  if (fs16.existsSync(pidFile)) {
49151
49443
  const pid = Number.parseInt(fs16.readFileSync(pidFile, "utf8").trim(), 10);
49152
- if (Number.isFinite(pid)) {
49444
+ if (Number.isFinite(pid) && pid !== process.pid) {
49153
49445
  stopped = killPid2(pid) || stopped;
49154
49446
  }
49155
49447
  }
@@ -49185,7 +49477,7 @@ function stopSessionHost() {
49185
49477
  const raw = (0, import_child_process11.execFileSync)("pgrep", ["-f", "session-host-daemon"], { encoding: "utf8" }).trim();
49186
49478
  for (const line of raw.split("\n")) {
49187
49479
  const pid = Number.parseInt(line.trim(), 10);
49188
- if (Number.isFinite(pid)) {
49480
+ if (Number.isFinite(pid) && pid !== process.pid && pid !== process.ppid) {
49189
49481
  stopped = killPid2(pid) || stopped;
49190
49482
  }
49191
49483
  }
@@ -49498,11 +49790,21 @@ function removeDaemonPid() {
49498
49790
  }
49499
49791
  function isDaemonRunning() {
49500
49792
  try {
49501
- const http3 = require("http");
49502
- const result = require("child_process").execSync(
49503
- `curl -s -o /dev/null -w "%{http_code}" --max-time 1 http://127.0.0.1:${DEFAULT_DAEMON_PORT}/health`,
49504
- { encoding: "utf-8", timeout: 2e3, stdio: ["ignore", "pipe", "ignore"] }
49505
- ).trim();
49793
+ const { execFileSync: execFileSync3 } = require("child_process");
49794
+ const probe = `
49795
+ const http = require('http');
49796
+ const req = http.get('http://127.0.0.1:${DEFAULT_DAEMON_PORT}/health', { timeout: 1500 }, (res) => {
49797
+ process.stdout.write(String(res.statusCode));
49798
+ res.resume();
49799
+ });
49800
+ req.on('error', () => process.stdout.write('0'));
49801
+ req.on('timeout', () => { req.destroy(); process.stdout.write('0'); });
49802
+ `;
49803
+ const result = execFileSync3(process.execPath, ["-e", probe], {
49804
+ encoding: "utf-8",
49805
+ timeout: 3e3,
49806
+ stdio: ["ignore", "pipe", "ignore"]
49807
+ }).trim();
49506
49808
  if (result === "200") return true;
49507
49809
  } catch {
49508
49810
  }
@@ -49511,12 +49813,46 @@ function isDaemonRunning() {
49511
49813
  if (!fs17.existsSync(pidFile)) return false;
49512
49814
  const pid = parseInt(fs17.readFileSync(pidFile, "utf-8").trim());
49513
49815
  process.kill(pid, 0);
49816
+ if (!isAdhdevProcess(pid)) {
49817
+ removeDaemonPid();
49818
+ return false;
49819
+ }
49514
49820
  return true;
49515
49821
  } catch {
49516
49822
  removeDaemonPid();
49517
49823
  return false;
49518
49824
  }
49519
49825
  }
49826
+ function isAdhdevProcess(pid) {
49827
+ try {
49828
+ if (process.platform === "win32") {
49829
+ const { execFileSync: execFileSync3 } = require("child_process");
49830
+ try {
49831
+ const psOut = execFileSync3("powershell.exe", [
49832
+ "-NoProfile",
49833
+ "-NonInteractive",
49834
+ "-ExecutionPolicy",
49835
+ "Bypass",
49836
+ "-Command",
49837
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`
49838
+ ], { encoding: "utf8", timeout: 5e3, stdio: ["ignore", "pipe", "ignore"] }).trim();
49839
+ return /adhdev|daemon/i.test(psOut);
49840
+ } catch {
49841
+ return true;
49842
+ }
49843
+ } else {
49844
+ const { execFileSync: execFileSync3 } = require("child_process");
49845
+ const cmdline = execFileSync3("ps", ["-o", "command=", "-p", String(pid)], {
49846
+ encoding: "utf-8",
49847
+ timeout: 2e3,
49848
+ stdio: ["ignore", "pipe", "ignore"]
49849
+ }).trim();
49850
+ return /adhdev|daemon/i.test(cmdline);
49851
+ }
49852
+ } catch {
49853
+ return true;
49854
+ }
49855
+ }
49520
49856
  function getDaemonPid() {
49521
49857
  const pidFile = getDaemonPidFile();
49522
49858
  try {
@@ -49558,7 +49894,7 @@ var init_adhdev_daemon = __esm({
49558
49894
  import_ws3 = require("ws");
49559
49895
  import_chalk2 = __toESM(require("chalk"));
49560
49896
  init_version();
49561
- pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.49" });
49897
+ pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.52" });
49562
49898
  ACTIVE_CHAT_POLL_STATUSES = /* @__PURE__ */ new Set([
49563
49899
  "generating",
49564
49900
  "waiting_approval",
@@ -49585,6 +49921,8 @@ var init_adhdev_daemon = __esm({
49585
49921
  ideType = "unknown";
49586
49922
  pendingMandatoryUpdate = null;
49587
49923
  mandatoryUpgradeInFlight = false;
49924
+ debugConfig = resolveDebugRuntimeConfig();
49925
+ recentInteractionIdsBySession = /* @__PURE__ */ new Map();
49588
49926
  static MANDATORY_UPDATE_BLOCKED_COMMANDS = /* @__PURE__ */ new Set([
49589
49927
  "launch_ide",
49590
49928
  "launch_cli",
@@ -49595,6 +49933,36 @@ var init_adhdev_daemon = __esm({
49595
49933
  constructor() {
49596
49934
  this.localPort = 19222;
49597
49935
  }
49936
+ applyDebugRuntime(options) {
49937
+ this.debugConfig = resolveDebugRuntimeConfig({
49938
+ dev: options.dev,
49939
+ logLevel: options.logLevel,
49940
+ trace: options.trace,
49941
+ traceContent: options.traceContent,
49942
+ traceBufferSize: options.traceBufferSize,
49943
+ traceCategories: options.traceCategories
49944
+ });
49945
+ setDebugRuntimeConfig(this.debugConfig);
49946
+ configureDebugTraceStore();
49947
+ setLogLevel(this.debugConfig.logLevel);
49948
+ 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}`);
49949
+ }
49950
+ ensureInteractionContext(args) {
49951
+ const normalized = args && typeof args === "object" ? { ...args } : {};
49952
+ if (typeof normalized._interactionId !== "string" || !String(normalized._interactionId).trim()) {
49953
+ normalized._interactionId = createInteractionId();
49954
+ }
49955
+ const interactionId = String(normalized._interactionId);
49956
+ const targetSessionId = typeof normalized.targetSessionId === "string" ? normalized.targetSessionId : "";
49957
+ if (targetSessionId) {
49958
+ this.recentInteractionIdsBySession.set(targetSessionId, interactionId);
49959
+ }
49960
+ return normalized;
49961
+ }
49962
+ getSessionInteractionId(sessionId) {
49963
+ if (!sessionId) return void 0;
49964
+ return this.recentInteractionIdsBySession.get(sessionId);
49965
+ }
49598
49966
  getCliPresentationMode(sessionId) {
49599
49967
  if (!sessionId || !this.components) return null;
49600
49968
  const instance = this.components.instanceManager.getInstance(sessionId);
@@ -49709,11 +50077,27 @@ var init_adhdev_daemon = __esm({
49709
50077
  return null;
49710
50078
  }
49711
50079
  subscription.lastDeliveredSignature = deliverySignature;
50080
+ const interactionId = this.getSessionInteractionId(subscription.params.targetSessionId);
50081
+ recordDebugTrace({
50082
+ interactionId,
50083
+ category: "topic",
50084
+ stage: "session.chat_tail_published",
50085
+ level: "info",
50086
+ sessionId: subscription.params.targetSessionId,
50087
+ payload: {
50088
+ syncMode,
50089
+ totalMessages: Number(result.totalMessages || 0),
50090
+ replaceFrom: Number(result.replaceFrom || 0),
50091
+ hasModal: !!activeModal,
50092
+ hasTitle: typeof result.title === "string"
50093
+ }
50094
+ });
49712
50095
  return {
49713
50096
  topic: "session.chat_tail",
49714
50097
  key: subscription.key,
49715
50098
  sessionId: subscription.params.targetSessionId,
49716
50099
  ...subscription.params.historySessionId ? { historySessionId: subscription.params.historySessionId } : {},
50100
+ ...interactionId ? { interactionId } : {},
49717
50101
  seq: subscription.seq,
49718
50102
  timestamp: Date.now(),
49719
50103
  messages: Array.isArray(result.messages) ? result.messages : [],
@@ -49859,6 +50243,20 @@ var init_adhdev_daemon = __esm({
49859
50243
  subscription.lastDeliveredSignature = deliverySignature;
49860
50244
  subscription.seq += 1;
49861
50245
  subscription.lastSentAt = now;
50246
+ const interactionId = this.getSessionInteractionId(subscription.params.targetSessionId);
50247
+ recordDebugTrace({
50248
+ interactionId,
50249
+ category: "topic",
50250
+ stage: "session.modal_published",
50251
+ level: "info",
50252
+ sessionId: subscription.params.targetSessionId,
50253
+ payload: {
50254
+ status,
50255
+ hasTitle: !!title,
50256
+ modalMessage: modalMessage ? modalMessage.slice(0, 140) : void 0,
50257
+ modalButtonCount: modalButtons.length
50258
+ }
50259
+ });
49862
50260
  return {
49863
50261
  topic: "session.modal",
49864
50262
  key: subscription.key,
@@ -49867,6 +50265,7 @@ var init_adhdev_daemon = __esm({
49867
50265
  ...title ? { title } : {},
49868
50266
  ...modalMessage ? { modalMessage } : {},
49869
50267
  ...modalButtons.length > 0 ? { modalButtons } : {},
50268
+ ...interactionId ? { interactionId } : {},
49870
50269
  seq: subscription.seq,
49871
50270
  timestamp: now
49872
50271
  };
@@ -49912,6 +50311,7 @@ var init_adhdev_daemon = __esm({
49912
50311
  }
49913
50312
  async start(options = {}) {
49914
50313
  installGlobalInterceptor();
50314
+ this.applyDebugRuntime(options);
49915
50315
  process.on("uncaughtException", (err) => {
49916
50316
  LOG.error("Daemon", `Uncaught exception: ${err?.message}
49917
50317
  ${err?.stack || ""}`);
@@ -49938,6 +50338,7 @@ ${err?.stack || ""}`);
49938
50338
  console.log(import_chalk2.default.gray(" Run `adhdev setup` first.\n"));
49939
50339
  process.exit(1);
49940
50340
  }
50341
+ await this.startLocalIpcServer();
49941
50342
  const sessionHostEndpoint = await ensureSessionHostReady2();
49942
50343
  this.sessionHostEndpoint = sessionHostEndpoint;
49943
50344
  this.sessionHostController = new SessionHostController(
@@ -49962,6 +50363,7 @@ ${err?.stack || ""}`);
49962
50363
  }),
49963
50364
  onStatusChange: () => this.statusReporter?.onStatusChange(),
49964
50365
  removeAgentTracking: (key) => this.statusReporter?.removeAgentTracking(key),
50366
+ hostedRuntimeManagerTag: "adhdev-cloud",
49965
50367
  createPtyTransportFactory: ({ runtimeId, providerType, workspace, cliArgs, providerSessionId, attachExisting }) => new SessionHostPtyTransportFactory({
49966
50368
  endpoint: sessionHostEndpoint,
49967
50369
  ensureReady: async () => {
@@ -49972,12 +50374,13 @@ ${err?.stack || ""}`);
49972
50374
  runtimeId,
49973
50375
  providerType,
49974
50376
  workspace,
50377
+ attachExisting,
49975
50378
  appName: process.env.ADHDEV_SESSION_HOST_NAME || "adhdev",
49976
50379
  meta: {
49977
50380
  cliArgs,
49978
- providerSessionId
49979
- },
49980
- attachExisting
50381
+ providerSessionId,
50382
+ managedBy: "adhdev-cloud"
50383
+ }
49981
50384
  }),
49982
50385
  listHostedCliRuntimes: async () => listHostedCliRuntimes2(sessionHostEndpoint)
49983
50386
  },
@@ -50000,7 +50403,6 @@ ${err?.stack || ""}`);
50000
50403
  }
50001
50404
  });
50002
50405
  await this.components.cliManager.restoreHostedSessions();
50003
- await this.startLocalIpcServer();
50004
50406
  this.components.providerLoader.fetchLatest().then(({ updated }) => {
50005
50407
  if (updated) {
50006
50408
  this.components.providerLoader.reload();
@@ -50214,7 +50616,9 @@ ${err?.stack || ""}`);
50214
50616
  });
50215
50617
  }
50216
50618
  async handleCommand(msg, cmd, args) {
50217
- LOG.info("Command", `${cmd}${args?.targetSessionId ? ` \u2192 session:${String(args.targetSessionId).split("_")[0]}` : ""}`);
50619
+ const normalizedArgs = this.ensureInteractionContext(args);
50620
+ const interactionId = String(normalizedArgs._interactionId);
50621
+ LOG.info("Command", `${cmd}${normalizedArgs?.targetSessionId ? ` \u2192 session:${String(normalizedArgs.targetSessionId).split("_")[0]}` : ""} [${interactionId}]`);
50218
50622
  const cmdStart = Date.now();
50219
50623
  const source = msg.ipcWs ? "ext" : typeof msg.source === "string" && msg.source.trim() ? msg.source : "ws";
50220
50624
  try {
@@ -50224,18 +50628,20 @@ ${err?.stack || ""}`);
50224
50628
  code: "DAEMON_UPDATE_REQUIRED",
50225
50629
  required: true,
50226
50630
  latest: this.pendingMandatoryUpdate.targetVersion,
50227
- reason: this.pendingMandatoryUpdate.reason
50631
+ reason: this.pendingMandatoryUpdate.reason,
50632
+ interactionId
50228
50633
  });
50229
50634
  return;
50230
50635
  }
50231
50636
  if (source === "api" && !loadConfig().allowServerApiProxy) {
50232
50637
  this.sendResult(msg, false, {
50233
50638
  error: "Server API relay is disabled on this daemon. Enable it explicitly with `adhdev daemon:api enable`.",
50234
- code: "SERVER_API_DISABLED"
50639
+ code: "SERVER_API_DISABLED",
50640
+ interactionId
50235
50641
  });
50236
50642
  return;
50237
50643
  }
50238
- const result = await this.components.router.execute(cmd, args, source);
50644
+ const result = await this.components.router.execute(cmd, normalizedArgs, source);
50239
50645
  if (cmd.startsWith("workspace_")) this.statusReporter?.throttledReport();
50240
50646
  if (cmd === "get_status_metadata" || cmd.startsWith("workspace_") || cmd.startsWith("session_host_")) {
50241
50647
  void this.flushP2PDaemonMetadataSubscriptions();
@@ -50246,24 +50652,34 @@ ${err?.stack || ""}`);
50246
50652
  if (cmd === "resolve_action" || cmd === "send_chat" || cmd === "read_chat") {
50247
50653
  void this.flushP2PSessionModalSubscriptions();
50248
50654
  }
50249
- this.sendResult(msg, result.success, result);
50655
+ this.sendResult(msg, result.success, { ...result, interactionId });
50656
+ recordDebugTrace({
50657
+ interactionId,
50658
+ category: "command",
50659
+ stage: "result_sent",
50660
+ level: result.success ? "info" : "warn",
50661
+ sessionId: typeof normalizedArgs.targetSessionId === "string" ? normalizedArgs.targetSessionId : void 0,
50662
+ payload: { cmd, source, durationMs: Date.now() - cmdStart, success: result.success }
50663
+ });
50250
50664
  } catch (e) {
50251
50665
  console.error(import_chalk2.default.red(` \u2717 Command failed: ${e.message}`));
50252
- this.sendResult(msg, false, { error: e.message });
50666
+ this.sendResult(msg, false, { error: e.message, interactionId });
50253
50667
  }
50254
50668
  }
50255
50669
  /** P2P command processing — P2P-only commands + unified router */
50256
50670
  async handleP2PCommand(cmdType, data) {
50671
+ const normalizedData = this.ensureInteractionContext(data);
50672
+ const interactionId = String(normalizedData._interactionId);
50257
50673
  const cmdStart = Date.now();
50258
50674
  try {
50259
50675
  switch (cmdType) {
50260
50676
  case "get_runtime_snapshot": {
50261
- const sessionId = typeof data.sessionId === "string" ? data.sessionId : "";
50262
- if (!sessionId) return { success: false, error: "sessionId is required" };
50677
+ const sessionId = typeof normalizedData.sessionId === "string" ? normalizedData.sessionId : "";
50678
+ if (!sessionId) return { success: false, error: "sessionId is required", interactionId };
50263
50679
  if (!this.isCliSession(sessionId)) {
50264
- return { success: false, error: "CLI session runtime unavailable", code: "CLI_RUNTIME_UNAVAILABLE" };
50680
+ return { success: false, error: "CLI session runtime unavailable", code: "CLI_RUNTIME_UNAVAILABLE", interactionId };
50265
50681
  }
50266
- if (!this.sessionHostEndpoint) return { success: false, error: "Session host unavailable" };
50682
+ if (!this.sessionHostEndpoint) return { success: false, error: "Session host unavailable", interactionId };
50267
50683
  const client = new SessionHostClient({ endpoint: this.sessionHostEndpoint });
50268
50684
  try {
50269
50685
  await client.connect();
@@ -50272,31 +50688,30 @@ ${err?.stack || ""}`);
50272
50688
  payload: { sessionId }
50273
50689
  });
50274
50690
  if (!snapshot.success || !snapshot.result) {
50275
- return { success: false, error: snapshot.error || "Runtime snapshot unavailable" };
50691
+ return { success: false, error: snapshot.error || "Runtime snapshot unavailable", interactionId };
50276
50692
  }
50277
- return { success: true, result: snapshot.result };
50693
+ return { success: true, result: snapshot.result, interactionId };
50278
50694
  } finally {
50279
50695
  await client.close().catch(() => {
50280
50696
  });
50281
50697
  }
50282
50698
  }
50283
50699
  case "set_machine_nickname": {
50284
- const nickname = data.nickname?.trim() || null;
50700
+ const nickname = normalizedData.nickname?.trim() || null;
50285
50701
  const config2 = loadConfig();
50286
50702
  config2.machineNickname = nickname;
50287
50703
  saveConfig(config2);
50288
50704
  void this.flushP2PDaemonMetadataSubscriptions();
50289
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd: cmdType, source: "p2p", args: { nickname }, success: true, durationMs: Date.now() - cmdStart });
50290
- return { success: true, nickname };
50705
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd: cmdType, source: "p2p", interactionId, args: { nickname }, success: true, durationMs: Date.now() - cmdStart });
50706
+ return { success: true, nickname, interactionId };
50291
50707
  }
50292
50708
  case "get_command_history": {
50293
- const { getRecentCommands: getRecentCommands2 } = require("./logging/command-log");
50294
- const count = parseInt(data.count) || 50;
50295
- const history = getRecentCommands2(count);
50296
- return { success: true, history };
50709
+ const count = parseInt(normalizedData.count) || 50;
50710
+ const history = getRecentCommands(count);
50711
+ return { success: true, history, interactionId };
50297
50712
  }
50298
50713
  }
50299
- const routed = await this.components.router.execute(cmdType, data, "p2p");
50714
+ const routed = await this.components.router.execute(cmdType, normalizedData, "p2p");
50300
50715
  if (cmdType.startsWith("workspace_")) this.statusReporter?.throttledReport();
50301
50716
  if (cmdType === "get_status_metadata" || cmdType.startsWith("workspace_") || cmdType.startsWith("session_host_")) {
50302
50717
  void this.flushP2PDaemonMetadataSubscriptions();
@@ -50307,10 +50722,10 @@ ${err?.stack || ""}`);
50307
50722
  if (cmdType === "resolve_action" || cmdType === "send_chat" || cmdType === "read_chat") {
50308
50723
  void this.flushP2PSessionModalSubscriptions();
50309
50724
  }
50310
- return routed;
50725
+ return { ...routed, interactionId };
50311
50726
  } catch (e) {
50312
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd: cmdType, source: "p2p", success: false, error: e.message, durationMs: Date.now() - cmdStart });
50313
- return { success: false, error: e.message };
50727
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd: cmdType, source: "p2p", interactionId, success: false, error: e.message, durationMs: Date.now() - cmdStart });
50728
+ return { success: false, error: e.message, interactionId };
50314
50729
  }
50315
50730
  }
50316
50731
  async startLocalIpcServer() {