adhdev 0.8.24 → 0.8.27

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
@@ -2852,6 +2852,7 @@ var init_extension_provider_instance = __esm({
2852
2852
  currentStatus = "idle";
2853
2853
  agentStreams = [];
2854
2854
  messages = [];
2855
+ prevMessageHashes = /* @__PURE__ */ new Map();
2855
2856
  activeModal = null;
2856
2857
  currentModel = "";
2857
2858
  currentMode = "";
@@ -2917,7 +2918,7 @@ var init_extension_provider_instance = __esm({
2917
2918
  onEvent(event, data) {
2918
2919
  if (event === "stream_update") {
2919
2920
  if (data?.streams) this.agentStreams = data.streams;
2920
- if (data?.messages) this.messages = data.messages;
2921
+ if (data?.messages) this.messages = this.assignReceivedAt(data.messages);
2921
2922
  if (data?.activeModal !== void 0) this.activeModal = data.activeModal;
2922
2923
  if (data?.model) this.currentModel = data.model;
2923
2924
  if (data?.mode) this.currentMode = data.mode;
@@ -2943,6 +2944,7 @@ var init_extension_provider_instance = __esm({
2943
2944
  dispose() {
2944
2945
  this.agentStreams = [];
2945
2946
  this.messages = [];
2947
+ this.prevMessageHashes.clear();
2946
2948
  this.monitor.reset();
2947
2949
  this.appliedEffectKeys.clear();
2948
2950
  this.runtimeMessages = [];
@@ -3098,6 +3100,23 @@ var init_extension_provider_instance = __esm({
3098
3100
  this.chatId || this.instanceId
3099
3101
  );
3100
3102
  }
3103
+ /**
3104
+ * Assign stable receivedAt to extension messages.
3105
+ * Same pattern as IdeProviderInstance.readChat() prevByHash —
3106
+ * preserves first-seen timestamp across polling cycles.
3107
+ */
3108
+ assignReceivedAt(messages) {
3109
+ const now = Date.now();
3110
+ const nextHashes = /* @__PURE__ */ new Map();
3111
+ for (const msg of messages) {
3112
+ const hash2 = `${msg.role}:${(msg.content || "").slice(0, 100)}`;
3113
+ const prevTime = this.prevMessageHashes.get(hash2);
3114
+ msg.receivedAt = prevTime || now;
3115
+ nextHashes.set(hash2, msg.receivedAt);
3116
+ }
3117
+ this.prevMessageHashes = nextHashes;
3118
+ return messages;
3119
+ }
3101
3120
  mergeConversationMessages(messages) {
3102
3121
  if (this.runtimeMessages.length === 0) return messages;
3103
3122
  return [...messages, ...this.runtimeMessages.map((entry) => entry.message)].map((message, index) => ({ message, index })).sort((a, b) => {
@@ -3154,6 +3173,7 @@ ${effect.notification.body || ""}`.trim();
3154
3173
  }
3155
3174
  this.agentStreams = [];
3156
3175
  this.messages = [];
3176
+ this.prevMessageHashes.clear();
3157
3177
  this.activeModal = null;
3158
3178
  this.currentModel = "";
3159
3179
  this.currentMode = "";
@@ -4161,16 +4181,28 @@ function trimMessageForStatus(message, stringLimit) {
4161
4181
  if (!message || typeof message !== "object") return message;
4162
4182
  return trimStructuredStrings(message, stringLimit);
4163
4183
  }
4184
+ function normalizeMessageTime(message) {
4185
+ if (!message || typeof message !== "object") return message;
4186
+ const msg = message;
4187
+ if (msg.receivedAt == null) {
4188
+ const fallback = msg.timestamp ?? msg.createdAt;
4189
+ if (fallback != null) {
4190
+ const ts2 = typeof fallback === "string" ? Date.parse(fallback) : Number(fallback);
4191
+ if (Number.isFinite(ts2) && ts2 > 0) msg.receivedAt = ts2;
4192
+ }
4193
+ }
4194
+ return msg;
4195
+ }
4164
4196
  function trimMessagesForStatus(messages) {
4165
4197
  if (!Array.isArray(messages) || messages.length === 0) return [];
4166
4198
  const recent = messages.slice(-STATUS_ACTIVE_CHAT_MESSAGE_LIMIT);
4167
4199
  const kept = [];
4168
4200
  let totalBytes = 0;
4169
4201
  for (let i = recent.length - 1; i >= 0; i -= 1) {
4170
- let normalized = trimMessageForStatus(recent[i], STATUS_ACTIVE_CHAT_STRING_LIMIT);
4202
+ let normalized = normalizeMessageTime(trimMessageForStatus(recent[i], STATUS_ACTIVE_CHAT_STRING_LIMIT));
4171
4203
  let size = estimateBytes(normalized);
4172
4204
  if (size > STATUS_ACTIVE_CHAT_TOTAL_BYTES_LIMIT) {
4173
- normalized = trimMessageForStatus(recent[i], STATUS_ACTIVE_CHAT_FALLBACK_STRING_LIMIT);
4205
+ normalized = normalizeMessageTime(trimMessageForStatus(recent[i], STATUS_ACTIVE_CHAT_FALLBACK_STRING_LIMIT));
4174
4206
  size = estimateBytes(normalized);
4175
4207
  }
4176
4208
  if (kept.length > 0 && totalBytes + size > STATUS_ACTIVE_CHAT_TOTAL_BYTES_LIMIT) {
@@ -4510,6 +4542,56 @@ var init_builders = __esm({
4510
4542
  }
4511
4543
  });
4512
4544
 
4545
+ // ../../oss/packages/daemon-core/src/sessions/reconcile.ts
4546
+ function upsertSessionTarget(sessionRegistry, target) {
4547
+ const existing = sessionRegistry.get(target.sessionId);
4548
+ if (existing && existing.parentSessionId === target.parentSessionId && existing.providerType === target.providerType && existing.transport === target.transport && existing.cdpManagerKey === target.cdpManagerKey && existing.instanceKey === target.instanceKey) {
4549
+ return;
4550
+ }
4551
+ sessionRegistry.register(target);
4552
+ }
4553
+ function reconcileIdeRuntimeSessions(instanceManager, sessionRegistry) {
4554
+ if (!instanceManager || !sessionRegistry) return;
4555
+ for (const instanceKey of instanceManager.listInstanceIds()) {
4556
+ if (!instanceKey.startsWith("ide:")) continue;
4557
+ const ideInstance = instanceManager.getInstance(instanceKey);
4558
+ if (!ideInstance || ideInstance.category !== "ide" || typeof ideInstance.getInstanceId !== "function") {
4559
+ continue;
4560
+ }
4561
+ const managerKey = instanceKey.slice(4);
4562
+ const ideType = typeof ideInstance.type === "string" && ideInstance.type.trim() ? ideInstance.type.trim() : managerKey.split("_")[0];
4563
+ const parentSessionId = ideInstance.getInstanceId();
4564
+ if (!parentSessionId) continue;
4565
+ upsertSessionTarget(sessionRegistry, {
4566
+ sessionId: parentSessionId,
4567
+ parentSessionId: null,
4568
+ providerType: ideType,
4569
+ transport: "cdp-page",
4570
+ cdpManagerKey: managerKey,
4571
+ instanceKey
4572
+ });
4573
+ const extensions = ideInstance.getExtensionInstances?.() || [];
4574
+ for (const ext of extensions) {
4575
+ const extType = typeof ext?.type === "string" ? ext.type.trim() : "";
4576
+ const extSessionId = ext?.getInstanceId?.();
4577
+ if (!extType || !extSessionId) continue;
4578
+ upsertSessionTarget(sessionRegistry, {
4579
+ sessionId: extSessionId,
4580
+ parentSessionId,
4581
+ providerType: extType,
4582
+ transport: "cdp-webview",
4583
+ cdpManagerKey: managerKey,
4584
+ instanceKey
4585
+ });
4586
+ }
4587
+ }
4588
+ }
4589
+ var init_reconcile = __esm({
4590
+ "../../oss/packages/daemon-core/src/sessions/reconcile.ts"() {
4591
+ "use strict";
4592
+ }
4593
+ });
4594
+
4513
4595
  // ../../oss/packages/daemon-core/src/commands/chat-commands.ts
4514
4596
  function getCurrentProviderType(h, fallback = "") {
4515
4597
  return h.currentSession?.providerType || h.currentProviderType || fallback;
@@ -4770,7 +4852,7 @@ async function handleSendChat(h, args) {
4770
4852
  if (isExtensionTransport(transport)) {
4771
4853
  _log(`Extension: ${provider?.type || "unknown_extension"}`);
4772
4854
  try {
4773
- const evalResult = await h.evaluateProviderScript("sendMessage", { MESSAGE: text }, 3e4);
4855
+ const evalResult = await h.evaluateProviderScript("sendMessage", { message: text }, 3e4);
4774
4856
  if (evalResult?.result) {
4775
4857
  const parsed = parseMaybeJson(evalResult.result);
4776
4858
  if (didProviderConfirmSend(parsed)) {
@@ -4801,7 +4883,7 @@ async function handleSendChat(h, args) {
4801
4883
  return { success: false, error: `CDP for ${managerKey || "unknown"} not connected` };
4802
4884
  }
4803
4885
  _log(`Targeting IDE: ${getCurrentManagerKey(h)}`);
4804
- const sendScript = h.getProviderScript("sendMessage", { MESSAGE: text });
4886
+ const sendScript = h.getProviderScript("sendMessage", { message: text });
4805
4887
  if (sendScript) {
4806
4888
  try {
4807
4889
  const result = await targetCdp.evaluate(sendScript, 3e4);
@@ -5809,10 +5891,10 @@ function getCliScriptCommand(payload) {
5809
5891
  }
5810
5892
  const command = payload.command;
5811
5893
  if (!command || typeof command !== "object") return null;
5812
- if (command.type !== "send_message") return null;
5894
+ if (command.type !== "send_message" && command.type !== "pty_write") return null;
5813
5895
  const text = typeof command.text === "string" ? command.text.trim() : typeof command.message === "string" ? command.message.trim() : "";
5814
5896
  if (!text) return null;
5815
- return { type: "send_message", text };
5897
+ return { type: command.type, text };
5816
5898
  }
5817
5899
  function applyProviderPatch(h, args, payload) {
5818
5900
  if (!payload || typeof payload !== "object") return;
@@ -5853,6 +5935,8 @@ async function executeProviderScript(h, args, scriptName) {
5853
5935
  const cliCommand = getCliScriptCommand(parsed.payload);
5854
5936
  if (cliCommand?.type === "send_message" && cliCommand.text) {
5855
5937
  await adapter.sendMessage(cliCommand.text);
5938
+ } else if (cliCommand?.type === "pty_write" && cliCommand.text && adapter.writeRaw) {
5939
+ adapter.writeRaw(cliCommand.text + "\r");
5856
5940
  }
5857
5941
  applyProviderPatch(h, args, parsed.payload);
5858
5942
  return { success: true, ...parsed.payload && typeof parsed.payload === "object" ? parsed.payload : { result: parsed.payload } };
@@ -6166,6 +6250,7 @@ var init_handler = __esm({
6166
6250
  init_devtools();
6167
6251
  init_builders();
6168
6252
  init_chat_history();
6253
+ init_reconcile();
6169
6254
  init_logger();
6170
6255
  init_chat_commands();
6171
6256
  init_cdp_commands();
@@ -6242,9 +6327,26 @@ var init_handler = __esm({
6242
6327
  if (provider?.scripts) {
6243
6328
  const fn = provider.scripts[scriptName];
6244
6329
  if (typeof fn === "function") {
6245
- const firstVal = params ? Object.values(params)[0] : void 0;
6246
- const script = firstVal ? fn(firstVal) : fn();
6247
- if (script) return script;
6330
+ if (params && Object.keys(params).length > 0) {
6331
+ const firstVal = Object.values(params)[0];
6332
+ if (scriptName === "sendMessage" && typeof firstVal === "string") {
6333
+ const legacyScript = fn(firstVal);
6334
+ if (legacyScript) return legacyScript;
6335
+ }
6336
+ const script = fn(params);
6337
+ if (script) {
6338
+ const likelyLegacyObjectLeak = typeof script === "string" && script.includes("[object Object]") && typeof firstVal === "string";
6339
+ if (!likelyLegacyObjectLeak) return script;
6340
+ }
6341
+ if (firstVal !== void 0) {
6342
+ const legacyScript = fn(firstVal);
6343
+ if (legacyScript) return legacyScript;
6344
+ }
6345
+ if (script) return script;
6346
+ } else {
6347
+ const script = fn();
6348
+ if (script) return script;
6349
+ }
6248
6350
  }
6249
6351
  }
6250
6352
  return null;
@@ -6300,17 +6402,27 @@ var init_handler = __esm({
6300
6402
  return key.split("_")[0];
6301
6403
  }
6302
6404
  resolveRoute(args) {
6303
- const session = this._ctx.sessionRegistry?.get(args?.targetSessionId);
6304
- const managerKey = this.extractIdeType(args);
6305
- const providerType = args?.agentType || args?.providerType || session?.providerType || this.inferProviderType(managerKey);
6306
- return { session, managerKey, providerType };
6405
+ const targetSessionId = typeof args?.targetSessionId === "string" ? args.targetSessionId.trim() : "";
6406
+ let session = targetSessionId ? this._ctx.sessionRegistry?.get(targetSessionId) : void 0;
6407
+ if (targetSessionId && !session) {
6408
+ reconcileIdeRuntimeSessions(this._ctx.instanceManager, this._ctx.sessionRegistry);
6409
+ session = this._ctx.sessionRegistry?.get(targetSessionId);
6410
+ }
6411
+ const sessionLookupFailed = !!targetSessionId && !session;
6412
+ const managerKey = this.extractIdeType(args, sessionLookupFailed);
6413
+ let providerType;
6414
+ if (!sessionLookupFailed) {
6415
+ providerType = session?.providerType || args?.agentType || args?.providerType || this.inferProviderType(managerKey);
6416
+ }
6417
+ return { session, managerKey, providerType, sessionLookupFailed };
6307
6418
  }
6308
6419
  /** Extract CDP scope key from target session or explicit ideType */
6309
- extractIdeType(args) {
6420
+ extractIdeType(args, sessionLookupFailed = false) {
6310
6421
  if (args?.targetSessionId) {
6311
6422
  const target = this._ctx.sessionRegistry?.get(args.targetSessionId);
6312
6423
  if (target?.cdpManagerKey) return target.cdpManagerKey;
6313
6424
  if (this._ctx.cdpManagers.has(args.targetSessionId)) return args.targetSessionId;
6425
+ if (sessionLookupFailed) return void 0;
6314
6426
  }
6315
6427
  if (args?.ideType) {
6316
6428
  const target = this._ctx.sessionRegistry?.get(args.ideType);
@@ -6357,6 +6469,33 @@ var init_handler = __esm({
6357
6469
  this._currentRoute = this.resolveRoute(args);
6358
6470
  const startedAt = Date.now();
6359
6471
  this.logCommandStart(cmd, args);
6472
+ const sessionScopedCommands = /* @__PURE__ */ new Set([
6473
+ "read_chat",
6474
+ "send_chat",
6475
+ "list_chats",
6476
+ "new_chat",
6477
+ "switch_chat",
6478
+ "set_mode",
6479
+ "change_model",
6480
+ "set_thought_level",
6481
+ "resolve_action",
6482
+ "focus_session",
6483
+ "pty_input",
6484
+ "pty_resize",
6485
+ "invoke_provider_script",
6486
+ "list_extension_models",
6487
+ "set_extension_model",
6488
+ "list_extension_modes",
6489
+ "set_extension_mode"
6490
+ ]);
6491
+ if (this._currentRoute.sessionLookupFailed && sessionScopedCommands.has(cmd)) {
6492
+ const result2 = {
6493
+ success: false,
6494
+ error: `Live session not found for targetSessionId: ${String(args?.targetSessionId || "").trim() || "unknown"}`
6495
+ };
6496
+ this.logCommandEnd(cmd, result2, startedAt);
6497
+ return result2;
6498
+ }
6360
6499
  let result;
6361
6500
  if (!this._currentRoute.session && !this._currentRoute.managerKey && !this._currentRoute.providerType) {
6362
6501
  const cdpCommands = ["send_chat", "read_chat", "list_chats", "new_chat", "switch_chat", "set_mode", "change_model", "set_thought_level", "resolve_action"];
@@ -6852,6 +6991,86 @@ var init_terminal_screen = __esm({
6852
6991
  });
6853
6992
 
6854
6993
  // ../../oss/packages/session-host-core/dist/index.mjs
6994
+ var dist_exports = {};
6995
+ __export(dist_exports, {
6996
+ SessionHostClient: () => SessionHostClient,
6997
+ SessionHostRegistry: () => SessionHostRegistry,
6998
+ SessionRingBuffer: () => SessionRingBuffer,
6999
+ applyTerminalColorEnv: () => applyTerminalColorEnv,
7000
+ buildRuntimeDisplayName: () => buildRuntimeDisplayName,
7001
+ buildRuntimeKey: () => buildRuntimeKey,
7002
+ createLineParser: () => createLineParser,
7003
+ createResponseEnvelope: () => createResponseEnvelope,
7004
+ ensureNodePtySpawnHelperPermissions: () => ensureNodePtySpawnHelperPermissions,
7005
+ formatRuntimeOwner: () => formatRuntimeOwner,
7006
+ getDefaultSessionHostEndpoint: () => getDefaultSessionHostEndpoint,
7007
+ getWorkspaceLabel: () => getWorkspaceLabel,
7008
+ resolveRuntimeRecord: () => resolveRuntimeRecord,
7009
+ sanitizeSpawnEnv: () => sanitizeSpawnEnv,
7010
+ writeEnvelope: () => writeEnvelope
7011
+ });
7012
+ function normalizeSlug(input) {
7013
+ return input.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48);
7014
+ }
7015
+ function normalizeValue(input) {
7016
+ return input.trim().toLowerCase();
7017
+ }
7018
+ function getWorkspaceLabel(workspace) {
7019
+ const trimmed = workspace.trim();
7020
+ if (!trimmed) return "workspace";
7021
+ const normalized = trimmed.replace(/[\\/]+$/, "");
7022
+ const base = path7.basename(normalized);
7023
+ return base || normalized;
7024
+ }
7025
+ function buildRuntimeDisplayName(payload) {
7026
+ const explicit = payload.displayName?.trim();
7027
+ if (explicit) return explicit;
7028
+ const workspaceLabel = getWorkspaceLabel(payload.workspace);
7029
+ const providerLabel = payload.providerType.trim() || "runtime";
7030
+ return `${providerLabel} @ ${workspaceLabel}`;
7031
+ }
7032
+ function buildRuntimeKey(payload, existingKeys) {
7033
+ const requested = payload.runtimeKey?.trim();
7034
+ const existing = new Set(Array.from(existingKeys, (key) => key.toLowerCase()));
7035
+ const displayName = buildRuntimeDisplayName(payload);
7036
+ const baseKey = normalizeSlug(requested || displayName || getWorkspaceLabel(payload.workspace) || payload.providerType || "runtime") || "runtime";
7037
+ if (!existing.has(baseKey)) return baseKey;
7038
+ let suffix = 2;
7039
+ let candidate = `${baseKey}-${suffix}`;
7040
+ while (existing.has(candidate)) {
7041
+ suffix += 1;
7042
+ candidate = `${baseKey}-${suffix}`;
7043
+ }
7044
+ return candidate;
7045
+ }
7046
+ function uniqueMatch(records, predicate) {
7047
+ const matches = records.filter(predicate);
7048
+ if (matches.length === 1) return matches[0] || null;
7049
+ if (matches.length === 0) return null;
7050
+ const labels = matches.map((record2) => `${record2.runtimeKey} (${record2.sessionId})`).join(", ");
7051
+ throw new Error(`Ambiguous runtime target. Matches: ${labels}`);
7052
+ }
7053
+ function resolveRuntimeRecord(records, identifier) {
7054
+ const target = identifier.trim();
7055
+ if (!target) {
7056
+ throw new Error("Runtime target is required");
7057
+ }
7058
+ const exact = uniqueMatch(
7059
+ records,
7060
+ (record2) => record2.sessionId === target || normalizeValue(record2.runtimeKey) === normalizeValue(target) || normalizeValue(record2.displayName) === normalizeValue(target)
7061
+ );
7062
+ if (exact) return exact;
7063
+ const prefix = uniqueMatch(
7064
+ records,
7065
+ (record2) => record2.sessionId.startsWith(target) || normalizeValue(record2.runtimeKey).startsWith(normalizeValue(target))
7066
+ );
7067
+ if (prefix) return prefix;
7068
+ throw new Error(`Unknown runtime target: ${target}`);
7069
+ }
7070
+ function formatRuntimeOwner(record2) {
7071
+ if (!record2.writeOwner) return "none";
7072
+ return `${record2.writeOwner.ownerType}:${record2.writeOwner.clientId}`;
7073
+ }
6855
7074
  function getDefaultSessionHostEndpoint(appName = "adhdev") {
6856
7075
  if (process.platform === "win32") {
6857
7076
  return {
@@ -6883,6 +7102,16 @@ function createLineParser(onEnvelope) {
6883
7102
  }
6884
7103
  };
6885
7104
  }
7105
+ function createResponseEnvelope(requestId, response) {
7106
+ return {
7107
+ kind: "response",
7108
+ requestId,
7109
+ response
7110
+ };
7111
+ }
7112
+ function writeEnvelope(socket, envelope) {
7113
+ socket.write(serializeEnvelope(envelope));
7114
+ }
6886
7115
  function sanitizeSpawnEnv(baseEnv, overrides) {
6887
7116
  const env = {};
6888
7117
  const source = { ...baseEnv, ...overrides || {} };
@@ -6926,14 +7155,16 @@ function ensureNodePtySpawnHelperPermissions(logFn) {
6926
7155
  } catch {
6927
7156
  }
6928
7157
  }
6929
- var os7, path22, net, import_crypto3, os22, path32, __require, SessionHostClient;
7158
+ var import_crypto3, path7, os7, path22, net, import_crypto4, os22, path32, __require, SessionRingBuffer, SessionHostRegistry, SessionHostClient;
6930
7159
  var init_dist = __esm({
6931
7160
  "../../oss/packages/session-host-core/dist/index.mjs"() {
6932
7161
  "use strict";
7162
+ import_crypto3 = require("crypto");
7163
+ path7 = __toESM(require("path"), 1);
6933
7164
  os7 = __toESM(require("os"), 1);
6934
7165
  path22 = __toESM(require("path"), 1);
6935
7166
  net = __toESM(require("net"), 1);
6936
- import_crypto3 = require("crypto");
7167
+ import_crypto4 = require("crypto");
6937
7168
  os22 = __toESM(require("os"), 1);
6938
7169
  path32 = __toESM(require("path"), 1);
6939
7170
  __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -6942,6 +7173,278 @@ var init_dist = __esm({
6942
7173
  if (typeof require !== "undefined") return require.apply(this, arguments);
6943
7174
  throw Error('Dynamic require of "' + x + '" is not supported');
6944
7175
  });
7176
+ SessionRingBuffer = class {
7177
+ maxBytes;
7178
+ chunks = [];
7179
+ nextSeq = 1;
7180
+ totalBytes = 0;
7181
+ constructor(options = {}) {
7182
+ this.maxBytes = options.maxBytes ?? 512 * 1024;
7183
+ }
7184
+ append(data) {
7185
+ const normalized = typeof data === "string" ? data : String(data ?? "");
7186
+ const bytes = Buffer.byteLength(normalized, "utf8");
7187
+ const seq = this.nextSeq++;
7188
+ this.chunks.push({ seq, data: normalized, bytes });
7189
+ this.totalBytes += bytes;
7190
+ this.trim();
7191
+ return seq;
7192
+ }
7193
+ snapshot(sinceSeq) {
7194
+ const relevant = typeof sinceSeq === "number" ? this.chunks.filter((chunk) => chunk.seq > sinceSeq) : this.chunks;
7195
+ const text = relevant.map((chunk) => chunk.data).join("");
7196
+ const truncated = !!this.chunks[0] && typeof sinceSeq === "number" && sinceSeq < this.chunks[0].seq - 1;
7197
+ return {
7198
+ seq: this.nextSeq - 1,
7199
+ text,
7200
+ truncated
7201
+ };
7202
+ }
7203
+ getState() {
7204
+ return {
7205
+ scrollbackBytes: this.totalBytes,
7206
+ snapshotSeq: this.nextSeq - 1
7207
+ };
7208
+ }
7209
+ clear() {
7210
+ this.chunks = [];
7211
+ this.totalBytes = 0;
7212
+ this.nextSeq = 1;
7213
+ }
7214
+ restore(snapshot) {
7215
+ this.clear();
7216
+ const text = String(snapshot.text || "");
7217
+ if (!text) {
7218
+ this.nextSeq = Math.max(1, Number(snapshot.seq || 0) + 1);
7219
+ return;
7220
+ }
7221
+ const bytes = Buffer.byteLength(text, "utf8");
7222
+ const seq = Math.max(1, Number(snapshot.seq || 1));
7223
+ this.chunks = [{ seq, data: text, bytes }];
7224
+ this.totalBytes = bytes;
7225
+ this.nextSeq = seq + 1;
7226
+ this.trim();
7227
+ }
7228
+ trim() {
7229
+ while (this.totalBytes > this.maxBytes && this.chunks.length > 1) {
7230
+ const removed = this.chunks.shift();
7231
+ if (!removed) break;
7232
+ this.totalBytes -= removed.bytes;
7233
+ }
7234
+ }
7235
+ };
7236
+ SessionHostRegistry = class {
7237
+ sessions = /* @__PURE__ */ new Map();
7238
+ createSession(payload) {
7239
+ const sessionId = payload.sessionId || (0, import_crypto3.randomUUID)();
7240
+ if (this.sessions.has(sessionId)) {
7241
+ throw new Error(`Session already exists: ${sessionId}`);
7242
+ }
7243
+ const now = Date.now();
7244
+ const initialClient = payload.clientId ? [{
7245
+ clientId: payload.clientId,
7246
+ type: payload.clientType || "daemon",
7247
+ readOnly: false,
7248
+ attachedAt: now,
7249
+ lastSeenAt: now
7250
+ }] : [];
7251
+ const record2 = {
7252
+ sessionId,
7253
+ runtimeKey: buildRuntimeKey(
7254
+ payload,
7255
+ Array.from(this.sessions.values(), (state) => state.record.runtimeKey)
7256
+ ),
7257
+ displayName: buildRuntimeDisplayName(payload),
7258
+ workspaceLabel: getWorkspaceLabel(payload.workspace),
7259
+ transport: "pty",
7260
+ providerType: payload.providerType,
7261
+ category: payload.category,
7262
+ workspace: payload.workspace,
7263
+ launchCommand: payload.launchCommand,
7264
+ createdAt: now,
7265
+ lastActivityAt: now,
7266
+ lifecycle: "starting",
7267
+ writeOwner: null,
7268
+ attachedClients: initialClient,
7269
+ buffer: {
7270
+ scrollbackBytes: 0,
7271
+ snapshotSeq: 0
7272
+ },
7273
+ meta: payload.meta || {}
7274
+ };
7275
+ record2.meta = {
7276
+ sessionHostCols: payload.cols || 80,
7277
+ sessionHostRows: payload.rows || 24,
7278
+ ...record2.meta
7279
+ };
7280
+ this.sessions.set(sessionId, {
7281
+ record: record2,
7282
+ buffer: new SessionRingBuffer()
7283
+ });
7284
+ return this.cloneRecord(record2);
7285
+ }
7286
+ restoreSession(record2, snapshot) {
7287
+ const cloned = this.cloneRecord(record2);
7288
+ this.sessions.set(cloned.sessionId, {
7289
+ record: cloned,
7290
+ buffer: (() => {
7291
+ const buffer = new SessionRingBuffer();
7292
+ if (snapshot) buffer.restore(snapshot);
7293
+ return buffer;
7294
+ })()
7295
+ });
7296
+ return this.cloneRecord(cloned);
7297
+ }
7298
+ listSessions() {
7299
+ return Array.from(this.sessions.values()).map((state) => this.cloneRecord(state.record)).sort((a, b) => b.lastActivityAt - a.lastActivityAt);
7300
+ }
7301
+ getSession(sessionId) {
7302
+ const state = this.sessions.get(sessionId);
7303
+ return state ? this.cloneRecord(state.record) : null;
7304
+ }
7305
+ attachClient(payload) {
7306
+ const state = this.requireSession(payload.sessionId);
7307
+ const now = Date.now();
7308
+ let removedDaemonOwner = false;
7309
+ if (payload.clientType === "daemon") {
7310
+ const staleDaemonClientIds = state.record.attachedClients.filter((client) => client.type === "daemon" && client.clientId !== payload.clientId).map((client) => client.clientId);
7311
+ if (staleDaemonClientIds.length > 0) {
7312
+ state.record.attachedClients = state.record.attachedClients.filter(
7313
+ (client) => !(client.type === "daemon" && client.clientId !== payload.clientId)
7314
+ );
7315
+ if (state.record.writeOwner && staleDaemonClientIds.includes(state.record.writeOwner.clientId)) {
7316
+ removedDaemonOwner = true;
7317
+ }
7318
+ }
7319
+ }
7320
+ const existing = state.record.attachedClients.find((client) => client.clientId === payload.clientId);
7321
+ if (existing) {
7322
+ existing.type = payload.clientType;
7323
+ existing.readOnly = !!payload.readOnly;
7324
+ existing.lastSeenAt = now;
7325
+ } else {
7326
+ state.record.attachedClients.push({
7327
+ clientId: payload.clientId,
7328
+ type: payload.clientType,
7329
+ readOnly: !!payload.readOnly,
7330
+ attachedAt: now,
7331
+ lastSeenAt: now
7332
+ });
7333
+ }
7334
+ if (removedDaemonOwner) {
7335
+ state.record.writeOwner = null;
7336
+ }
7337
+ state.record.lastActivityAt = now;
7338
+ return this.cloneRecord(state.record);
7339
+ }
7340
+ detachClient(payload) {
7341
+ const state = this.requireSession(payload.sessionId);
7342
+ state.record.attachedClients = state.record.attachedClients.filter((client) => client.clientId !== payload.clientId);
7343
+ if (state.record.writeOwner?.clientId === payload.clientId) {
7344
+ state.record.writeOwner = null;
7345
+ }
7346
+ state.record.lastActivityAt = Date.now();
7347
+ return this.cloneRecord(state.record);
7348
+ }
7349
+ acquireWrite(payload) {
7350
+ const state = this.requireSession(payload.sessionId);
7351
+ if (state.record.writeOwner && state.record.writeOwner.clientId !== payload.clientId && !payload.force) {
7352
+ throw new Error(`Write owned by ${state.record.writeOwner.clientId}`);
7353
+ }
7354
+ const attachedClient = state.record.attachedClients.find((client) => client.clientId === payload.clientId);
7355
+ if (attachedClient) {
7356
+ attachedClient.readOnly = false;
7357
+ attachedClient.lastSeenAt = Date.now();
7358
+ }
7359
+ state.record.writeOwner = {
7360
+ clientId: payload.clientId,
7361
+ ownerType: payload.ownerType,
7362
+ acquiredAt: Date.now()
7363
+ };
7364
+ state.record.lastActivityAt = Date.now();
7365
+ return this.cloneRecord(state.record);
7366
+ }
7367
+ releaseWrite(payload) {
7368
+ const state = this.requireSession(payload.sessionId);
7369
+ const attachedClient = state.record.attachedClients.find((client) => client.clientId === payload.clientId);
7370
+ if (attachedClient) {
7371
+ attachedClient.readOnly = false;
7372
+ attachedClient.lastSeenAt = Date.now();
7373
+ }
7374
+ if (state.record.writeOwner?.clientId === payload.clientId) {
7375
+ state.record.writeOwner = null;
7376
+ }
7377
+ state.record.lastActivityAt = Date.now();
7378
+ return this.cloneRecord(state.record);
7379
+ }
7380
+ appendOutput(sessionId, data) {
7381
+ const state = this.requireSession(sessionId);
7382
+ const seq = state.buffer.append(data);
7383
+ state.record.buffer = state.buffer.getState();
7384
+ state.record.lastActivityAt = Date.now();
7385
+ return { record: this.cloneRecord(state.record), seq };
7386
+ }
7387
+ getSnapshot(sessionId, sinceSeq) {
7388
+ const state = this.requireSession(sessionId);
7389
+ state.record.buffer = state.buffer.getState();
7390
+ return state.buffer.snapshot(sinceSeq);
7391
+ }
7392
+ clearBuffer(sessionId) {
7393
+ const state = this.requireSession(sessionId);
7394
+ state.buffer.clear();
7395
+ state.record.buffer = state.buffer.getState();
7396
+ state.record.lastActivityAt = Date.now();
7397
+ return this.cloneRecord(state.record);
7398
+ }
7399
+ updateSessionMeta(sessionId, meta3, replace = false) {
7400
+ const state = this.requireSession(sessionId);
7401
+ state.record.meta = replace ? { ...meta3 } : {
7402
+ ...state.record.meta || {},
7403
+ ...meta3
7404
+ };
7405
+ state.record.lastActivityAt = Date.now();
7406
+ return this.cloneRecord(state.record);
7407
+ }
7408
+ markStarted(sessionId, pid) {
7409
+ const state = this.requireSession(sessionId);
7410
+ state.record.lifecycle = "running";
7411
+ state.record.startedAt = state.record.startedAt || Date.now();
7412
+ if (typeof pid === "number") state.record.osPid = pid;
7413
+ state.record.lastActivityAt = Date.now();
7414
+ return this.cloneRecord(state.record);
7415
+ }
7416
+ markStopped(sessionId, lifecycle = "stopped") {
7417
+ const state = this.requireSession(sessionId);
7418
+ state.record.lifecycle = lifecycle;
7419
+ state.record.lastActivityAt = Date.now();
7420
+ return this.cloneRecord(state.record);
7421
+ }
7422
+ setLifecycle(sessionId, lifecycle) {
7423
+ const state = this.requireSession(sessionId);
7424
+ state.record.lifecycle = lifecycle;
7425
+ state.record.lastActivityAt = Date.now();
7426
+ return this.cloneRecord(state.record);
7427
+ }
7428
+ requireSession(sessionId) {
7429
+ const state = this.sessions.get(sessionId);
7430
+ if (!state) throw new Error(`Unknown session: ${sessionId}`);
7431
+ return state;
7432
+ }
7433
+ cloneRecord(record2) {
7434
+ return {
7435
+ ...record2,
7436
+ launchCommand: {
7437
+ ...record2.launchCommand,
7438
+ args: [...record2.launchCommand.args],
7439
+ env: record2.launchCommand.env ? { ...record2.launchCommand.env } : void 0
7440
+ },
7441
+ writeOwner: record2.writeOwner ? { ...record2.writeOwner } : null,
7442
+ attachedClients: record2.attachedClients.map((client) => ({ ...client })),
7443
+ buffer: { ...record2.buffer },
7444
+ meta: { ...record2.meta }
7445
+ };
7446
+ }
7447
+ };
6945
7448
  SessionHostClient = class {
6946
7449
  endpoint;
6947
7450
  socket = null;
@@ -7001,7 +7504,7 @@ var init_dist = __esm({
7001
7504
  async request(request) {
7002
7505
  await this.connect();
7003
7506
  if (!this.socket) throw new Error("Session host socket unavailable");
7004
- const requestId = (0, import_crypto3.randomUUID)();
7507
+ const requestId = (0, import_crypto4.randomUUID)();
7005
7508
  const envelope = {
7006
7509
  kind: "request",
7007
7510
  requestId,
@@ -7215,7 +7718,7 @@ function findBinary(name) {
7215
7718
  }
7216
7719
  }
7217
7720
  function isScriptBinary(binaryPath) {
7218
- if (!path7.isAbsolute(binaryPath)) return false;
7721
+ if (!path8.isAbsolute(binaryPath)) return false;
7219
7722
  try {
7220
7723
  const fs19 = require("fs");
7221
7724
  const resolved = fs19.realpathSync(binaryPath);
@@ -7231,7 +7734,7 @@ function isScriptBinary(binaryPath) {
7231
7734
  }
7232
7735
  }
7233
7736
  function looksLikeMachOOrElf(filePath) {
7234
- if (!path7.isAbsolute(filePath)) return false;
7737
+ if (!path8.isAbsolute(filePath)) return false;
7235
7738
  try {
7236
7739
  const fs19 = require("fs");
7237
7740
  const resolved = fs19.realpathSync(filePath);
@@ -7355,12 +7858,12 @@ function normalizeCliProviderForRuntime(raw) {
7355
7858
  }
7356
7859
  };
7357
7860
  }
7358
- var os9, path7, import_child_process4, buildCliSpawnEnv, ProviderCliAdapter;
7861
+ var os9, path8, import_child_process4, buildCliSpawnEnv, ProviderCliAdapter;
7359
7862
  var init_provider_cli_adapter = __esm({
7360
7863
  "../../oss/packages/daemon-core/src/cli-adapters/provider-cli-adapter.ts"() {
7361
7864
  "use strict";
7362
7865
  os9 = __toESM(require("os"));
7363
- path7 = __toESM(require("path"));
7866
+ path8 = __toESM(require("path"));
7364
7867
  import_child_process4 = require("child_process");
7365
7868
  init_logger();
7366
7869
  init_terminal_screen();
@@ -7722,9 +8225,9 @@ var init_provider_cli_adapter = __esm({
7722
8225
  this.resetTraceSession();
7723
8226
  let shellCmd;
7724
8227
  let shellArgs;
7725
- const useShellUnix = !isWin && (!!spawnConfig.shell || !path7.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
8228
+ const useShellUnix = !isWin && (!!spawnConfig.shell || !path8.isAbsolute(binaryPath) || isScriptBinary(binaryPath) || !looksLikeMachOOrElf(binaryPath));
7726
8229
  const isCmdShim = isWin && /\.(cmd|bat)$/i.test(binaryPath);
7727
- const useShellWin = !!spawnConfig.shell || isCmdShim || !path7.isAbsolute(binaryPath) || isScriptBinary(binaryPath);
8230
+ const useShellWin = !!spawnConfig.shell || isCmdShim || !path8.isAbsolute(binaryPath) || isScriptBinary(binaryPath);
7728
8231
  const useShell = isWin ? useShellWin : useShellUnix;
7729
8232
  if (useShell) {
7730
8233
  if (!spawnConfig.shell && !isWin) {
@@ -9132,7 +9635,7 @@ ${data.message || ""}`.trim();
9132
9635
  // ../../oss/packages/daemon-core/src/providers/cli-provider-instance.ts
9133
9636
  function getDatabaseSync() {
9134
9637
  if (CachedDatabaseSync) return CachedDatabaseSync;
9135
- const requireFn = typeof require === "function" ? require : (0, import_node_module.createRequire)(path8.join(process.cwd(), "__adhdev_sqlite_loader__.js"));
9638
+ const requireFn = typeof require === "function" ? require : (0, import_node_module.createRequire)(path9.join(process.cwd(), "__adhdev_sqlite_loader__.js"));
9136
9639
  const sqliteModule = requireFn(`node:${"sqlite"}`);
9137
9640
  CachedDatabaseSync = sqliteModule.DatabaseSync;
9138
9641
  if (!CachedDatabaseSync) {
@@ -9140,12 +9643,12 @@ function getDatabaseSync() {
9140
9643
  }
9141
9644
  return CachedDatabaseSync;
9142
9645
  }
9143
- var os10, path8, crypto3, fs5, import_node_module, CachedDatabaseSync, CliProviderInstance;
9646
+ var os10, path9, crypto3, fs5, import_node_module, CachedDatabaseSync, CliProviderInstance;
9144
9647
  var init_cli_provider_instance = __esm({
9145
9648
  "../../oss/packages/daemon-core/src/providers/cli-provider-instance.ts"() {
9146
9649
  "use strict";
9147
9650
  os10 = __toESM(require("os"));
9148
- path8 = __toESM(require("path"));
9651
+ path9 = __toESM(require("path"));
9149
9652
  crypto3 = __toESM(require("crypto"));
9150
9653
  fs5 = __toESM(require("fs"));
9151
9654
  import_node_module = require("module");
@@ -9212,6 +9715,7 @@ var init_cli_provider_instance = __esm({
9212
9715
  this.detectStatusTransition();
9213
9716
  });
9214
9717
  await this.adapter.spawn();
9718
+ this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
9215
9719
  if (this.providerSessionId) {
9216
9720
  const restoredHistory = readChatHistory(this.type, 0, 200, this.providerSessionId);
9217
9721
  if (restoredHistory.messages.length > 0) {
@@ -9306,6 +9810,7 @@ var init_cli_provider_instance = __esm({
9306
9810
  this.promoteProviderSessionId(parsedProviderSessionId);
9307
9811
  }
9308
9812
  const runtime = this.adapter.getRuntimeMetadata();
9813
+ this.maybeAppendRuntimeRecoveryMessage(runtime);
9309
9814
  const parsedMessages = Array.isArray(parsedStatus?.messages) ? parsedStatus.messages : [];
9310
9815
  const controlValues = extractProviderControlValues(this.provider.controls, parsedStatus);
9311
9816
  if (controlValues) {
@@ -9632,6 +10137,28 @@ ${effect.notification.body || ""}`.trim();
9632
10137
  const pad = (value) => String(value).padStart(2, "0");
9633
10138
  return `${date5.getFullYear()}-${pad(date5.getMonth() + 1)}-${pad(date5.getDate())} ${pad(date5.getHours())}:${pad(date5.getMinutes())}:${pad(date5.getSeconds())}`;
9634
10139
  }
10140
+ maybeAppendRuntimeRecoveryMessage(runtime) {
10141
+ if (!runtime?.restoredFromStorage || !runtime.runtimeId) return;
10142
+ const recoveryState = String(runtime.recoveryState || "").trim();
10143
+ if (!recoveryState) return;
10144
+ let content = "";
10145
+ if (recoveryState === "auto_resumed") {
10146
+ content = "Session host restored this CLI after restart and reattached it from a saved snapshot.";
10147
+ } else if (recoveryState === "resume_failed") {
10148
+ const errorSuffix = runtime.recoveryError ? ` Resume failed: ${runtime.recoveryError}` : "";
10149
+ content = `Session host found this CLI after restart, but automatic resume failed.${errorSuffix}`;
10150
+ } else if (recoveryState === "host_restart_interrupted") {
10151
+ content = "Session host found this CLI in interrupted state after restart and is attempting to resume it.";
10152
+ } else if (recoveryState === "orphan_snapshot") {
10153
+ content = "Session host restored the last snapshot for this CLI, but the original runtime was not resumed automatically.";
10154
+ } else {
10155
+ content = `Session host restored this CLI after restart (${recoveryState}).`;
10156
+ }
10157
+ this.appendRuntimeSystemMessage(
10158
+ content,
10159
+ `runtime_recovery:${runtime.runtimeId}:${recoveryState}`
10160
+ );
10161
+ }
9635
10162
  appendRuntimeSystemMessage(content, dedupKey, receivedAt = Date.now()) {
9636
10163
  const normalizedContent = String(content || "").trim();
9637
10164
  if (!normalizedContent) return;
@@ -9990,10 +10517,10 @@ function mergeDefs(...defs) {
9990
10517
  function cloneDef(schema) {
9991
10518
  return mergeDefs(schema._zod.def);
9992
10519
  }
9993
- function getElementAtPath(obj, path24) {
9994
- if (!path24)
10520
+ function getElementAtPath(obj, path25) {
10521
+ if (!path25)
9995
10522
  return obj;
9996
- return path24.reduce((acc, key) => acc?.[key], obj);
10523
+ return path25.reduce((acc, key) => acc?.[key], obj);
9997
10524
  }
9998
10525
  function promiseAllObject(promisesObj) {
9999
10526
  const keys = Object.keys(promisesObj);
@@ -10305,11 +10832,11 @@ function aborted(x, startIndex = 0) {
10305
10832
  }
10306
10833
  return false;
10307
10834
  }
10308
- function prefixIssues(path24, issues) {
10835
+ function prefixIssues(path25, issues) {
10309
10836
  return issues.map((iss) => {
10310
10837
  var _a2;
10311
10838
  (_a2 = iss).path ?? (_a2.path = []);
10312
- iss.path.unshift(path24);
10839
+ iss.path.unshift(path25);
10313
10840
  return iss;
10314
10841
  });
10315
10842
  }
@@ -10552,7 +11079,7 @@ function formatError(error48, mapper = (issue2) => issue2.message) {
10552
11079
  }
10553
11080
  function treeifyError(error48, mapper = (issue2) => issue2.message) {
10554
11081
  const result = { errors: [] };
10555
- const processError = (error49, path24 = []) => {
11082
+ const processError = (error49, path25 = []) => {
10556
11083
  var _a2, _b;
10557
11084
  for (const issue2 of error49.issues) {
10558
11085
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -10562,7 +11089,7 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
10562
11089
  } else if (issue2.code === "invalid_element") {
10563
11090
  processError({ issues: issue2.issues }, issue2.path);
10564
11091
  } else {
10565
- const fullpath = [...path24, ...issue2.path];
11092
+ const fullpath = [...path25, ...issue2.path];
10566
11093
  if (fullpath.length === 0) {
10567
11094
  result.errors.push(mapper(issue2));
10568
11095
  continue;
@@ -10594,8 +11121,8 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
10594
11121
  }
10595
11122
  function toDotPath(_path) {
10596
11123
  const segs = [];
10597
- const path24 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
10598
- for (const seg of path24) {
11124
+ const path25 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
11125
+ for (const seg of path25) {
10599
11126
  if (typeof seg === "number")
10600
11127
  segs.push(`[${seg}]`);
10601
11128
  else if (typeof seg === "symbol")
@@ -23359,13 +23886,13 @@ function resolveRef(ref, ctx) {
23359
23886
  if (!ref.startsWith("#")) {
23360
23887
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
23361
23888
  }
23362
- const path24 = ref.slice(1).split("/").filter(Boolean);
23363
- if (path24.length === 0) {
23889
+ const path25 = ref.slice(1).split("/").filter(Boolean);
23890
+ if (path25.length === 0) {
23364
23891
  return ctx.rootSchema;
23365
23892
  }
23366
23893
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
23367
- if (path24[0] === defsKey) {
23368
- const key = path24[1];
23894
+ if (path25[0] === defsKey) {
23895
+ const key = path25[1];
23369
23896
  if (!key || !ctx.defs[key]) {
23370
23897
  throw new Error(`Reference not found: ${ref}`);
23371
23898
  }
@@ -27058,12 +27585,12 @@ function resolveCliSessionBinding(provider, normalizedType, cliArgs, requestedRe
27058
27585
  launchMode: "new"
27059
27586
  };
27060
27587
  }
27061
- var os11, path9, crypto4, import_chalk, chalkApi, DaemonCliManager;
27588
+ var os11, path10, crypto4, import_chalk, chalkApi, DaemonCliManager;
27062
27589
  var init_cli_manager = __esm({
27063
27590
  "../../oss/packages/daemon-core/src/commands/cli-manager.ts"() {
27064
27591
  "use strict";
27065
27592
  os11 = __toESM(require("os"));
27066
- path9 = __toESM(require("path"));
27593
+ path10 = __toESM(require("path"));
27067
27594
  crypto4 = __toESM(require("crypto"));
27068
27595
  import_chalk = __toESM(require("chalk"));
27069
27596
  init_provider_cli_adapter();
@@ -27215,7 +27742,7 @@ var init_cli_manager = __esm({
27215
27742
  async startSession(cliType, workingDir, cliArgs, initialModel, options) {
27216
27743
  const trimmed = (workingDir || "").trim();
27217
27744
  if (!trimmed) throw new Error("working directory required");
27218
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os11.homedir()) : path9.resolve(trimmed);
27745
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os11.homedir()) : path10.resolve(trimmed);
27219
27746
  const normalizedType = this.providerLoader.resolveAlias(cliType);
27220
27747
  const provider = this.providerLoader.getByAlias(cliType);
27221
27748
  const key = crypto4.randomUUID();
@@ -27767,7 +28294,7 @@ var init_readdirp = __esm({
27767
28294
  this._directoryFilter = normalizeFilter(opts.directoryFilter);
27768
28295
  const statMethod = opts.lstat ? import_promises.lstat : import_promises.stat;
27769
28296
  if (wantBigintFsStats) {
27770
- this._stat = (path24) => statMethod(path24, { bigint: true });
28297
+ this._stat = (path25) => statMethod(path25, { bigint: true });
27771
28298
  } else {
27772
28299
  this._stat = statMethod;
27773
28300
  }
@@ -27792,8 +28319,8 @@ var init_readdirp = __esm({
27792
28319
  const par = this.parent;
27793
28320
  const fil = par && par.files;
27794
28321
  if (fil && fil.length > 0) {
27795
- const { path: path24, depth } = par;
27796
- const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path24));
28322
+ const { path: path25, depth } = par;
28323
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path25));
27797
28324
  const awaited = await Promise.all(slice);
27798
28325
  for (const entry of awaited) {
27799
28326
  if (!entry)
@@ -27833,21 +28360,21 @@ var init_readdirp = __esm({
27833
28360
  this.reading = false;
27834
28361
  }
27835
28362
  }
27836
- async _exploreDir(path24, depth) {
28363
+ async _exploreDir(path25, depth) {
27837
28364
  let files;
27838
28365
  try {
27839
- files = await (0, import_promises.readdir)(path24, this._rdOptions);
28366
+ files = await (0, import_promises.readdir)(path25, this._rdOptions);
27840
28367
  } catch (error48) {
27841
28368
  this._onError(error48);
27842
28369
  }
27843
- return { files, depth, path: path24 };
28370
+ return { files, depth, path: path25 };
27844
28371
  }
27845
- async _formatEntry(dirent, path24) {
28372
+ async _formatEntry(dirent, path25) {
27846
28373
  let entry;
27847
- const basename7 = this._isDirent ? dirent.name : dirent;
28374
+ const basename8 = this._isDirent ? dirent.name : dirent;
27848
28375
  try {
27849
- const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path24, basename7));
27850
- entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename7 };
28376
+ const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path25, basename8));
28377
+ entry = { path: (0, import_node_path.relative)(this._root, fullPath), fullPath, basename: basename8 };
27851
28378
  entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
27852
28379
  } catch (err) {
27853
28380
  this._onError(err);
@@ -27903,16 +28430,16 @@ var init_readdirp = __esm({
27903
28430
  });
27904
28431
 
27905
28432
  // ../../oss/packages/daemon-core/node_modules/chokidar/handler.js
27906
- function createFsWatchInstance(path24, options, listener, errHandler, emitRaw) {
28433
+ function createFsWatchInstance(path25, options, listener, errHandler, emitRaw) {
27907
28434
  const handleEvent = (rawEvent, evPath) => {
27908
- listener(path24);
27909
- emitRaw(rawEvent, evPath, { watchedPath: path24 });
27910
- if (evPath && path24 !== evPath) {
27911
- fsWatchBroadcast(sp.resolve(path24, evPath), KEY_LISTENERS, sp.join(path24, evPath));
28435
+ listener(path25);
28436
+ emitRaw(rawEvent, evPath, { watchedPath: path25 });
28437
+ if (evPath && path25 !== evPath) {
28438
+ fsWatchBroadcast(sp.resolve(path25, evPath), KEY_LISTENERS, sp.join(path25, evPath));
27912
28439
  }
27913
28440
  };
27914
28441
  try {
27915
- return (0, import_node_fs.watch)(path24, {
28442
+ return (0, import_node_fs.watch)(path25, {
27916
28443
  persistent: options.persistent
27917
28444
  }, handleEvent);
27918
28445
  } catch (error48) {
@@ -28261,12 +28788,12 @@ var init_handler2 = __esm({
28261
28788
  listener(val1, val2, val3);
28262
28789
  });
28263
28790
  };
28264
- setFsWatchListener = (path24, fullPath, options, handlers) => {
28791
+ setFsWatchListener = (path25, fullPath, options, handlers) => {
28265
28792
  const { listener, errHandler, rawEmitter } = handlers;
28266
28793
  let cont = FsWatchInstances.get(fullPath);
28267
28794
  let watcher;
28268
28795
  if (!options.persistent) {
28269
- watcher = createFsWatchInstance(path24, options, listener, errHandler, rawEmitter);
28796
+ watcher = createFsWatchInstance(path25, options, listener, errHandler, rawEmitter);
28270
28797
  if (!watcher)
28271
28798
  return;
28272
28799
  return watcher.close.bind(watcher);
@@ -28277,7 +28804,7 @@ var init_handler2 = __esm({
28277
28804
  addAndConvert(cont, KEY_RAW, rawEmitter);
28278
28805
  } else {
28279
28806
  watcher = createFsWatchInstance(
28280
- path24,
28807
+ path25,
28281
28808
  options,
28282
28809
  fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
28283
28810
  errHandler,
@@ -28292,7 +28819,7 @@ var init_handler2 = __esm({
28292
28819
  cont.watcherUnusable = true;
28293
28820
  if (isWindows && error48.code === "EPERM") {
28294
28821
  try {
28295
- const fd = await (0, import_promises2.open)(path24, "r");
28822
+ const fd = await (0, import_promises2.open)(path25, "r");
28296
28823
  await fd.close();
28297
28824
  broadcastErr(error48);
28298
28825
  } catch (err) {
@@ -28323,7 +28850,7 @@ var init_handler2 = __esm({
28323
28850
  };
28324
28851
  };
28325
28852
  FsWatchFileInstances = /* @__PURE__ */ new Map();
28326
- setFsWatchFileListener = (path24, fullPath, options, handlers) => {
28853
+ setFsWatchFileListener = (path25, fullPath, options, handlers) => {
28327
28854
  const { listener, rawEmitter } = handlers;
28328
28855
  let cont = FsWatchFileInstances.get(fullPath);
28329
28856
  const copts = cont && cont.options;
@@ -28345,7 +28872,7 @@ var init_handler2 = __esm({
28345
28872
  });
28346
28873
  const currmtime = curr.mtimeMs;
28347
28874
  if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
28348
- foreach(cont.listeners, (listener2) => listener2(path24, curr));
28875
+ foreach(cont.listeners, (listener2) => listener2(path25, curr));
28349
28876
  }
28350
28877
  })
28351
28878
  };
@@ -28375,13 +28902,13 @@ var init_handler2 = __esm({
28375
28902
  * @param listener on fs change
28376
28903
  * @returns closer for the watcher instance
28377
28904
  */
28378
- _watchWithNodeFs(path24, listener) {
28905
+ _watchWithNodeFs(path25, listener) {
28379
28906
  const opts = this.fsw.options;
28380
- const directory = sp.dirname(path24);
28381
- const basename7 = sp.basename(path24);
28907
+ const directory = sp.dirname(path25);
28908
+ const basename8 = sp.basename(path25);
28382
28909
  const parent = this.fsw._getWatchedDir(directory);
28383
- parent.add(basename7);
28384
- const absolutePath = sp.resolve(path24);
28910
+ parent.add(basename8);
28911
+ const absolutePath = sp.resolve(path25);
28385
28912
  const options = {
28386
28913
  persistent: opts.persistent
28387
28914
  };
@@ -28390,13 +28917,13 @@ var init_handler2 = __esm({
28390
28917
  let closer;
28391
28918
  if (opts.usePolling) {
28392
28919
  const enableBin = opts.interval !== opts.binaryInterval;
28393
- options.interval = enableBin && isBinaryPath(basename7) ? opts.binaryInterval : opts.interval;
28394
- closer = setFsWatchFileListener(path24, absolutePath, options, {
28920
+ options.interval = enableBin && isBinaryPath(basename8) ? opts.binaryInterval : opts.interval;
28921
+ closer = setFsWatchFileListener(path25, absolutePath, options, {
28395
28922
  listener,
28396
28923
  rawEmitter: this.fsw._emitRaw
28397
28924
  });
28398
28925
  } else {
28399
- closer = setFsWatchListener(path24, absolutePath, options, {
28926
+ closer = setFsWatchListener(path25, absolutePath, options, {
28400
28927
  listener,
28401
28928
  errHandler: this._boundHandleError,
28402
28929
  rawEmitter: this.fsw._emitRaw
@@ -28413,12 +28940,12 @@ var init_handler2 = __esm({
28413
28940
  return;
28414
28941
  }
28415
28942
  const dirname9 = sp.dirname(file2);
28416
- const basename7 = sp.basename(file2);
28943
+ const basename8 = sp.basename(file2);
28417
28944
  const parent = this.fsw._getWatchedDir(dirname9);
28418
28945
  let prevStats = stats;
28419
- if (parent.has(basename7))
28946
+ if (parent.has(basename8))
28420
28947
  return;
28421
- const listener = async (path24, newStats) => {
28948
+ const listener = async (path25, newStats) => {
28422
28949
  if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
28423
28950
  return;
28424
28951
  if (!newStats || newStats.mtimeMs === 0) {
@@ -28432,18 +28959,18 @@ var init_handler2 = __esm({
28432
28959
  this.fsw._emit(EV.CHANGE, file2, newStats2);
28433
28960
  }
28434
28961
  if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
28435
- this.fsw._closeFile(path24);
28962
+ this.fsw._closeFile(path25);
28436
28963
  prevStats = newStats2;
28437
28964
  const closer2 = this._watchWithNodeFs(file2, listener);
28438
28965
  if (closer2)
28439
- this.fsw._addPathCloser(path24, closer2);
28966
+ this.fsw._addPathCloser(path25, closer2);
28440
28967
  } else {
28441
28968
  prevStats = newStats2;
28442
28969
  }
28443
28970
  } catch (error48) {
28444
- this.fsw._remove(dirname9, basename7);
28971
+ this.fsw._remove(dirname9, basename8);
28445
28972
  }
28446
- } else if (parent.has(basename7)) {
28973
+ } else if (parent.has(basename8)) {
28447
28974
  const at = newStats.atimeMs;
28448
28975
  const mt = newStats.mtimeMs;
28449
28976
  if (!at || at <= mt || mt !== prevStats.mtimeMs) {
@@ -28468,7 +28995,7 @@ var init_handler2 = __esm({
28468
28995
  * @param item basename of this item
28469
28996
  * @returns true if no more processing is needed for this entry.
28470
28997
  */
28471
- async _handleSymlink(entry, directory, path24, item) {
28998
+ async _handleSymlink(entry, directory, path25, item) {
28472
28999
  if (this.fsw.closed) {
28473
29000
  return;
28474
29001
  }
@@ -28478,7 +29005,7 @@ var init_handler2 = __esm({
28478
29005
  this.fsw._incrReadyCount();
28479
29006
  let linkPath;
28480
29007
  try {
28481
- linkPath = await (0, import_promises2.realpath)(path24);
29008
+ linkPath = await (0, import_promises2.realpath)(path25);
28482
29009
  } catch (e) {
28483
29010
  this.fsw._emitReady();
28484
29011
  return true;
@@ -28488,12 +29015,12 @@ var init_handler2 = __esm({
28488
29015
  if (dir.has(item)) {
28489
29016
  if (this.fsw._symlinkPaths.get(full) !== linkPath) {
28490
29017
  this.fsw._symlinkPaths.set(full, linkPath);
28491
- this.fsw._emit(EV.CHANGE, path24, entry.stats);
29018
+ this.fsw._emit(EV.CHANGE, path25, entry.stats);
28492
29019
  }
28493
29020
  } else {
28494
29021
  dir.add(item);
28495
29022
  this.fsw._symlinkPaths.set(full, linkPath);
28496
- this.fsw._emit(EV.ADD, path24, entry.stats);
29023
+ this.fsw._emit(EV.ADD, path25, entry.stats);
28497
29024
  }
28498
29025
  this.fsw._emitReady();
28499
29026
  return true;
@@ -28523,9 +29050,9 @@ var init_handler2 = __esm({
28523
29050
  return;
28524
29051
  }
28525
29052
  const item = entry.path;
28526
- let path24 = sp.join(directory, item);
29053
+ let path25 = sp.join(directory, item);
28527
29054
  current.add(item);
28528
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path24, item)) {
29055
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path25, item)) {
28529
29056
  return;
28530
29057
  }
28531
29058
  if (this.fsw.closed) {
@@ -28534,8 +29061,8 @@ var init_handler2 = __esm({
28534
29061
  }
28535
29062
  if (item === target || !target && !previous.has(item)) {
28536
29063
  this.fsw._incrReadyCount();
28537
- path24 = sp.join(dir, sp.relative(dir, path24));
28538
- this._addToNodeFs(path24, initialAdd, wh, depth + 1);
29064
+ path25 = sp.join(dir, sp.relative(dir, path25));
29065
+ this._addToNodeFs(path25, initialAdd, wh, depth + 1);
28539
29066
  }
28540
29067
  }).on(EV.ERROR, this._boundHandleError);
28541
29068
  return new Promise((resolve14, reject) => {
@@ -28604,13 +29131,13 @@ var init_handler2 = __esm({
28604
29131
  * @param depth Child path actually targeted for watch
28605
29132
  * @param target Child path actually targeted for watch
28606
29133
  */
28607
- async _addToNodeFs(path24, initialAdd, priorWh, depth, target) {
29134
+ async _addToNodeFs(path25, initialAdd, priorWh, depth, target) {
28608
29135
  const ready = this.fsw._emitReady;
28609
- if (this.fsw._isIgnored(path24) || this.fsw.closed) {
29136
+ if (this.fsw._isIgnored(path25) || this.fsw.closed) {
28610
29137
  ready();
28611
29138
  return false;
28612
29139
  }
28613
- const wh = this.fsw._getWatchHelpers(path24);
29140
+ const wh = this.fsw._getWatchHelpers(path25);
28614
29141
  if (priorWh) {
28615
29142
  wh.filterPath = (entry) => priorWh.filterPath(entry);
28616
29143
  wh.filterDir = (entry) => priorWh.filterDir(entry);
@@ -28626,8 +29153,8 @@ var init_handler2 = __esm({
28626
29153
  const follow = this.fsw.options.followSymlinks;
28627
29154
  let closer;
28628
29155
  if (stats.isDirectory()) {
28629
- const absPath = sp.resolve(path24);
28630
- const targetPath = follow ? await (0, import_promises2.realpath)(path24) : path24;
29156
+ const absPath = sp.resolve(path25);
29157
+ const targetPath = follow ? await (0, import_promises2.realpath)(path25) : path25;
28631
29158
  if (this.fsw.closed)
28632
29159
  return;
28633
29160
  closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
@@ -28637,29 +29164,29 @@ var init_handler2 = __esm({
28637
29164
  this.fsw._symlinkPaths.set(absPath, targetPath);
28638
29165
  }
28639
29166
  } else if (stats.isSymbolicLink()) {
28640
- const targetPath = follow ? await (0, import_promises2.realpath)(path24) : path24;
29167
+ const targetPath = follow ? await (0, import_promises2.realpath)(path25) : path25;
28641
29168
  if (this.fsw.closed)
28642
29169
  return;
28643
29170
  const parent = sp.dirname(wh.watchPath);
28644
29171
  this.fsw._getWatchedDir(parent).add(wh.watchPath);
28645
29172
  this.fsw._emit(EV.ADD, wh.watchPath, stats);
28646
- closer = await this._handleDir(parent, stats, initialAdd, depth, path24, wh, targetPath);
29173
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path25, wh, targetPath);
28647
29174
  if (this.fsw.closed)
28648
29175
  return;
28649
29176
  if (targetPath !== void 0) {
28650
- this.fsw._symlinkPaths.set(sp.resolve(path24), targetPath);
29177
+ this.fsw._symlinkPaths.set(sp.resolve(path25), targetPath);
28651
29178
  }
28652
29179
  } else {
28653
29180
  closer = this._handleFile(wh.watchPath, stats, initialAdd);
28654
29181
  }
28655
29182
  ready();
28656
29183
  if (closer)
28657
- this.fsw._addPathCloser(path24, closer);
29184
+ this.fsw._addPathCloser(path25, closer);
28658
29185
  return false;
28659
29186
  } catch (error48) {
28660
29187
  if (this.fsw._handleError(error48)) {
28661
29188
  ready();
28662
- return path24;
29189
+ return path25;
28663
29190
  }
28664
29191
  }
28665
29192
  }
@@ -28694,24 +29221,24 @@ function createPattern(matcher) {
28694
29221
  }
28695
29222
  return () => false;
28696
29223
  }
28697
- function normalizePath(path24) {
28698
- if (typeof path24 !== "string")
29224
+ function normalizePath(path25) {
29225
+ if (typeof path25 !== "string")
28699
29226
  throw new Error("string expected");
28700
- path24 = sp2.normalize(path24);
28701
- path24 = path24.replace(/\\/g, "/");
29227
+ path25 = sp2.normalize(path25);
29228
+ path25 = path25.replace(/\\/g, "/");
28702
29229
  let prepend = false;
28703
- if (path24.startsWith("//"))
29230
+ if (path25.startsWith("//"))
28704
29231
  prepend = true;
28705
- path24 = path24.replace(DOUBLE_SLASH_RE, "/");
29232
+ path25 = path25.replace(DOUBLE_SLASH_RE, "/");
28706
29233
  if (prepend)
28707
- path24 = "/" + path24;
28708
- return path24;
29234
+ path25 = "/" + path25;
29235
+ return path25;
28709
29236
  }
28710
29237
  function matchPatterns(patterns, testString, stats) {
28711
- const path24 = normalizePath(testString);
29238
+ const path25 = normalizePath(testString);
28712
29239
  for (let index = 0; index < patterns.length; index++) {
28713
29240
  const pattern = patterns[index];
28714
- if (pattern(path24, stats)) {
29241
+ if (pattern(path25, stats)) {
28715
29242
  return true;
28716
29243
  }
28717
29244
  }
@@ -28774,19 +29301,19 @@ var init_chokidar = __esm({
28774
29301
  }
28775
29302
  return str;
28776
29303
  };
28777
- normalizePathToUnix = (path24) => toUnix(sp2.normalize(toUnix(path24)));
28778
- normalizeIgnored = (cwd = "") => (path24) => {
28779
- if (typeof path24 === "string") {
28780
- return normalizePathToUnix(sp2.isAbsolute(path24) ? path24 : sp2.join(cwd, path24));
29304
+ normalizePathToUnix = (path25) => toUnix(sp2.normalize(toUnix(path25)));
29305
+ normalizeIgnored = (cwd = "") => (path25) => {
29306
+ if (typeof path25 === "string") {
29307
+ return normalizePathToUnix(sp2.isAbsolute(path25) ? path25 : sp2.join(cwd, path25));
28781
29308
  } else {
28782
- return path24;
29309
+ return path25;
28783
29310
  }
28784
29311
  };
28785
- getAbsolutePath = (path24, cwd) => {
28786
- if (sp2.isAbsolute(path24)) {
28787
- return path24;
29312
+ getAbsolutePath = (path25, cwd) => {
29313
+ if (sp2.isAbsolute(path25)) {
29314
+ return path25;
28788
29315
  }
28789
- return sp2.join(cwd, path24);
29316
+ return sp2.join(cwd, path25);
28790
29317
  };
28791
29318
  EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
28792
29319
  DirEntry = class {
@@ -28851,10 +29378,10 @@ var init_chokidar = __esm({
28851
29378
  dirParts;
28852
29379
  followSymlinks;
28853
29380
  statMethod;
28854
- constructor(path24, follow, fsw) {
29381
+ constructor(path25, follow, fsw) {
28855
29382
  this.fsw = fsw;
28856
- const watchPath = path24;
28857
- this.path = path24 = path24.replace(REPLACER_RE, "");
29383
+ const watchPath = path25;
29384
+ this.path = path25 = path25.replace(REPLACER_RE, "");
28858
29385
  this.watchPath = watchPath;
28859
29386
  this.fullWatchPath = sp2.resolve(watchPath);
28860
29387
  this.dirParts = [];
@@ -28994,20 +29521,20 @@ var init_chokidar = __esm({
28994
29521
  this._closePromise = void 0;
28995
29522
  let paths = unifyPaths(paths_);
28996
29523
  if (cwd) {
28997
- paths = paths.map((path24) => {
28998
- const absPath = getAbsolutePath(path24, cwd);
29524
+ paths = paths.map((path25) => {
29525
+ const absPath = getAbsolutePath(path25, cwd);
28999
29526
  return absPath;
29000
29527
  });
29001
29528
  }
29002
- paths.forEach((path24) => {
29003
- this._removeIgnoredPath(path24);
29529
+ paths.forEach((path25) => {
29530
+ this._removeIgnoredPath(path25);
29004
29531
  });
29005
29532
  this._userIgnored = void 0;
29006
29533
  if (!this._readyCount)
29007
29534
  this._readyCount = 0;
29008
29535
  this._readyCount += paths.length;
29009
- Promise.all(paths.map(async (path24) => {
29010
- const res = await this._nodeFsHandler._addToNodeFs(path24, !_internal, void 0, 0, _origAdd);
29536
+ Promise.all(paths.map(async (path25) => {
29537
+ const res = await this._nodeFsHandler._addToNodeFs(path25, !_internal, void 0, 0, _origAdd);
29011
29538
  if (res)
29012
29539
  this._emitReady();
29013
29540
  return res;
@@ -29029,17 +29556,17 @@ var init_chokidar = __esm({
29029
29556
  return this;
29030
29557
  const paths = unifyPaths(paths_);
29031
29558
  const { cwd } = this.options;
29032
- paths.forEach((path24) => {
29033
- if (!sp2.isAbsolute(path24) && !this._closers.has(path24)) {
29559
+ paths.forEach((path25) => {
29560
+ if (!sp2.isAbsolute(path25) && !this._closers.has(path25)) {
29034
29561
  if (cwd)
29035
- path24 = sp2.join(cwd, path24);
29036
- path24 = sp2.resolve(path24);
29562
+ path25 = sp2.join(cwd, path25);
29563
+ path25 = sp2.resolve(path25);
29037
29564
  }
29038
- this._closePath(path24);
29039
- this._addIgnoredPath(path24);
29040
- if (this._watched.has(path24)) {
29565
+ this._closePath(path25);
29566
+ this._addIgnoredPath(path25);
29567
+ if (this._watched.has(path25)) {
29041
29568
  this._addIgnoredPath({
29042
- path: path24,
29569
+ path: path25,
29043
29570
  recursive: true
29044
29571
  });
29045
29572
  }
@@ -29103,38 +29630,38 @@ var init_chokidar = __esm({
29103
29630
  * @param stats arguments to be passed with event
29104
29631
  * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
29105
29632
  */
29106
- async _emit(event, path24, stats) {
29633
+ async _emit(event, path25, stats) {
29107
29634
  if (this.closed)
29108
29635
  return;
29109
29636
  const opts = this.options;
29110
29637
  if (isWindows)
29111
- path24 = sp2.normalize(path24);
29638
+ path25 = sp2.normalize(path25);
29112
29639
  if (opts.cwd)
29113
- path24 = sp2.relative(opts.cwd, path24);
29114
- const args = [path24];
29640
+ path25 = sp2.relative(opts.cwd, path25);
29641
+ const args = [path25];
29115
29642
  if (stats != null)
29116
29643
  args.push(stats);
29117
29644
  const awf = opts.awaitWriteFinish;
29118
29645
  let pw;
29119
- if (awf && (pw = this._pendingWrites.get(path24))) {
29646
+ if (awf && (pw = this._pendingWrites.get(path25))) {
29120
29647
  pw.lastChange = /* @__PURE__ */ new Date();
29121
29648
  return this;
29122
29649
  }
29123
29650
  if (opts.atomic) {
29124
29651
  if (event === EVENTS.UNLINK) {
29125
- this._pendingUnlinks.set(path24, [event, ...args]);
29652
+ this._pendingUnlinks.set(path25, [event, ...args]);
29126
29653
  setTimeout(() => {
29127
- this._pendingUnlinks.forEach((entry, path25) => {
29654
+ this._pendingUnlinks.forEach((entry, path26) => {
29128
29655
  this.emit(...entry);
29129
29656
  this.emit(EVENTS.ALL, ...entry);
29130
- this._pendingUnlinks.delete(path25);
29657
+ this._pendingUnlinks.delete(path26);
29131
29658
  });
29132
29659
  }, typeof opts.atomic === "number" ? opts.atomic : 100);
29133
29660
  return this;
29134
29661
  }
29135
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path24)) {
29662
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path25)) {
29136
29663
  event = EVENTS.CHANGE;
29137
- this._pendingUnlinks.delete(path24);
29664
+ this._pendingUnlinks.delete(path25);
29138
29665
  }
29139
29666
  }
29140
29667
  if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
@@ -29152,16 +29679,16 @@ var init_chokidar = __esm({
29152
29679
  this.emitWithAll(event, args);
29153
29680
  }
29154
29681
  };
29155
- this._awaitWriteFinish(path24, awf.stabilityThreshold, event, awfEmit);
29682
+ this._awaitWriteFinish(path25, awf.stabilityThreshold, event, awfEmit);
29156
29683
  return this;
29157
29684
  }
29158
29685
  if (event === EVENTS.CHANGE) {
29159
- const isThrottled = !this._throttle(EVENTS.CHANGE, path24, 50);
29686
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path25, 50);
29160
29687
  if (isThrottled)
29161
29688
  return this;
29162
29689
  }
29163
29690
  if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
29164
- const fullPath = opts.cwd ? sp2.join(opts.cwd, path24) : path24;
29691
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path25) : path25;
29165
29692
  let stats2;
29166
29693
  try {
29167
29694
  stats2 = await (0, import_promises3.stat)(fullPath);
@@ -29192,23 +29719,23 @@ var init_chokidar = __esm({
29192
29719
  * @param timeout duration of time to suppress duplicate actions
29193
29720
  * @returns tracking object or false if action should be suppressed
29194
29721
  */
29195
- _throttle(actionType, path24, timeout) {
29722
+ _throttle(actionType, path25, timeout) {
29196
29723
  if (!this._throttled.has(actionType)) {
29197
29724
  this._throttled.set(actionType, /* @__PURE__ */ new Map());
29198
29725
  }
29199
29726
  const action = this._throttled.get(actionType);
29200
29727
  if (!action)
29201
29728
  throw new Error("invalid throttle");
29202
- const actionPath = action.get(path24);
29729
+ const actionPath = action.get(path25);
29203
29730
  if (actionPath) {
29204
29731
  actionPath.count++;
29205
29732
  return false;
29206
29733
  }
29207
29734
  let timeoutObject;
29208
29735
  const clear = () => {
29209
- const item = action.get(path24);
29736
+ const item = action.get(path25);
29210
29737
  const count = item ? item.count : 0;
29211
- action.delete(path24);
29738
+ action.delete(path25);
29212
29739
  clearTimeout(timeoutObject);
29213
29740
  if (item)
29214
29741
  clearTimeout(item.timeoutObject);
@@ -29216,7 +29743,7 @@ var init_chokidar = __esm({
29216
29743
  };
29217
29744
  timeoutObject = setTimeout(clear, timeout);
29218
29745
  const thr = { timeoutObject, clear, count: 0 };
29219
- action.set(path24, thr);
29746
+ action.set(path25, thr);
29220
29747
  return thr;
29221
29748
  }
29222
29749
  _incrReadyCount() {
@@ -29230,44 +29757,44 @@ var init_chokidar = __esm({
29230
29757
  * @param event
29231
29758
  * @param awfEmit Callback to be called when ready for event to be emitted.
29232
29759
  */
29233
- _awaitWriteFinish(path24, threshold, event, awfEmit) {
29760
+ _awaitWriteFinish(path25, threshold, event, awfEmit) {
29234
29761
  const awf = this.options.awaitWriteFinish;
29235
29762
  if (typeof awf !== "object")
29236
29763
  return;
29237
29764
  const pollInterval = awf.pollInterval;
29238
29765
  let timeoutHandler;
29239
- let fullPath = path24;
29240
- if (this.options.cwd && !sp2.isAbsolute(path24)) {
29241
- fullPath = sp2.join(this.options.cwd, path24);
29766
+ let fullPath = path25;
29767
+ if (this.options.cwd && !sp2.isAbsolute(path25)) {
29768
+ fullPath = sp2.join(this.options.cwd, path25);
29242
29769
  }
29243
29770
  const now = /* @__PURE__ */ new Date();
29244
29771
  const writes = this._pendingWrites;
29245
29772
  function awaitWriteFinishFn(prevStat) {
29246
29773
  (0, import_node_fs2.stat)(fullPath, (err, curStat) => {
29247
- if (err || !writes.has(path24)) {
29774
+ if (err || !writes.has(path25)) {
29248
29775
  if (err && err.code !== "ENOENT")
29249
29776
  awfEmit(err);
29250
29777
  return;
29251
29778
  }
29252
29779
  const now2 = Number(/* @__PURE__ */ new Date());
29253
29780
  if (prevStat && curStat.size !== prevStat.size) {
29254
- writes.get(path24).lastChange = now2;
29781
+ writes.get(path25).lastChange = now2;
29255
29782
  }
29256
- const pw = writes.get(path24);
29783
+ const pw = writes.get(path25);
29257
29784
  const df = now2 - pw.lastChange;
29258
29785
  if (df >= threshold) {
29259
- writes.delete(path24);
29786
+ writes.delete(path25);
29260
29787
  awfEmit(void 0, curStat);
29261
29788
  } else {
29262
29789
  timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
29263
29790
  }
29264
29791
  });
29265
29792
  }
29266
- if (!writes.has(path24)) {
29267
- writes.set(path24, {
29793
+ if (!writes.has(path25)) {
29794
+ writes.set(path25, {
29268
29795
  lastChange: now,
29269
29796
  cancelWait: () => {
29270
- writes.delete(path24);
29797
+ writes.delete(path25);
29271
29798
  clearTimeout(timeoutHandler);
29272
29799
  return event;
29273
29800
  }
@@ -29278,8 +29805,8 @@ var init_chokidar = __esm({
29278
29805
  /**
29279
29806
  * Determines whether user has asked to ignore this path.
29280
29807
  */
29281
- _isIgnored(path24, stats) {
29282
- if (this.options.atomic && DOT_RE.test(path24))
29808
+ _isIgnored(path25, stats) {
29809
+ if (this.options.atomic && DOT_RE.test(path25))
29283
29810
  return true;
29284
29811
  if (!this._userIgnored) {
29285
29812
  const { cwd } = this.options;
@@ -29289,17 +29816,17 @@ var init_chokidar = __esm({
29289
29816
  const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
29290
29817
  this._userIgnored = anymatch(list, void 0);
29291
29818
  }
29292
- return this._userIgnored(path24, stats);
29819
+ return this._userIgnored(path25, stats);
29293
29820
  }
29294
- _isntIgnored(path24, stat4) {
29295
- return !this._isIgnored(path24, stat4);
29821
+ _isntIgnored(path25, stat4) {
29822
+ return !this._isIgnored(path25, stat4);
29296
29823
  }
29297
29824
  /**
29298
29825
  * Provides a set of common helpers and properties relating to symlink handling.
29299
29826
  * @param path file or directory pattern being watched
29300
29827
  */
29301
- _getWatchHelpers(path24) {
29302
- return new WatchHelper(path24, this.options.followSymlinks, this);
29828
+ _getWatchHelpers(path25) {
29829
+ return new WatchHelper(path25, this.options.followSymlinks, this);
29303
29830
  }
29304
29831
  // Directory helpers
29305
29832
  // -----------------
@@ -29331,63 +29858,63 @@ var init_chokidar = __esm({
29331
29858
  * @param item base path of item/directory
29332
29859
  */
29333
29860
  _remove(directory, item, isDirectory) {
29334
- const path24 = sp2.join(directory, item);
29335
- const fullPath = sp2.resolve(path24);
29336
- isDirectory = isDirectory != null ? isDirectory : this._watched.has(path24) || this._watched.has(fullPath);
29337
- if (!this._throttle("remove", path24, 100))
29861
+ const path25 = sp2.join(directory, item);
29862
+ const fullPath = sp2.resolve(path25);
29863
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path25) || this._watched.has(fullPath);
29864
+ if (!this._throttle("remove", path25, 100))
29338
29865
  return;
29339
29866
  if (!isDirectory && this._watched.size === 1) {
29340
29867
  this.add(directory, item, true);
29341
29868
  }
29342
- const wp = this._getWatchedDir(path24);
29869
+ const wp = this._getWatchedDir(path25);
29343
29870
  const nestedDirectoryChildren = wp.getChildren();
29344
- nestedDirectoryChildren.forEach((nested) => this._remove(path24, nested));
29871
+ nestedDirectoryChildren.forEach((nested) => this._remove(path25, nested));
29345
29872
  const parent = this._getWatchedDir(directory);
29346
29873
  const wasTracked = parent.has(item);
29347
29874
  parent.remove(item);
29348
29875
  if (this._symlinkPaths.has(fullPath)) {
29349
29876
  this._symlinkPaths.delete(fullPath);
29350
29877
  }
29351
- let relPath = path24;
29878
+ let relPath = path25;
29352
29879
  if (this.options.cwd)
29353
- relPath = sp2.relative(this.options.cwd, path24);
29880
+ relPath = sp2.relative(this.options.cwd, path25);
29354
29881
  if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
29355
29882
  const event = this._pendingWrites.get(relPath).cancelWait();
29356
29883
  if (event === EVENTS.ADD)
29357
29884
  return;
29358
29885
  }
29359
- this._watched.delete(path24);
29886
+ this._watched.delete(path25);
29360
29887
  this._watched.delete(fullPath);
29361
29888
  const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
29362
- if (wasTracked && !this._isIgnored(path24))
29363
- this._emit(eventName, path24);
29364
- this._closePath(path24);
29889
+ if (wasTracked && !this._isIgnored(path25))
29890
+ this._emit(eventName, path25);
29891
+ this._closePath(path25);
29365
29892
  }
29366
29893
  /**
29367
29894
  * Closes all watchers for a path
29368
29895
  */
29369
- _closePath(path24) {
29370
- this._closeFile(path24);
29371
- const dir = sp2.dirname(path24);
29372
- this._getWatchedDir(dir).remove(sp2.basename(path24));
29896
+ _closePath(path25) {
29897
+ this._closeFile(path25);
29898
+ const dir = sp2.dirname(path25);
29899
+ this._getWatchedDir(dir).remove(sp2.basename(path25));
29373
29900
  }
29374
29901
  /**
29375
29902
  * Closes only file-specific watchers
29376
29903
  */
29377
- _closeFile(path24) {
29378
- const closers = this._closers.get(path24);
29904
+ _closeFile(path25) {
29905
+ const closers = this._closers.get(path25);
29379
29906
  if (!closers)
29380
29907
  return;
29381
29908
  closers.forEach((closer) => closer());
29382
- this._closers.delete(path24);
29909
+ this._closers.delete(path25);
29383
29910
  }
29384
- _addPathCloser(path24, closer) {
29911
+ _addPathCloser(path25, closer) {
29385
29912
  if (!closer)
29386
29913
  return;
29387
- let list = this._closers.get(path24);
29914
+ let list = this._closers.get(path25);
29388
29915
  if (!list) {
29389
29916
  list = [];
29390
- this._closers.set(path24, list);
29917
+ this._closers.set(path25, list);
29391
29918
  }
29392
29919
  list.push(closer);
29393
29920
  }
@@ -29413,12 +29940,12 @@ var init_chokidar = __esm({
29413
29940
  });
29414
29941
 
29415
29942
  // ../../oss/packages/daemon-core/src/providers/provider-loader.ts
29416
- var fs6, path10, os12, ProviderLoader;
29943
+ var fs6, path11, os12, ProviderLoader;
29417
29944
  var init_provider_loader = __esm({
29418
29945
  "../../oss/packages/daemon-core/src/providers/provider-loader.ts"() {
29419
29946
  "use strict";
29420
29947
  fs6 = __toESM(require("fs"));
29421
- path10 = __toESM(require("path"));
29948
+ path11 = __toESM(require("path"));
29422
29949
  os12 = __toESM(require("os"));
29423
29950
  init_chokidar();
29424
29951
  init_ide_detector();
@@ -29440,12 +29967,12 @@ var init_provider_loader = __esm({
29440
29967
  static META_FILE = ".meta.json";
29441
29968
  constructor(options) {
29442
29969
  this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
29443
- const defaultProvidersDir = path10.join(os12.homedir(), ".adhdev", "providers");
29970
+ const defaultProvidersDir = path11.join(os12.homedir(), ".adhdev", "providers");
29444
29971
  if (options?.userDir) {
29445
29972
  this.userDir = options.userDir;
29446
29973
  this.log(`Config 'providerDir' applied: ${this.userDir}`);
29447
29974
  } else {
29448
- const localRepoPath = path10.resolve(__dirname, "../../../../../adhdev-providers");
29975
+ const localRepoPath = path11.resolve(__dirname, "../../../../../adhdev-providers");
29449
29976
  if (fs6.existsSync(localRepoPath)) {
29450
29977
  this.userDir = localRepoPath;
29451
29978
  this.log(`Auto-detected local public repository: ${this.userDir} (Dev workspace speedup)`);
@@ -29454,7 +29981,7 @@ var init_provider_loader = __esm({
29454
29981
  this.log(`Using default user providers directory: ${this.userDir}`);
29455
29982
  }
29456
29983
  }
29457
- this.upstreamDir = path10.join(defaultProvidersDir, ".upstream");
29984
+ this.upstreamDir = path11.join(defaultProvidersDir, ".upstream");
29458
29985
  this.disableUpstream = options?.disableUpstream ?? false;
29459
29986
  }
29460
29987
  log(msg) {
@@ -29484,7 +30011,7 @@ var init_provider_loader = __esm({
29484
30011
  * Canonical provider directory shape for a given root.
29485
30012
  */
29486
30013
  getProviderDir(root, category, type) {
29487
- return path10.join(root, category, type);
30014
+ return path11.join(root, category, type);
29488
30015
  }
29489
30016
  /**
29490
30017
  * Canonical user override directory for a provider.
@@ -29511,7 +30038,7 @@ var init_provider_loader = __esm({
29511
30038
  resolveProviderFile(type, ...segments) {
29512
30039
  const dir = this.findProviderDirInternal(type);
29513
30040
  if (!dir) return null;
29514
- return path10.join(dir, ...segments);
30041
+ return path11.join(dir, ...segments);
29515
30042
  }
29516
30043
  /**
29517
30044
  * Load all providers (3-tier priority)
@@ -29549,7 +30076,7 @@ var init_provider_loader = __esm({
29549
30076
  if (!fs6.existsSync(this.upstreamDir)) return false;
29550
30077
  try {
29551
30078
  return fs6.readdirSync(this.upstreamDir).some(
29552
- (d) => fs6.statSync(path10.join(this.upstreamDir, d)).isDirectory()
30079
+ (d) => fs6.statSync(path11.join(this.upstreamDir, d)).isDirectory()
29553
30080
  );
29554
30081
  } catch {
29555
30082
  return false;
@@ -29799,8 +30326,8 @@ var init_provider_loader = __esm({
29799
30326
  resolved._resolvedScriptDir = entry.scriptDir;
29800
30327
  resolved._resolvedScriptsSource = `compatibility:${entry.ideVersion}`;
29801
30328
  if (providerDir) {
29802
- const fullDir = path10.join(providerDir, entry.scriptDir);
29803
- resolved._resolvedScriptsPath = fs6.existsSync(path10.join(fullDir, "scripts.js")) ? path10.join(fullDir, "scripts.js") : fullDir;
30329
+ const fullDir = path11.join(providerDir, entry.scriptDir);
30330
+ resolved._resolvedScriptsPath = fs6.existsSync(path11.join(fullDir, "scripts.js")) ? path11.join(fullDir, "scripts.js") : fullDir;
29804
30331
  }
29805
30332
  matched = true;
29806
30333
  }
@@ -29815,8 +30342,8 @@ var init_provider_loader = __esm({
29815
30342
  resolved._resolvedScriptDir = base.defaultScriptDir;
29816
30343
  resolved._resolvedScriptsSource = "defaultScriptDir:version_miss";
29817
30344
  if (providerDir) {
29818
- const fullDir = path10.join(providerDir, base.defaultScriptDir);
29819
- resolved._resolvedScriptsPath = fs6.existsSync(path10.join(fullDir, "scripts.js")) ? path10.join(fullDir, "scripts.js") : fullDir;
30345
+ const fullDir = path11.join(providerDir, base.defaultScriptDir);
30346
+ resolved._resolvedScriptsPath = fs6.existsSync(path11.join(fullDir, "scripts.js")) ? path11.join(fullDir, "scripts.js") : fullDir;
29820
30347
  }
29821
30348
  }
29822
30349
  resolved._versionWarning = `Version ${currentVersion} not in compatibility matrix. Using default scripts.`;
@@ -29833,8 +30360,8 @@ var init_provider_loader = __esm({
29833
30360
  resolved._resolvedScriptDir = dirOverride;
29834
30361
  resolved._resolvedScriptsSource = `versions:${range}`;
29835
30362
  if (providerDir) {
29836
- const fullDir = path10.join(providerDir, dirOverride);
29837
- resolved._resolvedScriptsPath = fs6.existsSync(path10.join(fullDir, "scripts.js")) ? path10.join(fullDir, "scripts.js") : fullDir;
30363
+ const fullDir = path11.join(providerDir, dirOverride);
30364
+ resolved._resolvedScriptsPath = fs6.existsSync(path11.join(fullDir, "scripts.js")) ? path11.join(fullDir, "scripts.js") : fullDir;
29838
30365
  }
29839
30366
  }
29840
30367
  } else if (override.scripts) {
@@ -29850,8 +30377,8 @@ var init_provider_loader = __esm({
29850
30377
  resolved._resolvedScriptDir = base.defaultScriptDir;
29851
30378
  resolved._resolvedScriptsSource = "defaultScriptDir:no_version";
29852
30379
  if (providerDir) {
29853
- const fullDir = path10.join(providerDir, base.defaultScriptDir);
29854
- resolved._resolvedScriptsPath = fs6.existsSync(path10.join(fullDir, "scripts.js")) ? path10.join(fullDir, "scripts.js") : fullDir;
30380
+ const fullDir = path11.join(providerDir, base.defaultScriptDir);
30381
+ resolved._resolvedScriptsPath = fs6.existsSync(path11.join(fullDir, "scripts.js")) ? path11.join(fullDir, "scripts.js") : fullDir;
29855
30382
  }
29856
30383
  }
29857
30384
  }
@@ -29876,14 +30403,14 @@ var init_provider_loader = __esm({
29876
30403
  this.log(` [loadScriptsFromDir] ${type}: providerDir not found`);
29877
30404
  return null;
29878
30405
  }
29879
- const dir = path10.join(providerDir, scriptDir);
30406
+ const dir = path11.join(providerDir, scriptDir);
29880
30407
  if (!fs6.existsSync(dir)) {
29881
30408
  this.log(` [loadScriptsFromDir] ${type}: dir not found: ${dir}`);
29882
30409
  return null;
29883
30410
  }
29884
30411
  const cached2 = this.scriptsCache.get(dir);
29885
30412
  if (cached2) return cached2;
29886
- const scriptsJs = path10.join(dir, "scripts.js");
30413
+ const scriptsJs = path11.join(dir, "scripts.js");
29887
30414
  if (fs6.existsSync(scriptsJs)) {
29888
30415
  try {
29889
30416
  delete require.cache[require.resolve(scriptsJs)];
@@ -29925,7 +30452,7 @@ var init_provider_loader = __esm({
29925
30452
  return;
29926
30453
  }
29927
30454
  if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
29928
- this.log(`File changed: ${path10.basename(filePath)}, reloading...`);
30455
+ this.log(`File changed: ${path11.basename(filePath)}, reloading...`);
29929
30456
  this.reload();
29930
30457
  }
29931
30458
  };
@@ -29980,7 +30507,7 @@ var init_provider_loader = __esm({
29980
30507
  }
29981
30508
  const https = require("https");
29982
30509
  const { execSync: execSync7 } = require("child_process");
29983
- const metaPath = path10.join(this.upstreamDir, _ProviderLoader.META_FILE);
30510
+ const metaPath = path11.join(this.upstreamDir, _ProviderLoader.META_FILE);
29984
30511
  let prevEtag = "";
29985
30512
  let prevTimestamp = 0;
29986
30513
  try {
@@ -30040,17 +30567,17 @@ var init_provider_loader = __esm({
30040
30567
  return { updated: false };
30041
30568
  }
30042
30569
  this.log("Downloading latest providers from GitHub...");
30043
- const tmpTar = path10.join(os12.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
30044
- const tmpExtract = path10.join(os12.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
30570
+ const tmpTar = path11.join(os12.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
30571
+ const tmpExtract = path11.join(os12.tmpdir(), `adhdev-providers-extract-${Date.now()}`);
30045
30572
  await this.downloadFile(_ProviderLoader.GITHUB_TARBALL_URL, tmpTar);
30046
30573
  fs6.mkdirSync(tmpExtract, { recursive: true });
30047
30574
  execSync7(`tar -xzf "${tmpTar}" -C "${tmpExtract}"`, { timeout: 3e4 });
30048
30575
  const extracted = fs6.readdirSync(tmpExtract);
30049
30576
  const rootDir = extracted.find(
30050
- (d) => fs6.statSync(path10.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
30577
+ (d) => fs6.statSync(path11.join(tmpExtract, d)).isDirectory() && d.startsWith("adhdev-providers")
30051
30578
  );
30052
30579
  if (!rootDir) throw new Error("Unexpected tarball structure");
30053
- const sourceDir = path10.join(tmpExtract, rootDir);
30580
+ const sourceDir = path11.join(tmpExtract, rootDir);
30054
30581
  const backupDir = this.upstreamDir + ".bak";
30055
30582
  if (fs6.existsSync(this.upstreamDir)) {
30056
30583
  if (fs6.existsSync(backupDir)) fs6.rmSync(backupDir, { recursive: true, force: true });
@@ -30125,8 +30652,8 @@ var init_provider_loader = __esm({
30125
30652
  copyDirRecursive(src, dest) {
30126
30653
  fs6.mkdirSync(dest, { recursive: true });
30127
30654
  for (const entry of fs6.readdirSync(src, { withFileTypes: true })) {
30128
- const srcPath = path10.join(src, entry.name);
30129
- const destPath = path10.join(dest, entry.name);
30655
+ const srcPath = path11.join(src, entry.name);
30656
+ const destPath = path11.join(dest, entry.name);
30130
30657
  if (entry.isDirectory()) {
30131
30658
  this.copyDirRecursive(srcPath, destPath);
30132
30659
  } else {
@@ -30137,7 +30664,7 @@ var init_provider_loader = __esm({
30137
30664
  /** .meta.json save */
30138
30665
  writeMeta(metaPath, etag, timestamp) {
30139
30666
  try {
30140
- fs6.mkdirSync(path10.dirname(metaPath), { recursive: true });
30667
+ fs6.mkdirSync(path11.dirname(metaPath), { recursive: true });
30141
30668
  fs6.writeFileSync(metaPath, JSON.stringify({
30142
30669
  etag,
30143
30670
  timestamp,
@@ -30154,7 +30681,7 @@ var init_provider_loader = __esm({
30154
30681
  const scan = (d) => {
30155
30682
  try {
30156
30683
  for (const entry of fs6.readdirSync(d, { withFileTypes: true })) {
30157
- if (entry.isDirectory()) scan(path10.join(d, entry.name));
30684
+ if (entry.isDirectory()) scan(path11.join(d, entry.name));
30158
30685
  else if (entry.name === "provider.json") count++;
30159
30686
  }
30160
30687
  } catch {
@@ -30253,17 +30780,17 @@ var init_provider_loader = __esm({
30253
30780
  for (const root of searchRoots) {
30254
30781
  if (!fs6.existsSync(root)) continue;
30255
30782
  const candidate = this.getProviderDir(root, cat, type);
30256
- if (fs6.existsSync(path10.join(candidate, "provider.json"))) return candidate;
30257
- const catDir = path10.join(root, cat);
30783
+ if (fs6.existsSync(path11.join(candidate, "provider.json"))) return candidate;
30784
+ const catDir = path11.join(root, cat);
30258
30785
  if (fs6.existsSync(catDir)) {
30259
30786
  try {
30260
30787
  for (const entry of fs6.readdirSync(catDir, { withFileTypes: true })) {
30261
30788
  if (!entry.isDirectory()) continue;
30262
- const jsonPath = path10.join(catDir, entry.name, "provider.json");
30789
+ const jsonPath = path11.join(catDir, entry.name, "provider.json");
30263
30790
  if (fs6.existsSync(jsonPath)) {
30264
30791
  try {
30265
30792
  const data = JSON.parse(fs6.readFileSync(jsonPath, "utf-8"));
30266
- if (data.type === type) return path10.join(catDir, entry.name);
30793
+ if (data.type === type) return path11.join(catDir, entry.name);
30267
30794
  } catch {
30268
30795
  }
30269
30796
  }
@@ -30280,7 +30807,7 @@ var init_provider_loader = __esm({
30280
30807
  * (template substitution is NOT applied here — scripts.js handles that)
30281
30808
  */
30282
30809
  buildScriptWrappersFromDir(dir) {
30283
- const scriptsJs = path10.join(dir, "scripts.js");
30810
+ const scriptsJs = path11.join(dir, "scripts.js");
30284
30811
  if (fs6.existsSync(scriptsJs)) {
30285
30812
  try {
30286
30813
  delete require.cache[require.resolve(scriptsJs)];
@@ -30294,7 +30821,7 @@ var init_provider_loader = __esm({
30294
30821
  for (const file2 of fs6.readdirSync(dir)) {
30295
30822
  if (!file2.endsWith(".js")) continue;
30296
30823
  const scriptName = toCamel(file2.replace(".js", ""));
30297
- const filePath = path10.join(dir, file2);
30824
+ const filePath = path11.join(dir, file2);
30298
30825
  result[scriptName] = (...args) => {
30299
30826
  try {
30300
30827
  let content = fs6.readFileSync(filePath, "utf-8");
@@ -30354,7 +30881,7 @@ var init_provider_loader = __esm({
30354
30881
  }
30355
30882
  const hasJson = entries.some((e) => e.name === "provider.json");
30356
30883
  if (hasJson) {
30357
- const jsonPath = path10.join(d, "provider.json");
30884
+ const jsonPath = path11.join(d, "provider.json");
30358
30885
  try {
30359
30886
  const raw = fs6.readFileSync(jsonPath, "utf-8");
30360
30887
  const mod = JSON.parse(raw);
@@ -30367,7 +30894,7 @@ var init_provider_loader = __esm({
30367
30894
  delete mod.extensionIdPattern_flags;
30368
30895
  }
30369
30896
  const hasCompatibility = Array.isArray(mod.compatibility);
30370
- const scriptsPath = path10.join(d, "scripts.js");
30897
+ const scriptsPath = path11.join(d, "scripts.js");
30371
30898
  if (!hasCompatibility && fs6.existsSync(scriptsPath)) {
30372
30899
  try {
30373
30900
  delete require.cache[require.resolve(scriptsPath)];
@@ -30393,7 +30920,7 @@ var init_provider_loader = __esm({
30393
30920
  if (!entry.isDirectory()) continue;
30394
30921
  if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
30395
30922
  if (excludeDirs && d === dir && excludeDirs.includes(entry.name)) continue;
30396
- scan(path10.join(d, entry.name));
30923
+ scan(path11.join(d, entry.name));
30397
30924
  }
30398
30925
  }
30399
30926
  };
@@ -30652,8 +31179,8 @@ function detectCurrentWorkspace(ideId) {
30652
31179
  const appNameMap = getMacAppIdentifiers();
30653
31180
  const appName = appNameMap[ideId];
30654
31181
  if (appName) {
30655
- const storagePath = path11.join(
30656
- process.env.APPDATA || path11.join(os13.homedir(), "AppData", "Roaming"),
31182
+ const storagePath = path12.join(
31183
+ process.env.APPDATA || path12.join(os13.homedir(), "AppData", "Roaming"),
30657
31184
  appName,
30658
31185
  "storage.json"
30659
31186
  );
@@ -30824,14 +31351,14 @@ async function launchLinux(ide, port, workspace, newWindow) {
30824
31351
  function getAvailableIdeIds() {
30825
31352
  return getProviderLoader().getAvailableIdeTypes();
30826
31353
  }
30827
- var import_child_process6, net2, os13, path11, _providerLoader;
31354
+ var import_child_process6, net2, os13, path12, _providerLoader;
30828
31355
  var init_launch = __esm({
30829
31356
  "../../oss/packages/daemon-core/src/launch.ts"() {
30830
31357
  "use strict";
30831
31358
  import_child_process6 = require("child_process");
30832
31359
  net2 = __toESM(require("net"));
30833
31360
  os13 = __toESM(require("os"));
30834
- path11 = __toESM(require("path"));
31361
+ path12 = __toESM(require("path"));
30835
31362
  init_ide_detector();
30836
31363
  init_provider_loader();
30837
31364
  _providerLoader = null;
@@ -30862,7 +31389,7 @@ function checkRotation() {
30862
31389
  const today = getDateStr2();
30863
31390
  if (today !== currentDate2) {
30864
31391
  currentDate2 = today;
30865
- currentFile = path12.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
31392
+ currentFile = path13.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
30866
31393
  cleanOldFiles();
30867
31394
  }
30868
31395
  }
@@ -30876,7 +31403,7 @@ function cleanOldFiles() {
30876
31403
  const dateMatch = file2.match(/commands-(\d{4}-\d{2}-\d{2})/);
30877
31404
  if (dateMatch && dateMatch[1] < cutoffStr) {
30878
31405
  try {
30879
- fs7.unlinkSync(path12.join(LOG_DIR2, file2));
31406
+ fs7.unlinkSync(path13.join(LOG_DIR2, file2));
30880
31407
  } catch {
30881
31408
  }
30882
31409
  }
@@ -30943,14 +31470,14 @@ function getRecentCommands(count = 50) {
30943
31470
  return [];
30944
31471
  }
30945
31472
  }
30946
- var fs7, path12, os14, LOG_DIR2, MAX_FILE_SIZE, MAX_DAYS, SENSITIVE_KEYS, currentDate2, currentFile, writeCount2, SKIP_COMMANDS;
31473
+ var fs7, path13, os14, LOG_DIR2, MAX_FILE_SIZE, MAX_DAYS, SENSITIVE_KEYS, currentDate2, currentFile, writeCount2, SKIP_COMMANDS;
30947
31474
  var init_command_log = __esm({
30948
31475
  "../../oss/packages/daemon-core/src/logging/command-log.ts"() {
30949
31476
  "use strict";
30950
31477
  fs7 = __toESM(require("fs"));
30951
- path12 = __toESM(require("path"));
31478
+ path13 = __toESM(require("path"));
30952
31479
  os14 = __toESM(require("os"));
30953
- LOG_DIR2 = process.platform === "win32" ? path12.join(process.env.LOCALAPPDATA || process.env.APPDATA || path12.join(os14.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path12.join(os14.homedir(), "Library", "Logs", "adhdev") : path12.join(os14.homedir(), ".local", "share", "adhdev", "logs");
31480
+ LOG_DIR2 = process.platform === "win32" ? path13.join(process.env.LOCALAPPDATA || process.env.APPDATA || path13.join(os14.homedir(), "AppData", "Local"), "adhdev", "logs") : process.platform === "darwin" ? path13.join(os14.homedir(), "Library", "Logs", "adhdev") : path13.join(os14.homedir(), ".local", "share", "adhdev", "logs");
30954
31481
  MAX_FILE_SIZE = 5 * 1024 * 1024;
30955
31482
  MAX_DAYS = 7;
30956
31483
  try {
@@ -30969,7 +31496,7 @@ var init_command_log = __esm({
30969
31496
  "text"
30970
31497
  ]);
30971
31498
  currentDate2 = getDateStr2();
30972
- currentFile = path12.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
31499
+ currentFile = path13.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
30973
31500
  writeCount2 = 0;
30974
31501
  SKIP_COMMANDS = /* @__PURE__ */ new Set([
30975
31502
  "heartbeat",
@@ -31009,17 +31536,17 @@ function parseMessageTime(value) {
31009
31536
  function getSessionMessageUpdatedAt(session) {
31010
31537
  const lastMessage = session.activeChat?.messages?.at?.(-1);
31011
31538
  if (!lastMessage) return 0;
31012
- return parseMessageTime(lastMessage.timestamp) || parseMessageTime(lastMessage.receivedAt) || parseMessageTime(lastMessage.createdAt) || 0;
31539
+ return parseMessageTime(lastMessage.receivedAt) || 0;
31013
31540
  }
31014
31541
  function getSessionCompletionMarker(session) {
31015
31542
  const lastMessage = session.activeChat?.messages?.at?.(-1);
31016
31543
  if (!lastMessage) return "";
31017
31544
  const role = typeof lastMessage.role === "string" ? lastMessage.role : "";
31018
- if (role === "user" || role === "human") return "";
31545
+ if (role === "user" || role === "human" || role === "system") return "";
31019
31546
  if (typeof lastMessage._turnKey === "string" && lastMessage._turnKey) return `turn:${lastMessage._turnKey}`;
31020
31547
  if (typeof lastMessage.id === "string" && lastMessage.id) return `id:${lastMessage.id}`;
31021
31548
  if (typeof lastMessage.index === "number" && Number.isFinite(lastMessage.index)) return `idx:${lastMessage.index}`;
31022
- const timestamp = parseMessageTime(lastMessage.timestamp) || parseMessageTime(lastMessage.receivedAt) || parseMessageTime(lastMessage.createdAt);
31549
+ const timestamp = parseMessageTime(lastMessage.receivedAt);
31023
31550
  return timestamp > 0 ? `ts:${timestamp}` : "";
31024
31551
  }
31025
31552
  function getSessionLastUsedAt(session) {
@@ -31036,7 +31563,7 @@ function getUnreadState(hasContentChange, status, lastUsedAt, lastSeenAt, lastRo
31036
31563
  if (status === "generating" || status === "starting") {
31037
31564
  return { unread: false, inboxBucket: "working" };
31038
31565
  }
31039
- const unread = completionMarker ? completionMarker !== seenCompletionMarker : hasContentChange && lastUsedAt > lastSeenAt && lastRole !== "user" && lastRole !== "human";
31566
+ const unread = completionMarker ? completionMarker !== seenCompletionMarker : hasContentChange && lastUsedAt > lastSeenAt && lastRole !== "user" && lastRole !== "human" && lastRole !== "system";
31040
31567
  return { unread, inboxBucket: unread ? "task_complete" : "idle" };
31041
31568
  }
31042
31569
  function buildRecentLaunches(recentActivity) {
@@ -31137,9 +31664,9 @@ var init_snapshot = __esm({
31137
31664
  // ../../oss/packages/daemon-core/src/commands/upgrade-helper.ts
31138
31665
  function getUpgradeLogPath() {
31139
31666
  const home = os16.homedir();
31140
- const dir = path13.join(home, ".adhdev");
31667
+ const dir = path14.join(home, ".adhdev");
31141
31668
  fs8.mkdirSync(dir, { recursive: true });
31142
- return path13.join(dir, "daemon-upgrade.log");
31669
+ return path14.join(dir, "daemon-upgrade.log");
31143
31670
  }
31144
31671
  function appendUpgradeLog(message) {
31145
31672
  const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
@@ -31179,7 +31706,7 @@ async function waitForPidExit(pid, timeoutMs) {
31179
31706
  }
31180
31707
  }
31181
31708
  function stopSessionHostProcesses(appName) {
31182
- const pidFile = path13.join(os16.homedir(), ".adhdev", `${appName}-session-host.pid`);
31709
+ const pidFile = path14.join(os16.homedir(), ".adhdev", `${appName}-session-host.pid`);
31183
31710
  try {
31184
31711
  if (fs8.existsSync(pidFile)) {
31185
31712
  const pid = Number.parseInt(fs8.readFileSync(pidFile, "utf8").trim(), 10);
@@ -31208,7 +31735,7 @@ function stopSessionHostProcesses(appName) {
31208
31735
  }
31209
31736
  }
31210
31737
  function removeDaemonPidFile() {
31211
- const pidFile = path13.join(os16.homedir(), ".adhdev", "daemon.pid");
31738
+ const pidFile = path14.join(os16.homedir(), ".adhdev", "daemon.pid");
31212
31739
  try {
31213
31740
  fs8.unlinkSync(pidFile);
31214
31741
  } catch {
@@ -31219,7 +31746,7 @@ function cleanupStaleGlobalInstallDirs(pkgName) {
31219
31746
  const npmRoot = (0, import_child_process7.execFileSync)(getNpmExecutable(), ["root", "-g"], { encoding: "utf8", ...npmExecOpts }).trim();
31220
31747
  if (!npmRoot) return;
31221
31748
  const npmPrefix = (0, import_child_process7.execFileSync)(getNpmExecutable(), ["prefix", "-g"], { encoding: "utf8", ...npmExecOpts }).trim();
31222
- const binDir = process.platform === "win32" ? npmPrefix : path13.join(npmPrefix, "bin");
31749
+ const binDir = process.platform === "win32" ? npmPrefix : path14.join(npmPrefix, "bin");
31223
31750
  const packageBaseName = pkgName.startsWith("@") ? pkgName.split("/")[1] : pkgName;
31224
31751
  const binNames = /* @__PURE__ */ new Set([packageBaseName]);
31225
31752
  if (pkgName === "@adhdev/daemon-standalone") {
@@ -31227,25 +31754,25 @@ function cleanupStaleGlobalInstallDirs(pkgName) {
31227
31754
  }
31228
31755
  if (pkgName.startsWith("@")) {
31229
31756
  const [scope, name] = pkgName.split("/");
31230
- const scopeDir = path13.join(npmRoot, scope);
31757
+ const scopeDir = path14.join(npmRoot, scope);
31231
31758
  if (!fs8.existsSync(scopeDir)) return;
31232
31759
  for (const entry of fs8.readdirSync(scopeDir)) {
31233
31760
  if (!entry.startsWith(`.${name}-`)) continue;
31234
- fs8.rmSync(path13.join(scopeDir, entry), { recursive: true, force: true });
31235
- appendUpgradeLog(`Removed stale scoped staging dir: ${path13.join(scopeDir, entry)}`);
31761
+ fs8.rmSync(path14.join(scopeDir, entry), { recursive: true, force: true });
31762
+ appendUpgradeLog(`Removed stale scoped staging dir: ${path14.join(scopeDir, entry)}`);
31236
31763
  }
31237
31764
  } else {
31238
31765
  for (const entry of fs8.readdirSync(npmRoot)) {
31239
31766
  if (!entry.startsWith(`.${pkgName}-`)) continue;
31240
- fs8.rmSync(path13.join(npmRoot, entry), { recursive: true, force: true });
31241
- appendUpgradeLog(`Removed stale staging dir: ${path13.join(npmRoot, entry)}`);
31767
+ fs8.rmSync(path14.join(npmRoot, entry), { recursive: true, force: true });
31768
+ appendUpgradeLog(`Removed stale staging dir: ${path14.join(npmRoot, entry)}`);
31242
31769
  }
31243
31770
  }
31244
31771
  if (fs8.existsSync(binDir)) {
31245
31772
  for (const entry of fs8.readdirSync(binDir)) {
31246
31773
  if (![...binNames].some((name) => entry.startsWith(`.${name}-`))) continue;
31247
- fs8.rmSync(path13.join(binDir, entry), { recursive: true, force: true });
31248
- appendUpgradeLog(`Removed stale bin staging entry: ${path13.join(binDir, entry)}`);
31774
+ fs8.rmSync(path14.join(binDir, entry), { recursive: true, force: true });
31775
+ appendUpgradeLog(`Removed stale bin staging entry: ${path14.join(binDir, entry)}`);
31249
31776
  }
31250
31777
  }
31251
31778
  }
@@ -31320,7 +31847,7 @@ async function maybeRunDaemonUpgradeHelperFromEnv() {
31320
31847
  process.exit(1);
31321
31848
  }
31322
31849
  }
31323
- var import_child_process7, import_child_process8, fs8, os16, path13, UPGRADE_HELPER_ENV;
31850
+ var import_child_process7, import_child_process8, fs8, os16, path14, UPGRADE_HELPER_ENV;
31324
31851
  var init_upgrade_helper = __esm({
31325
31852
  "../../oss/packages/daemon-core/src/commands/upgrade-helper.ts"() {
31326
31853
  "use strict";
@@ -31328,12 +31855,31 @@ var init_upgrade_helper = __esm({
31328
31855
  import_child_process8 = require("child_process");
31329
31856
  fs8 = __toESM(require("fs"));
31330
31857
  os16 = __toESM(require("os"));
31331
- path13 = __toESM(require("path"));
31858
+ path14 = __toESM(require("path"));
31332
31859
  UPGRADE_HELPER_ENV = "ADHDEV_DAEMON_UPGRADE_HELPER";
31333
31860
  }
31334
31861
  });
31335
31862
 
31336
31863
  // ../../oss/packages/daemon-core/src/commands/router.ts
31864
+ function toHostedCliRuntimeDescriptor(record2) {
31865
+ if (!record2 || typeof record2 !== "object") return null;
31866
+ const runtimeId = typeof record2.sessionId === "string" ? record2.sessionId : "";
31867
+ const cliType = typeof record2.providerType === "string" ? record2.providerType : "";
31868
+ const workspace = typeof record2.workspace === "string" ? record2.workspace : "";
31869
+ if (!runtimeId || !cliType || !workspace) return null;
31870
+ return {
31871
+ runtimeId,
31872
+ runtimeKey: typeof record2.runtimeKey === "string" ? record2.runtimeKey : void 0,
31873
+ displayName: typeof record2.displayName === "string" ? record2.displayName : void 0,
31874
+ workspaceLabel: typeof record2.workspaceLabel === "string" ? record2.workspaceLabel : void 0,
31875
+ lifecycle: typeof record2.lifecycle === "string" ? record2.lifecycle : void 0,
31876
+ recoveryState: typeof record2.meta?.runtimeRecoveryState === "string" ? String(record2.meta.runtimeRecoveryState) : null,
31877
+ cliType,
31878
+ workspace,
31879
+ cliArgs: Array.isArray(record2.meta?.cliArgs) ? record2.meta.cliArgs : [],
31880
+ providerSessionId: typeof record2.meta?.providerSessionId === "string" ? String(record2.meta.providerSessionId) : void 0
31881
+ };
31882
+ }
31337
31883
  var fs9, CHAT_COMMANDS, READ_DEBUG_ENABLED2, DaemonCommandRouter;
31338
31884
  var init_router = __esm({
31339
31885
  "../../oss/packages/daemon-core/src/commands/router.ts"() {
@@ -31437,6 +31983,90 @@ var init_router = __esm({
31437
31983
  return { success: false, error: e.message };
31438
31984
  }
31439
31985
  }
31986
+ case "session_host_get_diagnostics": {
31987
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
31988
+ const diagnostics = await this.deps.sessionHostControl.getDiagnostics({
31989
+ includeSessions: args?.includeSessions !== false,
31990
+ limit: Number(args?.limit) || void 0
31991
+ });
31992
+ return { success: true, diagnostics };
31993
+ }
31994
+ case "session_host_list_sessions": {
31995
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
31996
+ const sessions = await this.deps.sessionHostControl.listSessions();
31997
+ return { success: true, sessions };
31998
+ }
31999
+ case "session_host_stop_session": {
32000
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
32001
+ const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
32002
+ if (!sessionId) return { success: false, error: "sessionId required" };
32003
+ const record2 = await this.deps.sessionHostControl.stopSession(sessionId);
32004
+ return { success: true, record: record2 };
32005
+ }
32006
+ case "session_host_resume_session": {
32007
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
32008
+ const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
32009
+ if (!sessionId) return { success: false, error: "sessionId required" };
32010
+ const record2 = await this.deps.sessionHostControl.resumeSession(sessionId);
32011
+ const hosted = toHostedCliRuntimeDescriptor(record2);
32012
+ if (hosted) {
32013
+ await this.deps.cliManager.restoreHostedSessions([hosted]);
32014
+ }
32015
+ return { success: true, record: record2 };
32016
+ }
32017
+ case "session_host_restart_session": {
32018
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
32019
+ const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
32020
+ if (!sessionId) return { success: false, error: "sessionId required" };
32021
+ const record2 = await this.deps.sessionHostControl.restartSession(sessionId);
32022
+ const hosted = toHostedCliRuntimeDescriptor(record2);
32023
+ if (hosted) {
32024
+ await this.deps.cliManager.restoreHostedSessions([hosted]);
32025
+ }
32026
+ return { success: true, record: record2 };
32027
+ }
32028
+ case "session_host_send_signal": {
32029
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
32030
+ const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
32031
+ const signal = typeof args?.signal === "string" ? args.signal : "";
32032
+ if (!sessionId) return { success: false, error: "sessionId required" };
32033
+ if (!signal) return { success: false, error: "signal required" };
32034
+ const record2 = await this.deps.sessionHostControl.sendSignal(sessionId, signal);
32035
+ return { success: true, record: record2 };
32036
+ }
32037
+ case "session_host_force_detach_client": {
32038
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
32039
+ const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
32040
+ const clientId = typeof args?.clientId === "string" ? args.clientId : "";
32041
+ if (!sessionId) return { success: false, error: "sessionId required" };
32042
+ if (!clientId) return { success: false, error: "clientId required" };
32043
+ const record2 = await this.deps.sessionHostControl.forceDetachClient(sessionId, clientId);
32044
+ return { success: true, record: record2 };
32045
+ }
32046
+ case "session_host_acquire_write": {
32047
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
32048
+ const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
32049
+ const clientId = typeof args?.clientId === "string" ? args.clientId : "";
32050
+ const ownerType = args?.ownerType === "agent" ? "agent" : "user";
32051
+ if (!sessionId) return { success: false, error: "sessionId required" };
32052
+ if (!clientId) return { success: false, error: "clientId required" };
32053
+ const record2 = await this.deps.sessionHostControl.acquireWrite({
32054
+ sessionId,
32055
+ clientId,
32056
+ ownerType,
32057
+ force: args?.force !== false
32058
+ });
32059
+ return { success: true, record: record2 };
32060
+ }
32061
+ case "session_host_release_write": {
32062
+ if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
32063
+ const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
32064
+ const clientId = typeof args?.clientId === "string" ? args.clientId : "";
32065
+ if (!sessionId) return { success: false, error: "sessionId required" };
32066
+ if (!clientId) return { success: false, error: "clientId required" };
32067
+ const record2 = await this.deps.sessionHostControl.releaseWrite({ sessionId, clientId });
32068
+ return { success: true, record: record2 };
32069
+ }
31440
32070
  case "list_saved_sessions": {
31441
32071
  const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : typeof args?.agentType === "string" ? args.agentType.trim() : "";
31442
32072
  const kind = args?.kind === "acp" ? "acp" : "cli";
@@ -31983,6 +32613,14 @@ var init_provider_adapter = __esm({
31983
32613
  hasScript(name) {
31984
32614
  return typeof this.provider.scripts?.[name] === "function";
31985
32615
  }
32616
+ parseMaybeJson(raw) {
32617
+ if (typeof raw !== "string") return raw;
32618
+ try {
32619
+ return JSON.parse(raw);
32620
+ } catch {
32621
+ return raw;
32622
+ }
32623
+ }
31986
32624
  summarizeRaw(raw) {
31987
32625
  try {
31988
32626
  if (typeof raw === "string") return raw.replace(/\s+/g, " ").trim().slice(0, 240);
@@ -32043,12 +32681,30 @@ var init_provider_adapter = __esm({
32043
32681
  }
32044
32682
  }
32045
32683
  async sendMessage(evaluate, text) {
32046
- const script = this.callScript("sendMessage", text);
32684
+ const params = { message: text };
32685
+ const script = this.callScript("sendMessage", params) || this.callScript("sendMessage", text);
32047
32686
  if (!script) throw new Error(`[${this.agentName}] sendMessage script not available`);
32048
32687
  const result = await evaluate(script);
32049
32688
  if (result && typeof result === "string" && result.startsWith("error:")) {
32050
32689
  throw new Error(`[${this.agentName}] sendMessage failed: ${result}`);
32051
32690
  }
32691
+ const parsed = this.parseMaybeJson(result);
32692
+ if (parsed === true) return;
32693
+ if (typeof parsed === "string") {
32694
+ const normalized = parsed.trim().toLowerCase();
32695
+ if (normalized === "ok" || normalized === "sent" || normalized === "success" || normalized === "true") {
32696
+ return;
32697
+ }
32698
+ }
32699
+ if (parsed && typeof parsed === "object") {
32700
+ if (parsed.sent === true || parsed.success === true || parsed.ok === true || parsed.submitted === true || parsed.dispatched === true) {
32701
+ return;
32702
+ }
32703
+ if (typeof parsed.error === "string" && parsed.error.trim()) {
32704
+ throw new Error(`[${this.agentName}] sendMessage failed: ${parsed.error}`);
32705
+ }
32706
+ }
32707
+ throw new Error(`[${this.agentName}] sendMessage was not confirmed`);
32052
32708
  }
32053
32709
  async resolveAction(evaluate, action, button) {
32054
32710
  const script = this.callScript("resolveAction", { action, button });
@@ -32415,6 +33071,7 @@ var init_poller = __esm({
32415
33071
  "../../oss/packages/daemon-core/src/agent-stream/poller.ts"() {
32416
33072
  "use strict";
32417
33073
  init_setup();
33074
+ init_reconcile();
32418
33075
  init_logger();
32419
33076
  AgentStreamPoller = class {
32420
33077
  deps;
@@ -32454,6 +33111,7 @@ var init_poller = __esm({
32454
33111
  sessionRegistry
32455
33112
  } = this.deps;
32456
33113
  if (!agentStreamManager || cdpManagers.size === 0) return;
33114
+ reconcileIdeRuntimeSessions(instanceManager, sessionRegistry);
32457
33115
  for (const [ideType, cdp] of cdpManagers) {
32458
33116
  registerExtensionProviders(providerLoader, cdp, ideType);
32459
33117
  const ideInstance = instanceManager.getInstance(`ide:${ideType}`);
@@ -32847,7 +33505,7 @@ function checkPathExists2(paths) {
32847
33505
  for (const p of paths) {
32848
33506
  if (p.includes("*")) {
32849
33507
  const home = os17.homedir();
32850
- const resolved = p.replace(/\*/g, home.split(path14.sep).pop() || "");
33508
+ const resolved = p.replace(/\*/g, home.split(path15.sep).pop() || "");
32851
33509
  if (fs10.existsSync(resolved)) return resolved;
32852
33510
  } else {
32853
33511
  if (fs10.existsSync(p)) return p;
@@ -32857,7 +33515,7 @@ function checkPathExists2(paths) {
32857
33515
  }
32858
33516
  function getMacAppVersion(appPath) {
32859
33517
  if ((0, import_os3.platform)() !== "darwin" || !appPath.endsWith(".app")) return null;
32860
- const plistPath = path14.join(appPath, "Contents", "Info.plist");
33518
+ const plistPath = path15.join(appPath, "Contents", "Info.plist");
32861
33519
  if (!fs10.existsSync(plistPath)) return null;
32862
33520
  const raw = runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
32863
33521
  return raw || null;
@@ -32884,7 +33542,7 @@ async function detectAllVersions(loader, archive) {
32884
33542
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
32885
33543
  let resolvedBin = cliBin;
32886
33544
  if (!resolvedBin && appPath && currentOs === "darwin") {
32887
- const bundled = path14.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
33545
+ const bundled = path15.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
32888
33546
  if (provider.cli && fs10.existsSync(bundled)) resolvedBin = bundled;
32889
33547
  }
32890
33548
  info.installed = !!(appPath || resolvedBin);
@@ -32921,16 +33579,16 @@ async function detectAllVersions(loader, archive) {
32921
33579
  }
32922
33580
  return results;
32923
33581
  }
32924
- var fs10, path14, os17, import_child_process9, import_os3, ARCHIVE_PATH, MAX_ENTRIES_PER_PROVIDER, VersionArchive;
33582
+ var fs10, path15, os17, import_child_process9, import_os3, ARCHIVE_PATH, MAX_ENTRIES_PER_PROVIDER, VersionArchive;
32925
33583
  var init_version_archive = __esm({
32926
33584
  "../../oss/packages/daemon-core/src/providers/version-archive.ts"() {
32927
33585
  "use strict";
32928
33586
  fs10 = __toESM(require("fs"));
32929
- path14 = __toESM(require("path"));
33587
+ path15 = __toESM(require("path"));
32930
33588
  os17 = __toESM(require("os"));
32931
33589
  import_child_process9 = require("child_process");
32932
33590
  import_os3 = require("os");
32933
- ARCHIVE_PATH = path14.join(os17.homedir(), ".adhdev", "version-history.json");
33591
+ ARCHIVE_PATH = path15.join(os17.homedir(), ".adhdev", "version-history.json");
32934
33592
  MAX_ENTRIES_PER_PROVIDER = 20;
32935
33593
  VersionArchive = class {
32936
33594
  history = {};
@@ -32977,7 +33635,7 @@ var init_version_archive = __esm({
32977
33635
  }
32978
33636
  save() {
32979
33637
  try {
32980
- fs10.mkdirSync(path14.dirname(ARCHIVE_PATH), { recursive: true });
33638
+ fs10.mkdirSync(path15.dirname(ARCHIVE_PATH), { recursive: true });
32981
33639
  fs10.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
32982
33640
  } catch {
32983
33641
  }
@@ -33498,17 +34156,17 @@ async function handleScriptHints(ctx, type, _req, res) {
33498
34156
  return;
33499
34157
  }
33500
34158
  let scriptsPath = "";
33501
- const directScripts = path15.join(dir, "scripts.js");
34159
+ const directScripts = path16.join(dir, "scripts.js");
33502
34160
  if (fs11.existsSync(directScripts)) {
33503
34161
  scriptsPath = directScripts;
33504
34162
  } else {
33505
- const scriptsDir = path15.join(dir, "scripts");
34163
+ const scriptsDir = path16.join(dir, "scripts");
33506
34164
  if (fs11.existsSync(scriptsDir)) {
33507
34165
  const versions = fs11.readdirSync(scriptsDir).filter((d) => {
33508
- return fs11.statSync(path15.join(scriptsDir, d)).isDirectory();
34166
+ return fs11.statSync(path16.join(scriptsDir, d)).isDirectory();
33509
34167
  }).sort().reverse();
33510
34168
  for (const ver of versions) {
33511
- const p = path15.join(scriptsDir, ver, "scripts.js");
34169
+ const p = path16.join(scriptsDir, ver, "scripts.js");
33512
34170
  if (fs11.existsSync(p)) {
33513
34171
  scriptsPath = p;
33514
34172
  break;
@@ -34324,12 +34982,12 @@ async function handleDomContext(ctx, type, req, res) {
34324
34982
  ctx.json(res, 500, { error: `DOM context collection failed: ${e.message}` });
34325
34983
  }
34326
34984
  }
34327
- var fs11, path15;
34985
+ var fs11, path16;
34328
34986
  var init_dev_cdp_handlers = __esm({
34329
34987
  "../../oss/packages/daemon-core/src/daemon/dev-cdp-handlers.ts"() {
34330
34988
  "use strict";
34331
34989
  fs11 = __toESM(require("fs"));
34332
- path15 = __toESM(require("path"));
34990
+ path16 = __toESM(require("path"));
34333
34991
  init_logger();
34334
34992
  }
34335
34993
  });
@@ -34344,11 +35002,11 @@ function getCliFixtureDir(ctx, type) {
34344
35002
  if (!providerDir) {
34345
35003
  throw new Error(`Provider directory not found for '${type}'`);
34346
35004
  }
34347
- return path16.join(providerDir, "fixtures");
35005
+ return path17.join(providerDir, "fixtures");
34348
35006
  }
34349
35007
  function readCliFixture(ctx, type, name) {
34350
35008
  const fixtureDir = getCliFixtureDir(ctx, type);
34351
- const filePath = path16.join(fixtureDir, `${name}.json`);
35009
+ const filePath = path17.join(fixtureDir, `${name}.json`);
34352
35010
  if (!fs12.existsSync(filePath)) {
34353
35011
  throw new Error(`Fixture not found: ${filePath}`);
34354
35012
  }
@@ -35107,7 +35765,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
35107
35765
  },
35108
35766
  notes: typeof body?.notes === "string" ? body.notes : void 0
35109
35767
  };
35110
- const filePath = path16.join(fixtureDir, `${name}.json`);
35768
+ const filePath = path17.join(fixtureDir, `${name}.json`);
35111
35769
  fs12.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
35112
35770
  ctx.json(res, 200, {
35113
35771
  saved: true,
@@ -35131,7 +35789,7 @@ async function handleCliFixtureList(ctx, type, _req, res) {
35131
35789
  return;
35132
35790
  }
35133
35791
  const fixtures = fs12.readdirSync(fixtureDir).filter((file2) => file2.endsWith(".json")).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" })).map((file2) => {
35134
- const fullPath = path16.join(fixtureDir, file2);
35792
+ const fullPath = path17.join(fixtureDir, file2);
35135
35793
  try {
35136
35794
  const raw = JSON.parse(fs12.readFileSync(fullPath, "utf-8"));
35137
35795
  return {
@@ -35264,12 +35922,12 @@ async function handleCliRaw(ctx, req, res) {
35264
35922
  ctx.json(res, 500, { error: `Raw send failed: ${e.message}` });
35265
35923
  }
35266
35924
  }
35267
- var fs12, path16;
35925
+ var fs12, path17;
35268
35926
  var init_dev_cli_debug = __esm({
35269
35927
  "../../oss/packages/daemon-core/src/daemon/dev-cli-debug.ts"() {
35270
35928
  "use strict";
35271
35929
  fs12 = __toESM(require("fs"));
35272
- path16 = __toESM(require("path"));
35930
+ path17 = __toESM(require("path"));
35273
35931
  }
35274
35932
  });
35275
35933
 
@@ -35312,22 +35970,22 @@ function getLatestScriptVersionDir(scriptsDir) {
35312
35970
  if (!fs13.existsSync(scriptsDir)) return null;
35313
35971
  const versions = fs13.readdirSync(scriptsDir).filter((d) => {
35314
35972
  try {
35315
- return fs13.statSync(path17.join(scriptsDir, d)).isDirectory();
35973
+ return fs13.statSync(path18.join(scriptsDir, d)).isDirectory();
35316
35974
  } catch {
35317
35975
  return false;
35318
35976
  }
35319
35977
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
35320
35978
  if (versions.length === 0) return null;
35321
- return path17.join(scriptsDir, versions[0]);
35979
+ return path18.join(scriptsDir, versions[0]);
35322
35980
  }
35323
35981
  function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
35324
- const canonicalUserDir = path17.resolve(ctx.providerLoader.getUserProviderDir(category, type));
35325
- const desiredDir = requestedDir ? path17.resolve(requestedDir) : canonicalUserDir;
35326
- const upstreamRoot = path17.resolve(ctx.providerLoader.getUpstreamDir());
35327
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path17.sep}`)) {
35982
+ const canonicalUserDir = path18.resolve(ctx.providerLoader.getUserProviderDir(category, type));
35983
+ const desiredDir = requestedDir ? path18.resolve(requestedDir) : canonicalUserDir;
35984
+ const upstreamRoot = path18.resolve(ctx.providerLoader.getUpstreamDir());
35985
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path18.sep}`)) {
35328
35986
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
35329
35987
  }
35330
- if (path17.basename(desiredDir) !== type) {
35988
+ if (path18.basename(desiredDir) !== type) {
35331
35989
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
35332
35990
  }
35333
35991
  const sourceDir = ctx.findProviderDir(type);
@@ -35335,11 +35993,11 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
35335
35993
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
35336
35994
  }
35337
35995
  if (!fs13.existsSync(desiredDir)) {
35338
- fs13.mkdirSync(path17.dirname(desiredDir), { recursive: true });
35996
+ fs13.mkdirSync(path18.dirname(desiredDir), { recursive: true });
35339
35997
  fs13.cpSync(sourceDir, desiredDir, { recursive: true });
35340
35998
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
35341
35999
  }
35342
- const providerJson = path17.join(desiredDir, "provider.json");
36000
+ const providerJson = path18.join(desiredDir, "provider.json");
35343
36001
  if (!fs13.existsSync(providerJson)) {
35344
36002
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
35345
36003
  }
@@ -35362,13 +36020,13 @@ function loadAutoImplReferenceScripts(ctx, referenceType) {
35362
36020
  const refDir = ctx.findProviderDir(referenceType);
35363
36021
  if (!refDir || !fs13.existsSync(refDir)) return {};
35364
36022
  const referenceScripts = {};
35365
- const scriptsDir = path17.join(refDir, "scripts");
36023
+ const scriptsDir = path18.join(refDir, "scripts");
35366
36024
  const latestDir = getLatestScriptVersionDir(scriptsDir);
35367
36025
  if (!latestDir) return referenceScripts;
35368
36026
  for (const file2 of fs13.readdirSync(latestDir)) {
35369
36027
  if (!file2.endsWith(".js")) continue;
35370
36028
  try {
35371
- referenceScripts[file2] = fs13.readFileSync(path17.join(latestDir, file2), "utf-8");
36029
+ referenceScripts[file2] = fs13.readFileSync(path18.join(latestDir, file2), "utf-8");
35372
36030
  } catch {
35373
36031
  }
35374
36032
  }
@@ -35476,9 +36134,9 @@ async function handleAutoImplement(ctx, type, req, res) {
35476
36134
  });
35477
36135
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
35478
36136
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
35479
- const tmpDir = path17.join(os18.tmpdir(), "adhdev-autoimpl");
36137
+ const tmpDir = path18.join(os18.tmpdir(), "adhdev-autoimpl");
35480
36138
  if (!fs13.existsSync(tmpDir)) fs13.mkdirSync(tmpDir, { recursive: true });
35481
- const promptFile = path17.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
36139
+ const promptFile = path18.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
35482
36140
  fs13.writeFileSync(promptFile, prompt, "utf-8");
35483
36141
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
35484
36142
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
@@ -35905,7 +36563,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
35905
36563
  setMode: "set_mode.js"
35906
36564
  };
35907
36565
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
35908
- const scriptsDir = path17.join(providerDir, "scripts");
36566
+ const scriptsDir = path18.join(providerDir, "scripts");
35909
36567
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
35910
36568
  if (latestScriptsDir) {
35911
36569
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -35916,7 +36574,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
35916
36574
  for (const file2 of fs13.readdirSync(latestScriptsDir)) {
35917
36575
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
35918
36576
  try {
35919
- const content = fs13.readFileSync(path17.join(latestScriptsDir, file2), "utf-8");
36577
+ const content = fs13.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
35920
36578
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
35921
36579
  lines.push("```javascript");
35922
36580
  lines.push(content);
@@ -35933,7 +36591,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
35933
36591
  lines.push("");
35934
36592
  for (const file2 of refFiles) {
35935
36593
  try {
35936
- const content = fs13.readFileSync(path17.join(latestScriptsDir, file2), "utf-8");
36594
+ const content = fs13.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
35937
36595
  lines.push(`### \`${file2}\` \u{1F512}`);
35938
36596
  lines.push("```javascript");
35939
36597
  lines.push(content);
@@ -35974,10 +36632,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
35974
36632
  lines.push("");
35975
36633
  }
35976
36634
  }
35977
- const docsDir = path17.join(providerDir, "../../docs");
36635
+ const docsDir = path18.join(providerDir, "../../docs");
35978
36636
  const loadGuide = (name) => {
35979
36637
  try {
35980
- const p = path17.join(docsDir, name);
36638
+ const p = path18.join(docsDir, name);
35981
36639
  if (fs13.existsSync(p)) return fs13.readFileSync(p, "utf-8");
35982
36640
  } catch {
35983
36641
  }
@@ -36212,7 +36870,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
36212
36870
  parseApproval: "parse_approval.js"
36213
36871
  };
36214
36872
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
36215
- const scriptsDir = path17.join(providerDir, "scripts");
36873
+ const scriptsDir = path18.join(providerDir, "scripts");
36216
36874
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
36217
36875
  if (latestScriptsDir) {
36218
36876
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -36224,7 +36882,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
36224
36882
  if (!file2.endsWith(".js")) continue;
36225
36883
  if (!targetFileNames.has(file2)) continue;
36226
36884
  try {
36227
- const content = fs13.readFileSync(path17.join(latestScriptsDir, file2), "utf-8");
36885
+ const content = fs13.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
36228
36886
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
36229
36887
  lines.push("```javascript");
36230
36888
  lines.push(content);
@@ -36240,7 +36898,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
36240
36898
  lines.push("");
36241
36899
  for (const file2 of refFiles) {
36242
36900
  try {
36243
- const content = fs13.readFileSync(path17.join(latestScriptsDir, file2), "utf-8");
36901
+ const content = fs13.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
36244
36902
  lines.push(`### \`${file2}\` \u{1F512}`);
36245
36903
  lines.push("```javascript");
36246
36904
  lines.push(content);
@@ -36273,10 +36931,10 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
36273
36931
  lines.push("");
36274
36932
  }
36275
36933
  }
36276
- const docsDir = path17.join(providerDir, "../../docs");
36934
+ const docsDir = path18.join(providerDir, "../../docs");
36277
36935
  const loadGuide = (name) => {
36278
36936
  try {
36279
- const p = path17.join(docsDir, name);
36937
+ const p = path18.join(docsDir, name);
36280
36938
  if (fs13.existsSync(p)) return fs13.readFileSync(p, "utf-8");
36281
36939
  } catch {
36282
36940
  }
@@ -36588,12 +37246,12 @@ data: ${JSON.stringify(msg.data)}
36588
37246
  }
36589
37247
  }
36590
37248
  }
36591
- var fs13, path17, os18;
37249
+ var fs13, path18, os18;
36592
37250
  var init_dev_auto_implement = __esm({
36593
37251
  "../../oss/packages/daemon-core/src/daemon/dev-auto-implement.ts"() {
36594
37252
  "use strict";
36595
37253
  fs13 = __toESM(require("fs"));
36596
- path17 = __toESM(require("path"));
37254
+ path18 = __toESM(require("path"));
36597
37255
  os18 = __toESM(require("os"));
36598
37256
  init_dev_server();
36599
37257
  init_dev_cli_debug();
@@ -36601,13 +37259,13 @@ var init_dev_auto_implement = __esm({
36601
37259
  });
36602
37260
 
36603
37261
  // ../../oss/packages/daemon-core/src/daemon/dev-server.ts
36604
- var http2, fs14, path18, DEV_SERVER_PORT, DevServer;
37262
+ var http2, fs14, path19, DEV_SERVER_PORT, DevServer;
36605
37263
  var init_dev_server = __esm({
36606
37264
  "../../oss/packages/daemon-core/src/daemon/dev-server.ts"() {
36607
37265
  "use strict";
36608
37266
  http2 = __toESM(require("http"));
36609
37267
  fs14 = __toESM(require("fs"));
36610
- path18 = __toESM(require("path"));
37268
+ path19 = __toESM(require("path"));
36611
37269
  init_scaffold_template();
36612
37270
  init_version_archive();
36613
37271
  init_logger();
@@ -36711,8 +37369,8 @@ var init_dev_server = __esm({
36711
37369
  }
36712
37370
  getEndpointList() {
36713
37371
  return this.routes.map((r) => {
36714
- const path24 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
36715
- return `${r.method.padEnd(5)} ${path24}`;
37372
+ const path25 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
37373
+ return `${r.method.padEnd(5)} ${path25}`;
36716
37374
  });
36717
37375
  }
36718
37376
  async start(port = DEV_SERVER_PORT) {
@@ -36994,12 +37652,12 @@ var init_dev_server = __esm({
36994
37652
  // ─── DevConsole SPA ───
36995
37653
  getConsoleDistDir() {
36996
37654
  const candidates = [
36997
- path18.resolve(__dirname, "../../web-devconsole/dist"),
36998
- path18.resolve(__dirname, "../../../web-devconsole/dist"),
36999
- path18.join(process.cwd(), "packages/web-devconsole/dist")
37655
+ path19.resolve(__dirname, "../../web-devconsole/dist"),
37656
+ path19.resolve(__dirname, "../../../web-devconsole/dist"),
37657
+ path19.join(process.cwd(), "packages/web-devconsole/dist")
37000
37658
  ];
37001
37659
  for (const dir of candidates) {
37002
- if (fs14.existsSync(path18.join(dir, "index.html"))) return dir;
37660
+ if (fs14.existsSync(path19.join(dir, "index.html"))) return dir;
37003
37661
  }
37004
37662
  return null;
37005
37663
  }
@@ -37009,7 +37667,7 @@ var init_dev_server = __esm({
37009
37667
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
37010
37668
  return;
37011
37669
  }
37012
- const htmlPath = path18.join(distDir, "index.html");
37670
+ const htmlPath = path19.join(distDir, "index.html");
37013
37671
  try {
37014
37672
  const html = fs14.readFileSync(htmlPath, "utf-8");
37015
37673
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
@@ -37034,15 +37692,15 @@ var init_dev_server = __esm({
37034
37692
  this.json(res, 404, { error: "Not found" });
37035
37693
  return;
37036
37694
  }
37037
- const safePath = path18.normalize(pathname).replace(/^\.\.\//, "");
37038
- const filePath = path18.join(distDir, safePath);
37695
+ const safePath = path19.normalize(pathname).replace(/^\.\.\//, "");
37696
+ const filePath = path19.join(distDir, safePath);
37039
37697
  if (!filePath.startsWith(distDir)) {
37040
37698
  this.json(res, 403, { error: "Forbidden" });
37041
37699
  return;
37042
37700
  }
37043
37701
  try {
37044
37702
  const content = fs14.readFileSync(filePath);
37045
- const ext = path18.extname(filePath);
37703
+ const ext = path19.extname(filePath);
37046
37704
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
37047
37705
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
37048
37706
  res.end(content);
@@ -37155,9 +37813,9 @@ var init_dev_server = __esm({
37155
37813
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
37156
37814
  if (entry.isDirectory()) {
37157
37815
  files.push({ path: rel, size: 0, type: "dir" });
37158
- scan(path18.join(d, entry.name), rel);
37816
+ scan(path19.join(d, entry.name), rel);
37159
37817
  } else {
37160
- const stat4 = fs14.statSync(path18.join(d, entry.name));
37818
+ const stat4 = fs14.statSync(path19.join(d, entry.name));
37161
37819
  files.push({ path: rel, size: stat4.size, type: "file" });
37162
37820
  }
37163
37821
  }
@@ -37180,7 +37838,7 @@ var init_dev_server = __esm({
37180
37838
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
37181
37839
  return;
37182
37840
  }
37183
- const fullPath = path18.resolve(dir, path18.normalize(filePath));
37841
+ const fullPath = path19.resolve(dir, path19.normalize(filePath));
37184
37842
  if (!fullPath.startsWith(dir)) {
37185
37843
  this.json(res, 403, { error: "Forbidden" });
37186
37844
  return;
@@ -37205,14 +37863,14 @@ var init_dev_server = __esm({
37205
37863
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
37206
37864
  return;
37207
37865
  }
37208
- const fullPath = path18.resolve(dir, path18.normalize(filePath));
37866
+ const fullPath = path19.resolve(dir, path19.normalize(filePath));
37209
37867
  if (!fullPath.startsWith(dir)) {
37210
37868
  this.json(res, 403, { error: "Forbidden" });
37211
37869
  return;
37212
37870
  }
37213
37871
  try {
37214
37872
  if (fs14.existsSync(fullPath)) fs14.copyFileSync(fullPath, fullPath + ".bak");
37215
- fs14.mkdirSync(path18.dirname(fullPath), { recursive: true });
37873
+ fs14.mkdirSync(path19.dirname(fullPath), { recursive: true });
37216
37874
  fs14.writeFileSync(fullPath, content, "utf-8");
37217
37875
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
37218
37876
  this.providerLoader.reload();
@@ -37229,7 +37887,7 @@ var init_dev_server = __esm({
37229
37887
  return;
37230
37888
  }
37231
37889
  for (const name of ["scripts.js", "provider.json"]) {
37232
- const p = path18.join(dir, name);
37890
+ const p = path19.join(dir, name);
37233
37891
  if (fs14.existsSync(p)) {
37234
37892
  const source = fs14.readFileSync(p, "utf-8");
37235
37893
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
@@ -37250,8 +37908,8 @@ var init_dev_server = __esm({
37250
37908
  this.json(res, 404, { error: `Provider not found: ${type}` });
37251
37909
  return;
37252
37910
  }
37253
- const target = fs14.existsSync(path18.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
37254
- const targetPath = path18.join(dir, target);
37911
+ const target = fs14.existsSync(path19.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
37912
+ const targetPath = path19.join(dir, target);
37255
37913
  try {
37256
37914
  if (fs14.existsSync(targetPath)) fs14.copyFileSync(targetPath, targetPath + ".bak");
37257
37915
  fs14.writeFileSync(targetPath, source, "utf-8");
@@ -37411,7 +38069,7 @@ var init_dev_server = __esm({
37411
38069
  }
37412
38070
  let targetDir;
37413
38071
  targetDir = this.providerLoader.getUserProviderDir(category, type);
37414
- const jsonPath = path18.join(targetDir, "provider.json");
38072
+ const jsonPath = path19.join(targetDir, "provider.json");
37415
38073
  if (fs14.existsSync(jsonPath)) {
37416
38074
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
37417
38075
  return;
@@ -37423,8 +38081,8 @@ var init_dev_server = __esm({
37423
38081
  const createdFiles = ["provider.json"];
37424
38082
  if (result.files) {
37425
38083
  for (const [relPath, content] of Object.entries(result.files)) {
37426
- const fullPath = path18.join(targetDir, relPath);
37427
- fs14.mkdirSync(path18.dirname(fullPath), { recursive: true });
38084
+ const fullPath = path19.join(targetDir, relPath);
38085
+ fs14.mkdirSync(path19.dirname(fullPath), { recursive: true });
37428
38086
  fs14.writeFileSync(fullPath, content, "utf-8");
37429
38087
  createdFiles.push(relPath);
37430
38088
  }
@@ -37477,22 +38135,22 @@ var init_dev_server = __esm({
37477
38135
  if (!fs14.existsSync(scriptsDir)) return null;
37478
38136
  const versions = fs14.readdirSync(scriptsDir).filter((d) => {
37479
38137
  try {
37480
- return fs14.statSync(path18.join(scriptsDir, d)).isDirectory();
38138
+ return fs14.statSync(path19.join(scriptsDir, d)).isDirectory();
37481
38139
  } catch {
37482
38140
  return false;
37483
38141
  }
37484
38142
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
37485
38143
  if (versions.length === 0) return null;
37486
- return path18.join(scriptsDir, versions[0]);
38144
+ return path19.join(scriptsDir, versions[0]);
37487
38145
  }
37488
38146
  resolveAutoImplWritableProviderDir(category, type, requestedDir) {
37489
- const canonicalUserDir = path18.resolve(this.providerLoader.getUserProviderDir(category, type));
37490
- const desiredDir = requestedDir ? path18.resolve(requestedDir) : canonicalUserDir;
37491
- const upstreamRoot = path18.resolve(this.providerLoader.getUpstreamDir());
37492
- if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path18.sep}`)) {
38147
+ const canonicalUserDir = path19.resolve(this.providerLoader.getUserProviderDir(category, type));
38148
+ const desiredDir = requestedDir ? path19.resolve(requestedDir) : canonicalUserDir;
38149
+ const upstreamRoot = path19.resolve(this.providerLoader.getUpstreamDir());
38150
+ if (desiredDir === upstreamRoot || desiredDir.startsWith(`${upstreamRoot}${path19.sep}`)) {
37493
38151
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
37494
38152
  }
37495
- if (path18.basename(desiredDir) !== type) {
38153
+ if (path19.basename(desiredDir) !== type) {
37496
38154
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
37497
38155
  }
37498
38156
  const sourceDir = this.findProviderDir(type);
@@ -37500,11 +38158,11 @@ var init_dev_server = __esm({
37500
38158
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
37501
38159
  }
37502
38160
  if (!fs14.existsSync(desiredDir)) {
37503
- fs14.mkdirSync(path18.dirname(desiredDir), { recursive: true });
38161
+ fs14.mkdirSync(path19.dirname(desiredDir), { recursive: true });
37504
38162
  fs14.cpSync(sourceDir, desiredDir, { recursive: true });
37505
38163
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
37506
38164
  }
37507
- const providerJson = path18.join(desiredDir, "provider.json");
38165
+ const providerJson = path19.join(desiredDir, "provider.json");
37508
38166
  if (!fs14.existsSync(providerJson)) {
37509
38167
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
37510
38168
  }
@@ -37552,7 +38210,7 @@ var init_dev_server = __esm({
37552
38210
  setMode: "set_mode.js"
37553
38211
  };
37554
38212
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
37555
- const scriptsDir = path18.join(providerDir, "scripts");
38213
+ const scriptsDir = path19.join(providerDir, "scripts");
37556
38214
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
37557
38215
  if (latestScriptsDir) {
37558
38216
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -37563,7 +38221,7 @@ var init_dev_server = __esm({
37563
38221
  for (const file2 of fs14.readdirSync(latestScriptsDir)) {
37564
38222
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
37565
38223
  try {
37566
- const content = fs14.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
38224
+ const content = fs14.readFileSync(path19.join(latestScriptsDir, file2), "utf-8");
37567
38225
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
37568
38226
  lines.push("```javascript");
37569
38227
  lines.push(content);
@@ -37580,7 +38238,7 @@ var init_dev_server = __esm({
37580
38238
  lines.push("");
37581
38239
  for (const file2 of refFiles) {
37582
38240
  try {
37583
- const content = fs14.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
38241
+ const content = fs14.readFileSync(path19.join(latestScriptsDir, file2), "utf-8");
37584
38242
  lines.push(`### \`${file2}\` \u{1F512}`);
37585
38243
  lines.push("```javascript");
37586
38244
  lines.push(content);
@@ -37621,10 +38279,10 @@ var init_dev_server = __esm({
37621
38279
  lines.push("");
37622
38280
  }
37623
38281
  }
37624
- const docsDir = path18.join(providerDir, "../../docs");
38282
+ const docsDir = path19.join(providerDir, "../../docs");
37625
38283
  const loadGuide = (name) => {
37626
38284
  try {
37627
- const p = path18.join(docsDir, name);
38285
+ const p = path19.join(docsDir, name);
37628
38286
  if (fs14.existsSync(p)) return fs14.readFileSync(p, "utf-8");
37629
38287
  } catch {
37630
38288
  }
@@ -37798,7 +38456,7 @@ var init_dev_server = __esm({
37798
38456
  parseApproval: "parse_approval.js"
37799
38457
  };
37800
38458
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
37801
- const scriptsDir = path18.join(providerDir, "scripts");
38459
+ const scriptsDir = path19.join(providerDir, "scripts");
37802
38460
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
37803
38461
  if (latestScriptsDir) {
37804
38462
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -37810,7 +38468,7 @@ var init_dev_server = __esm({
37810
38468
  if (!file2.endsWith(".js")) continue;
37811
38469
  if (!targetFileNames.has(file2)) continue;
37812
38470
  try {
37813
- const content = fs14.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
38471
+ const content = fs14.readFileSync(path19.join(latestScriptsDir, file2), "utf-8");
37814
38472
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
37815
38473
  lines.push("```javascript");
37816
38474
  lines.push(content);
@@ -37826,7 +38484,7 @@ var init_dev_server = __esm({
37826
38484
  lines.push("");
37827
38485
  for (const file2 of refFiles) {
37828
38486
  try {
37829
- const content = fs14.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
38487
+ const content = fs14.readFileSync(path19.join(latestScriptsDir, file2), "utf-8");
37830
38488
  lines.push(`### \`${file2}\` \u{1F512}`);
37831
38489
  lines.push("```javascript");
37832
38490
  lines.push(content);
@@ -37859,10 +38517,10 @@ var init_dev_server = __esm({
37859
38517
  lines.push("");
37860
38518
  }
37861
38519
  }
37862
- const docsDir = path18.join(providerDir, "../../docs");
38520
+ const docsDir = path19.join(providerDir, "../../docs");
37863
38521
  const loadGuide = (name) => {
37864
38522
  try {
37865
- const p = path18.join(docsDir, name);
38523
+ const p = path19.join(docsDir, name);
37866
38524
  if (fs14.existsSync(p)) return fs14.readFileSync(p, "utf-8");
37867
38525
  } catch {
37868
38526
  }
@@ -38381,6 +39039,7 @@ var init_session_host_transport = __esm({
38381
39039
  }
38382
39040
  }
38383
39041
  handleEvent(event) {
39042
+ if (!("sessionId" in event)) return;
38384
39043
  if (event.sessionId !== this.options.runtimeId) return;
38385
39044
  if ((event.type === "session_started" || event.type === "session_resumed") && typeof event.pid === "number") {
38386
39045
  this.currentPid = event.pid;
@@ -38456,7 +39115,10 @@ var init_session_host_transport = __esm({
38456
39115
  clientId: client.clientId,
38457
39116
  type: client.type,
38458
39117
  readOnly: client.readOnly
38459
- }))
39118
+ })),
39119
+ restoredFromStorage: record2.meta?.restoredFromStorage === true,
39120
+ recoveryState: typeof record2.meta?.runtimeRecoveryState === "string" ? String(record2.meta.runtimeRecoveryState) : null,
39121
+ recoveryError: typeof record2.meta?.runtimeRecoveryError === "string" ? String(record2.meta.runtimeRecoveryError) : null
38460
39122
  };
38461
39123
  }
38462
39124
  enqueue(action) {
@@ -38918,6 +39580,7 @@ async function initDaemonComponents(config2) {
38918
39580
  onIdeConnected: () => poller?.start(),
38919
39581
  onStatusChange: config2.onStatusChange,
38920
39582
  onPostChatCommand: config2.onPostChatCommand,
39583
+ sessionHostControl: config2.sessionHostControl,
38921
39584
  getCdpLogFn: config2.getCdpLogFn || ((ideType) => LOG.forComponent(`CDP:${ideType}`).asLogFn())
38922
39585
  });
38923
39586
  poller = new AgentStreamPoller({
@@ -39576,17 +40239,17 @@ function canPeerUsePrivilegedShareCommand(commandType, permission) {
39576
40239
  return false;
39577
40240
  }
39578
40241
  }
39579
- var fs15, path19, os19, import_node_module2, esmRequire, logFile, log, logDebug, DaemonP2PSender;
40242
+ var fs15, path20, os19, import_node_module2, esmRequire, logFile, log, logDebug, DaemonP2PSender;
39580
40243
  var init_daemon_p2p = __esm({
39581
40244
  "src/daemon-p2p.ts"() {
39582
40245
  "use strict";
39583
40246
  fs15 = __toESM(require("fs"));
39584
40247
  init_src();
39585
- path19 = __toESM(require("path"));
40248
+ path20 = __toESM(require("path"));
39586
40249
  os19 = __toESM(require("os"));
39587
40250
  import_node_module2 = require("module");
39588
40251
  esmRequire = (0, import_node_module2.createRequire)(__filename);
39589
- logFile = path19.join(os19.tmpdir(), "adhdev_daemon_p2p.log");
40252
+ logFile = path20.join(os19.tmpdir(), "adhdev_daemon_p2p.log");
39590
40253
  log = (msg) => {
39591
40254
  LOG.info("P2P", `[${(/* @__PURE__ */ new Date()).toISOString()}] [P2P] ${msg}`);
39592
40255
  };
@@ -39654,15 +40317,15 @@ ${e?.stack || ""}`);
39654
40317
  const prebuildKey = `${platform11}-${arch3}`;
39655
40318
  try {
39656
40319
  const candidates = [
39657
- path19.join(__dirname, "node_modules", "node-datachannel"),
39658
- path19.join(__dirname, "..", "node_modules", "node-datachannel"),
39659
- path19.join(__dirname, "..", "..", "node_modules", "node-datachannel")
40320
+ path20.join(__dirname, "node_modules", "node-datachannel"),
40321
+ path20.join(__dirname, "..", "node_modules", "node-datachannel"),
40322
+ path20.join(__dirname, "..", "..", "node_modules", "node-datachannel")
39660
40323
  ];
39661
40324
  for (const candidate of candidates) {
39662
- const prebuildPath = path19.join(candidate, "prebuilds", prebuildKey, "node_datachannel.node");
40325
+ const prebuildPath = path20.join(candidate, "prebuilds", prebuildKey, "node_datachannel.node");
39663
40326
  if (fs15.existsSync(prebuildPath)) {
39664
- const targetDir = path19.join(candidate, "build", "Release");
39665
- const targetPath = path19.join(targetDir, "node_datachannel.node");
40327
+ const targetDir = path20.join(candidate, "build", "Release");
40328
+ const targetPath = path20.join(targetDir, "node_datachannel.node");
39666
40329
  fs15.mkdirSync(targetDir, { recursive: true });
39667
40330
  fs15.copyFileSync(prebuildPath, targetPath);
39668
40331
  try {
@@ -40442,16 +41105,16 @@ var require_filesystem = __commonJS({
40442
41105
  var LDD_PATH = "/usr/bin/ldd";
40443
41106
  var SELF_PATH = "/proc/self/exe";
40444
41107
  var MAX_LENGTH = 2048;
40445
- var readFileSync18 = (path24) => {
40446
- const fd = fs19.openSync(path24, "r");
41108
+ var readFileSync18 = (path25) => {
41109
+ const fd = fs19.openSync(path25, "r");
40447
41110
  const buffer = Buffer.alloc(MAX_LENGTH);
40448
41111
  const bytesRead = fs19.readSync(fd, buffer, 0, MAX_LENGTH, 0);
40449
41112
  fs19.close(fd, () => {
40450
41113
  });
40451
41114
  return buffer.subarray(0, bytesRead);
40452
41115
  };
40453
- var readFile = (path24) => new Promise((resolve14, reject) => {
40454
- fs19.open(path24, "r", (err, fd) => {
41116
+ var readFile = (path25) => new Promise((resolve14, reject) => {
41117
+ fs19.open(path25, "r", (err, fd) => {
40455
41118
  if (err) {
40456
41119
  reject(err);
40457
41120
  } else {
@@ -40570,11 +41233,11 @@ var require_detect_libc = __commonJS({
40570
41233
  }
40571
41234
  return null;
40572
41235
  };
40573
- var familyFromInterpreterPath = (path24) => {
40574
- if (path24) {
40575
- if (path24.includes("/ld-musl-")) {
41236
+ var familyFromInterpreterPath = (path25) => {
41237
+ if (path25) {
41238
+ if (path25.includes("/ld-musl-")) {
40576
41239
  return MUSL;
40577
- } else if (path24.includes("/ld-linux-")) {
41240
+ } else if (path25.includes("/ld-linux-")) {
40578
41241
  return GLIBC;
40579
41242
  }
40580
41243
  }
@@ -40621,8 +41284,8 @@ var require_detect_libc = __commonJS({
40621
41284
  cachedFamilyInterpreter = null;
40622
41285
  try {
40623
41286
  const selfContent = await readFile(SELF_PATH);
40624
- const path24 = interpreterPath(selfContent);
40625
- cachedFamilyInterpreter = familyFromInterpreterPath(path24);
41287
+ const path25 = interpreterPath(selfContent);
41288
+ cachedFamilyInterpreter = familyFromInterpreterPath(path25);
40626
41289
  } catch (e) {
40627
41290
  }
40628
41291
  return cachedFamilyInterpreter;
@@ -40634,8 +41297,8 @@ var require_detect_libc = __commonJS({
40634
41297
  cachedFamilyInterpreter = null;
40635
41298
  try {
40636
41299
  const selfContent = readFileSync18(SELF_PATH);
40637
- const path24 = interpreterPath(selfContent);
40638
- cachedFamilyInterpreter = familyFromInterpreterPath(path24);
41300
+ const path25 = interpreterPath(selfContent);
41301
+ cachedFamilyInterpreter = familyFromInterpreterPath(path25);
40639
41302
  } catch (e) {
40640
41303
  }
40641
41304
  return cachedFamilyInterpreter;
@@ -42354,18 +43017,18 @@ var require_sharp = __commonJS({
42354
43017
  `@img/sharp-${runtimePlatform}/sharp.node`,
42355
43018
  "@img/sharp-wasm32/sharp.node"
42356
43019
  ];
42357
- var path24;
43020
+ var path25;
42358
43021
  var sharp;
42359
43022
  var errors = [];
42360
- for (path24 of paths) {
43023
+ for (path25 of paths) {
42361
43024
  try {
42362
- sharp = require(path24);
43025
+ sharp = require(path25);
42363
43026
  break;
42364
43027
  } catch (err) {
42365
43028
  errors.push(err);
42366
43029
  }
42367
43030
  }
42368
- if (sharp && path24.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
43031
+ if (sharp && path25.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
42369
43032
  const err = new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");
42370
43033
  err.code = "Unsupported CPU";
42371
43034
  errors.push(err);
@@ -45274,15 +45937,15 @@ var require_color = __commonJS({
45274
45937
  };
45275
45938
  }
45276
45939
  function wrapConversion(toModel, graph) {
45277
- const path24 = [graph[toModel].parent, toModel];
45940
+ const path25 = [graph[toModel].parent, toModel];
45278
45941
  let fn = conversions_default[graph[toModel].parent][toModel];
45279
45942
  let cur = graph[toModel].parent;
45280
45943
  while (graph[cur].parent) {
45281
- path24.unshift(graph[cur].parent);
45944
+ path25.unshift(graph[cur].parent);
45282
45945
  fn = link(conversions_default[graph[cur].parent][cur], fn);
45283
45946
  cur = graph[cur].parent;
45284
45947
  }
45285
- fn.conversion = path24;
45948
+ fn.conversion = path25;
45286
45949
  return fn;
45287
45950
  }
45288
45951
  function route(fromModel) {
@@ -45899,7 +46562,7 @@ var require_channel = __commonJS({
45899
46562
  var require_output = __commonJS({
45900
46563
  "../../node_modules/sharp/lib/output.js"(exports2, module2) {
45901
46564
  "use strict";
45902
- var path24 = require("path");
46565
+ var path25 = require("path");
45903
46566
  var is = require_is();
45904
46567
  var sharp = require_sharp();
45905
46568
  var formats = /* @__PURE__ */ new Map([
@@ -45930,9 +46593,9 @@ var require_output = __commonJS({
45930
46593
  let err;
45931
46594
  if (!is.string(fileOut)) {
45932
46595
  err = new Error("Missing output file path");
45933
- } else if (is.string(this.options.input.file) && path24.resolve(this.options.input.file) === path24.resolve(fileOut)) {
46596
+ } else if (is.string(this.options.input.file) && path25.resolve(this.options.input.file) === path25.resolve(fileOut)) {
45934
46597
  err = new Error("Cannot use same file for input and output");
45935
- } else if (jp2Regex.test(path24.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
46598
+ } else if (jp2Regex.test(path25.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
45936
46599
  err = errJp2Save();
45937
46600
  }
45938
46601
  if (err) {
@@ -47146,8 +47809,8 @@ function buildSessionHostEnv(baseEnv) {
47146
47809
  }
47147
47810
  function resolveSessionHostEntry() {
47148
47811
  const packagedCandidates = [
47149
- path20.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
47150
- path20.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
47812
+ path21.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
47813
+ path21.resolve(__dirname, "../../vendor/session-host-daemon/index.js")
47151
47814
  ];
47152
47815
  for (const candidate of packagedCandidates) {
47153
47816
  if (fs16.existsSync(candidate)) {
@@ -47157,7 +47820,7 @@ function resolveSessionHostEntry() {
47157
47820
  return require.resolve("@adhdev/session-host-daemon");
47158
47821
  }
47159
47822
  function getSessionHostPidFile() {
47160
- return path20.join(os20.homedir(), ".adhdev", `${SESSION_HOST_APP_NAME}-session-host.pid`);
47823
+ return path21.join(os20.homedir(), ".adhdev", `${SESSION_HOST_APP_NAME}-session-host.pid`);
47161
47824
  }
47162
47825
  function getSessionHostStatusPaths() {
47163
47826
  return {
@@ -47270,9 +47933,9 @@ function stopSessionHost() {
47270
47933
  async function ensureSessionHostReady2() {
47271
47934
  const spawnHost = () => {
47272
47935
  const entry = resolveSessionHostEntry();
47273
- const logDir = path20.join(os20.homedir(), ".adhdev", "logs");
47936
+ const logDir = path21.join(os20.homedir(), ".adhdev", "logs");
47274
47937
  fs16.mkdirSync(logDir, { recursive: true });
47275
- const logFd = fs16.openSync(path20.join(logDir, "session-host.log"), "a");
47938
+ const logFd = fs16.openSync(path21.join(logDir, "session-host.log"), "a");
47276
47939
  const child = (0, import_child_process11.spawn)(process.execPath, [entry], {
47277
47940
  detached: true,
47278
47941
  stdio: ["ignore", logFd, logFd],
@@ -47334,14 +47997,14 @@ async function probeSessionHostStatus() {
47334
47997
  };
47335
47998
  }
47336
47999
  }
47337
- var import_child_process11, fs16, os20, path20, SESSION_HOST_APP_NAME, SESSION_HOST_START_TIMEOUT_MS;
48000
+ var import_child_process11, fs16, os20, path21, SESSION_HOST_APP_NAME, SESSION_HOST_START_TIMEOUT_MS;
47338
48001
  var init_session_host = __esm({
47339
48002
  "src/session-host.ts"() {
47340
48003
  "use strict";
47341
48004
  import_child_process11 = require("child_process");
47342
48005
  fs16 = __toESM(require("fs"));
47343
48006
  os20 = __toESM(require("os"));
47344
- path20 = __toESM(require("path"));
48007
+ path21 = __toESM(require("path"));
47345
48008
  init_src();
47346
48009
  init_dist();
47347
48010
  SESSION_HOST_APP_NAME = process.env.ADHDEV_SESSION_HOST_NAME || "adhdev";
@@ -47349,6 +48012,151 @@ var init_session_host = __esm({
47349
48012
  }
47350
48013
  });
47351
48014
 
48015
+ // src/session-host-controller.ts
48016
+ var SessionHostController;
48017
+ var init_session_host_controller = __esm({
48018
+ "src/session-host-controller.ts"() {
48019
+ "use strict";
48020
+ init_src();
48021
+ init_dist();
48022
+ SessionHostController = class {
48023
+ constructor(endpoint, onEvent) {
48024
+ this.onEvent = onEvent;
48025
+ this.client = new SessionHostClient({ endpoint });
48026
+ }
48027
+ client;
48028
+ reconnectTimer = null;
48029
+ unsubscribe = null;
48030
+ started = false;
48031
+ async start() {
48032
+ if (this.started) return;
48033
+ this.started = true;
48034
+ this.unsubscribe = this.client.onEvent((event) => this.handleEvent(event));
48035
+ await this.ensureConnected();
48036
+ this.reconnectTimer = setInterval(() => {
48037
+ void this.ensureConnected();
48038
+ }, 2e3);
48039
+ }
48040
+ async stop() {
48041
+ this.started = false;
48042
+ if (this.reconnectTimer) {
48043
+ clearInterval(this.reconnectTimer);
48044
+ this.reconnectTimer = null;
48045
+ }
48046
+ try {
48047
+ this.unsubscribe?.();
48048
+ this.unsubscribe = null;
48049
+ } catch {
48050
+ }
48051
+ await this.client.close().catch(() => {
48052
+ });
48053
+ }
48054
+ async getDiagnostics(payload = {}) {
48055
+ return this.request({
48056
+ type: "get_host_diagnostics",
48057
+ payload
48058
+ });
48059
+ }
48060
+ async listSessions() {
48061
+ return this.request({
48062
+ type: "list_sessions",
48063
+ payload: {}
48064
+ });
48065
+ }
48066
+ async stopSession(sessionId) {
48067
+ return this.request({
48068
+ type: "stop_session",
48069
+ payload: { sessionId }
48070
+ });
48071
+ }
48072
+ async resumeSession(sessionId) {
48073
+ return this.request({
48074
+ type: "resume_session",
48075
+ payload: { sessionId }
48076
+ });
48077
+ }
48078
+ async restartSession(sessionId) {
48079
+ return this.request({
48080
+ type: "restart_session",
48081
+ payload: { sessionId }
48082
+ });
48083
+ }
48084
+ async sendSignal(sessionId, signal) {
48085
+ return this.request({
48086
+ type: "send_signal",
48087
+ payload: { sessionId, signal }
48088
+ });
48089
+ }
48090
+ async forceDetachClient(sessionId, clientId) {
48091
+ return this.request({
48092
+ type: "force_detach_client",
48093
+ payload: { sessionId, clientId }
48094
+ });
48095
+ }
48096
+ async acquireWrite(payload) {
48097
+ return this.request({
48098
+ type: "acquire_write",
48099
+ payload
48100
+ });
48101
+ }
48102
+ async releaseWrite(payload) {
48103
+ return this.request({
48104
+ type: "release_write",
48105
+ payload
48106
+ });
48107
+ }
48108
+ async request(request) {
48109
+ await this.ensureConnected();
48110
+ const response = await this.client.request(request);
48111
+ if (!response.success) {
48112
+ throw new Error(response.error || `Session host request failed: ${request.type}`);
48113
+ }
48114
+ return response.result ?? null;
48115
+ }
48116
+ async ensureConnected() {
48117
+ try {
48118
+ await this.client.connect();
48119
+ } catch (error48) {
48120
+ if (!this.started) return;
48121
+ LOG.debug("SessionHost", `connect failed: ${error48?.message || error48}`);
48122
+ }
48123
+ }
48124
+ handleEvent(event) {
48125
+ if (event.type === "host_log") {
48126
+ const line = event.entry.sessionId ? `${event.entry.message} (session=${event.entry.sessionId})` : event.entry.message;
48127
+ switch (event.entry.level) {
48128
+ case "debug":
48129
+ LOG.debug("SessionHost", line);
48130
+ break;
48131
+ case "warn":
48132
+ LOG.warn("SessionHost", line);
48133
+ break;
48134
+ case "error":
48135
+ LOG.error("SessionHost", line);
48136
+ break;
48137
+ default:
48138
+ LOG.info("SessionHost", line);
48139
+ break;
48140
+ }
48141
+ } else if (event.type === "request_trace") {
48142
+ const line = `${event.trace.type} ${event.trace.success ? "ok" : "failed"} ${event.trace.durationMs}ms` + (event.trace.sessionId ? ` session=${event.trace.sessionId}` : "") + (event.trace.error ? ` error=${event.trace.error}` : "");
48143
+ if (event.trace.success) LOG.debug("SessionHost", line);
48144
+ else LOG.warn("SessionHost", line);
48145
+ } else if (event.type === "runtime_transition") {
48146
+ const line = `${event.transition.action} ${event.transition.success === false ? "failed" : "ok"}` + (event.transition.lifecycle ? ` lifecycle=${event.transition.lifecycle}` : "") + (event.transition.detail ? ` detail=${event.transition.detail}` : "") + (event.transition.error ? ` error=${event.transition.error}` : "");
48147
+ if (event.transition.success === false) LOG.warn("SessionHost", `[${event.transition.sessionId}] ${line}`);
48148
+ else LOG.info("SessionHost", `[${event.transition.sessionId}] ${line}`);
48149
+ }
48150
+ try {
48151
+ this.onEvent?.(event);
48152
+ } catch (error48) {
48153
+ LOG.warn("SessionHost", `event callback failed: ${error48?.message || error48}`);
48154
+ }
48155
+ }
48156
+ };
48157
+ }
48158
+ });
48159
+
47352
48160
  // src/version.ts
47353
48161
  function resolvePackageVersion(options) {
47354
48162
  const injectedVersion = options?.injectedVersion || "unknown";
@@ -47385,9 +48193,9 @@ __export(adhdev_daemon_exports, {
47385
48193
  stopDaemon: () => stopDaemon
47386
48194
  });
47387
48195
  function getDaemonPidFile() {
47388
- const dir = path21.join(os21.homedir(), ".adhdev");
48196
+ const dir = path23.join(os21.homedir(), ".adhdev");
47389
48197
  if (!fs17.existsSync(dir)) fs17.mkdirSync(dir, { recursive: true });
47390
- return path21.join(dir, "daemon.pid");
48198
+ return path23.join(dir, "daemon.pid");
47391
48199
  }
47392
48200
  function writeDaemonPid(pid) {
47393
48201
  fs17.writeFileSync(getDaemonPidFile(), String(pid), "utf-8");
@@ -47433,7 +48241,7 @@ function stopDaemon() {
47433
48241
  return false;
47434
48242
  }
47435
48243
  }
47436
- var os21, fs17, path21, import_http, import_ws3, import_chalk2, pkgVersion, DANGEROUS_PATTERNS, AdhdevDaemon;
48244
+ var os21, fs17, path23, import_http, import_ws3, import_chalk2, pkgVersion, DANGEROUS_PATTERNS, AdhdevDaemon;
47437
48245
  var init_adhdev_daemon = __esm({
47438
48246
  "src/adhdev-daemon.ts"() {
47439
48247
  "use strict";
@@ -47443,14 +48251,15 @@ var init_adhdev_daemon = __esm({
47443
48251
  init_screenshot_controller();
47444
48252
  init_session_host();
47445
48253
  init_dist();
48254
+ init_session_host_controller();
47446
48255
  os21 = __toESM(require("os"));
47447
48256
  fs17 = __toESM(require("fs"));
47448
- path21 = __toESM(require("path"));
48257
+ path23 = __toESM(require("path"));
47449
48258
  import_http = require("http");
47450
48259
  import_ws3 = require("ws");
47451
48260
  import_chalk2 = __toESM(require("chalk"));
47452
48261
  init_version();
47453
- pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.24" });
48262
+ pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.27" });
47454
48263
  DANGEROUS_PATTERNS = [
47455
48264
  /\brm\s+(-[a-z]*f|-[a-z]*r|--force|--recursive)/i,
47456
48265
  /\bsudo\b/i,
@@ -47473,6 +48282,7 @@ var init_adhdev_daemon = __esm({
47473
48282
  statusReporter = null;
47474
48283
  components = null;
47475
48284
  sessionHostEndpoint = null;
48285
+ sessionHostController = null;
47476
48286
  running = false;
47477
48287
  localPort;
47478
48288
  ideType = "unknown";
@@ -47523,6 +48333,11 @@ ${err?.stack || ""}`);
47523
48333
  }
47524
48334
  const sessionHostEndpoint = await ensureSessionHostReady2();
47525
48335
  this.sessionHostEndpoint = sessionHostEndpoint;
48336
+ this.sessionHostController = new SessionHostController(
48337
+ sessionHostEndpoint,
48338
+ (event) => this.broadcastLocalIpcMessage("daemon:session_host_event", event)
48339
+ );
48340
+ await this.sessionHostController.start();
47526
48341
  this.components = await initDaemonComponents({
47527
48342
  providerLogFn: LOG.forComponent("Provider").asLogFn(),
47528
48343
  cliManagerDeps: {
@@ -47560,6 +48375,7 @@ ${err?.stack || ""}`);
47560
48375
  setTimeout(() => this.statusReporter?.throttledReport(), 1e3);
47561
48376
  setTimeout(() => this.statusReporter?.throttledReport(), 3e3);
47562
48377
  },
48378
+ sessionHostControl: this.sessionHostController,
47563
48379
  getCdpLogFn: (ideType) => LOG.forComponent(`CDP:${ideType}`).asLogFn(),
47564
48380
  onCdpManagerSetup: (ideType) => {
47565
48381
  if (this.ideType === "unknown") this.ideType = ideType;
@@ -47916,13 +48732,24 @@ ${err?.stack || ""}`);
47916
48732
  serverConnected: this.serverConn?.isConnected() ?? false,
47917
48733
  cdpConnected: (this.components?.cdpManagers.size || 0) > 0,
47918
48734
  localPort: this.localPort,
47919
- cliAgents
48735
+ cliAgents,
48736
+ sessionHostConnected: !!this.sessionHostController
47920
48737
  }
47921
48738
  }));
47922
48739
  } catch (error48) {
47923
48740
  LOG.warn("IPC", `Failed to send welcome: ${error48?.message || error48}`);
47924
48741
  }
47925
48742
  }
48743
+ broadcastLocalIpcMessage(type, payload) {
48744
+ const message = JSON.stringify({ type, payload });
48745
+ for (const client of this.localClients) {
48746
+ if (client.readyState !== import_ws3.WebSocket.OPEN) continue;
48747
+ try {
48748
+ client.send(message);
48749
+ } catch {
48750
+ }
48751
+ }
48752
+ }
47926
48753
  async handleLocalIpcMessage(ws, raw) {
47927
48754
  let msg;
47928
48755
  try {
@@ -48013,6 +48840,11 @@ ${err?.stack || ""}`);
48013
48840
  this.serverConn?.disconnect();
48014
48841
  } catch {
48015
48842
  }
48843
+ try {
48844
+ await this.sessionHostController?.stop();
48845
+ this.sessionHostController = null;
48846
+ } catch {
48847
+ }
48016
48848
  try {
48017
48849
  for (const client of this.localClients) {
48018
48850
  client.close();
@@ -48844,6 +49676,45 @@ function hideCommand(command) {
48844
49676
  command.hideHelp?.();
48845
49677
  return command;
48846
49678
  }
49679
+ async function fetchLocalDaemonHealth(port) {
49680
+ const controller = new AbortController();
49681
+ const timer = setTimeout(() => controller.abort(), 1500);
49682
+ try {
49683
+ const res = await fetch(`http://127.0.0.1:${port}/health`, { signal: controller.signal });
49684
+ if (!res.ok) return null;
49685
+ return await res.json();
49686
+ } catch {
49687
+ return null;
49688
+ } finally {
49689
+ clearTimeout(timer);
49690
+ }
49691
+ }
49692
+ async function sendDaemonCommandSafe(command, args, port) {
49693
+ const { sendDaemonCommand: sendDaemonCommand2 } = await Promise.resolve().then(() => (init_cdp_utils(), cdp_utils_exports));
49694
+ return sendDaemonCommand2(command, args, port);
49695
+ }
49696
+ async function requestSessionHostDirect(request) {
49697
+ const { SessionHostClient: SessionHostClient2, getDefaultSessionHostEndpoint: getDefaultSessionHostEndpoint2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
49698
+ const endpoint = getDefaultSessionHostEndpoint2(process.env.ADHDEV_SESSION_HOST_NAME || "adhdev");
49699
+ const client = new SessionHostClient2({ endpoint });
49700
+ try {
49701
+ await client.connect();
49702
+ return await client.request(request);
49703
+ } finally {
49704
+ await client.close().catch(() => {
49705
+ });
49706
+ }
49707
+ }
49708
+ function summarizeLatestTransition(diagnostics) {
49709
+ const transitions = Array.isArray(diagnostics?.recentTransitions) ? diagnostics.recentTransitions : [];
49710
+ const latest = transitions.length > 0 ? transitions[transitions.length - 1] : null;
49711
+ if (!latest) return null;
49712
+ const at = latest.at ? new Date(latest.at).toISOString() : "unknown";
49713
+ const lifecycle = latest.lifecycle ? ` ${latest.lifecycle}` : "";
49714
+ const detail = latest.detail ? ` ${latest.detail}` : "";
49715
+ const status = latest.success === false ? "failed" : "ok";
49716
+ return `${latest.action} ${status}${lifecycle}${detail} @ ${at}`;
49717
+ }
48847
49718
  function registerDaemonCommands(program2, pkgVersion3) {
48848
49719
  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) => {
48849
49720
  const { AdhdevDaemon: AdhdevDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
@@ -48883,39 +49754,71 @@ function registerDaemonCommands(program2, pkgVersion3) {
48883
49754
  \u2717 Failed to start standalone server: ${err.message}`));
48884
49755
  });
48885
49756
  });
48886
- hideCommand(program2.command("daemon:status").description("Check ADHDev Daemon status").action(async () => {
49757
+ hideCommand(program2.command("daemon:status").description("Check ADHDev Daemon status").option("-p, --port <port>", "Local WS server port", "19222").action(async (options) => {
48887
49758
  const { isDaemonRunning: isDaemonRunning2, getDaemonPid: getDaemonPid2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
48888
49759
  const { getCurrentDaemonLogPath: getCurrentDaemonLogPath2 } = await Promise.resolve().then(() => (init_src(), src_exports));
48889
49760
  const { probeSessionHostStatus: probeSessionHostStatus2 } = await Promise.resolve().then(() => (init_session_host(), session_host_exports));
49761
+ const port = parseInt(options.port, 10) || 19222;
48890
49762
  if (isDaemonRunning2()) {
48891
49763
  console.log(import_chalk5.default.green(`
48892
49764
  \u2713 ADHDev Daemon is running.
48893
49765
  `));
48894
49766
  console.log(import_chalk5.default.gray(` PID: ${getDaemonPid2() ?? "unknown"}`));
48895
49767
  console.log(import_chalk5.default.gray(` Logs: ${getCurrentDaemonLogPath2()}`));
48896
- try {
48897
- const controller = new AbortController();
48898
- const timer = setTimeout(() => controller.abort(), 1500);
48899
- const res = await fetch("http://127.0.0.1:19222/health", { signal: controller.signal });
48900
- clearTimeout(timer);
48901
- if (res.ok) {
48902
- const data = await res.json();
48903
- console.log(import_chalk5.default.gray(` Local IPC: reachable (ws://127.0.0.1:${data.port}${data.wsPath})`));
48904
- } else {
48905
- console.log(import_chalk5.default.gray(" Local IPC: not reachable"));
48906
- }
48907
- } catch {
49768
+ const health = await fetchLocalDaemonHealth(port);
49769
+ if (health) {
49770
+ console.log(import_chalk5.default.gray(` Local IPC: reachable (ws://127.0.0.1:${health.port}${health.wsPath})`));
49771
+ } else {
48908
49772
  console.log(import_chalk5.default.gray(" Local IPC: not reachable"));
48909
49773
  }
48910
- try {
48911
- const sessionHost = await probeSessionHostStatus2();
48912
- console.log(import_chalk5.default.gray(
48913
- ` SessionHost: ${sessionHost.reachable ? `reachable (${sessionHost.runtimeCount} active runtime${sessionHost.runtimeCount === 1 ? "" : "s"})` : "not reachable"}`
48914
- ));
48915
- console.log(import_chalk5.default.gray(` Session IPC: ${sessionHost.endpoint.path}`));
48916
- console.log(import_chalk5.default.gray(` Session PID: ${sessionHost.pid ?? "unknown"}`));
48917
- } catch {
48918
- console.log(import_chalk5.default.gray(" SessionHost: status unavailable"));
49774
+ if (health) {
49775
+ try {
49776
+ const result = await sendDaemonCommandSafe("session_host_get_diagnostics", {
49777
+ includeSessions: true,
49778
+ limit: 5
49779
+ }, port);
49780
+ if (result?.success && result?.diagnostics) {
49781
+ const diagnostics = result.diagnostics;
49782
+ const runtimeCount = Number(diagnostics.runtimeCount) || 0;
49783
+ console.log(import_chalk5.default.gray(
49784
+ ` SessionHost: managed (${runtimeCount} active runtime${runtimeCount === 1 ? "" : "s"})`
49785
+ ));
49786
+ console.log(import_chalk5.default.gray(` Session IPC: ${diagnostics.endpoint || "-"}`));
49787
+ console.log(import_chalk5.default.gray(
49788
+ ` Session Obs: ${Array.isArray(diagnostics.recentLogs) ? diagnostics.recentLogs.length : 0} logs, ${Array.isArray(diagnostics.recentRequests) ? diagnostics.recentRequests.length : 0} requests, ${Array.isArray(diagnostics.recentTransitions) ? diagnostics.recentTransitions.length : 0} transitions`
49789
+ ));
49790
+ const latestTransition = summarizeLatestTransition(diagnostics);
49791
+ if (latestTransition) {
49792
+ console.log(import_chalk5.default.gray(` Session Last: ${latestTransition}`));
49793
+ }
49794
+ } else {
49795
+ throw new Error(result?.error || "session host diagnostics unavailable");
49796
+ }
49797
+ } catch {
49798
+ try {
49799
+ const sessionHost = await probeSessionHostStatus2();
49800
+ console.log(import_chalk5.default.gray(
49801
+ ` SessionHost: ${sessionHost.reachable ? `reachable (${sessionHost.runtimeCount} active runtime${sessionHost.runtimeCount === 1 ? "" : "s"})` : "not reachable"}`
49802
+ ));
49803
+ console.log(import_chalk5.default.gray(` Session IPC: ${sessionHost.endpoint.path}`));
49804
+ console.log(import_chalk5.default.gray(` Session PID: ${sessionHost.pid ?? "unknown"}`));
49805
+ console.log(import_chalk5.default.gray(" Session Mode: direct probe fallback"));
49806
+ } catch {
49807
+ console.log(import_chalk5.default.gray(" SessionHost: status unavailable"));
49808
+ }
49809
+ }
49810
+ } else {
49811
+ try {
49812
+ const sessionHost = await probeSessionHostStatus2();
49813
+ console.log(import_chalk5.default.gray(
49814
+ ` SessionHost: ${sessionHost.reachable ? `reachable (${sessionHost.runtimeCount} active runtime${sessionHost.runtimeCount === 1 ? "" : "s"})` : "not reachable"}`
49815
+ ));
49816
+ console.log(import_chalk5.default.gray(` Session IPC: ${sessionHost.endpoint.path}`));
49817
+ console.log(import_chalk5.default.gray(` Session PID: ${sessionHost.pid ?? "unknown"}`));
49818
+ console.log(import_chalk5.default.gray(" Session Mode: direct probe fallback"));
49819
+ } catch {
49820
+ console.log(import_chalk5.default.gray(" SessionHost: status unavailable"));
49821
+ }
48919
49822
  }
48920
49823
  try {
48921
49824
  const controller = new AbortController();
@@ -48941,6 +49844,135 @@ function registerDaemonCommands(program2, pkgVersion3) {
48941
49844
  `));
48942
49845
  }
48943
49846
  }));
49847
+ hideCommand(program2.command("daemon:session-host").description("Inspect and control the session host").option("-p, --port <port>", "Local WS server port", "19222").option("--json", "Print raw JSON diagnostics/result").option("--limit <count>", "Number of diagnostics entries to include", "20").option("--session <sessionId>", "Target session ID").option("--restart", "Restart the target session").option("--resume", "Resume the target session").option("--stop", "Stop the target session").option("--signal <signal>", "Send a signal to the target session").option("--detach-client <clientId>", "Force-detach a client from the target session").option("--acquire-write <clientId>", "Force-acquire write ownership for a client").option("--release-write <clientId>", "Release write ownership for a client").option("--owner-type <type>", "ownerType for --acquire-write (user|agent)", "user").action(async (options) => {
49848
+ const sessionId = typeof options.session === "string" ? options.session.trim() : "";
49849
+ const limit = Math.max(1, Math.min(200, parseInt(options.limit, 10) || 20));
49850
+ const port = parseInt(options.port, 10) || 19222;
49851
+ const requireSessionId = () => {
49852
+ if (!sessionId) {
49853
+ throw new Error("--session is required for this action");
49854
+ }
49855
+ };
49856
+ try {
49857
+ let daemonCommand = "session_host_get_diagnostics";
49858
+ let daemonArgs = {
49859
+ includeSessions: true,
49860
+ limit
49861
+ };
49862
+ let directRequest = {
49863
+ type: "get_host_diagnostics",
49864
+ payload: {
49865
+ includeSessions: true,
49866
+ limit
49867
+ }
49868
+ };
49869
+ if (options.restart) {
49870
+ requireSessionId();
49871
+ daemonCommand = "session_host_restart_session";
49872
+ daemonArgs = { sessionId };
49873
+ directRequest = { type: "restart_session", payload: { sessionId } };
49874
+ } else if (options.resume) {
49875
+ requireSessionId();
49876
+ daemonCommand = "session_host_resume_session";
49877
+ daemonArgs = { sessionId };
49878
+ directRequest = { type: "resume_session", payload: { sessionId } };
49879
+ } else if (options.stop) {
49880
+ requireSessionId();
49881
+ daemonCommand = "session_host_stop_session";
49882
+ daemonArgs = { sessionId };
49883
+ directRequest = { type: "stop_session", payload: { sessionId } };
49884
+ } else if (options.signal) {
49885
+ requireSessionId();
49886
+ daemonCommand = "session_host_send_signal";
49887
+ daemonArgs = { sessionId, signal: String(options.signal) };
49888
+ directRequest = { type: "send_signal", payload: { sessionId, signal: String(options.signal) } };
49889
+ } else if (options.detachClient) {
49890
+ requireSessionId();
49891
+ daemonCommand = "session_host_force_detach_client";
49892
+ daemonArgs = { sessionId, clientId: String(options.detachClient) };
49893
+ directRequest = { type: "force_detach_client", payload: { sessionId, clientId: String(options.detachClient) } };
49894
+ } else if (options.acquireWrite) {
49895
+ requireSessionId();
49896
+ daemonCommand = "session_host_acquire_write";
49897
+ daemonArgs = {
49898
+ sessionId,
49899
+ clientId: String(options.acquireWrite),
49900
+ ownerType: options.ownerType === "agent" ? "agent" : "user",
49901
+ force: true
49902
+ };
49903
+ directRequest = { type: "acquire_write", payload: daemonArgs };
49904
+ } else if (options.releaseWrite) {
49905
+ requireSessionId();
49906
+ daemonCommand = "session_host_release_write";
49907
+ daemonArgs = {
49908
+ sessionId,
49909
+ clientId: String(options.releaseWrite)
49910
+ };
49911
+ directRequest = { type: "release_write", payload: daemonArgs };
49912
+ }
49913
+ const health = await fetchLocalDaemonHealth(port);
49914
+ let source = "daemon";
49915
+ let payload;
49916
+ if (health) {
49917
+ const routed = await sendDaemonCommandSafe(daemonCommand, daemonArgs, port);
49918
+ if (!routed?.success) {
49919
+ throw new Error(routed?.error || "session host request failed");
49920
+ }
49921
+ payload = routed.diagnostics ?? routed.record ?? routed.sessions ?? null;
49922
+ } else {
49923
+ source = "direct";
49924
+ const envelope = await requestSessionHostDirect(directRequest);
49925
+ if (!envelope?.success) {
49926
+ throw new Error(envelope?.error || "session host request failed");
49927
+ }
49928
+ payload = envelope.result ?? null;
49929
+ }
49930
+ if (options.json) {
49931
+ console.log(JSON.stringify(payload, null, 2));
49932
+ return;
49933
+ }
49934
+ if (options.restart || options.resume || options.stop || options.signal || options.detachClient || options.acquireWrite || options.releaseWrite) {
49935
+ const record2 = payload;
49936
+ console.log(import_chalk5.default.green("\n \u2713 Session host action completed.\n"));
49937
+ console.log(import_chalk5.default.gray(` Source: ${source === "daemon" ? "daemon control plane" : "direct host fallback"}`));
49938
+ console.log(import_chalk5.default.gray(` Session: ${record2?.sessionId || sessionId}`));
49939
+ console.log(import_chalk5.default.gray(` Runtime: ${record2?.runtimeKey || "-"}`));
49940
+ console.log(import_chalk5.default.gray(` Lifecycle: ${record2?.lifecycle || "-"}`));
49941
+ console.log(import_chalk5.default.gray(` Clients: ${Array.isArray(record2?.attachedClients) ? record2.attachedClients.length : 0}`));
49942
+ console.log();
49943
+ return;
49944
+ }
49945
+ const diagnostics = payload || {};
49946
+ const sessions = Array.isArray(diagnostics.sessions) ? diagnostics.sessions : [];
49947
+ console.log(import_chalk5.default.bold("\n Session Host Diagnostics\n"));
49948
+ console.log(import_chalk5.default.gray(` Source: ${source === "daemon" ? "daemon control plane" : "direct host fallback"}`));
49949
+ console.log(import_chalk5.default.gray(` Endpoint: ${diagnostics.endpoint || "-"}`));
49950
+ console.log(import_chalk5.default.gray(` Started: ${diagnostics.hostStartedAt ? new Date(diagnostics.hostStartedAt).toISOString() : "unknown"}`));
49951
+ console.log(import_chalk5.default.gray(` Runtimes: ${diagnostics.runtimeCount || 0}`));
49952
+ console.log(import_chalk5.default.gray(` Logs: ${Array.isArray(diagnostics.recentLogs) ? diagnostics.recentLogs.length : 0}`));
49953
+ console.log(import_chalk5.default.gray(` Requests: ${Array.isArray(diagnostics.recentRequests) ? diagnostics.recentRequests.length : 0}`));
49954
+ console.log(import_chalk5.default.gray(` Transitions:${Array.isArray(diagnostics.recentTransitions) ? diagnostics.recentTransitions.length : 0}`));
49955
+ const latestTransition = summarizeLatestTransition(diagnostics);
49956
+ if (latestTransition) {
49957
+ console.log(import_chalk5.default.gray(` Last: ${latestTransition}`));
49958
+ }
49959
+ console.log();
49960
+ if (sessions.length > 0) {
49961
+ console.log(import_chalk5.default.bold(" Sessions:"));
49962
+ for (const record2 of sessions) {
49963
+ const owner = record2?.writeOwner?.clientId || "-";
49964
+ const clients = Array.isArray(record2?.attachedClients) ? record2.attachedClients.length : 0;
49965
+ console.log(import_chalk5.default.gray(` ${record2.sessionId} ${record2.lifecycle} owner=${owner} clients=${clients} ${record2.runtimeKey || record2.providerType || ""}`));
49966
+ }
49967
+ console.log();
49968
+ }
49969
+ } catch (error48) {
49970
+ console.error(import_chalk5.default.red(`
49971
+ \u2717 ${error48?.message || String(error48)}
49972
+ `));
49973
+ process.exit(1);
49974
+ }
49975
+ }));
48944
49976
  hideCommand(program2.command("daemon:stop").description("Stop ADHDev Daemon").action(async () => {
48945
49977
  const { stopDaemon: stopDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
48946
49978
  if (stopDaemon2()) {
@@ -49103,15 +50135,15 @@ var import_chalk6 = __toESM(require("chalk"));
49103
50135
  var import_child_process12 = require("child_process");
49104
50136
  var fs18 = __toESM(require("fs"));
49105
50137
  var os23 = __toESM(require("os"));
49106
- var path23 = __toESM(require("path"));
50138
+ var path24 = __toESM(require("path"));
49107
50139
  init_src();
49108
50140
  init_session_host();
49109
50141
  function resolvePackageRoot() {
49110
- return path23.resolve(__dirname, "..", "..");
50142
+ return path24.resolve(__dirname, "..", "..");
49111
50143
  }
49112
50144
  function isLinkedInstall(packageRoot) {
49113
- const normalized = path23.normalize(packageRoot);
49114
- return !normalized.includes(`${path23.sep}node_modules${path23.sep}adhdev`);
50145
+ const normalized = path24.normalize(packageRoot);
50146
+ return !normalized.includes(`${path24.sep}node_modules${path24.sep}adhdev`);
49115
50147
  }
49116
50148
  function formatCheck(check2) {
49117
50149
  const icon = check2.ok ? import_chalk6.default.green("\u2713") : import_chalk6.default.red("\u2717");
@@ -49165,8 +50197,8 @@ function probeNodeDatachannel(packageRoot) {
49165
50197
  }
49166
50198
  }
49167
50199
  function probeConfigAccess() {
49168
- const configDir = path23.join(os23.homedir(), ".adhdev");
49169
- const configPath = path23.join(configDir, "config.json");
50200
+ const configDir = path24.join(os23.homedir(), ".adhdev");
50201
+ const configPath = path24.join(configDir, "config.json");
49170
50202
  const checks = [];
49171
50203
  try {
49172
50204
  fs18.mkdirSync(configDir, { recursive: true });
@@ -49206,7 +50238,7 @@ function probeConfigAccess() {
49206
50238
  fatal: true
49207
50239
  });
49208
50240
  }
49209
- const probePath = path23.join(configDir, `.doctor-write-${process.pid}-${Date.now()}.tmp`);
50241
+ const probePath = path24.join(configDir, `.doctor-write-${process.pid}-${Date.now()}.tmp`);
49210
50242
  try {
49211
50243
  fs18.writeFileSync(probePath, "ok", "utf-8");
49212
50244
  fs18.rmSync(probePath, { force: true });
@@ -49374,7 +50406,7 @@ function registerDoctorCommands(program2, pkgVersion3) {
49374
50406
  const failures = checks.filter((check2) => !check2.ok && check2.fatal);
49375
50407
  const warnings = checks.filter((check2) => !check2.ok && !check2.fatal);
49376
50408
  const logHints = readLogHints(logPath);
49377
- const sessionHostLogPath = path23.join(os23.homedir(), ".adhdev", "logs", "session-host.log");
50409
+ const sessionHostLogPath = path24.join(os23.homedir(), ".adhdev", "logs", "session-host.log");
49378
50410
  console.log(import_chalk6.default.bold("\n\u{1FA7A} ADHDev Doctor\n"));
49379
50411
  console.log(import_chalk6.default.gray(` Version: ${pkgVersion3}`));
49380
50412
  console.log(import_chalk6.default.gray(` Platform: ${process.platform} ${process.arch}`));
@@ -49694,7 +50726,7 @@ function registerProviderCommands(program2) {
49694
50726
  let processNames = {};
49695
50727
  if (category === "ide") {
49696
50728
  const fs19 = await import("fs");
49697
- const path24 = await import("path");
50729
+ const path25 = await import("path");
49698
50730
  const os24 = await import("os");
49699
50731
  if (os24.platform() === "darwin") {
49700
50732
  while (true) {
@@ -49707,7 +50739,7 @@ function registerProviderCommands(program2) {
49707
50739
  }
49708
50740
  console.log(import_chalk7.default.green(` \u2713 Path verified: ${p}`));
49709
50741
  osPaths["darwin"] = [p];
49710
- processNames["darwin"] = path24.basename(p, ".app");
50742
+ processNames["darwin"] = path25.basename(p, ".app");
49711
50743
  break;
49712
50744
  }
49713
50745
  } else if (os24.platform() === "win32") {
@@ -49721,7 +50753,7 @@ function registerProviderCommands(program2) {
49721
50753
  }
49722
50754
  console.log(import_chalk7.default.green(` \u2713 Path verified: ${p}`));
49723
50755
  osPaths["win32"] = [p];
49724
- processNames["win32"] = path24.basename(p, ".exe");
50756
+ processNames["win32"] = path25.basename(p, ".exe");
49725
50757
  break;
49726
50758
  }
49727
50759
  }