@adhdev/daemon-core 0.8.48 → 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/index.mjs CHANGED
@@ -7398,6 +7398,134 @@ function flattenContent(content) {
7398
7398
 
7399
7399
  // src/commands/chat-commands.ts
7400
7400
  init_logger();
7401
+
7402
+ // src/logging/debug-config.ts
7403
+ var NORMAL_TRACE_BUFFER_SIZE = 200;
7404
+ var DEV_TRACE_BUFFER_SIZE = 1e3;
7405
+ var DEFAULT_CONFIG2 = {
7406
+ logLevel: "info",
7407
+ collectDebugTrace: false,
7408
+ traceContent: false,
7409
+ traceBufferSize: NORMAL_TRACE_BUFFER_SIZE,
7410
+ traceCategories: []
7411
+ };
7412
+ var currentConfig = { ...DEFAULT_CONFIG2 };
7413
+ function normalizeCategories(categories) {
7414
+ if (!Array.isArray(categories)) return [];
7415
+ return categories.map((category) => String(category || "").trim()).filter(Boolean);
7416
+ }
7417
+ function resolveDebugRuntimeConfig(options = {}) {
7418
+ const dev = options.dev === true;
7419
+ return {
7420
+ logLevel: options.logLevel || (dev ? "debug" : DEFAULT_CONFIG2.logLevel),
7421
+ collectDebugTrace: typeof options.trace === "boolean" ? options.trace : dev,
7422
+ traceContent: options.traceContent === true,
7423
+ traceBufferSize: Number.isFinite(options.traceBufferSize) ? Math.max(10, Math.floor(options.traceBufferSize)) : dev ? DEV_TRACE_BUFFER_SIZE : DEFAULT_CONFIG2.traceBufferSize,
7424
+ traceCategories: normalizeCategories(options.traceCategories)
7425
+ };
7426
+ }
7427
+ function setDebugRuntimeConfig(config) {
7428
+ currentConfig = {
7429
+ ...config,
7430
+ traceCategories: normalizeCategories(config.traceCategories),
7431
+ traceBufferSize: Math.max(10, Math.floor(config.traceBufferSize || DEFAULT_CONFIG2.traceBufferSize))
7432
+ };
7433
+ }
7434
+ function getDebugRuntimeConfig() {
7435
+ return { ...currentConfig, traceCategories: [...currentConfig.traceCategories] };
7436
+ }
7437
+ function resetDebugRuntimeConfig() {
7438
+ currentConfig = { ...DEFAULT_CONFIG2 };
7439
+ }
7440
+ function shouldCollectTraceCategory(category) {
7441
+ const config = currentConfig;
7442
+ if (!config.collectDebugTrace) return false;
7443
+ if (!category) return true;
7444
+ if (config.traceCategories.length === 0) return true;
7445
+ return config.traceCategories.includes(category);
7446
+ }
7447
+
7448
+ // src/logging/debug-trace.ts
7449
+ function summarizeString(value) {
7450
+ return `[${value.length} chars]`;
7451
+ }
7452
+ function sanitizeTraceValue(value, traceContent) {
7453
+ if (traceContent) {
7454
+ if (Array.isArray(value)) return value.map((entry) => sanitizeTraceValue(entry, traceContent));
7455
+ if (value && typeof value === "object") {
7456
+ return Object.fromEntries(
7457
+ Object.entries(value).map(([key, nested]) => [key, sanitizeTraceValue(nested, traceContent)])
7458
+ );
7459
+ }
7460
+ return value;
7461
+ }
7462
+ if (typeof value === "string") return summarizeString(value);
7463
+ if (Array.isArray(value)) return value.map((entry) => sanitizeTraceValue(entry, traceContent));
7464
+ if (value && typeof value === "object") {
7465
+ return Object.fromEntries(
7466
+ Object.entries(value).map(([key, nested]) => [key, sanitizeTraceValue(nested, traceContent)])
7467
+ );
7468
+ }
7469
+ return value;
7470
+ }
7471
+ function sanitizeTracePayload(payload) {
7472
+ if (!payload) return {};
7473
+ const { traceContent } = getDebugRuntimeConfig();
7474
+ return sanitizeTraceValue(payload, traceContent);
7475
+ }
7476
+ function createEntry(event) {
7477
+ return {
7478
+ id: `trace_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
7479
+ ts: Date.now(),
7480
+ ...event,
7481
+ payload: sanitizeTracePayload(event.payload)
7482
+ };
7483
+ }
7484
+ function createDebugTraceStore(options) {
7485
+ const entries = [];
7486
+ const capacity = Math.max(1, Math.floor(options.capacity || 100));
7487
+ return {
7488
+ record(event) {
7489
+ if (!options.enabled) return null;
7490
+ const entry = createEntry(event);
7491
+ entries.push(entry);
7492
+ if (entries.length > capacity) {
7493
+ entries.splice(0, entries.length - capacity);
7494
+ }
7495
+ return entry;
7496
+ },
7497
+ list(query = {}) {
7498
+ const limit = Math.max(1, Math.floor(query.limit || 100));
7499
+ 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 } : {} }));
7500
+ },
7501
+ clear() {
7502
+ entries.splice(0, entries.length);
7503
+ }
7504
+ };
7505
+ }
7506
+ var globalStore = createDebugTraceStore({ enabled: false, capacity: getDebugRuntimeConfig().traceBufferSize });
7507
+ function configureDebugTraceStore() {
7508
+ const config = getDebugRuntimeConfig();
7509
+ globalStore = createDebugTraceStore({
7510
+ enabled: config.collectDebugTrace,
7511
+ capacity: config.traceBufferSize
7512
+ });
7513
+ }
7514
+ function recordDebugTrace(event) {
7515
+ if (!shouldCollectTraceCategory(event.category)) return null;
7516
+ return globalStore.record(event);
7517
+ }
7518
+ function getRecentDebugTrace(query = {}) {
7519
+ return globalStore.list(query);
7520
+ }
7521
+ function clearDebugTrace() {
7522
+ globalStore.clear();
7523
+ }
7524
+ function createInteractionId(prefix = "ix") {
7525
+ return `${prefix}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
7526
+ }
7527
+
7528
+ // src/commands/chat-commands.ts
7401
7529
  var RECENT_SEND_WINDOW_MS = 1200;
7402
7530
  var recentSendByTarget = /* @__PURE__ */ new Map();
7403
7531
  function hashSignatureParts(parts) {
@@ -7464,6 +7592,20 @@ function getHistorySessionId(h, args) {
7464
7592
  const providerSessionId = typeof state?.providerSessionId === "string" ? state.providerSessionId.trim() : "";
7465
7593
  return providerSessionId || targetSessionId;
7466
7594
  }
7595
+ function getInteractionId(args) {
7596
+ return typeof args?._interactionId === "string" && args._interactionId.trim() ? args._interactionId.trim() : void 0;
7597
+ }
7598
+ function traceProviderEvent(args, category, stage, options) {
7599
+ recordDebugTrace({
7600
+ interactionId: getInteractionId(args),
7601
+ category,
7602
+ stage,
7603
+ level: options.level || "info",
7604
+ sessionId: typeof args?.targetSessionId === "string" ? args.targetSessionId : options.h.currentSession?.sessionId,
7605
+ providerType: options.provider?.type || options.h.currentProviderType || options.h.currentSession?.providerType,
7606
+ payload: options.payload
7607
+ });
7608
+ }
7467
7609
  function callLegacyTextScript(script, text) {
7468
7610
  if (typeof script !== "function") return null;
7469
7611
  return script(text);
@@ -7709,6 +7851,16 @@ async function handleReadChat(h, args) {
7709
7851
  }
7710
7852
  if (parsed && typeof parsed === "object") {
7711
7853
  _log(`Extension OK: ${parsed.messages?.length || 0} msgs`);
7854
+ traceProviderEvent(args, "provider", "extension.read_chat.success", {
7855
+ h,
7856
+ provider,
7857
+ payload: {
7858
+ method: "evaluateProviderScript",
7859
+ result: evalResult.result,
7860
+ parsed,
7861
+ messageCount: Array.isArray(parsed.messages) ? parsed.messages.length : 0
7862
+ }
7863
+ });
7712
7864
  h.historyWriter.appendNewMessages(
7713
7865
  provider?.type || "unknown_extension",
7714
7866
  toHistoryPersistedMessages(normalizeReadChatMessages(parsed)),
@@ -7721,6 +7873,12 @@ async function handleReadChat(h, args) {
7721
7873
  }
7722
7874
  } catch (e) {
7723
7875
  _log(`Extension error: ${e.message}`);
7876
+ traceProviderEvent(args, "provider", "extension.read_chat.error", {
7877
+ h,
7878
+ provider,
7879
+ level: "warn",
7880
+ payload: { method: "evaluateProviderScript", error: e.message }
7881
+ });
7724
7882
  }
7725
7883
  if (h.agentStream) {
7726
7884
  const cdp2 = h.getCdp();
@@ -7784,27 +7942,45 @@ async function handleReadChat(h, args) {
7784
7942
  const script = h.getProviderScript("readChat") || h.getProviderScript("read_chat");
7785
7943
  if (script) {
7786
7944
  try {
7787
- const result = await cdp.evaluate(script, 5e4);
7788
- let parsed = result;
7789
- if (typeof parsed === "string") {
7790
- try {
7791
- parsed = JSON.parse(parsed);
7792
- } catch {
7945
+ const evalResult = await h.evaluateProviderScript("readChat", void 0, 5e4);
7946
+ if (evalResult?.result) {
7947
+ let parsed = evalResult.result;
7948
+ if (typeof parsed === "string") {
7949
+ try {
7950
+ parsed = JSON.parse(parsed);
7951
+ } catch {
7952
+ }
7953
+ }
7954
+ if (parsed && typeof parsed === "object" && parsed.messages?.length > 0) {
7955
+ _log(`OK: ${parsed.messages?.length} msgs`);
7956
+ traceProviderEvent(args, "provider", "ide.read_chat.success", {
7957
+ h,
7958
+ provider,
7959
+ payload: {
7960
+ method: "evaluate",
7961
+ result: evalResult.result,
7962
+ parsed,
7963
+ messageCount: Array.isArray(parsed.messages) ? parsed.messages.length : 0
7964
+ }
7965
+ });
7966
+ h.historyWriter.appendNewMessages(
7967
+ provider?.type || getCurrentProviderType(h, "unknown_ide"),
7968
+ toHistoryPersistedMessages(normalizeReadChatMessages(parsed)),
7969
+ parsed.title,
7970
+ args?.targetSessionId,
7971
+ historySessionId
7972
+ );
7973
+ return buildReadChatCommandResult(parsed, args);
7793
7974
  }
7794
- }
7795
- if (parsed && typeof parsed === "object" && parsed.messages?.length > 0) {
7796
- _log(`OK: ${parsed.messages?.length} msgs`);
7797
- h.historyWriter.appendNewMessages(
7798
- provider?.type || getCurrentProviderType(h, "unknown_ide"),
7799
- toHistoryPersistedMessages(normalizeReadChatMessages(parsed)),
7800
- parsed.title,
7801
- args?.targetSessionId,
7802
- historySessionId
7803
- );
7804
- return buildReadChatCommandResult(parsed, args);
7805
7975
  }
7806
7976
  } catch (e) {
7807
7977
  LOG.info("Command", `[read_chat] Script error: ${e.message}`);
7978
+ traceProviderEvent(args, "provider", "ide.read_chat.error", {
7979
+ h,
7980
+ provider,
7981
+ level: "warn",
7982
+ payload: { method: "evaluate", error: e.message }
7983
+ });
7808
7984
  }
7809
7985
  }
7810
7986
  return buildReadChatCommandResult({ messages: [], status: "idle" }, args);
@@ -13697,6 +13873,7 @@ function logCommand(entry) {
13697
13873
  ts: entry.ts,
13698
13874
  cmd: entry.cmd,
13699
13875
  src: entry.source,
13876
+ ...entry.interactionId ? { interactionId: entry.interactionId } : {},
13700
13877
  ...entry.args ? { args: maskArgs(entry.args) } : {},
13701
13878
  ...entry.success !== void 0 ? { ok: entry.success } : {},
13702
13879
  ...entry.error ? { err: entry.error } : {},
@@ -13718,6 +13895,7 @@ function getRecentCommands(count = 50) {
13718
13895
  ts: parsed.ts,
13719
13896
  cmd: parsed.cmd,
13720
13897
  source: parsed.src,
13898
+ interactionId: parsed.interactionId,
13721
13899
  args: parsed.args,
13722
13900
  success: parsed.ok,
13723
13901
  error: parsed.err,
@@ -14185,6 +14363,13 @@ function normalizeCommandSource(source) {
14185
14363
  return "unknown";
14186
14364
  }
14187
14365
  }
14366
+ function normalizeCommandArgsWithInteractionId(args) {
14367
+ const base = args && typeof args === "object" ? { ...args } : {};
14368
+ if (typeof base._interactionId !== "string" || !String(base._interactionId).trim()) {
14369
+ base._interactionId = createInteractionId();
14370
+ }
14371
+ return base;
14372
+ }
14188
14373
  function toHostedCliRuntimeDescriptor(record) {
14189
14374
  if (!record || typeof record !== "object") return null;
14190
14375
  const runtimeId = typeof record.sessionId === "string" ? record.sessionId : "";
@@ -14223,20 +14408,50 @@ var DaemonCommandRouter = class {
14223
14408
  async execute(cmd, args, source = "unknown") {
14224
14409
  const cmdStart = Date.now();
14225
14410
  const logSource = normalizeCommandSource(source);
14411
+ const normalizedArgs = normalizeCommandArgsWithInteractionId(args);
14412
+ const interactionId = typeof normalizedArgs._interactionId === "string" ? normalizedArgs._interactionId : void 0;
14413
+ recordDebugTrace({
14414
+ interactionId,
14415
+ category: "command",
14416
+ stage: "received",
14417
+ level: "info",
14418
+ payload: { cmd, source: logSource }
14419
+ });
14226
14420
  try {
14227
- const daemonResult = await this.executeDaemonCommand(cmd, args);
14421
+ const daemonResult = await this.executeDaemonCommand(cmd, normalizedArgs);
14228
14422
  if (daemonResult) {
14229
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: daemonResult.success, durationMs: Date.now() - cmdStart });
14423
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: daemonResult.success, durationMs: Date.now() - cmdStart });
14424
+ recordDebugTrace({
14425
+ interactionId,
14426
+ category: "command",
14427
+ stage: "completed",
14428
+ level: daemonResult.success ? "info" : "warn",
14429
+ payload: { cmd, source: logSource, success: daemonResult.success, durationMs: Date.now() - cmdStart }
14430
+ });
14230
14431
  return daemonResult;
14231
14432
  }
14232
- const handlerResult = await this.deps.commandHandler.handle(cmd, args);
14233
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: handlerResult.success, durationMs: Date.now() - cmdStart });
14433
+ const handlerResult = await this.deps.commandHandler.handle(cmd, normalizedArgs);
14434
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: handlerResult.success, durationMs: Date.now() - cmdStart });
14435
+ recordDebugTrace({
14436
+ interactionId,
14437
+ category: "command",
14438
+ stage: "completed",
14439
+ level: handlerResult.success ? "info" : "warn",
14440
+ payload: { cmd, source: logSource, success: handlerResult.success, durationMs: Date.now() - cmdStart }
14441
+ });
14234
14442
  if (CHAT_COMMANDS.includes(cmd) && this.deps.onPostChatCommand) {
14235
14443
  this.deps.onPostChatCommand();
14236
14444
  }
14237
14445
  return handlerResult;
14238
14446
  } catch (e) {
14239
- logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, args, success: false, error: e.message, durationMs: Date.now() - cmdStart });
14447
+ logCommand({ ts: (/* @__PURE__ */ new Date()).toISOString(), cmd, source: logSource, interactionId, args: normalizedArgs, success: false, error: e.message, durationMs: Date.now() - cmdStart });
14448
+ recordDebugTrace({
14449
+ interactionId,
14450
+ category: "command",
14451
+ stage: "failed",
14452
+ level: "error",
14453
+ payload: { cmd, source: logSource, error: e?.message || String(e), durationMs: Date.now() - cmdStart }
14454
+ });
14240
14455
  throw e;
14241
14456
  }
14242
14457
  }
@@ -14278,6 +14493,14 @@ var DaemonCommandRouter = class {
14278
14493
  return { success: false, error: e.message };
14279
14494
  }
14280
14495
  }
14496
+ case "get_debug_trace": {
14497
+ const count = parseInt(args?.count) || parseInt(args?.limit) || 100;
14498
+ const sinceTs = Number(args?.since) || 0;
14499
+ const interactionId = typeof args?.interactionId === "string" ? args.interactionId : void 0;
14500
+ const category = typeof args?.category === "string" ? args.category : void 0;
14501
+ const trace = getRecentDebugTrace({ interactionId, category, limit: count }).filter((entry) => !sinceTs || entry.ts > sinceTs);
14502
+ return { success: true, trace, count: trace.length };
14503
+ }
14281
14504
  case "session_host_get_diagnostics": {
14282
14505
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
14283
14506
  const diagnostics = await this.deps.sessionHostControl.getDiagnostics({
@@ -21643,6 +21866,16 @@ var SessionHostPtyTransportFactory = class {
21643
21866
  }
21644
21867
  };
21645
21868
 
21869
+ // src/session-host/app-name.ts
21870
+ var DEFAULT_SESSION_HOST_APP_NAME = "adhdev";
21871
+ var DEFAULT_STANDALONE_SESSION_HOST_APP_NAME = "adhdev-standalone";
21872
+ function resolveSessionHostAppName(options = {}) {
21873
+ const env = options.env || process.env;
21874
+ const explicit = typeof env.ADHDEV_SESSION_HOST_NAME === "string" ? env.ADHDEV_SESSION_HOST_NAME.trim() : "";
21875
+ if (explicit) return explicit;
21876
+ return options.standalone ? DEFAULT_STANDALONE_SESSION_HOST_APP_NAME : DEFAULT_SESSION_HOST_APP_NAME;
21877
+ }
21878
+
21646
21879
  // src/session-host/runtime-support.ts
21647
21880
  import {
21648
21881
  SessionHostClient as SessionHostClient2,
@@ -22175,6 +22408,8 @@ export {
22175
22408
  CliProviderInstance,
22176
22409
  DAEMON_WS_PATH,
22177
22410
  DEFAULT_DAEMON_PORT,
22411
+ DEFAULT_SESSION_HOST_APP_NAME,
22412
+ DEFAULT_STANDALONE_SESSION_HOST_APP_NAME,
22178
22413
  DaemonAgentStreamManager,
22179
22414
  DaemonCdpInitializer,
22180
22415
  DaemonCdpManager,
@@ -22196,7 +22431,11 @@ export {
22196
22431
  buildMachineInfo,
22197
22432
  buildSessionEntries,
22198
22433
  buildStatusSnapshot,
22434
+ clearDebugTrace,
22435
+ configureDebugTraceStore,
22199
22436
  connectCdpManager,
22437
+ createDebugTraceStore,
22438
+ createInteractionId,
22200
22439
  detectAllVersions,
22201
22440
  detectCLIs,
22202
22441
  detectIDEs,
@@ -22207,10 +22446,12 @@ export {
22207
22446
  getAvailableIdeIds,
22208
22447
  getCurrentDaemonLogPath,
22209
22448
  getDaemonLogDir,
22449
+ getDebugRuntimeConfig,
22210
22450
  getHostMemorySnapshot,
22211
22451
  getLogLevel,
22212
22452
  getRecentActivity,
22213
22453
  getRecentCommands,
22454
+ getRecentDebugTrace,
22214
22455
  getRecentLogs,
22215
22456
  getSavedProviderSessions,
22216
22457
  getWorkspaceState,
@@ -22237,13 +22478,19 @@ export {
22237
22478
  normalizeManagedStatus,
22238
22479
  probeCdpPort,
22239
22480
  readChatHistory,
22481
+ recordDebugTrace,
22240
22482
  registerExtensionProviders,
22241
22483
  resetConfig,
22484
+ resetDebugRuntimeConfig,
22242
22485
  resetState,
22486
+ resolveDebugRuntimeConfig,
22487
+ resolveSessionHostAppName,
22243
22488
  saveConfig,
22244
22489
  saveState,
22490
+ setDebugRuntimeConfig,
22245
22491
  setLogLevel,
22246
22492
  setupIdeInstance,
22493
+ shouldCollectTraceCategory,
22247
22494
  shutdownDaemonComponents,
22248
22495
  spawnDetachedDaemonUpgradeHelper,
22249
22496
  startDaemonDevSupport,