adhdev 0.8.25 → 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) {
@@ -4820,7 +4852,7 @@ async function handleSendChat(h, args) {
4820
4852
  if (isExtensionTransport(transport)) {
4821
4853
  _log(`Extension: ${provider?.type || "unknown_extension"}`);
4822
4854
  try {
4823
- const evalResult = await h.evaluateProviderScript("sendMessage", { MESSAGE: text }, 3e4);
4855
+ const evalResult = await h.evaluateProviderScript("sendMessage", { message: text }, 3e4);
4824
4856
  if (evalResult?.result) {
4825
4857
  const parsed = parseMaybeJson(evalResult.result);
4826
4858
  if (didProviderConfirmSend(parsed)) {
@@ -4851,7 +4883,7 @@ async function handleSendChat(h, args) {
4851
4883
  return { success: false, error: `CDP for ${managerKey || "unknown"} not connected` };
4852
4884
  }
4853
4885
  _log(`Targeting IDE: ${getCurrentManagerKey(h)}`);
4854
- const sendScript = h.getProviderScript("sendMessage", { MESSAGE: text });
4886
+ const sendScript = h.getProviderScript("sendMessage", { message: text });
4855
4887
  if (sendScript) {
4856
4888
  try {
4857
4889
  const result = await targetCdp.evaluate(sendScript, 3e4);
@@ -5859,10 +5891,10 @@ function getCliScriptCommand(payload) {
5859
5891
  }
5860
5892
  const command = payload.command;
5861
5893
  if (!command || typeof command !== "object") return null;
5862
- if (command.type !== "send_message") return null;
5894
+ if (command.type !== "send_message" && command.type !== "pty_write") return null;
5863
5895
  const text = typeof command.text === "string" ? command.text.trim() : typeof command.message === "string" ? command.message.trim() : "";
5864
5896
  if (!text) return null;
5865
- return { type: "send_message", text };
5897
+ return { type: command.type, text };
5866
5898
  }
5867
5899
  function applyProviderPatch(h, args, payload) {
5868
5900
  if (!payload || typeof payload !== "object") return;
@@ -5903,6 +5935,8 @@ async function executeProviderScript(h, args, scriptName) {
5903
5935
  const cliCommand = getCliScriptCommand(parsed.payload);
5904
5936
  if (cliCommand?.type === "send_message" && cliCommand.text) {
5905
5937
  await adapter.sendMessage(cliCommand.text);
5938
+ } else if (cliCommand?.type === "pty_write" && cliCommand.text && adapter.writeRaw) {
5939
+ adapter.writeRaw(cliCommand.text + "\r");
5906
5940
  }
5907
5941
  applyProviderPatch(h, args, parsed.payload);
5908
5942
  return { success: true, ...parsed.payload && typeof parsed.payload === "object" ? parsed.payload : { result: parsed.payload } };
@@ -6293,9 +6327,26 @@ var init_handler = __esm({
6293
6327
  if (provider?.scripts) {
6294
6328
  const fn = provider.scripts[scriptName];
6295
6329
  if (typeof fn === "function") {
6296
- const firstVal = params ? Object.values(params)[0] : void 0;
6297
- const script = firstVal ? fn(firstVal) : fn();
6298
- 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
+ }
6299
6350
  }
6300
6351
  }
6301
6352
  return null;
@@ -6940,6 +6991,86 @@ var init_terminal_screen = __esm({
6940
6991
  });
6941
6992
 
6942
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
+ }
6943
7074
  function getDefaultSessionHostEndpoint(appName = "adhdev") {
6944
7075
  if (process.platform === "win32") {
6945
7076
  return {
@@ -6971,6 +7102,16 @@ function createLineParser(onEnvelope) {
6971
7102
  }
6972
7103
  };
6973
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
+ }
6974
7115
  function sanitizeSpawnEnv(baseEnv, overrides) {
6975
7116
  const env = {};
6976
7117
  const source = { ...baseEnv, ...overrides || {} };
@@ -7014,14 +7155,16 @@ function ensureNodePtySpawnHelperPermissions(logFn) {
7014
7155
  } catch {
7015
7156
  }
7016
7157
  }
7017
- 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;
7018
7159
  var init_dist = __esm({
7019
7160
  "../../oss/packages/session-host-core/dist/index.mjs"() {
7020
7161
  "use strict";
7162
+ import_crypto3 = require("crypto");
7163
+ path7 = __toESM(require("path"), 1);
7021
7164
  os7 = __toESM(require("os"), 1);
7022
7165
  path22 = __toESM(require("path"), 1);
7023
7166
  net = __toESM(require("net"), 1);
7024
- import_crypto3 = require("crypto");
7167
+ import_crypto4 = require("crypto");
7025
7168
  os22 = __toESM(require("os"), 1);
7026
7169
  path32 = __toESM(require("path"), 1);
7027
7170
  __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -7030,6 +7173,278 @@ var init_dist = __esm({
7030
7173
  if (typeof require !== "undefined") return require.apply(this, arguments);
7031
7174
  throw Error('Dynamic require of "' + x + '" is not supported');
7032
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
+ };
7033
7448
  SessionHostClient = class {
7034
7449
  endpoint;
7035
7450
  socket = null;
@@ -7089,7 +7504,7 @@ var init_dist = __esm({
7089
7504
  async request(request) {
7090
7505
  await this.connect();
7091
7506
  if (!this.socket) throw new Error("Session host socket unavailable");
7092
- const requestId = (0, import_crypto3.randomUUID)();
7507
+ const requestId = (0, import_crypto4.randomUUID)();
7093
7508
  const envelope = {
7094
7509
  kind: "request",
7095
7510
  requestId,
@@ -7303,7 +7718,7 @@ function findBinary(name) {
7303
7718
  }
7304
7719
  }
7305
7720
  function isScriptBinary(binaryPath) {
7306
- if (!path7.isAbsolute(binaryPath)) return false;
7721
+ if (!path8.isAbsolute(binaryPath)) return false;
7307
7722
  try {
7308
7723
  const fs19 = require("fs");
7309
7724
  const resolved = fs19.realpathSync(binaryPath);
@@ -7319,7 +7734,7 @@ function isScriptBinary(binaryPath) {
7319
7734
  }
7320
7735
  }
7321
7736
  function looksLikeMachOOrElf(filePath) {
7322
- if (!path7.isAbsolute(filePath)) return false;
7737
+ if (!path8.isAbsolute(filePath)) return false;
7323
7738
  try {
7324
7739
  const fs19 = require("fs");
7325
7740
  const resolved = fs19.realpathSync(filePath);
@@ -7443,12 +7858,12 @@ function normalizeCliProviderForRuntime(raw) {
7443
7858
  }
7444
7859
  };
7445
7860
  }
7446
- var os9, path7, import_child_process4, buildCliSpawnEnv, ProviderCliAdapter;
7861
+ var os9, path8, import_child_process4, buildCliSpawnEnv, ProviderCliAdapter;
7447
7862
  var init_provider_cli_adapter = __esm({
7448
7863
  "../../oss/packages/daemon-core/src/cli-adapters/provider-cli-adapter.ts"() {
7449
7864
  "use strict";
7450
7865
  os9 = __toESM(require("os"));
7451
- path7 = __toESM(require("path"));
7866
+ path8 = __toESM(require("path"));
7452
7867
  import_child_process4 = require("child_process");
7453
7868
  init_logger();
7454
7869
  init_terminal_screen();
@@ -7810,9 +8225,9 @@ var init_provider_cli_adapter = __esm({
7810
8225
  this.resetTraceSession();
7811
8226
  let shellCmd;
7812
8227
  let shellArgs;
7813
- 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));
7814
8229
  const isCmdShim = isWin && /\.(cmd|bat)$/i.test(binaryPath);
7815
- const useShellWin = !!spawnConfig.shell || isCmdShim || !path7.isAbsolute(binaryPath) || isScriptBinary(binaryPath);
8230
+ const useShellWin = !!spawnConfig.shell || isCmdShim || !path8.isAbsolute(binaryPath) || isScriptBinary(binaryPath);
7816
8231
  const useShell = isWin ? useShellWin : useShellUnix;
7817
8232
  if (useShell) {
7818
8233
  if (!spawnConfig.shell && !isWin) {
@@ -9220,7 +9635,7 @@ ${data.message || ""}`.trim();
9220
9635
  // ../../oss/packages/daemon-core/src/providers/cli-provider-instance.ts
9221
9636
  function getDatabaseSync() {
9222
9637
  if (CachedDatabaseSync) return CachedDatabaseSync;
9223
- 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"));
9224
9639
  const sqliteModule = requireFn(`node:${"sqlite"}`);
9225
9640
  CachedDatabaseSync = sqliteModule.DatabaseSync;
9226
9641
  if (!CachedDatabaseSync) {
@@ -9228,12 +9643,12 @@ function getDatabaseSync() {
9228
9643
  }
9229
9644
  return CachedDatabaseSync;
9230
9645
  }
9231
- var os10, path8, crypto3, fs5, import_node_module, CachedDatabaseSync, CliProviderInstance;
9646
+ var os10, path9, crypto3, fs5, import_node_module, CachedDatabaseSync, CliProviderInstance;
9232
9647
  var init_cli_provider_instance = __esm({
9233
9648
  "../../oss/packages/daemon-core/src/providers/cli-provider-instance.ts"() {
9234
9649
  "use strict";
9235
9650
  os10 = __toESM(require("os"));
9236
- path8 = __toESM(require("path"));
9651
+ path9 = __toESM(require("path"));
9237
9652
  crypto3 = __toESM(require("crypto"));
9238
9653
  fs5 = __toESM(require("fs"));
9239
9654
  import_node_module = require("module");
@@ -9300,6 +9715,7 @@ var init_cli_provider_instance = __esm({
9300
9715
  this.detectStatusTransition();
9301
9716
  });
9302
9717
  await this.adapter.spawn();
9718
+ this.maybeAppendRuntimeRecoveryMessage(this.adapter.getRuntimeMetadata());
9303
9719
  if (this.providerSessionId) {
9304
9720
  const restoredHistory = readChatHistory(this.type, 0, 200, this.providerSessionId);
9305
9721
  if (restoredHistory.messages.length > 0) {
@@ -9394,6 +9810,7 @@ var init_cli_provider_instance = __esm({
9394
9810
  this.promoteProviderSessionId(parsedProviderSessionId);
9395
9811
  }
9396
9812
  const runtime = this.adapter.getRuntimeMetadata();
9813
+ this.maybeAppendRuntimeRecoveryMessage(runtime);
9397
9814
  const parsedMessages = Array.isArray(parsedStatus?.messages) ? parsedStatus.messages : [];
9398
9815
  const controlValues = extractProviderControlValues(this.provider.controls, parsedStatus);
9399
9816
  if (controlValues) {
@@ -9720,6 +10137,28 @@ ${effect.notification.body || ""}`.trim();
9720
10137
  const pad = (value) => String(value).padStart(2, "0");
9721
10138
  return `${date5.getFullYear()}-${pad(date5.getMonth() + 1)}-${pad(date5.getDate())} ${pad(date5.getHours())}:${pad(date5.getMinutes())}:${pad(date5.getSeconds())}`;
9722
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
+ }
9723
10162
  appendRuntimeSystemMessage(content, dedupKey, receivedAt = Date.now()) {
9724
10163
  const normalizedContent = String(content || "").trim();
9725
10164
  if (!normalizedContent) return;
@@ -10078,10 +10517,10 @@ function mergeDefs(...defs) {
10078
10517
  function cloneDef(schema) {
10079
10518
  return mergeDefs(schema._zod.def);
10080
10519
  }
10081
- function getElementAtPath(obj, path24) {
10082
- if (!path24)
10520
+ function getElementAtPath(obj, path25) {
10521
+ if (!path25)
10083
10522
  return obj;
10084
- return path24.reduce((acc, key) => acc?.[key], obj);
10523
+ return path25.reduce((acc, key) => acc?.[key], obj);
10085
10524
  }
10086
10525
  function promiseAllObject(promisesObj) {
10087
10526
  const keys = Object.keys(promisesObj);
@@ -10393,11 +10832,11 @@ function aborted(x, startIndex = 0) {
10393
10832
  }
10394
10833
  return false;
10395
10834
  }
10396
- function prefixIssues(path24, issues) {
10835
+ function prefixIssues(path25, issues) {
10397
10836
  return issues.map((iss) => {
10398
10837
  var _a2;
10399
10838
  (_a2 = iss).path ?? (_a2.path = []);
10400
- iss.path.unshift(path24);
10839
+ iss.path.unshift(path25);
10401
10840
  return iss;
10402
10841
  });
10403
10842
  }
@@ -10640,7 +11079,7 @@ function formatError(error48, mapper = (issue2) => issue2.message) {
10640
11079
  }
10641
11080
  function treeifyError(error48, mapper = (issue2) => issue2.message) {
10642
11081
  const result = { errors: [] };
10643
- const processError = (error49, path24 = []) => {
11082
+ const processError = (error49, path25 = []) => {
10644
11083
  var _a2, _b;
10645
11084
  for (const issue2 of error49.issues) {
10646
11085
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -10650,7 +11089,7 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
10650
11089
  } else if (issue2.code === "invalid_element") {
10651
11090
  processError({ issues: issue2.issues }, issue2.path);
10652
11091
  } else {
10653
- const fullpath = [...path24, ...issue2.path];
11092
+ const fullpath = [...path25, ...issue2.path];
10654
11093
  if (fullpath.length === 0) {
10655
11094
  result.errors.push(mapper(issue2));
10656
11095
  continue;
@@ -10682,8 +11121,8 @@ function treeifyError(error48, mapper = (issue2) => issue2.message) {
10682
11121
  }
10683
11122
  function toDotPath(_path) {
10684
11123
  const segs = [];
10685
- const path24 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
10686
- for (const seg of path24) {
11124
+ const path25 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
11125
+ for (const seg of path25) {
10687
11126
  if (typeof seg === "number")
10688
11127
  segs.push(`[${seg}]`);
10689
11128
  else if (typeof seg === "symbol")
@@ -23447,13 +23886,13 @@ function resolveRef(ref, ctx) {
23447
23886
  if (!ref.startsWith("#")) {
23448
23887
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
23449
23888
  }
23450
- const path24 = ref.slice(1).split("/").filter(Boolean);
23451
- if (path24.length === 0) {
23889
+ const path25 = ref.slice(1).split("/").filter(Boolean);
23890
+ if (path25.length === 0) {
23452
23891
  return ctx.rootSchema;
23453
23892
  }
23454
23893
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
23455
- if (path24[0] === defsKey) {
23456
- const key = path24[1];
23894
+ if (path25[0] === defsKey) {
23895
+ const key = path25[1];
23457
23896
  if (!key || !ctx.defs[key]) {
23458
23897
  throw new Error(`Reference not found: ${ref}`);
23459
23898
  }
@@ -27146,12 +27585,12 @@ function resolveCliSessionBinding(provider, normalizedType, cliArgs, requestedRe
27146
27585
  launchMode: "new"
27147
27586
  };
27148
27587
  }
27149
- var os11, path9, crypto4, import_chalk, chalkApi, DaemonCliManager;
27588
+ var os11, path10, crypto4, import_chalk, chalkApi, DaemonCliManager;
27150
27589
  var init_cli_manager = __esm({
27151
27590
  "../../oss/packages/daemon-core/src/commands/cli-manager.ts"() {
27152
27591
  "use strict";
27153
27592
  os11 = __toESM(require("os"));
27154
- path9 = __toESM(require("path"));
27593
+ path10 = __toESM(require("path"));
27155
27594
  crypto4 = __toESM(require("crypto"));
27156
27595
  import_chalk = __toESM(require("chalk"));
27157
27596
  init_provider_cli_adapter();
@@ -27303,7 +27742,7 @@ var init_cli_manager = __esm({
27303
27742
  async startSession(cliType, workingDir, cliArgs, initialModel, options) {
27304
27743
  const trimmed = (workingDir || "").trim();
27305
27744
  if (!trimmed) throw new Error("working directory required");
27306
- const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os11.homedir()) : path9.resolve(trimmed);
27745
+ const resolvedDir = trimmed.startsWith("~") ? trimmed.replace(/^~/, os11.homedir()) : path10.resolve(trimmed);
27307
27746
  const normalizedType = this.providerLoader.resolveAlias(cliType);
27308
27747
  const provider = this.providerLoader.getByAlias(cliType);
27309
27748
  const key = crypto4.randomUUID();
@@ -27855,7 +28294,7 @@ var init_readdirp = __esm({
27855
28294
  this._directoryFilter = normalizeFilter(opts.directoryFilter);
27856
28295
  const statMethod = opts.lstat ? import_promises.lstat : import_promises.stat;
27857
28296
  if (wantBigintFsStats) {
27858
- this._stat = (path24) => statMethod(path24, { bigint: true });
28297
+ this._stat = (path25) => statMethod(path25, { bigint: true });
27859
28298
  } else {
27860
28299
  this._stat = statMethod;
27861
28300
  }
@@ -27880,8 +28319,8 @@ var init_readdirp = __esm({
27880
28319
  const par = this.parent;
27881
28320
  const fil = par && par.files;
27882
28321
  if (fil && fil.length > 0) {
27883
- const { path: path24, depth } = par;
27884
- 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));
27885
28324
  const awaited = await Promise.all(slice);
27886
28325
  for (const entry of awaited) {
27887
28326
  if (!entry)
@@ -27921,21 +28360,21 @@ var init_readdirp = __esm({
27921
28360
  this.reading = false;
27922
28361
  }
27923
28362
  }
27924
- async _exploreDir(path24, depth) {
28363
+ async _exploreDir(path25, depth) {
27925
28364
  let files;
27926
28365
  try {
27927
- files = await (0, import_promises.readdir)(path24, this._rdOptions);
28366
+ files = await (0, import_promises.readdir)(path25, this._rdOptions);
27928
28367
  } catch (error48) {
27929
28368
  this._onError(error48);
27930
28369
  }
27931
- return { files, depth, path: path24 };
28370
+ return { files, depth, path: path25 };
27932
28371
  }
27933
- async _formatEntry(dirent, path24) {
28372
+ async _formatEntry(dirent, path25) {
27934
28373
  let entry;
27935
- const basename7 = this._isDirent ? dirent.name : dirent;
28374
+ const basename8 = this._isDirent ? dirent.name : dirent;
27936
28375
  try {
27937
- const fullPath = (0, import_node_path.resolve)((0, import_node_path.join)(path24, basename7));
27938
- 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 };
27939
28378
  entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
27940
28379
  } catch (err) {
27941
28380
  this._onError(err);
@@ -27991,16 +28430,16 @@ var init_readdirp = __esm({
27991
28430
  });
27992
28431
 
27993
28432
  // ../../oss/packages/daemon-core/node_modules/chokidar/handler.js
27994
- function createFsWatchInstance(path24, options, listener, errHandler, emitRaw) {
28433
+ function createFsWatchInstance(path25, options, listener, errHandler, emitRaw) {
27995
28434
  const handleEvent = (rawEvent, evPath) => {
27996
- listener(path24);
27997
- emitRaw(rawEvent, evPath, { watchedPath: path24 });
27998
- if (evPath && path24 !== evPath) {
27999
- 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));
28000
28439
  }
28001
28440
  };
28002
28441
  try {
28003
- return (0, import_node_fs.watch)(path24, {
28442
+ return (0, import_node_fs.watch)(path25, {
28004
28443
  persistent: options.persistent
28005
28444
  }, handleEvent);
28006
28445
  } catch (error48) {
@@ -28349,12 +28788,12 @@ var init_handler2 = __esm({
28349
28788
  listener(val1, val2, val3);
28350
28789
  });
28351
28790
  };
28352
- setFsWatchListener = (path24, fullPath, options, handlers) => {
28791
+ setFsWatchListener = (path25, fullPath, options, handlers) => {
28353
28792
  const { listener, errHandler, rawEmitter } = handlers;
28354
28793
  let cont = FsWatchInstances.get(fullPath);
28355
28794
  let watcher;
28356
28795
  if (!options.persistent) {
28357
- watcher = createFsWatchInstance(path24, options, listener, errHandler, rawEmitter);
28796
+ watcher = createFsWatchInstance(path25, options, listener, errHandler, rawEmitter);
28358
28797
  if (!watcher)
28359
28798
  return;
28360
28799
  return watcher.close.bind(watcher);
@@ -28365,7 +28804,7 @@ var init_handler2 = __esm({
28365
28804
  addAndConvert(cont, KEY_RAW, rawEmitter);
28366
28805
  } else {
28367
28806
  watcher = createFsWatchInstance(
28368
- path24,
28807
+ path25,
28369
28808
  options,
28370
28809
  fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
28371
28810
  errHandler,
@@ -28380,7 +28819,7 @@ var init_handler2 = __esm({
28380
28819
  cont.watcherUnusable = true;
28381
28820
  if (isWindows && error48.code === "EPERM") {
28382
28821
  try {
28383
- const fd = await (0, import_promises2.open)(path24, "r");
28822
+ const fd = await (0, import_promises2.open)(path25, "r");
28384
28823
  await fd.close();
28385
28824
  broadcastErr(error48);
28386
28825
  } catch (err) {
@@ -28411,7 +28850,7 @@ var init_handler2 = __esm({
28411
28850
  };
28412
28851
  };
28413
28852
  FsWatchFileInstances = /* @__PURE__ */ new Map();
28414
- setFsWatchFileListener = (path24, fullPath, options, handlers) => {
28853
+ setFsWatchFileListener = (path25, fullPath, options, handlers) => {
28415
28854
  const { listener, rawEmitter } = handlers;
28416
28855
  let cont = FsWatchFileInstances.get(fullPath);
28417
28856
  const copts = cont && cont.options;
@@ -28433,7 +28872,7 @@ var init_handler2 = __esm({
28433
28872
  });
28434
28873
  const currmtime = curr.mtimeMs;
28435
28874
  if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
28436
- foreach(cont.listeners, (listener2) => listener2(path24, curr));
28875
+ foreach(cont.listeners, (listener2) => listener2(path25, curr));
28437
28876
  }
28438
28877
  })
28439
28878
  };
@@ -28463,13 +28902,13 @@ var init_handler2 = __esm({
28463
28902
  * @param listener on fs change
28464
28903
  * @returns closer for the watcher instance
28465
28904
  */
28466
- _watchWithNodeFs(path24, listener) {
28905
+ _watchWithNodeFs(path25, listener) {
28467
28906
  const opts = this.fsw.options;
28468
- const directory = sp.dirname(path24);
28469
- const basename7 = sp.basename(path24);
28907
+ const directory = sp.dirname(path25);
28908
+ const basename8 = sp.basename(path25);
28470
28909
  const parent = this.fsw._getWatchedDir(directory);
28471
- parent.add(basename7);
28472
- const absolutePath = sp.resolve(path24);
28910
+ parent.add(basename8);
28911
+ const absolutePath = sp.resolve(path25);
28473
28912
  const options = {
28474
28913
  persistent: opts.persistent
28475
28914
  };
@@ -28478,13 +28917,13 @@ var init_handler2 = __esm({
28478
28917
  let closer;
28479
28918
  if (opts.usePolling) {
28480
28919
  const enableBin = opts.interval !== opts.binaryInterval;
28481
- options.interval = enableBin && isBinaryPath(basename7) ? opts.binaryInterval : opts.interval;
28482
- closer = setFsWatchFileListener(path24, absolutePath, options, {
28920
+ options.interval = enableBin && isBinaryPath(basename8) ? opts.binaryInterval : opts.interval;
28921
+ closer = setFsWatchFileListener(path25, absolutePath, options, {
28483
28922
  listener,
28484
28923
  rawEmitter: this.fsw._emitRaw
28485
28924
  });
28486
28925
  } else {
28487
- closer = setFsWatchListener(path24, absolutePath, options, {
28926
+ closer = setFsWatchListener(path25, absolutePath, options, {
28488
28927
  listener,
28489
28928
  errHandler: this._boundHandleError,
28490
28929
  rawEmitter: this.fsw._emitRaw
@@ -28501,12 +28940,12 @@ var init_handler2 = __esm({
28501
28940
  return;
28502
28941
  }
28503
28942
  const dirname9 = sp.dirname(file2);
28504
- const basename7 = sp.basename(file2);
28943
+ const basename8 = sp.basename(file2);
28505
28944
  const parent = this.fsw._getWatchedDir(dirname9);
28506
28945
  let prevStats = stats;
28507
- if (parent.has(basename7))
28946
+ if (parent.has(basename8))
28508
28947
  return;
28509
- const listener = async (path24, newStats) => {
28948
+ const listener = async (path25, newStats) => {
28510
28949
  if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file2, 5))
28511
28950
  return;
28512
28951
  if (!newStats || newStats.mtimeMs === 0) {
@@ -28520,18 +28959,18 @@ var init_handler2 = __esm({
28520
28959
  this.fsw._emit(EV.CHANGE, file2, newStats2);
28521
28960
  }
28522
28961
  if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats2.ino) {
28523
- this.fsw._closeFile(path24);
28962
+ this.fsw._closeFile(path25);
28524
28963
  prevStats = newStats2;
28525
28964
  const closer2 = this._watchWithNodeFs(file2, listener);
28526
28965
  if (closer2)
28527
- this.fsw._addPathCloser(path24, closer2);
28966
+ this.fsw._addPathCloser(path25, closer2);
28528
28967
  } else {
28529
28968
  prevStats = newStats2;
28530
28969
  }
28531
28970
  } catch (error48) {
28532
- this.fsw._remove(dirname9, basename7);
28971
+ this.fsw._remove(dirname9, basename8);
28533
28972
  }
28534
- } else if (parent.has(basename7)) {
28973
+ } else if (parent.has(basename8)) {
28535
28974
  const at = newStats.atimeMs;
28536
28975
  const mt = newStats.mtimeMs;
28537
28976
  if (!at || at <= mt || mt !== prevStats.mtimeMs) {
@@ -28556,7 +28995,7 @@ var init_handler2 = __esm({
28556
28995
  * @param item basename of this item
28557
28996
  * @returns true if no more processing is needed for this entry.
28558
28997
  */
28559
- async _handleSymlink(entry, directory, path24, item) {
28998
+ async _handleSymlink(entry, directory, path25, item) {
28560
28999
  if (this.fsw.closed) {
28561
29000
  return;
28562
29001
  }
@@ -28566,7 +29005,7 @@ var init_handler2 = __esm({
28566
29005
  this.fsw._incrReadyCount();
28567
29006
  let linkPath;
28568
29007
  try {
28569
- linkPath = await (0, import_promises2.realpath)(path24);
29008
+ linkPath = await (0, import_promises2.realpath)(path25);
28570
29009
  } catch (e) {
28571
29010
  this.fsw._emitReady();
28572
29011
  return true;
@@ -28576,12 +29015,12 @@ var init_handler2 = __esm({
28576
29015
  if (dir.has(item)) {
28577
29016
  if (this.fsw._symlinkPaths.get(full) !== linkPath) {
28578
29017
  this.fsw._symlinkPaths.set(full, linkPath);
28579
- this.fsw._emit(EV.CHANGE, path24, entry.stats);
29018
+ this.fsw._emit(EV.CHANGE, path25, entry.stats);
28580
29019
  }
28581
29020
  } else {
28582
29021
  dir.add(item);
28583
29022
  this.fsw._symlinkPaths.set(full, linkPath);
28584
- this.fsw._emit(EV.ADD, path24, entry.stats);
29023
+ this.fsw._emit(EV.ADD, path25, entry.stats);
28585
29024
  }
28586
29025
  this.fsw._emitReady();
28587
29026
  return true;
@@ -28611,9 +29050,9 @@ var init_handler2 = __esm({
28611
29050
  return;
28612
29051
  }
28613
29052
  const item = entry.path;
28614
- let path24 = sp.join(directory, item);
29053
+ let path25 = sp.join(directory, item);
28615
29054
  current.add(item);
28616
- if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path24, item)) {
29055
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path25, item)) {
28617
29056
  return;
28618
29057
  }
28619
29058
  if (this.fsw.closed) {
@@ -28622,8 +29061,8 @@ var init_handler2 = __esm({
28622
29061
  }
28623
29062
  if (item === target || !target && !previous.has(item)) {
28624
29063
  this.fsw._incrReadyCount();
28625
- path24 = sp.join(dir, sp.relative(dir, path24));
28626
- this._addToNodeFs(path24, initialAdd, wh, depth + 1);
29064
+ path25 = sp.join(dir, sp.relative(dir, path25));
29065
+ this._addToNodeFs(path25, initialAdd, wh, depth + 1);
28627
29066
  }
28628
29067
  }).on(EV.ERROR, this._boundHandleError);
28629
29068
  return new Promise((resolve14, reject) => {
@@ -28692,13 +29131,13 @@ var init_handler2 = __esm({
28692
29131
  * @param depth Child path actually targeted for watch
28693
29132
  * @param target Child path actually targeted for watch
28694
29133
  */
28695
- async _addToNodeFs(path24, initialAdd, priorWh, depth, target) {
29134
+ async _addToNodeFs(path25, initialAdd, priorWh, depth, target) {
28696
29135
  const ready = this.fsw._emitReady;
28697
- if (this.fsw._isIgnored(path24) || this.fsw.closed) {
29136
+ if (this.fsw._isIgnored(path25) || this.fsw.closed) {
28698
29137
  ready();
28699
29138
  return false;
28700
29139
  }
28701
- const wh = this.fsw._getWatchHelpers(path24);
29140
+ const wh = this.fsw._getWatchHelpers(path25);
28702
29141
  if (priorWh) {
28703
29142
  wh.filterPath = (entry) => priorWh.filterPath(entry);
28704
29143
  wh.filterDir = (entry) => priorWh.filterDir(entry);
@@ -28714,8 +29153,8 @@ var init_handler2 = __esm({
28714
29153
  const follow = this.fsw.options.followSymlinks;
28715
29154
  let closer;
28716
29155
  if (stats.isDirectory()) {
28717
- const absPath = sp.resolve(path24);
28718
- 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;
28719
29158
  if (this.fsw.closed)
28720
29159
  return;
28721
29160
  closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
@@ -28725,29 +29164,29 @@ var init_handler2 = __esm({
28725
29164
  this.fsw._symlinkPaths.set(absPath, targetPath);
28726
29165
  }
28727
29166
  } else if (stats.isSymbolicLink()) {
28728
- const targetPath = follow ? await (0, import_promises2.realpath)(path24) : path24;
29167
+ const targetPath = follow ? await (0, import_promises2.realpath)(path25) : path25;
28729
29168
  if (this.fsw.closed)
28730
29169
  return;
28731
29170
  const parent = sp.dirname(wh.watchPath);
28732
29171
  this.fsw._getWatchedDir(parent).add(wh.watchPath);
28733
29172
  this.fsw._emit(EV.ADD, wh.watchPath, stats);
28734
- closer = await this._handleDir(parent, stats, initialAdd, depth, path24, wh, targetPath);
29173
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path25, wh, targetPath);
28735
29174
  if (this.fsw.closed)
28736
29175
  return;
28737
29176
  if (targetPath !== void 0) {
28738
- this.fsw._symlinkPaths.set(sp.resolve(path24), targetPath);
29177
+ this.fsw._symlinkPaths.set(sp.resolve(path25), targetPath);
28739
29178
  }
28740
29179
  } else {
28741
29180
  closer = this._handleFile(wh.watchPath, stats, initialAdd);
28742
29181
  }
28743
29182
  ready();
28744
29183
  if (closer)
28745
- this.fsw._addPathCloser(path24, closer);
29184
+ this.fsw._addPathCloser(path25, closer);
28746
29185
  return false;
28747
29186
  } catch (error48) {
28748
29187
  if (this.fsw._handleError(error48)) {
28749
29188
  ready();
28750
- return path24;
29189
+ return path25;
28751
29190
  }
28752
29191
  }
28753
29192
  }
@@ -28782,24 +29221,24 @@ function createPattern(matcher) {
28782
29221
  }
28783
29222
  return () => false;
28784
29223
  }
28785
- function normalizePath(path24) {
28786
- if (typeof path24 !== "string")
29224
+ function normalizePath(path25) {
29225
+ if (typeof path25 !== "string")
28787
29226
  throw new Error("string expected");
28788
- path24 = sp2.normalize(path24);
28789
- path24 = path24.replace(/\\/g, "/");
29227
+ path25 = sp2.normalize(path25);
29228
+ path25 = path25.replace(/\\/g, "/");
28790
29229
  let prepend = false;
28791
- if (path24.startsWith("//"))
29230
+ if (path25.startsWith("//"))
28792
29231
  prepend = true;
28793
- path24 = path24.replace(DOUBLE_SLASH_RE, "/");
29232
+ path25 = path25.replace(DOUBLE_SLASH_RE, "/");
28794
29233
  if (prepend)
28795
- path24 = "/" + path24;
28796
- return path24;
29234
+ path25 = "/" + path25;
29235
+ return path25;
28797
29236
  }
28798
29237
  function matchPatterns(patterns, testString, stats) {
28799
- const path24 = normalizePath(testString);
29238
+ const path25 = normalizePath(testString);
28800
29239
  for (let index = 0; index < patterns.length; index++) {
28801
29240
  const pattern = patterns[index];
28802
- if (pattern(path24, stats)) {
29241
+ if (pattern(path25, stats)) {
28803
29242
  return true;
28804
29243
  }
28805
29244
  }
@@ -28862,19 +29301,19 @@ var init_chokidar = __esm({
28862
29301
  }
28863
29302
  return str;
28864
29303
  };
28865
- normalizePathToUnix = (path24) => toUnix(sp2.normalize(toUnix(path24)));
28866
- normalizeIgnored = (cwd = "") => (path24) => {
28867
- if (typeof path24 === "string") {
28868
- 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));
28869
29308
  } else {
28870
- return path24;
29309
+ return path25;
28871
29310
  }
28872
29311
  };
28873
- getAbsolutePath = (path24, cwd) => {
28874
- if (sp2.isAbsolute(path24)) {
28875
- return path24;
29312
+ getAbsolutePath = (path25, cwd) => {
29313
+ if (sp2.isAbsolute(path25)) {
29314
+ return path25;
28876
29315
  }
28877
- return sp2.join(cwd, path24);
29316
+ return sp2.join(cwd, path25);
28878
29317
  };
28879
29318
  EMPTY_SET = Object.freeze(/* @__PURE__ */ new Set());
28880
29319
  DirEntry = class {
@@ -28939,10 +29378,10 @@ var init_chokidar = __esm({
28939
29378
  dirParts;
28940
29379
  followSymlinks;
28941
29380
  statMethod;
28942
- constructor(path24, follow, fsw) {
29381
+ constructor(path25, follow, fsw) {
28943
29382
  this.fsw = fsw;
28944
- const watchPath = path24;
28945
- this.path = path24 = path24.replace(REPLACER_RE, "");
29383
+ const watchPath = path25;
29384
+ this.path = path25 = path25.replace(REPLACER_RE, "");
28946
29385
  this.watchPath = watchPath;
28947
29386
  this.fullWatchPath = sp2.resolve(watchPath);
28948
29387
  this.dirParts = [];
@@ -29082,20 +29521,20 @@ var init_chokidar = __esm({
29082
29521
  this._closePromise = void 0;
29083
29522
  let paths = unifyPaths(paths_);
29084
29523
  if (cwd) {
29085
- paths = paths.map((path24) => {
29086
- const absPath = getAbsolutePath(path24, cwd);
29524
+ paths = paths.map((path25) => {
29525
+ const absPath = getAbsolutePath(path25, cwd);
29087
29526
  return absPath;
29088
29527
  });
29089
29528
  }
29090
- paths.forEach((path24) => {
29091
- this._removeIgnoredPath(path24);
29529
+ paths.forEach((path25) => {
29530
+ this._removeIgnoredPath(path25);
29092
29531
  });
29093
29532
  this._userIgnored = void 0;
29094
29533
  if (!this._readyCount)
29095
29534
  this._readyCount = 0;
29096
29535
  this._readyCount += paths.length;
29097
- Promise.all(paths.map(async (path24) => {
29098
- 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);
29099
29538
  if (res)
29100
29539
  this._emitReady();
29101
29540
  return res;
@@ -29117,17 +29556,17 @@ var init_chokidar = __esm({
29117
29556
  return this;
29118
29557
  const paths = unifyPaths(paths_);
29119
29558
  const { cwd } = this.options;
29120
- paths.forEach((path24) => {
29121
- if (!sp2.isAbsolute(path24) && !this._closers.has(path24)) {
29559
+ paths.forEach((path25) => {
29560
+ if (!sp2.isAbsolute(path25) && !this._closers.has(path25)) {
29122
29561
  if (cwd)
29123
- path24 = sp2.join(cwd, path24);
29124
- path24 = sp2.resolve(path24);
29562
+ path25 = sp2.join(cwd, path25);
29563
+ path25 = sp2.resolve(path25);
29125
29564
  }
29126
- this._closePath(path24);
29127
- this._addIgnoredPath(path24);
29128
- if (this._watched.has(path24)) {
29565
+ this._closePath(path25);
29566
+ this._addIgnoredPath(path25);
29567
+ if (this._watched.has(path25)) {
29129
29568
  this._addIgnoredPath({
29130
- path: path24,
29569
+ path: path25,
29131
29570
  recursive: true
29132
29571
  });
29133
29572
  }
@@ -29191,38 +29630,38 @@ var init_chokidar = __esm({
29191
29630
  * @param stats arguments to be passed with event
29192
29631
  * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
29193
29632
  */
29194
- async _emit(event, path24, stats) {
29633
+ async _emit(event, path25, stats) {
29195
29634
  if (this.closed)
29196
29635
  return;
29197
29636
  const opts = this.options;
29198
29637
  if (isWindows)
29199
- path24 = sp2.normalize(path24);
29638
+ path25 = sp2.normalize(path25);
29200
29639
  if (opts.cwd)
29201
- path24 = sp2.relative(opts.cwd, path24);
29202
- const args = [path24];
29640
+ path25 = sp2.relative(opts.cwd, path25);
29641
+ const args = [path25];
29203
29642
  if (stats != null)
29204
29643
  args.push(stats);
29205
29644
  const awf = opts.awaitWriteFinish;
29206
29645
  let pw;
29207
- if (awf && (pw = this._pendingWrites.get(path24))) {
29646
+ if (awf && (pw = this._pendingWrites.get(path25))) {
29208
29647
  pw.lastChange = /* @__PURE__ */ new Date();
29209
29648
  return this;
29210
29649
  }
29211
29650
  if (opts.atomic) {
29212
29651
  if (event === EVENTS.UNLINK) {
29213
- this._pendingUnlinks.set(path24, [event, ...args]);
29652
+ this._pendingUnlinks.set(path25, [event, ...args]);
29214
29653
  setTimeout(() => {
29215
- this._pendingUnlinks.forEach((entry, path25) => {
29654
+ this._pendingUnlinks.forEach((entry, path26) => {
29216
29655
  this.emit(...entry);
29217
29656
  this.emit(EVENTS.ALL, ...entry);
29218
- this._pendingUnlinks.delete(path25);
29657
+ this._pendingUnlinks.delete(path26);
29219
29658
  });
29220
29659
  }, typeof opts.atomic === "number" ? opts.atomic : 100);
29221
29660
  return this;
29222
29661
  }
29223
- if (event === EVENTS.ADD && this._pendingUnlinks.has(path24)) {
29662
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path25)) {
29224
29663
  event = EVENTS.CHANGE;
29225
- this._pendingUnlinks.delete(path24);
29664
+ this._pendingUnlinks.delete(path25);
29226
29665
  }
29227
29666
  }
29228
29667
  if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
@@ -29240,16 +29679,16 @@ var init_chokidar = __esm({
29240
29679
  this.emitWithAll(event, args);
29241
29680
  }
29242
29681
  };
29243
- this._awaitWriteFinish(path24, awf.stabilityThreshold, event, awfEmit);
29682
+ this._awaitWriteFinish(path25, awf.stabilityThreshold, event, awfEmit);
29244
29683
  return this;
29245
29684
  }
29246
29685
  if (event === EVENTS.CHANGE) {
29247
- const isThrottled = !this._throttle(EVENTS.CHANGE, path24, 50);
29686
+ const isThrottled = !this._throttle(EVENTS.CHANGE, path25, 50);
29248
29687
  if (isThrottled)
29249
29688
  return this;
29250
29689
  }
29251
29690
  if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
29252
- const fullPath = opts.cwd ? sp2.join(opts.cwd, path24) : path24;
29691
+ const fullPath = opts.cwd ? sp2.join(opts.cwd, path25) : path25;
29253
29692
  let stats2;
29254
29693
  try {
29255
29694
  stats2 = await (0, import_promises3.stat)(fullPath);
@@ -29280,23 +29719,23 @@ var init_chokidar = __esm({
29280
29719
  * @param timeout duration of time to suppress duplicate actions
29281
29720
  * @returns tracking object or false if action should be suppressed
29282
29721
  */
29283
- _throttle(actionType, path24, timeout) {
29722
+ _throttle(actionType, path25, timeout) {
29284
29723
  if (!this._throttled.has(actionType)) {
29285
29724
  this._throttled.set(actionType, /* @__PURE__ */ new Map());
29286
29725
  }
29287
29726
  const action = this._throttled.get(actionType);
29288
29727
  if (!action)
29289
29728
  throw new Error("invalid throttle");
29290
- const actionPath = action.get(path24);
29729
+ const actionPath = action.get(path25);
29291
29730
  if (actionPath) {
29292
29731
  actionPath.count++;
29293
29732
  return false;
29294
29733
  }
29295
29734
  let timeoutObject;
29296
29735
  const clear = () => {
29297
- const item = action.get(path24);
29736
+ const item = action.get(path25);
29298
29737
  const count = item ? item.count : 0;
29299
- action.delete(path24);
29738
+ action.delete(path25);
29300
29739
  clearTimeout(timeoutObject);
29301
29740
  if (item)
29302
29741
  clearTimeout(item.timeoutObject);
@@ -29304,7 +29743,7 @@ var init_chokidar = __esm({
29304
29743
  };
29305
29744
  timeoutObject = setTimeout(clear, timeout);
29306
29745
  const thr = { timeoutObject, clear, count: 0 };
29307
- action.set(path24, thr);
29746
+ action.set(path25, thr);
29308
29747
  return thr;
29309
29748
  }
29310
29749
  _incrReadyCount() {
@@ -29318,44 +29757,44 @@ var init_chokidar = __esm({
29318
29757
  * @param event
29319
29758
  * @param awfEmit Callback to be called when ready for event to be emitted.
29320
29759
  */
29321
- _awaitWriteFinish(path24, threshold, event, awfEmit) {
29760
+ _awaitWriteFinish(path25, threshold, event, awfEmit) {
29322
29761
  const awf = this.options.awaitWriteFinish;
29323
29762
  if (typeof awf !== "object")
29324
29763
  return;
29325
29764
  const pollInterval = awf.pollInterval;
29326
29765
  let timeoutHandler;
29327
- let fullPath = path24;
29328
- if (this.options.cwd && !sp2.isAbsolute(path24)) {
29329
- 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);
29330
29769
  }
29331
29770
  const now = /* @__PURE__ */ new Date();
29332
29771
  const writes = this._pendingWrites;
29333
29772
  function awaitWriteFinishFn(prevStat) {
29334
29773
  (0, import_node_fs2.stat)(fullPath, (err, curStat) => {
29335
- if (err || !writes.has(path24)) {
29774
+ if (err || !writes.has(path25)) {
29336
29775
  if (err && err.code !== "ENOENT")
29337
29776
  awfEmit(err);
29338
29777
  return;
29339
29778
  }
29340
29779
  const now2 = Number(/* @__PURE__ */ new Date());
29341
29780
  if (prevStat && curStat.size !== prevStat.size) {
29342
- writes.get(path24).lastChange = now2;
29781
+ writes.get(path25).lastChange = now2;
29343
29782
  }
29344
- const pw = writes.get(path24);
29783
+ const pw = writes.get(path25);
29345
29784
  const df = now2 - pw.lastChange;
29346
29785
  if (df >= threshold) {
29347
- writes.delete(path24);
29786
+ writes.delete(path25);
29348
29787
  awfEmit(void 0, curStat);
29349
29788
  } else {
29350
29789
  timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
29351
29790
  }
29352
29791
  });
29353
29792
  }
29354
- if (!writes.has(path24)) {
29355
- writes.set(path24, {
29793
+ if (!writes.has(path25)) {
29794
+ writes.set(path25, {
29356
29795
  lastChange: now,
29357
29796
  cancelWait: () => {
29358
- writes.delete(path24);
29797
+ writes.delete(path25);
29359
29798
  clearTimeout(timeoutHandler);
29360
29799
  return event;
29361
29800
  }
@@ -29366,8 +29805,8 @@ var init_chokidar = __esm({
29366
29805
  /**
29367
29806
  * Determines whether user has asked to ignore this path.
29368
29807
  */
29369
- _isIgnored(path24, stats) {
29370
- if (this.options.atomic && DOT_RE.test(path24))
29808
+ _isIgnored(path25, stats) {
29809
+ if (this.options.atomic && DOT_RE.test(path25))
29371
29810
  return true;
29372
29811
  if (!this._userIgnored) {
29373
29812
  const { cwd } = this.options;
@@ -29377,17 +29816,17 @@ var init_chokidar = __esm({
29377
29816
  const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
29378
29817
  this._userIgnored = anymatch(list, void 0);
29379
29818
  }
29380
- return this._userIgnored(path24, stats);
29819
+ return this._userIgnored(path25, stats);
29381
29820
  }
29382
- _isntIgnored(path24, stat4) {
29383
- return !this._isIgnored(path24, stat4);
29821
+ _isntIgnored(path25, stat4) {
29822
+ return !this._isIgnored(path25, stat4);
29384
29823
  }
29385
29824
  /**
29386
29825
  * Provides a set of common helpers and properties relating to symlink handling.
29387
29826
  * @param path file or directory pattern being watched
29388
29827
  */
29389
- _getWatchHelpers(path24) {
29390
- return new WatchHelper(path24, this.options.followSymlinks, this);
29828
+ _getWatchHelpers(path25) {
29829
+ return new WatchHelper(path25, this.options.followSymlinks, this);
29391
29830
  }
29392
29831
  // Directory helpers
29393
29832
  // -----------------
@@ -29419,63 +29858,63 @@ var init_chokidar = __esm({
29419
29858
  * @param item base path of item/directory
29420
29859
  */
29421
29860
  _remove(directory, item, isDirectory) {
29422
- const path24 = sp2.join(directory, item);
29423
- const fullPath = sp2.resolve(path24);
29424
- isDirectory = isDirectory != null ? isDirectory : this._watched.has(path24) || this._watched.has(fullPath);
29425
- 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))
29426
29865
  return;
29427
29866
  if (!isDirectory && this._watched.size === 1) {
29428
29867
  this.add(directory, item, true);
29429
29868
  }
29430
- const wp = this._getWatchedDir(path24);
29869
+ const wp = this._getWatchedDir(path25);
29431
29870
  const nestedDirectoryChildren = wp.getChildren();
29432
- nestedDirectoryChildren.forEach((nested) => this._remove(path24, nested));
29871
+ nestedDirectoryChildren.forEach((nested) => this._remove(path25, nested));
29433
29872
  const parent = this._getWatchedDir(directory);
29434
29873
  const wasTracked = parent.has(item);
29435
29874
  parent.remove(item);
29436
29875
  if (this._symlinkPaths.has(fullPath)) {
29437
29876
  this._symlinkPaths.delete(fullPath);
29438
29877
  }
29439
- let relPath = path24;
29878
+ let relPath = path25;
29440
29879
  if (this.options.cwd)
29441
- relPath = sp2.relative(this.options.cwd, path24);
29880
+ relPath = sp2.relative(this.options.cwd, path25);
29442
29881
  if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
29443
29882
  const event = this._pendingWrites.get(relPath).cancelWait();
29444
29883
  if (event === EVENTS.ADD)
29445
29884
  return;
29446
29885
  }
29447
- this._watched.delete(path24);
29886
+ this._watched.delete(path25);
29448
29887
  this._watched.delete(fullPath);
29449
29888
  const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
29450
- if (wasTracked && !this._isIgnored(path24))
29451
- this._emit(eventName, path24);
29452
- this._closePath(path24);
29889
+ if (wasTracked && !this._isIgnored(path25))
29890
+ this._emit(eventName, path25);
29891
+ this._closePath(path25);
29453
29892
  }
29454
29893
  /**
29455
29894
  * Closes all watchers for a path
29456
29895
  */
29457
- _closePath(path24) {
29458
- this._closeFile(path24);
29459
- const dir = sp2.dirname(path24);
29460
- 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));
29461
29900
  }
29462
29901
  /**
29463
29902
  * Closes only file-specific watchers
29464
29903
  */
29465
- _closeFile(path24) {
29466
- const closers = this._closers.get(path24);
29904
+ _closeFile(path25) {
29905
+ const closers = this._closers.get(path25);
29467
29906
  if (!closers)
29468
29907
  return;
29469
29908
  closers.forEach((closer) => closer());
29470
- this._closers.delete(path24);
29909
+ this._closers.delete(path25);
29471
29910
  }
29472
- _addPathCloser(path24, closer) {
29911
+ _addPathCloser(path25, closer) {
29473
29912
  if (!closer)
29474
29913
  return;
29475
- let list = this._closers.get(path24);
29914
+ let list = this._closers.get(path25);
29476
29915
  if (!list) {
29477
29916
  list = [];
29478
- this._closers.set(path24, list);
29917
+ this._closers.set(path25, list);
29479
29918
  }
29480
29919
  list.push(closer);
29481
29920
  }
@@ -29501,12 +29940,12 @@ var init_chokidar = __esm({
29501
29940
  });
29502
29941
 
29503
29942
  // ../../oss/packages/daemon-core/src/providers/provider-loader.ts
29504
- var fs6, path10, os12, ProviderLoader;
29943
+ var fs6, path11, os12, ProviderLoader;
29505
29944
  var init_provider_loader = __esm({
29506
29945
  "../../oss/packages/daemon-core/src/providers/provider-loader.ts"() {
29507
29946
  "use strict";
29508
29947
  fs6 = __toESM(require("fs"));
29509
- path10 = __toESM(require("path"));
29948
+ path11 = __toESM(require("path"));
29510
29949
  os12 = __toESM(require("os"));
29511
29950
  init_chokidar();
29512
29951
  init_ide_detector();
@@ -29528,12 +29967,12 @@ var init_provider_loader = __esm({
29528
29967
  static META_FILE = ".meta.json";
29529
29968
  constructor(options) {
29530
29969
  this.logFn = options?.logFn || LOG.forComponent("Provider").asLogFn();
29531
- const defaultProvidersDir = path10.join(os12.homedir(), ".adhdev", "providers");
29970
+ const defaultProvidersDir = path11.join(os12.homedir(), ".adhdev", "providers");
29532
29971
  if (options?.userDir) {
29533
29972
  this.userDir = options.userDir;
29534
29973
  this.log(`Config 'providerDir' applied: ${this.userDir}`);
29535
29974
  } else {
29536
- const localRepoPath = path10.resolve(__dirname, "../../../../../adhdev-providers");
29975
+ const localRepoPath = path11.resolve(__dirname, "../../../../../adhdev-providers");
29537
29976
  if (fs6.existsSync(localRepoPath)) {
29538
29977
  this.userDir = localRepoPath;
29539
29978
  this.log(`Auto-detected local public repository: ${this.userDir} (Dev workspace speedup)`);
@@ -29542,7 +29981,7 @@ var init_provider_loader = __esm({
29542
29981
  this.log(`Using default user providers directory: ${this.userDir}`);
29543
29982
  }
29544
29983
  }
29545
- this.upstreamDir = path10.join(defaultProvidersDir, ".upstream");
29984
+ this.upstreamDir = path11.join(defaultProvidersDir, ".upstream");
29546
29985
  this.disableUpstream = options?.disableUpstream ?? false;
29547
29986
  }
29548
29987
  log(msg) {
@@ -29572,7 +30011,7 @@ var init_provider_loader = __esm({
29572
30011
  * Canonical provider directory shape for a given root.
29573
30012
  */
29574
30013
  getProviderDir(root, category, type) {
29575
- return path10.join(root, category, type);
30014
+ return path11.join(root, category, type);
29576
30015
  }
29577
30016
  /**
29578
30017
  * Canonical user override directory for a provider.
@@ -29599,7 +30038,7 @@ var init_provider_loader = __esm({
29599
30038
  resolveProviderFile(type, ...segments) {
29600
30039
  const dir = this.findProviderDirInternal(type);
29601
30040
  if (!dir) return null;
29602
- return path10.join(dir, ...segments);
30041
+ return path11.join(dir, ...segments);
29603
30042
  }
29604
30043
  /**
29605
30044
  * Load all providers (3-tier priority)
@@ -29637,7 +30076,7 @@ var init_provider_loader = __esm({
29637
30076
  if (!fs6.existsSync(this.upstreamDir)) return false;
29638
30077
  try {
29639
30078
  return fs6.readdirSync(this.upstreamDir).some(
29640
- (d) => fs6.statSync(path10.join(this.upstreamDir, d)).isDirectory()
30079
+ (d) => fs6.statSync(path11.join(this.upstreamDir, d)).isDirectory()
29641
30080
  );
29642
30081
  } catch {
29643
30082
  return false;
@@ -29887,8 +30326,8 @@ var init_provider_loader = __esm({
29887
30326
  resolved._resolvedScriptDir = entry.scriptDir;
29888
30327
  resolved._resolvedScriptsSource = `compatibility:${entry.ideVersion}`;
29889
30328
  if (providerDir) {
29890
- const fullDir = path10.join(providerDir, entry.scriptDir);
29891
- 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;
29892
30331
  }
29893
30332
  matched = true;
29894
30333
  }
@@ -29903,8 +30342,8 @@ var init_provider_loader = __esm({
29903
30342
  resolved._resolvedScriptDir = base.defaultScriptDir;
29904
30343
  resolved._resolvedScriptsSource = "defaultScriptDir:version_miss";
29905
30344
  if (providerDir) {
29906
- const fullDir = path10.join(providerDir, base.defaultScriptDir);
29907
- 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;
29908
30347
  }
29909
30348
  }
29910
30349
  resolved._versionWarning = `Version ${currentVersion} not in compatibility matrix. Using default scripts.`;
@@ -29921,8 +30360,8 @@ var init_provider_loader = __esm({
29921
30360
  resolved._resolvedScriptDir = dirOverride;
29922
30361
  resolved._resolvedScriptsSource = `versions:${range}`;
29923
30362
  if (providerDir) {
29924
- const fullDir = path10.join(providerDir, dirOverride);
29925
- 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;
29926
30365
  }
29927
30366
  }
29928
30367
  } else if (override.scripts) {
@@ -29938,8 +30377,8 @@ var init_provider_loader = __esm({
29938
30377
  resolved._resolvedScriptDir = base.defaultScriptDir;
29939
30378
  resolved._resolvedScriptsSource = "defaultScriptDir:no_version";
29940
30379
  if (providerDir) {
29941
- const fullDir = path10.join(providerDir, base.defaultScriptDir);
29942
- 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;
29943
30382
  }
29944
30383
  }
29945
30384
  }
@@ -29964,14 +30403,14 @@ var init_provider_loader = __esm({
29964
30403
  this.log(` [loadScriptsFromDir] ${type}: providerDir not found`);
29965
30404
  return null;
29966
30405
  }
29967
- const dir = path10.join(providerDir, scriptDir);
30406
+ const dir = path11.join(providerDir, scriptDir);
29968
30407
  if (!fs6.existsSync(dir)) {
29969
30408
  this.log(` [loadScriptsFromDir] ${type}: dir not found: ${dir}`);
29970
30409
  return null;
29971
30410
  }
29972
30411
  const cached2 = this.scriptsCache.get(dir);
29973
30412
  if (cached2) return cached2;
29974
- const scriptsJs = path10.join(dir, "scripts.js");
30413
+ const scriptsJs = path11.join(dir, "scripts.js");
29975
30414
  if (fs6.existsSync(scriptsJs)) {
29976
30415
  try {
29977
30416
  delete require.cache[require.resolve(scriptsJs)];
@@ -30013,7 +30452,7 @@ var init_provider_loader = __esm({
30013
30452
  return;
30014
30453
  }
30015
30454
  if (filePath.endsWith(".js") || filePath.endsWith(".json")) {
30016
- this.log(`File changed: ${path10.basename(filePath)}, reloading...`);
30455
+ this.log(`File changed: ${path11.basename(filePath)}, reloading...`);
30017
30456
  this.reload();
30018
30457
  }
30019
30458
  };
@@ -30068,7 +30507,7 @@ var init_provider_loader = __esm({
30068
30507
  }
30069
30508
  const https = require("https");
30070
30509
  const { execSync: execSync7 } = require("child_process");
30071
- const metaPath = path10.join(this.upstreamDir, _ProviderLoader.META_FILE);
30510
+ const metaPath = path11.join(this.upstreamDir, _ProviderLoader.META_FILE);
30072
30511
  let prevEtag = "";
30073
30512
  let prevTimestamp = 0;
30074
30513
  try {
@@ -30128,17 +30567,17 @@ var init_provider_loader = __esm({
30128
30567
  return { updated: false };
30129
30568
  }
30130
30569
  this.log("Downloading latest providers from GitHub...");
30131
- const tmpTar = path10.join(os12.tmpdir(), `adhdev-providers-${Date.now()}.tar.gz`);
30132
- 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()}`);
30133
30572
  await this.downloadFile(_ProviderLoader.GITHUB_TARBALL_URL, tmpTar);
30134
30573
  fs6.mkdirSync(tmpExtract, { recursive: true });
30135
30574
  execSync7(`tar -xzf "${tmpTar}" -C "${tmpExtract}"`, { timeout: 3e4 });
30136
30575
  const extracted = fs6.readdirSync(tmpExtract);
30137
30576
  const rootDir = extracted.find(
30138
- (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")
30139
30578
  );
30140
30579
  if (!rootDir) throw new Error("Unexpected tarball structure");
30141
- const sourceDir = path10.join(tmpExtract, rootDir);
30580
+ const sourceDir = path11.join(tmpExtract, rootDir);
30142
30581
  const backupDir = this.upstreamDir + ".bak";
30143
30582
  if (fs6.existsSync(this.upstreamDir)) {
30144
30583
  if (fs6.existsSync(backupDir)) fs6.rmSync(backupDir, { recursive: true, force: true });
@@ -30213,8 +30652,8 @@ var init_provider_loader = __esm({
30213
30652
  copyDirRecursive(src, dest) {
30214
30653
  fs6.mkdirSync(dest, { recursive: true });
30215
30654
  for (const entry of fs6.readdirSync(src, { withFileTypes: true })) {
30216
- const srcPath = path10.join(src, entry.name);
30217
- const destPath = path10.join(dest, entry.name);
30655
+ const srcPath = path11.join(src, entry.name);
30656
+ const destPath = path11.join(dest, entry.name);
30218
30657
  if (entry.isDirectory()) {
30219
30658
  this.copyDirRecursive(srcPath, destPath);
30220
30659
  } else {
@@ -30225,7 +30664,7 @@ var init_provider_loader = __esm({
30225
30664
  /** .meta.json save */
30226
30665
  writeMeta(metaPath, etag, timestamp) {
30227
30666
  try {
30228
- fs6.mkdirSync(path10.dirname(metaPath), { recursive: true });
30667
+ fs6.mkdirSync(path11.dirname(metaPath), { recursive: true });
30229
30668
  fs6.writeFileSync(metaPath, JSON.stringify({
30230
30669
  etag,
30231
30670
  timestamp,
@@ -30242,7 +30681,7 @@ var init_provider_loader = __esm({
30242
30681
  const scan = (d) => {
30243
30682
  try {
30244
30683
  for (const entry of fs6.readdirSync(d, { withFileTypes: true })) {
30245
- if (entry.isDirectory()) scan(path10.join(d, entry.name));
30684
+ if (entry.isDirectory()) scan(path11.join(d, entry.name));
30246
30685
  else if (entry.name === "provider.json") count++;
30247
30686
  }
30248
30687
  } catch {
@@ -30341,17 +30780,17 @@ var init_provider_loader = __esm({
30341
30780
  for (const root of searchRoots) {
30342
30781
  if (!fs6.existsSync(root)) continue;
30343
30782
  const candidate = this.getProviderDir(root, cat, type);
30344
- if (fs6.existsSync(path10.join(candidate, "provider.json"))) return candidate;
30345
- const catDir = path10.join(root, cat);
30783
+ if (fs6.existsSync(path11.join(candidate, "provider.json"))) return candidate;
30784
+ const catDir = path11.join(root, cat);
30346
30785
  if (fs6.existsSync(catDir)) {
30347
30786
  try {
30348
30787
  for (const entry of fs6.readdirSync(catDir, { withFileTypes: true })) {
30349
30788
  if (!entry.isDirectory()) continue;
30350
- const jsonPath = path10.join(catDir, entry.name, "provider.json");
30789
+ const jsonPath = path11.join(catDir, entry.name, "provider.json");
30351
30790
  if (fs6.existsSync(jsonPath)) {
30352
30791
  try {
30353
30792
  const data = JSON.parse(fs6.readFileSync(jsonPath, "utf-8"));
30354
- if (data.type === type) return path10.join(catDir, entry.name);
30793
+ if (data.type === type) return path11.join(catDir, entry.name);
30355
30794
  } catch {
30356
30795
  }
30357
30796
  }
@@ -30368,7 +30807,7 @@ var init_provider_loader = __esm({
30368
30807
  * (template substitution is NOT applied here — scripts.js handles that)
30369
30808
  */
30370
30809
  buildScriptWrappersFromDir(dir) {
30371
- const scriptsJs = path10.join(dir, "scripts.js");
30810
+ const scriptsJs = path11.join(dir, "scripts.js");
30372
30811
  if (fs6.existsSync(scriptsJs)) {
30373
30812
  try {
30374
30813
  delete require.cache[require.resolve(scriptsJs)];
@@ -30382,7 +30821,7 @@ var init_provider_loader = __esm({
30382
30821
  for (const file2 of fs6.readdirSync(dir)) {
30383
30822
  if (!file2.endsWith(".js")) continue;
30384
30823
  const scriptName = toCamel(file2.replace(".js", ""));
30385
- const filePath = path10.join(dir, file2);
30824
+ const filePath = path11.join(dir, file2);
30386
30825
  result[scriptName] = (...args) => {
30387
30826
  try {
30388
30827
  let content = fs6.readFileSync(filePath, "utf-8");
@@ -30442,7 +30881,7 @@ var init_provider_loader = __esm({
30442
30881
  }
30443
30882
  const hasJson = entries.some((e) => e.name === "provider.json");
30444
30883
  if (hasJson) {
30445
- const jsonPath = path10.join(d, "provider.json");
30884
+ const jsonPath = path11.join(d, "provider.json");
30446
30885
  try {
30447
30886
  const raw = fs6.readFileSync(jsonPath, "utf-8");
30448
30887
  const mod = JSON.parse(raw);
@@ -30455,7 +30894,7 @@ var init_provider_loader = __esm({
30455
30894
  delete mod.extensionIdPattern_flags;
30456
30895
  }
30457
30896
  const hasCompatibility = Array.isArray(mod.compatibility);
30458
- const scriptsPath = path10.join(d, "scripts.js");
30897
+ const scriptsPath = path11.join(d, "scripts.js");
30459
30898
  if (!hasCompatibility && fs6.existsSync(scriptsPath)) {
30460
30899
  try {
30461
30900
  delete require.cache[require.resolve(scriptsPath)];
@@ -30481,7 +30920,7 @@ var init_provider_loader = __esm({
30481
30920
  if (!entry.isDirectory()) continue;
30482
30921
  if (entry.name.startsWith("_") || entry.name.startsWith(".")) continue;
30483
30922
  if (excludeDirs && d === dir && excludeDirs.includes(entry.name)) continue;
30484
- scan(path10.join(d, entry.name));
30923
+ scan(path11.join(d, entry.name));
30485
30924
  }
30486
30925
  }
30487
30926
  };
@@ -30740,8 +31179,8 @@ function detectCurrentWorkspace(ideId) {
30740
31179
  const appNameMap = getMacAppIdentifiers();
30741
31180
  const appName = appNameMap[ideId];
30742
31181
  if (appName) {
30743
- const storagePath = path11.join(
30744
- process.env.APPDATA || path11.join(os13.homedir(), "AppData", "Roaming"),
31182
+ const storagePath = path12.join(
31183
+ process.env.APPDATA || path12.join(os13.homedir(), "AppData", "Roaming"),
30745
31184
  appName,
30746
31185
  "storage.json"
30747
31186
  );
@@ -30912,14 +31351,14 @@ async function launchLinux(ide, port, workspace, newWindow) {
30912
31351
  function getAvailableIdeIds() {
30913
31352
  return getProviderLoader().getAvailableIdeTypes();
30914
31353
  }
30915
- var import_child_process6, net2, os13, path11, _providerLoader;
31354
+ var import_child_process6, net2, os13, path12, _providerLoader;
30916
31355
  var init_launch = __esm({
30917
31356
  "../../oss/packages/daemon-core/src/launch.ts"() {
30918
31357
  "use strict";
30919
31358
  import_child_process6 = require("child_process");
30920
31359
  net2 = __toESM(require("net"));
30921
31360
  os13 = __toESM(require("os"));
30922
- path11 = __toESM(require("path"));
31361
+ path12 = __toESM(require("path"));
30923
31362
  init_ide_detector();
30924
31363
  init_provider_loader();
30925
31364
  _providerLoader = null;
@@ -30950,7 +31389,7 @@ function checkRotation() {
30950
31389
  const today = getDateStr2();
30951
31390
  if (today !== currentDate2) {
30952
31391
  currentDate2 = today;
30953
- currentFile = path12.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
31392
+ currentFile = path13.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
30954
31393
  cleanOldFiles();
30955
31394
  }
30956
31395
  }
@@ -30964,7 +31403,7 @@ function cleanOldFiles() {
30964
31403
  const dateMatch = file2.match(/commands-(\d{4}-\d{2}-\d{2})/);
30965
31404
  if (dateMatch && dateMatch[1] < cutoffStr) {
30966
31405
  try {
30967
- fs7.unlinkSync(path12.join(LOG_DIR2, file2));
31406
+ fs7.unlinkSync(path13.join(LOG_DIR2, file2));
30968
31407
  } catch {
30969
31408
  }
30970
31409
  }
@@ -31031,14 +31470,14 @@ function getRecentCommands(count = 50) {
31031
31470
  return [];
31032
31471
  }
31033
31472
  }
31034
- 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;
31035
31474
  var init_command_log = __esm({
31036
31475
  "../../oss/packages/daemon-core/src/logging/command-log.ts"() {
31037
31476
  "use strict";
31038
31477
  fs7 = __toESM(require("fs"));
31039
- path12 = __toESM(require("path"));
31478
+ path13 = __toESM(require("path"));
31040
31479
  os14 = __toESM(require("os"));
31041
- 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");
31042
31481
  MAX_FILE_SIZE = 5 * 1024 * 1024;
31043
31482
  MAX_DAYS = 7;
31044
31483
  try {
@@ -31057,7 +31496,7 @@ var init_command_log = __esm({
31057
31496
  "text"
31058
31497
  ]);
31059
31498
  currentDate2 = getDateStr2();
31060
- currentFile = path12.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
31499
+ currentFile = path13.join(LOG_DIR2, `commands-${currentDate2}.jsonl`);
31061
31500
  writeCount2 = 0;
31062
31501
  SKIP_COMMANDS = /* @__PURE__ */ new Set([
31063
31502
  "heartbeat",
@@ -31097,17 +31536,17 @@ function parseMessageTime(value) {
31097
31536
  function getSessionMessageUpdatedAt(session) {
31098
31537
  const lastMessage = session.activeChat?.messages?.at?.(-1);
31099
31538
  if (!lastMessage) return 0;
31100
- return parseMessageTime(lastMessage.timestamp) || parseMessageTime(lastMessage.receivedAt) || parseMessageTime(lastMessage.createdAt) || 0;
31539
+ return parseMessageTime(lastMessage.receivedAt) || 0;
31101
31540
  }
31102
31541
  function getSessionCompletionMarker(session) {
31103
31542
  const lastMessage = session.activeChat?.messages?.at?.(-1);
31104
31543
  if (!lastMessage) return "";
31105
31544
  const role = typeof lastMessage.role === "string" ? lastMessage.role : "";
31106
- if (role === "user" || role === "human") return "";
31545
+ if (role === "user" || role === "human" || role === "system") return "";
31107
31546
  if (typeof lastMessage._turnKey === "string" && lastMessage._turnKey) return `turn:${lastMessage._turnKey}`;
31108
31547
  if (typeof lastMessage.id === "string" && lastMessage.id) return `id:${lastMessage.id}`;
31109
31548
  if (typeof lastMessage.index === "number" && Number.isFinite(lastMessage.index)) return `idx:${lastMessage.index}`;
31110
- const timestamp = parseMessageTime(lastMessage.timestamp) || parseMessageTime(lastMessage.receivedAt) || parseMessageTime(lastMessage.createdAt);
31549
+ const timestamp = parseMessageTime(lastMessage.receivedAt);
31111
31550
  return timestamp > 0 ? `ts:${timestamp}` : "";
31112
31551
  }
31113
31552
  function getSessionLastUsedAt(session) {
@@ -31124,7 +31563,7 @@ function getUnreadState(hasContentChange, status, lastUsedAt, lastSeenAt, lastRo
31124
31563
  if (status === "generating" || status === "starting") {
31125
31564
  return { unread: false, inboxBucket: "working" };
31126
31565
  }
31127
- 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";
31128
31567
  return { unread, inboxBucket: unread ? "task_complete" : "idle" };
31129
31568
  }
31130
31569
  function buildRecentLaunches(recentActivity) {
@@ -31225,9 +31664,9 @@ var init_snapshot = __esm({
31225
31664
  // ../../oss/packages/daemon-core/src/commands/upgrade-helper.ts
31226
31665
  function getUpgradeLogPath() {
31227
31666
  const home = os16.homedir();
31228
- const dir = path13.join(home, ".adhdev");
31667
+ const dir = path14.join(home, ".adhdev");
31229
31668
  fs8.mkdirSync(dir, { recursive: true });
31230
- return path13.join(dir, "daemon-upgrade.log");
31669
+ return path14.join(dir, "daemon-upgrade.log");
31231
31670
  }
31232
31671
  function appendUpgradeLog(message) {
31233
31672
  const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
@@ -31267,7 +31706,7 @@ async function waitForPidExit(pid, timeoutMs) {
31267
31706
  }
31268
31707
  }
31269
31708
  function stopSessionHostProcesses(appName) {
31270
- const pidFile = path13.join(os16.homedir(), ".adhdev", `${appName}-session-host.pid`);
31709
+ const pidFile = path14.join(os16.homedir(), ".adhdev", `${appName}-session-host.pid`);
31271
31710
  try {
31272
31711
  if (fs8.existsSync(pidFile)) {
31273
31712
  const pid = Number.parseInt(fs8.readFileSync(pidFile, "utf8").trim(), 10);
@@ -31296,7 +31735,7 @@ function stopSessionHostProcesses(appName) {
31296
31735
  }
31297
31736
  }
31298
31737
  function removeDaemonPidFile() {
31299
- const pidFile = path13.join(os16.homedir(), ".adhdev", "daemon.pid");
31738
+ const pidFile = path14.join(os16.homedir(), ".adhdev", "daemon.pid");
31300
31739
  try {
31301
31740
  fs8.unlinkSync(pidFile);
31302
31741
  } catch {
@@ -31307,7 +31746,7 @@ function cleanupStaleGlobalInstallDirs(pkgName) {
31307
31746
  const npmRoot = (0, import_child_process7.execFileSync)(getNpmExecutable(), ["root", "-g"], { encoding: "utf8", ...npmExecOpts }).trim();
31308
31747
  if (!npmRoot) return;
31309
31748
  const npmPrefix = (0, import_child_process7.execFileSync)(getNpmExecutable(), ["prefix", "-g"], { encoding: "utf8", ...npmExecOpts }).trim();
31310
- const binDir = process.platform === "win32" ? npmPrefix : path13.join(npmPrefix, "bin");
31749
+ const binDir = process.platform === "win32" ? npmPrefix : path14.join(npmPrefix, "bin");
31311
31750
  const packageBaseName = pkgName.startsWith("@") ? pkgName.split("/")[1] : pkgName;
31312
31751
  const binNames = /* @__PURE__ */ new Set([packageBaseName]);
31313
31752
  if (pkgName === "@adhdev/daemon-standalone") {
@@ -31315,25 +31754,25 @@ function cleanupStaleGlobalInstallDirs(pkgName) {
31315
31754
  }
31316
31755
  if (pkgName.startsWith("@")) {
31317
31756
  const [scope, name] = pkgName.split("/");
31318
- const scopeDir = path13.join(npmRoot, scope);
31757
+ const scopeDir = path14.join(npmRoot, scope);
31319
31758
  if (!fs8.existsSync(scopeDir)) return;
31320
31759
  for (const entry of fs8.readdirSync(scopeDir)) {
31321
31760
  if (!entry.startsWith(`.${name}-`)) continue;
31322
- fs8.rmSync(path13.join(scopeDir, entry), { recursive: true, force: true });
31323
- 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)}`);
31324
31763
  }
31325
31764
  } else {
31326
31765
  for (const entry of fs8.readdirSync(npmRoot)) {
31327
31766
  if (!entry.startsWith(`.${pkgName}-`)) continue;
31328
- fs8.rmSync(path13.join(npmRoot, entry), { recursive: true, force: true });
31329
- 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)}`);
31330
31769
  }
31331
31770
  }
31332
31771
  if (fs8.existsSync(binDir)) {
31333
31772
  for (const entry of fs8.readdirSync(binDir)) {
31334
31773
  if (![...binNames].some((name) => entry.startsWith(`.${name}-`))) continue;
31335
- fs8.rmSync(path13.join(binDir, entry), { recursive: true, force: true });
31336
- 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)}`);
31337
31776
  }
31338
31777
  }
31339
31778
  }
@@ -31408,7 +31847,7 @@ async function maybeRunDaemonUpgradeHelperFromEnv() {
31408
31847
  process.exit(1);
31409
31848
  }
31410
31849
  }
31411
- 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;
31412
31851
  var init_upgrade_helper = __esm({
31413
31852
  "../../oss/packages/daemon-core/src/commands/upgrade-helper.ts"() {
31414
31853
  "use strict";
@@ -31416,12 +31855,31 @@ var init_upgrade_helper = __esm({
31416
31855
  import_child_process8 = require("child_process");
31417
31856
  fs8 = __toESM(require("fs"));
31418
31857
  os16 = __toESM(require("os"));
31419
- path13 = __toESM(require("path"));
31858
+ path14 = __toESM(require("path"));
31420
31859
  UPGRADE_HELPER_ENV = "ADHDEV_DAEMON_UPGRADE_HELPER";
31421
31860
  }
31422
31861
  });
31423
31862
 
31424
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
+ }
31425
31883
  var fs9, CHAT_COMMANDS, READ_DEBUG_ENABLED2, DaemonCommandRouter;
31426
31884
  var init_router = __esm({
31427
31885
  "../../oss/packages/daemon-core/src/commands/router.ts"() {
@@ -31525,6 +31983,90 @@ var init_router = __esm({
31525
31983
  return { success: false, error: e.message };
31526
31984
  }
31527
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
+ }
31528
32070
  case "list_saved_sessions": {
31529
32071
  const providerType = typeof args?.providerType === "string" ? args.providerType.trim() : typeof args?.agentType === "string" ? args.agentType.trim() : "";
31530
32072
  const kind = args?.kind === "acp" ? "acp" : "cli";
@@ -32071,6 +32613,14 @@ var init_provider_adapter = __esm({
32071
32613
  hasScript(name) {
32072
32614
  return typeof this.provider.scripts?.[name] === "function";
32073
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
+ }
32074
32624
  summarizeRaw(raw) {
32075
32625
  try {
32076
32626
  if (typeof raw === "string") return raw.replace(/\s+/g, " ").trim().slice(0, 240);
@@ -32131,12 +32681,30 @@ var init_provider_adapter = __esm({
32131
32681
  }
32132
32682
  }
32133
32683
  async sendMessage(evaluate, text) {
32134
- const script = this.callScript("sendMessage", text);
32684
+ const params = { message: text };
32685
+ const script = this.callScript("sendMessage", params) || this.callScript("sendMessage", text);
32135
32686
  if (!script) throw new Error(`[${this.agentName}] sendMessage script not available`);
32136
32687
  const result = await evaluate(script);
32137
32688
  if (result && typeof result === "string" && result.startsWith("error:")) {
32138
32689
  throw new Error(`[${this.agentName}] sendMessage failed: ${result}`);
32139
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`);
32140
32708
  }
32141
32709
  async resolveAction(evaluate, action, button) {
32142
32710
  const script = this.callScript("resolveAction", { action, button });
@@ -32937,7 +33505,7 @@ function checkPathExists2(paths) {
32937
33505
  for (const p of paths) {
32938
33506
  if (p.includes("*")) {
32939
33507
  const home = os17.homedir();
32940
- const resolved = p.replace(/\*/g, home.split(path14.sep).pop() || "");
33508
+ const resolved = p.replace(/\*/g, home.split(path15.sep).pop() || "");
32941
33509
  if (fs10.existsSync(resolved)) return resolved;
32942
33510
  } else {
32943
33511
  if (fs10.existsSync(p)) return p;
@@ -32947,7 +33515,7 @@ function checkPathExists2(paths) {
32947
33515
  }
32948
33516
  function getMacAppVersion(appPath) {
32949
33517
  if ((0, import_os3.platform)() !== "darwin" || !appPath.endsWith(".app")) return null;
32950
- const plistPath = path14.join(appPath, "Contents", "Info.plist");
33518
+ const plistPath = path15.join(appPath, "Contents", "Info.plist");
32951
33519
  if (!fs10.existsSync(plistPath)) return null;
32952
33520
  const raw = runCommand(`/usr/libexec/PlistBuddy -c "Print CFBundleShortVersionString" "${plistPath}"`);
32953
33521
  return raw || null;
@@ -32974,7 +33542,7 @@ async function detectAllVersions(loader, archive) {
32974
33542
  const cliBin = provider.cli ? findBinary2(provider.cli) : null;
32975
33543
  let resolvedBin = cliBin;
32976
33544
  if (!resolvedBin && appPath && currentOs === "darwin") {
32977
- const bundled = path14.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
33545
+ const bundled = path15.join(appPath, "Contents", "Resources", "app", "bin", provider.cli || "");
32978
33546
  if (provider.cli && fs10.existsSync(bundled)) resolvedBin = bundled;
32979
33547
  }
32980
33548
  info.installed = !!(appPath || resolvedBin);
@@ -33011,16 +33579,16 @@ async function detectAllVersions(loader, archive) {
33011
33579
  }
33012
33580
  return results;
33013
33581
  }
33014
- 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;
33015
33583
  var init_version_archive = __esm({
33016
33584
  "../../oss/packages/daemon-core/src/providers/version-archive.ts"() {
33017
33585
  "use strict";
33018
33586
  fs10 = __toESM(require("fs"));
33019
- path14 = __toESM(require("path"));
33587
+ path15 = __toESM(require("path"));
33020
33588
  os17 = __toESM(require("os"));
33021
33589
  import_child_process9 = require("child_process");
33022
33590
  import_os3 = require("os");
33023
- ARCHIVE_PATH = path14.join(os17.homedir(), ".adhdev", "version-history.json");
33591
+ ARCHIVE_PATH = path15.join(os17.homedir(), ".adhdev", "version-history.json");
33024
33592
  MAX_ENTRIES_PER_PROVIDER = 20;
33025
33593
  VersionArchive = class {
33026
33594
  history = {};
@@ -33067,7 +33635,7 @@ var init_version_archive = __esm({
33067
33635
  }
33068
33636
  save() {
33069
33637
  try {
33070
- fs10.mkdirSync(path14.dirname(ARCHIVE_PATH), { recursive: true });
33638
+ fs10.mkdirSync(path15.dirname(ARCHIVE_PATH), { recursive: true });
33071
33639
  fs10.writeFileSync(ARCHIVE_PATH, JSON.stringify(this.history, null, 2));
33072
33640
  } catch {
33073
33641
  }
@@ -33588,17 +34156,17 @@ async function handleScriptHints(ctx, type, _req, res) {
33588
34156
  return;
33589
34157
  }
33590
34158
  let scriptsPath = "";
33591
- const directScripts = path15.join(dir, "scripts.js");
34159
+ const directScripts = path16.join(dir, "scripts.js");
33592
34160
  if (fs11.existsSync(directScripts)) {
33593
34161
  scriptsPath = directScripts;
33594
34162
  } else {
33595
- const scriptsDir = path15.join(dir, "scripts");
34163
+ const scriptsDir = path16.join(dir, "scripts");
33596
34164
  if (fs11.existsSync(scriptsDir)) {
33597
34165
  const versions = fs11.readdirSync(scriptsDir).filter((d) => {
33598
- return fs11.statSync(path15.join(scriptsDir, d)).isDirectory();
34166
+ return fs11.statSync(path16.join(scriptsDir, d)).isDirectory();
33599
34167
  }).sort().reverse();
33600
34168
  for (const ver of versions) {
33601
- const p = path15.join(scriptsDir, ver, "scripts.js");
34169
+ const p = path16.join(scriptsDir, ver, "scripts.js");
33602
34170
  if (fs11.existsSync(p)) {
33603
34171
  scriptsPath = p;
33604
34172
  break;
@@ -34414,12 +34982,12 @@ async function handleDomContext(ctx, type, req, res) {
34414
34982
  ctx.json(res, 500, { error: `DOM context collection failed: ${e.message}` });
34415
34983
  }
34416
34984
  }
34417
- var fs11, path15;
34985
+ var fs11, path16;
34418
34986
  var init_dev_cdp_handlers = __esm({
34419
34987
  "../../oss/packages/daemon-core/src/daemon/dev-cdp-handlers.ts"() {
34420
34988
  "use strict";
34421
34989
  fs11 = __toESM(require("fs"));
34422
- path15 = __toESM(require("path"));
34990
+ path16 = __toESM(require("path"));
34423
34991
  init_logger();
34424
34992
  }
34425
34993
  });
@@ -34434,11 +35002,11 @@ function getCliFixtureDir(ctx, type) {
34434
35002
  if (!providerDir) {
34435
35003
  throw new Error(`Provider directory not found for '${type}'`);
34436
35004
  }
34437
- return path16.join(providerDir, "fixtures");
35005
+ return path17.join(providerDir, "fixtures");
34438
35006
  }
34439
35007
  function readCliFixture(ctx, type, name) {
34440
35008
  const fixtureDir = getCliFixtureDir(ctx, type);
34441
- const filePath = path16.join(fixtureDir, `${name}.json`);
35009
+ const filePath = path17.join(fixtureDir, `${name}.json`);
34442
35010
  if (!fs12.existsSync(filePath)) {
34443
35011
  throw new Error(`Fixture not found: ${filePath}`);
34444
35012
  }
@@ -35197,7 +35765,7 @@ async function handleCliFixtureCapture(ctx, req, res) {
35197
35765
  },
35198
35766
  notes: typeof body?.notes === "string" ? body.notes : void 0
35199
35767
  };
35200
- const filePath = path16.join(fixtureDir, `${name}.json`);
35768
+ const filePath = path17.join(fixtureDir, `${name}.json`);
35201
35769
  fs12.writeFileSync(filePath, JSON.stringify(fixture, null, 2));
35202
35770
  ctx.json(res, 200, {
35203
35771
  saved: true,
@@ -35221,7 +35789,7 @@ async function handleCliFixtureList(ctx, type, _req, res) {
35221
35789
  return;
35222
35790
  }
35223
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) => {
35224
- const fullPath = path16.join(fixtureDir, file2);
35792
+ const fullPath = path17.join(fixtureDir, file2);
35225
35793
  try {
35226
35794
  const raw = JSON.parse(fs12.readFileSync(fullPath, "utf-8"));
35227
35795
  return {
@@ -35354,12 +35922,12 @@ async function handleCliRaw(ctx, req, res) {
35354
35922
  ctx.json(res, 500, { error: `Raw send failed: ${e.message}` });
35355
35923
  }
35356
35924
  }
35357
- var fs12, path16;
35925
+ var fs12, path17;
35358
35926
  var init_dev_cli_debug = __esm({
35359
35927
  "../../oss/packages/daemon-core/src/daemon/dev-cli-debug.ts"() {
35360
35928
  "use strict";
35361
35929
  fs12 = __toESM(require("fs"));
35362
- path16 = __toESM(require("path"));
35930
+ path17 = __toESM(require("path"));
35363
35931
  }
35364
35932
  });
35365
35933
 
@@ -35402,22 +35970,22 @@ function getLatestScriptVersionDir(scriptsDir) {
35402
35970
  if (!fs13.existsSync(scriptsDir)) return null;
35403
35971
  const versions = fs13.readdirSync(scriptsDir).filter((d) => {
35404
35972
  try {
35405
- return fs13.statSync(path17.join(scriptsDir, d)).isDirectory();
35973
+ return fs13.statSync(path18.join(scriptsDir, d)).isDirectory();
35406
35974
  } catch {
35407
35975
  return false;
35408
35976
  }
35409
35977
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
35410
35978
  if (versions.length === 0) return null;
35411
- return path17.join(scriptsDir, versions[0]);
35979
+ return path18.join(scriptsDir, versions[0]);
35412
35980
  }
35413
35981
  function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
35414
- const canonicalUserDir = path17.resolve(ctx.providerLoader.getUserProviderDir(category, type));
35415
- const desiredDir = requestedDir ? path17.resolve(requestedDir) : canonicalUserDir;
35416
- const upstreamRoot = path17.resolve(ctx.providerLoader.getUpstreamDir());
35417
- 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}`)) {
35418
35986
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
35419
35987
  }
35420
- if (path17.basename(desiredDir) !== type) {
35988
+ if (path18.basename(desiredDir) !== type) {
35421
35989
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
35422
35990
  }
35423
35991
  const sourceDir = ctx.findProviderDir(type);
@@ -35425,11 +35993,11 @@ function resolveAutoImplWritableProviderDir(ctx, category, type, requestedDir) {
35425
35993
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
35426
35994
  }
35427
35995
  if (!fs13.existsSync(desiredDir)) {
35428
- fs13.mkdirSync(path17.dirname(desiredDir), { recursive: true });
35996
+ fs13.mkdirSync(path18.dirname(desiredDir), { recursive: true });
35429
35997
  fs13.cpSync(sourceDir, desiredDir, { recursive: true });
35430
35998
  ctx.log(`Auto-implement writable copy created: ${desiredDir}`);
35431
35999
  }
35432
- const providerJson = path17.join(desiredDir, "provider.json");
36000
+ const providerJson = path18.join(desiredDir, "provider.json");
35433
36001
  if (!fs13.existsSync(providerJson)) {
35434
36002
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
35435
36003
  }
@@ -35452,13 +36020,13 @@ function loadAutoImplReferenceScripts(ctx, referenceType) {
35452
36020
  const refDir = ctx.findProviderDir(referenceType);
35453
36021
  if (!refDir || !fs13.existsSync(refDir)) return {};
35454
36022
  const referenceScripts = {};
35455
- const scriptsDir = path17.join(refDir, "scripts");
36023
+ const scriptsDir = path18.join(refDir, "scripts");
35456
36024
  const latestDir = getLatestScriptVersionDir(scriptsDir);
35457
36025
  if (!latestDir) return referenceScripts;
35458
36026
  for (const file2 of fs13.readdirSync(latestDir)) {
35459
36027
  if (!file2.endsWith(".js")) continue;
35460
36028
  try {
35461
- referenceScripts[file2] = fs13.readFileSync(path17.join(latestDir, file2), "utf-8");
36029
+ referenceScripts[file2] = fs13.readFileSync(path18.join(latestDir, file2), "utf-8");
35462
36030
  } catch {
35463
36031
  }
35464
36032
  }
@@ -35566,9 +36134,9 @@ async function handleAutoImplement(ctx, type, req, res) {
35566
36134
  });
35567
36135
  const referenceScripts = loadAutoImplReferenceScripts(ctx, resolvedReference);
35568
36136
  const prompt = buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domContext, referenceScripts, comment, resolvedReference, verification);
35569
- const tmpDir = path17.join(os18.tmpdir(), "adhdev-autoimpl");
36137
+ const tmpDir = path18.join(os18.tmpdir(), "adhdev-autoimpl");
35570
36138
  if (!fs13.existsSync(tmpDir)) fs13.mkdirSync(tmpDir, { recursive: true });
35571
- const promptFile = path17.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
36139
+ const promptFile = path18.join(tmpDir, `prompt-${type}-${Date.now()}.md`);
35572
36140
  fs13.writeFileSync(promptFile, prompt, "utf-8");
35573
36141
  ctx.log(`Auto-implement prompt written to ${promptFile} (${prompt.length} chars)`);
35574
36142
  const agentProvider = ctx.providerLoader.resolve(agent) || ctx.providerLoader.getMeta(agent);
@@ -35995,7 +36563,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
35995
36563
  setMode: "set_mode.js"
35996
36564
  };
35997
36565
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
35998
- const scriptsDir = path17.join(providerDir, "scripts");
36566
+ const scriptsDir = path18.join(providerDir, "scripts");
35999
36567
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
36000
36568
  if (latestScriptsDir) {
36001
36569
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -36006,7 +36574,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
36006
36574
  for (const file2 of fs13.readdirSync(latestScriptsDir)) {
36007
36575
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
36008
36576
  try {
36009
- const content = fs13.readFileSync(path17.join(latestScriptsDir, file2), "utf-8");
36577
+ const content = fs13.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
36010
36578
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
36011
36579
  lines.push("```javascript");
36012
36580
  lines.push(content);
@@ -36023,7 +36591,7 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
36023
36591
  lines.push("");
36024
36592
  for (const file2 of refFiles) {
36025
36593
  try {
36026
- const content = fs13.readFileSync(path17.join(latestScriptsDir, file2), "utf-8");
36594
+ const content = fs13.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
36027
36595
  lines.push(`### \`${file2}\` \u{1F512}`);
36028
36596
  lines.push("```javascript");
36029
36597
  lines.push(content);
@@ -36064,10 +36632,10 @@ function buildAutoImplPrompt(ctx, type, provider, providerDir, functions, domCon
36064
36632
  lines.push("");
36065
36633
  }
36066
36634
  }
36067
- const docsDir = path17.join(providerDir, "../../docs");
36635
+ const docsDir = path18.join(providerDir, "../../docs");
36068
36636
  const loadGuide = (name) => {
36069
36637
  try {
36070
- const p = path17.join(docsDir, name);
36638
+ const p = path18.join(docsDir, name);
36071
36639
  if (fs13.existsSync(p)) return fs13.readFileSync(p, "utf-8");
36072
36640
  } catch {
36073
36641
  }
@@ -36302,7 +36870,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
36302
36870
  parseApproval: "parse_approval.js"
36303
36871
  };
36304
36872
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
36305
- const scriptsDir = path17.join(providerDir, "scripts");
36873
+ const scriptsDir = path18.join(providerDir, "scripts");
36306
36874
  const latestScriptsDir = getLatestScriptVersionDir(scriptsDir);
36307
36875
  if (latestScriptsDir) {
36308
36876
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -36314,7 +36882,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
36314
36882
  if (!file2.endsWith(".js")) continue;
36315
36883
  if (!targetFileNames.has(file2)) continue;
36316
36884
  try {
36317
- const content = fs13.readFileSync(path17.join(latestScriptsDir, file2), "utf-8");
36885
+ const content = fs13.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
36318
36886
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
36319
36887
  lines.push("```javascript");
36320
36888
  lines.push(content);
@@ -36330,7 +36898,7 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
36330
36898
  lines.push("");
36331
36899
  for (const file2 of refFiles) {
36332
36900
  try {
36333
- const content = fs13.readFileSync(path17.join(latestScriptsDir, file2), "utf-8");
36901
+ const content = fs13.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
36334
36902
  lines.push(`### \`${file2}\` \u{1F512}`);
36335
36903
  lines.push("```javascript");
36336
36904
  lines.push(content);
@@ -36363,10 +36931,10 @@ function buildCliAutoImplPrompt(ctx, type, provider, providerDir, functions, ref
36363
36931
  lines.push("");
36364
36932
  }
36365
36933
  }
36366
- const docsDir = path17.join(providerDir, "../../docs");
36934
+ const docsDir = path18.join(providerDir, "../../docs");
36367
36935
  const loadGuide = (name) => {
36368
36936
  try {
36369
- const p = path17.join(docsDir, name);
36937
+ const p = path18.join(docsDir, name);
36370
36938
  if (fs13.existsSync(p)) return fs13.readFileSync(p, "utf-8");
36371
36939
  } catch {
36372
36940
  }
@@ -36678,12 +37246,12 @@ data: ${JSON.stringify(msg.data)}
36678
37246
  }
36679
37247
  }
36680
37248
  }
36681
- var fs13, path17, os18;
37249
+ var fs13, path18, os18;
36682
37250
  var init_dev_auto_implement = __esm({
36683
37251
  "../../oss/packages/daemon-core/src/daemon/dev-auto-implement.ts"() {
36684
37252
  "use strict";
36685
37253
  fs13 = __toESM(require("fs"));
36686
- path17 = __toESM(require("path"));
37254
+ path18 = __toESM(require("path"));
36687
37255
  os18 = __toESM(require("os"));
36688
37256
  init_dev_server();
36689
37257
  init_dev_cli_debug();
@@ -36691,13 +37259,13 @@ var init_dev_auto_implement = __esm({
36691
37259
  });
36692
37260
 
36693
37261
  // ../../oss/packages/daemon-core/src/daemon/dev-server.ts
36694
- var http2, fs14, path18, DEV_SERVER_PORT, DevServer;
37262
+ var http2, fs14, path19, DEV_SERVER_PORT, DevServer;
36695
37263
  var init_dev_server = __esm({
36696
37264
  "../../oss/packages/daemon-core/src/daemon/dev-server.ts"() {
36697
37265
  "use strict";
36698
37266
  http2 = __toESM(require("http"));
36699
37267
  fs14 = __toESM(require("fs"));
36700
- path18 = __toESM(require("path"));
37268
+ path19 = __toESM(require("path"));
36701
37269
  init_scaffold_template();
36702
37270
  init_version_archive();
36703
37271
  init_logger();
@@ -36801,8 +37369,8 @@ var init_dev_server = __esm({
36801
37369
  }
36802
37370
  getEndpointList() {
36803
37371
  return this.routes.map((r) => {
36804
- const path24 = typeof r.pattern === "string" ? r.pattern : r.pattern.source.replace(/\\\//g, "/").replace(/\(\[.*?\]\+\)/g, ":type").replace(/[\^$]/g, "");
36805
- 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}`;
36806
37374
  });
36807
37375
  }
36808
37376
  async start(port = DEV_SERVER_PORT) {
@@ -37084,12 +37652,12 @@ var init_dev_server = __esm({
37084
37652
  // ─── DevConsole SPA ───
37085
37653
  getConsoleDistDir() {
37086
37654
  const candidates = [
37087
- path18.resolve(__dirname, "../../web-devconsole/dist"),
37088
- path18.resolve(__dirname, "../../../web-devconsole/dist"),
37089
- 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")
37090
37658
  ];
37091
37659
  for (const dir of candidates) {
37092
- if (fs14.existsSync(path18.join(dir, "index.html"))) return dir;
37660
+ if (fs14.existsSync(path19.join(dir, "index.html"))) return dir;
37093
37661
  }
37094
37662
  return null;
37095
37663
  }
@@ -37099,7 +37667,7 @@ var init_dev_server = __esm({
37099
37667
  this.json(res, 500, { error: "DevConsole not found. Run: npm run build -w packages/web-devconsole" });
37100
37668
  return;
37101
37669
  }
37102
- const htmlPath = path18.join(distDir, "index.html");
37670
+ const htmlPath = path19.join(distDir, "index.html");
37103
37671
  try {
37104
37672
  const html = fs14.readFileSync(htmlPath, "utf-8");
37105
37673
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
@@ -37124,15 +37692,15 @@ var init_dev_server = __esm({
37124
37692
  this.json(res, 404, { error: "Not found" });
37125
37693
  return;
37126
37694
  }
37127
- const safePath = path18.normalize(pathname).replace(/^\.\.\//, "");
37128
- const filePath = path18.join(distDir, safePath);
37695
+ const safePath = path19.normalize(pathname).replace(/^\.\.\//, "");
37696
+ const filePath = path19.join(distDir, safePath);
37129
37697
  if (!filePath.startsWith(distDir)) {
37130
37698
  this.json(res, 403, { error: "Forbidden" });
37131
37699
  return;
37132
37700
  }
37133
37701
  try {
37134
37702
  const content = fs14.readFileSync(filePath);
37135
- const ext = path18.extname(filePath);
37703
+ const ext = path19.extname(filePath);
37136
37704
  const contentType = _DevServer.MIME_MAP[ext] || "application/octet-stream";
37137
37705
  res.writeHead(200, { "Content-Type": contentType, "Cache-Control": "public, max-age=31536000, immutable" });
37138
37706
  res.end(content);
@@ -37245,9 +37813,9 @@ var init_dev_server = __esm({
37245
37813
  const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
37246
37814
  if (entry.isDirectory()) {
37247
37815
  files.push({ path: rel, size: 0, type: "dir" });
37248
- scan(path18.join(d, entry.name), rel);
37816
+ scan(path19.join(d, entry.name), rel);
37249
37817
  } else {
37250
- const stat4 = fs14.statSync(path18.join(d, entry.name));
37818
+ const stat4 = fs14.statSync(path19.join(d, entry.name));
37251
37819
  files.push({ path: rel, size: stat4.size, type: "file" });
37252
37820
  }
37253
37821
  }
@@ -37270,7 +37838,7 @@ var init_dev_server = __esm({
37270
37838
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
37271
37839
  return;
37272
37840
  }
37273
- const fullPath = path18.resolve(dir, path18.normalize(filePath));
37841
+ const fullPath = path19.resolve(dir, path19.normalize(filePath));
37274
37842
  if (!fullPath.startsWith(dir)) {
37275
37843
  this.json(res, 403, { error: "Forbidden" });
37276
37844
  return;
@@ -37295,14 +37863,14 @@ var init_dev_server = __esm({
37295
37863
  this.json(res, 404, { error: `Provider directory not found: ${type}` });
37296
37864
  return;
37297
37865
  }
37298
- const fullPath = path18.resolve(dir, path18.normalize(filePath));
37866
+ const fullPath = path19.resolve(dir, path19.normalize(filePath));
37299
37867
  if (!fullPath.startsWith(dir)) {
37300
37868
  this.json(res, 403, { error: "Forbidden" });
37301
37869
  return;
37302
37870
  }
37303
37871
  try {
37304
37872
  if (fs14.existsSync(fullPath)) fs14.copyFileSync(fullPath, fullPath + ".bak");
37305
- fs14.mkdirSync(path18.dirname(fullPath), { recursive: true });
37873
+ fs14.mkdirSync(path19.dirname(fullPath), { recursive: true });
37306
37874
  fs14.writeFileSync(fullPath, content, "utf-8");
37307
37875
  this.log(`File saved: ${fullPath} (${content.length} chars)`);
37308
37876
  this.providerLoader.reload();
@@ -37319,7 +37887,7 @@ var init_dev_server = __esm({
37319
37887
  return;
37320
37888
  }
37321
37889
  for (const name of ["scripts.js", "provider.json"]) {
37322
- const p = path18.join(dir, name);
37890
+ const p = path19.join(dir, name);
37323
37891
  if (fs14.existsSync(p)) {
37324
37892
  const source = fs14.readFileSync(p, "utf-8");
37325
37893
  this.json(res, 200, { type, path: p, source, lines: source.split("\n").length });
@@ -37340,8 +37908,8 @@ var init_dev_server = __esm({
37340
37908
  this.json(res, 404, { error: `Provider not found: ${type}` });
37341
37909
  return;
37342
37910
  }
37343
- const target = fs14.existsSync(path18.join(dir, "scripts.js")) ? "scripts.js" : "provider.json";
37344
- 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);
37345
37913
  try {
37346
37914
  if (fs14.existsSync(targetPath)) fs14.copyFileSync(targetPath, targetPath + ".bak");
37347
37915
  fs14.writeFileSync(targetPath, source, "utf-8");
@@ -37501,7 +38069,7 @@ var init_dev_server = __esm({
37501
38069
  }
37502
38070
  let targetDir;
37503
38071
  targetDir = this.providerLoader.getUserProviderDir(category, type);
37504
- const jsonPath = path18.join(targetDir, "provider.json");
38072
+ const jsonPath = path19.join(targetDir, "provider.json");
37505
38073
  if (fs14.existsSync(jsonPath)) {
37506
38074
  this.json(res, 409, { error: `Provider already exists at ${targetDir}`, path: targetDir });
37507
38075
  return;
@@ -37513,8 +38081,8 @@ var init_dev_server = __esm({
37513
38081
  const createdFiles = ["provider.json"];
37514
38082
  if (result.files) {
37515
38083
  for (const [relPath, content] of Object.entries(result.files)) {
37516
- const fullPath = path18.join(targetDir, relPath);
37517
- fs14.mkdirSync(path18.dirname(fullPath), { recursive: true });
38084
+ const fullPath = path19.join(targetDir, relPath);
38085
+ fs14.mkdirSync(path19.dirname(fullPath), { recursive: true });
37518
38086
  fs14.writeFileSync(fullPath, content, "utf-8");
37519
38087
  createdFiles.push(relPath);
37520
38088
  }
@@ -37567,22 +38135,22 @@ var init_dev_server = __esm({
37567
38135
  if (!fs14.existsSync(scriptsDir)) return null;
37568
38136
  const versions = fs14.readdirSync(scriptsDir).filter((d) => {
37569
38137
  try {
37570
- return fs14.statSync(path18.join(scriptsDir, d)).isDirectory();
38138
+ return fs14.statSync(path19.join(scriptsDir, d)).isDirectory();
37571
38139
  } catch {
37572
38140
  return false;
37573
38141
  }
37574
38142
  }).sort((a, b) => b.localeCompare(a, void 0, { numeric: true, sensitivity: "base" }));
37575
38143
  if (versions.length === 0) return null;
37576
- return path18.join(scriptsDir, versions[0]);
38144
+ return path19.join(scriptsDir, versions[0]);
37577
38145
  }
37578
38146
  resolveAutoImplWritableProviderDir(category, type, requestedDir) {
37579
- const canonicalUserDir = path18.resolve(this.providerLoader.getUserProviderDir(category, type));
37580
- const desiredDir = requestedDir ? path18.resolve(requestedDir) : canonicalUserDir;
37581
- const upstreamRoot = path18.resolve(this.providerLoader.getUpstreamDir());
37582
- 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}`)) {
37583
38151
  return { dir: null, reason: `Refusing to write into upstream provider directory: ${desiredDir}` };
37584
38152
  }
37585
- if (path18.basename(desiredDir) !== type) {
38153
+ if (path19.basename(desiredDir) !== type) {
37586
38154
  return { dir: null, reason: `Requested writable provider directory must end with '${type}': ${desiredDir}` };
37587
38155
  }
37588
38156
  const sourceDir = this.findProviderDir(type);
@@ -37590,11 +38158,11 @@ var init_dev_server = __esm({
37590
38158
  return { dir: null, reason: `Provider source directory not found for '${type}'` };
37591
38159
  }
37592
38160
  if (!fs14.existsSync(desiredDir)) {
37593
- fs14.mkdirSync(path18.dirname(desiredDir), { recursive: true });
38161
+ fs14.mkdirSync(path19.dirname(desiredDir), { recursive: true });
37594
38162
  fs14.cpSync(sourceDir, desiredDir, { recursive: true });
37595
38163
  this.log(`Auto-implement writable copy created: ${desiredDir}`);
37596
38164
  }
37597
- const providerJson = path18.join(desiredDir, "provider.json");
38165
+ const providerJson = path19.join(desiredDir, "provider.json");
37598
38166
  if (!fs14.existsSync(providerJson)) {
37599
38167
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
37600
38168
  }
@@ -37642,7 +38210,7 @@ var init_dev_server = __esm({
37642
38210
  setMode: "set_mode.js"
37643
38211
  };
37644
38212
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
37645
- const scriptsDir = path18.join(providerDir, "scripts");
38213
+ const scriptsDir = path19.join(providerDir, "scripts");
37646
38214
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
37647
38215
  if (latestScriptsDir) {
37648
38216
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -37653,7 +38221,7 @@ var init_dev_server = __esm({
37653
38221
  for (const file2 of fs14.readdirSync(latestScriptsDir)) {
37654
38222
  if (file2.endsWith(".js") && targetFileNames.has(file2)) {
37655
38223
  try {
37656
- const content = fs14.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
38224
+ const content = fs14.readFileSync(path19.join(latestScriptsDir, file2), "utf-8");
37657
38225
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
37658
38226
  lines.push("```javascript");
37659
38227
  lines.push(content);
@@ -37670,7 +38238,7 @@ var init_dev_server = __esm({
37670
38238
  lines.push("");
37671
38239
  for (const file2 of refFiles) {
37672
38240
  try {
37673
- const content = fs14.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
38241
+ const content = fs14.readFileSync(path19.join(latestScriptsDir, file2), "utf-8");
37674
38242
  lines.push(`### \`${file2}\` \u{1F512}`);
37675
38243
  lines.push("```javascript");
37676
38244
  lines.push(content);
@@ -37711,10 +38279,10 @@ var init_dev_server = __esm({
37711
38279
  lines.push("");
37712
38280
  }
37713
38281
  }
37714
- const docsDir = path18.join(providerDir, "../../docs");
38282
+ const docsDir = path19.join(providerDir, "../../docs");
37715
38283
  const loadGuide = (name) => {
37716
38284
  try {
37717
- const p = path18.join(docsDir, name);
38285
+ const p = path19.join(docsDir, name);
37718
38286
  if (fs14.existsSync(p)) return fs14.readFileSync(p, "utf-8");
37719
38287
  } catch {
37720
38288
  }
@@ -37888,7 +38456,7 @@ var init_dev_server = __esm({
37888
38456
  parseApproval: "parse_approval.js"
37889
38457
  };
37890
38458
  const targetFileNames = new Set(functions.map((fn) => funcToFile[fn]).filter(Boolean));
37891
- const scriptsDir = path18.join(providerDir, "scripts");
38459
+ const scriptsDir = path19.join(providerDir, "scripts");
37892
38460
  const latestScriptsDir = this.getLatestScriptVersionDir(scriptsDir);
37893
38461
  if (latestScriptsDir) {
37894
38462
  lines.push(`Scripts version directory: \`${latestScriptsDir}\``);
@@ -37900,7 +38468,7 @@ var init_dev_server = __esm({
37900
38468
  if (!file2.endsWith(".js")) continue;
37901
38469
  if (!targetFileNames.has(file2)) continue;
37902
38470
  try {
37903
- const content = fs14.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
38471
+ const content = fs14.readFileSync(path19.join(latestScriptsDir, file2), "utf-8");
37904
38472
  lines.push(`### \`${file2}\` \u270F\uFE0F EDIT`);
37905
38473
  lines.push("```javascript");
37906
38474
  lines.push(content);
@@ -37916,7 +38484,7 @@ var init_dev_server = __esm({
37916
38484
  lines.push("");
37917
38485
  for (const file2 of refFiles) {
37918
38486
  try {
37919
- const content = fs14.readFileSync(path18.join(latestScriptsDir, file2), "utf-8");
38487
+ const content = fs14.readFileSync(path19.join(latestScriptsDir, file2), "utf-8");
37920
38488
  lines.push(`### \`${file2}\` \u{1F512}`);
37921
38489
  lines.push("```javascript");
37922
38490
  lines.push(content);
@@ -37949,10 +38517,10 @@ var init_dev_server = __esm({
37949
38517
  lines.push("");
37950
38518
  }
37951
38519
  }
37952
- const docsDir = path18.join(providerDir, "../../docs");
38520
+ const docsDir = path19.join(providerDir, "../../docs");
37953
38521
  const loadGuide = (name) => {
37954
38522
  try {
37955
- const p = path18.join(docsDir, name);
38523
+ const p = path19.join(docsDir, name);
37956
38524
  if (fs14.existsSync(p)) return fs14.readFileSync(p, "utf-8");
37957
38525
  } catch {
37958
38526
  }
@@ -38471,6 +39039,7 @@ var init_session_host_transport = __esm({
38471
39039
  }
38472
39040
  }
38473
39041
  handleEvent(event) {
39042
+ if (!("sessionId" in event)) return;
38474
39043
  if (event.sessionId !== this.options.runtimeId) return;
38475
39044
  if ((event.type === "session_started" || event.type === "session_resumed") && typeof event.pid === "number") {
38476
39045
  this.currentPid = event.pid;
@@ -38546,7 +39115,10 @@ var init_session_host_transport = __esm({
38546
39115
  clientId: client.clientId,
38547
39116
  type: client.type,
38548
39117
  readOnly: client.readOnly
38549
- }))
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
38550
39122
  };
38551
39123
  }
38552
39124
  enqueue(action) {
@@ -39008,6 +39580,7 @@ async function initDaemonComponents(config2) {
39008
39580
  onIdeConnected: () => poller?.start(),
39009
39581
  onStatusChange: config2.onStatusChange,
39010
39582
  onPostChatCommand: config2.onPostChatCommand,
39583
+ sessionHostControl: config2.sessionHostControl,
39011
39584
  getCdpLogFn: config2.getCdpLogFn || ((ideType) => LOG.forComponent(`CDP:${ideType}`).asLogFn())
39012
39585
  });
39013
39586
  poller = new AgentStreamPoller({
@@ -39666,17 +40239,17 @@ function canPeerUsePrivilegedShareCommand(commandType, permission) {
39666
40239
  return false;
39667
40240
  }
39668
40241
  }
39669
- 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;
39670
40243
  var init_daemon_p2p = __esm({
39671
40244
  "src/daemon-p2p.ts"() {
39672
40245
  "use strict";
39673
40246
  fs15 = __toESM(require("fs"));
39674
40247
  init_src();
39675
- path19 = __toESM(require("path"));
40248
+ path20 = __toESM(require("path"));
39676
40249
  os19 = __toESM(require("os"));
39677
40250
  import_node_module2 = require("module");
39678
40251
  esmRequire = (0, import_node_module2.createRequire)(__filename);
39679
- logFile = path19.join(os19.tmpdir(), "adhdev_daemon_p2p.log");
40252
+ logFile = path20.join(os19.tmpdir(), "adhdev_daemon_p2p.log");
39680
40253
  log = (msg) => {
39681
40254
  LOG.info("P2P", `[${(/* @__PURE__ */ new Date()).toISOString()}] [P2P] ${msg}`);
39682
40255
  };
@@ -39744,15 +40317,15 @@ ${e?.stack || ""}`);
39744
40317
  const prebuildKey = `${platform11}-${arch3}`;
39745
40318
  try {
39746
40319
  const candidates = [
39747
- path19.join(__dirname, "node_modules", "node-datachannel"),
39748
- path19.join(__dirname, "..", "node_modules", "node-datachannel"),
39749
- 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")
39750
40323
  ];
39751
40324
  for (const candidate of candidates) {
39752
- const prebuildPath = path19.join(candidate, "prebuilds", prebuildKey, "node_datachannel.node");
40325
+ const prebuildPath = path20.join(candidate, "prebuilds", prebuildKey, "node_datachannel.node");
39753
40326
  if (fs15.existsSync(prebuildPath)) {
39754
- const targetDir = path19.join(candidate, "build", "Release");
39755
- 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");
39756
40329
  fs15.mkdirSync(targetDir, { recursive: true });
39757
40330
  fs15.copyFileSync(prebuildPath, targetPath);
39758
40331
  try {
@@ -40532,16 +41105,16 @@ var require_filesystem = __commonJS({
40532
41105
  var LDD_PATH = "/usr/bin/ldd";
40533
41106
  var SELF_PATH = "/proc/self/exe";
40534
41107
  var MAX_LENGTH = 2048;
40535
- var readFileSync18 = (path24) => {
40536
- const fd = fs19.openSync(path24, "r");
41108
+ var readFileSync18 = (path25) => {
41109
+ const fd = fs19.openSync(path25, "r");
40537
41110
  const buffer = Buffer.alloc(MAX_LENGTH);
40538
41111
  const bytesRead = fs19.readSync(fd, buffer, 0, MAX_LENGTH, 0);
40539
41112
  fs19.close(fd, () => {
40540
41113
  });
40541
41114
  return buffer.subarray(0, bytesRead);
40542
41115
  };
40543
- var readFile = (path24) => new Promise((resolve14, reject) => {
40544
- fs19.open(path24, "r", (err, fd) => {
41116
+ var readFile = (path25) => new Promise((resolve14, reject) => {
41117
+ fs19.open(path25, "r", (err, fd) => {
40545
41118
  if (err) {
40546
41119
  reject(err);
40547
41120
  } else {
@@ -40660,11 +41233,11 @@ var require_detect_libc = __commonJS({
40660
41233
  }
40661
41234
  return null;
40662
41235
  };
40663
- var familyFromInterpreterPath = (path24) => {
40664
- if (path24) {
40665
- if (path24.includes("/ld-musl-")) {
41236
+ var familyFromInterpreterPath = (path25) => {
41237
+ if (path25) {
41238
+ if (path25.includes("/ld-musl-")) {
40666
41239
  return MUSL;
40667
- } else if (path24.includes("/ld-linux-")) {
41240
+ } else if (path25.includes("/ld-linux-")) {
40668
41241
  return GLIBC;
40669
41242
  }
40670
41243
  }
@@ -40711,8 +41284,8 @@ var require_detect_libc = __commonJS({
40711
41284
  cachedFamilyInterpreter = null;
40712
41285
  try {
40713
41286
  const selfContent = await readFile(SELF_PATH);
40714
- const path24 = interpreterPath(selfContent);
40715
- cachedFamilyInterpreter = familyFromInterpreterPath(path24);
41287
+ const path25 = interpreterPath(selfContent);
41288
+ cachedFamilyInterpreter = familyFromInterpreterPath(path25);
40716
41289
  } catch (e) {
40717
41290
  }
40718
41291
  return cachedFamilyInterpreter;
@@ -40724,8 +41297,8 @@ var require_detect_libc = __commonJS({
40724
41297
  cachedFamilyInterpreter = null;
40725
41298
  try {
40726
41299
  const selfContent = readFileSync18(SELF_PATH);
40727
- const path24 = interpreterPath(selfContent);
40728
- cachedFamilyInterpreter = familyFromInterpreterPath(path24);
41300
+ const path25 = interpreterPath(selfContent);
41301
+ cachedFamilyInterpreter = familyFromInterpreterPath(path25);
40729
41302
  } catch (e) {
40730
41303
  }
40731
41304
  return cachedFamilyInterpreter;
@@ -42444,18 +43017,18 @@ var require_sharp = __commonJS({
42444
43017
  `@img/sharp-${runtimePlatform}/sharp.node`,
42445
43018
  "@img/sharp-wasm32/sharp.node"
42446
43019
  ];
42447
- var path24;
43020
+ var path25;
42448
43021
  var sharp;
42449
43022
  var errors = [];
42450
- for (path24 of paths) {
43023
+ for (path25 of paths) {
42451
43024
  try {
42452
- sharp = require(path24);
43025
+ sharp = require(path25);
42453
43026
  break;
42454
43027
  } catch (err) {
42455
43028
  errors.push(err);
42456
43029
  }
42457
43030
  }
42458
- if (sharp && path24.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
43031
+ if (sharp && path25.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
42459
43032
  const err = new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");
42460
43033
  err.code = "Unsupported CPU";
42461
43034
  errors.push(err);
@@ -45364,15 +45937,15 @@ var require_color = __commonJS({
45364
45937
  };
45365
45938
  }
45366
45939
  function wrapConversion(toModel, graph) {
45367
- const path24 = [graph[toModel].parent, toModel];
45940
+ const path25 = [graph[toModel].parent, toModel];
45368
45941
  let fn = conversions_default[graph[toModel].parent][toModel];
45369
45942
  let cur = graph[toModel].parent;
45370
45943
  while (graph[cur].parent) {
45371
- path24.unshift(graph[cur].parent);
45944
+ path25.unshift(graph[cur].parent);
45372
45945
  fn = link(conversions_default[graph[cur].parent][cur], fn);
45373
45946
  cur = graph[cur].parent;
45374
45947
  }
45375
- fn.conversion = path24;
45948
+ fn.conversion = path25;
45376
45949
  return fn;
45377
45950
  }
45378
45951
  function route(fromModel) {
@@ -45989,7 +46562,7 @@ var require_channel = __commonJS({
45989
46562
  var require_output = __commonJS({
45990
46563
  "../../node_modules/sharp/lib/output.js"(exports2, module2) {
45991
46564
  "use strict";
45992
- var path24 = require("path");
46565
+ var path25 = require("path");
45993
46566
  var is = require_is();
45994
46567
  var sharp = require_sharp();
45995
46568
  var formats = /* @__PURE__ */ new Map([
@@ -46020,9 +46593,9 @@ var require_output = __commonJS({
46020
46593
  let err;
46021
46594
  if (!is.string(fileOut)) {
46022
46595
  err = new Error("Missing output file path");
46023
- } 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)) {
46024
46597
  err = new Error("Cannot use same file for input and output");
46025
- } 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) {
46026
46599
  err = errJp2Save();
46027
46600
  }
46028
46601
  if (err) {
@@ -47236,8 +47809,8 @@ function buildSessionHostEnv(baseEnv) {
47236
47809
  }
47237
47810
  function resolveSessionHostEntry() {
47238
47811
  const packagedCandidates = [
47239
- path20.resolve(__dirname, "../vendor/session-host-daemon/index.js"),
47240
- 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")
47241
47814
  ];
47242
47815
  for (const candidate of packagedCandidates) {
47243
47816
  if (fs16.existsSync(candidate)) {
@@ -47247,7 +47820,7 @@ function resolveSessionHostEntry() {
47247
47820
  return require.resolve("@adhdev/session-host-daemon");
47248
47821
  }
47249
47822
  function getSessionHostPidFile() {
47250
- 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`);
47251
47824
  }
47252
47825
  function getSessionHostStatusPaths() {
47253
47826
  return {
@@ -47360,9 +47933,9 @@ function stopSessionHost() {
47360
47933
  async function ensureSessionHostReady2() {
47361
47934
  const spawnHost = () => {
47362
47935
  const entry = resolveSessionHostEntry();
47363
- const logDir = path20.join(os20.homedir(), ".adhdev", "logs");
47936
+ const logDir = path21.join(os20.homedir(), ".adhdev", "logs");
47364
47937
  fs16.mkdirSync(logDir, { recursive: true });
47365
- const logFd = fs16.openSync(path20.join(logDir, "session-host.log"), "a");
47938
+ const logFd = fs16.openSync(path21.join(logDir, "session-host.log"), "a");
47366
47939
  const child = (0, import_child_process11.spawn)(process.execPath, [entry], {
47367
47940
  detached: true,
47368
47941
  stdio: ["ignore", logFd, logFd],
@@ -47424,14 +47997,14 @@ async function probeSessionHostStatus() {
47424
47997
  };
47425
47998
  }
47426
47999
  }
47427
- 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;
47428
48001
  var init_session_host = __esm({
47429
48002
  "src/session-host.ts"() {
47430
48003
  "use strict";
47431
48004
  import_child_process11 = require("child_process");
47432
48005
  fs16 = __toESM(require("fs"));
47433
48006
  os20 = __toESM(require("os"));
47434
- path20 = __toESM(require("path"));
48007
+ path21 = __toESM(require("path"));
47435
48008
  init_src();
47436
48009
  init_dist();
47437
48010
  SESSION_HOST_APP_NAME = process.env.ADHDEV_SESSION_HOST_NAME || "adhdev";
@@ -47439,6 +48012,151 @@ var init_session_host = __esm({
47439
48012
  }
47440
48013
  });
47441
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
+
47442
48160
  // src/version.ts
47443
48161
  function resolvePackageVersion(options) {
47444
48162
  const injectedVersion = options?.injectedVersion || "unknown";
@@ -47475,9 +48193,9 @@ __export(adhdev_daemon_exports, {
47475
48193
  stopDaemon: () => stopDaemon
47476
48194
  });
47477
48195
  function getDaemonPidFile() {
47478
- const dir = path21.join(os21.homedir(), ".adhdev");
48196
+ const dir = path23.join(os21.homedir(), ".adhdev");
47479
48197
  if (!fs17.existsSync(dir)) fs17.mkdirSync(dir, { recursive: true });
47480
- return path21.join(dir, "daemon.pid");
48198
+ return path23.join(dir, "daemon.pid");
47481
48199
  }
47482
48200
  function writeDaemonPid(pid) {
47483
48201
  fs17.writeFileSync(getDaemonPidFile(), String(pid), "utf-8");
@@ -47523,7 +48241,7 @@ function stopDaemon() {
47523
48241
  return false;
47524
48242
  }
47525
48243
  }
47526
- 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;
47527
48245
  var init_adhdev_daemon = __esm({
47528
48246
  "src/adhdev-daemon.ts"() {
47529
48247
  "use strict";
@@ -47533,14 +48251,15 @@ var init_adhdev_daemon = __esm({
47533
48251
  init_screenshot_controller();
47534
48252
  init_session_host();
47535
48253
  init_dist();
48254
+ init_session_host_controller();
47536
48255
  os21 = __toESM(require("os"));
47537
48256
  fs17 = __toESM(require("fs"));
47538
- path21 = __toESM(require("path"));
48257
+ path23 = __toESM(require("path"));
47539
48258
  import_http = require("http");
47540
48259
  import_ws3 = require("ws");
47541
48260
  import_chalk2 = __toESM(require("chalk"));
47542
48261
  init_version();
47543
- pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.25" });
48262
+ pkgVersion = resolvePackageVersion({ injectedVersion: "0.8.27" });
47544
48263
  DANGEROUS_PATTERNS = [
47545
48264
  /\brm\s+(-[a-z]*f|-[a-z]*r|--force|--recursive)/i,
47546
48265
  /\bsudo\b/i,
@@ -47563,6 +48282,7 @@ var init_adhdev_daemon = __esm({
47563
48282
  statusReporter = null;
47564
48283
  components = null;
47565
48284
  sessionHostEndpoint = null;
48285
+ sessionHostController = null;
47566
48286
  running = false;
47567
48287
  localPort;
47568
48288
  ideType = "unknown";
@@ -47613,6 +48333,11 @@ ${err?.stack || ""}`);
47613
48333
  }
47614
48334
  const sessionHostEndpoint = await ensureSessionHostReady2();
47615
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();
47616
48341
  this.components = await initDaemonComponents({
47617
48342
  providerLogFn: LOG.forComponent("Provider").asLogFn(),
47618
48343
  cliManagerDeps: {
@@ -47650,6 +48375,7 @@ ${err?.stack || ""}`);
47650
48375
  setTimeout(() => this.statusReporter?.throttledReport(), 1e3);
47651
48376
  setTimeout(() => this.statusReporter?.throttledReport(), 3e3);
47652
48377
  },
48378
+ sessionHostControl: this.sessionHostController,
47653
48379
  getCdpLogFn: (ideType) => LOG.forComponent(`CDP:${ideType}`).asLogFn(),
47654
48380
  onCdpManagerSetup: (ideType) => {
47655
48381
  if (this.ideType === "unknown") this.ideType = ideType;
@@ -48006,13 +48732,24 @@ ${err?.stack || ""}`);
48006
48732
  serverConnected: this.serverConn?.isConnected() ?? false,
48007
48733
  cdpConnected: (this.components?.cdpManagers.size || 0) > 0,
48008
48734
  localPort: this.localPort,
48009
- cliAgents
48735
+ cliAgents,
48736
+ sessionHostConnected: !!this.sessionHostController
48010
48737
  }
48011
48738
  }));
48012
48739
  } catch (error48) {
48013
48740
  LOG.warn("IPC", `Failed to send welcome: ${error48?.message || error48}`);
48014
48741
  }
48015
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
+ }
48016
48753
  async handleLocalIpcMessage(ws, raw) {
48017
48754
  let msg;
48018
48755
  try {
@@ -48103,6 +48840,11 @@ ${err?.stack || ""}`);
48103
48840
  this.serverConn?.disconnect();
48104
48841
  } catch {
48105
48842
  }
48843
+ try {
48844
+ await this.sessionHostController?.stop();
48845
+ this.sessionHostController = null;
48846
+ } catch {
48847
+ }
48106
48848
  try {
48107
48849
  for (const client of this.localClients) {
48108
48850
  client.close();
@@ -48934,6 +49676,45 @@ function hideCommand(command) {
48934
49676
  command.hideHelp?.();
48935
49677
  return command;
48936
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
+ }
48937
49718
  function registerDaemonCommands(program2, pkgVersion3) {
48938
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) => {
48939
49720
  const { AdhdevDaemon: AdhdevDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
@@ -48973,39 +49754,71 @@ function registerDaemonCommands(program2, pkgVersion3) {
48973
49754
  \u2717 Failed to start standalone server: ${err.message}`));
48974
49755
  });
48975
49756
  });
48976
- 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) => {
48977
49758
  const { isDaemonRunning: isDaemonRunning2, getDaemonPid: getDaemonPid2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
48978
49759
  const { getCurrentDaemonLogPath: getCurrentDaemonLogPath2 } = await Promise.resolve().then(() => (init_src(), src_exports));
48979
49760
  const { probeSessionHostStatus: probeSessionHostStatus2 } = await Promise.resolve().then(() => (init_session_host(), session_host_exports));
49761
+ const port = parseInt(options.port, 10) || 19222;
48980
49762
  if (isDaemonRunning2()) {
48981
49763
  console.log(import_chalk5.default.green(`
48982
49764
  \u2713 ADHDev Daemon is running.
48983
49765
  `));
48984
49766
  console.log(import_chalk5.default.gray(` PID: ${getDaemonPid2() ?? "unknown"}`));
48985
49767
  console.log(import_chalk5.default.gray(` Logs: ${getCurrentDaemonLogPath2()}`));
48986
- try {
48987
- const controller = new AbortController();
48988
- const timer = setTimeout(() => controller.abort(), 1500);
48989
- const res = await fetch("http://127.0.0.1:19222/health", { signal: controller.signal });
48990
- clearTimeout(timer);
48991
- if (res.ok) {
48992
- const data = await res.json();
48993
- console.log(import_chalk5.default.gray(` Local IPC: reachable (ws://127.0.0.1:${data.port}${data.wsPath})`));
48994
- } else {
48995
- console.log(import_chalk5.default.gray(" Local IPC: not reachable"));
48996
- }
48997
- } 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 {
48998
49772
  console.log(import_chalk5.default.gray(" Local IPC: not reachable"));
48999
49773
  }
49000
- try {
49001
- const sessionHost = await probeSessionHostStatus2();
49002
- console.log(import_chalk5.default.gray(
49003
- ` SessionHost: ${sessionHost.reachable ? `reachable (${sessionHost.runtimeCount} active runtime${sessionHost.runtimeCount === 1 ? "" : "s"})` : "not reachable"}`
49004
- ));
49005
- console.log(import_chalk5.default.gray(` Session IPC: ${sessionHost.endpoint.path}`));
49006
- console.log(import_chalk5.default.gray(` Session PID: ${sessionHost.pid ?? "unknown"}`));
49007
- } catch {
49008
- 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
+ }
49009
49822
  }
49010
49823
  try {
49011
49824
  const controller = new AbortController();
@@ -49031,6 +49844,135 @@ function registerDaemonCommands(program2, pkgVersion3) {
49031
49844
  `));
49032
49845
  }
49033
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
+ }));
49034
49976
  hideCommand(program2.command("daemon:stop").description("Stop ADHDev Daemon").action(async () => {
49035
49977
  const { stopDaemon: stopDaemon2 } = await Promise.resolve().then(() => (init_adhdev_daemon(), adhdev_daemon_exports));
49036
49978
  if (stopDaemon2()) {
@@ -49193,15 +50135,15 @@ var import_chalk6 = __toESM(require("chalk"));
49193
50135
  var import_child_process12 = require("child_process");
49194
50136
  var fs18 = __toESM(require("fs"));
49195
50137
  var os23 = __toESM(require("os"));
49196
- var path23 = __toESM(require("path"));
50138
+ var path24 = __toESM(require("path"));
49197
50139
  init_src();
49198
50140
  init_session_host();
49199
50141
  function resolvePackageRoot() {
49200
- return path23.resolve(__dirname, "..", "..");
50142
+ return path24.resolve(__dirname, "..", "..");
49201
50143
  }
49202
50144
  function isLinkedInstall(packageRoot) {
49203
- const normalized = path23.normalize(packageRoot);
49204
- 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`);
49205
50147
  }
49206
50148
  function formatCheck(check2) {
49207
50149
  const icon = check2.ok ? import_chalk6.default.green("\u2713") : import_chalk6.default.red("\u2717");
@@ -49255,8 +50197,8 @@ function probeNodeDatachannel(packageRoot) {
49255
50197
  }
49256
50198
  }
49257
50199
  function probeConfigAccess() {
49258
- const configDir = path23.join(os23.homedir(), ".adhdev");
49259
- const configPath = path23.join(configDir, "config.json");
50200
+ const configDir = path24.join(os23.homedir(), ".adhdev");
50201
+ const configPath = path24.join(configDir, "config.json");
49260
50202
  const checks = [];
49261
50203
  try {
49262
50204
  fs18.mkdirSync(configDir, { recursive: true });
@@ -49296,7 +50238,7 @@ function probeConfigAccess() {
49296
50238
  fatal: true
49297
50239
  });
49298
50240
  }
49299
- 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`);
49300
50242
  try {
49301
50243
  fs18.writeFileSync(probePath, "ok", "utf-8");
49302
50244
  fs18.rmSync(probePath, { force: true });
@@ -49464,7 +50406,7 @@ function registerDoctorCommands(program2, pkgVersion3) {
49464
50406
  const failures = checks.filter((check2) => !check2.ok && check2.fatal);
49465
50407
  const warnings = checks.filter((check2) => !check2.ok && !check2.fatal);
49466
50408
  const logHints = readLogHints(logPath);
49467
- const sessionHostLogPath = path23.join(os23.homedir(), ".adhdev", "logs", "session-host.log");
50409
+ const sessionHostLogPath = path24.join(os23.homedir(), ".adhdev", "logs", "session-host.log");
49468
50410
  console.log(import_chalk6.default.bold("\n\u{1FA7A} ADHDev Doctor\n"));
49469
50411
  console.log(import_chalk6.default.gray(` Version: ${pkgVersion3}`));
49470
50412
  console.log(import_chalk6.default.gray(` Platform: ${process.platform} ${process.arch}`));
@@ -49784,7 +50726,7 @@ function registerProviderCommands(program2) {
49784
50726
  let processNames = {};
49785
50727
  if (category === "ide") {
49786
50728
  const fs19 = await import("fs");
49787
- const path24 = await import("path");
50729
+ const path25 = await import("path");
49788
50730
  const os24 = await import("os");
49789
50731
  if (os24.platform() === "darwin") {
49790
50732
  while (true) {
@@ -49797,7 +50739,7 @@ function registerProviderCommands(program2) {
49797
50739
  }
49798
50740
  console.log(import_chalk7.default.green(` \u2713 Path verified: ${p}`));
49799
50741
  osPaths["darwin"] = [p];
49800
- processNames["darwin"] = path24.basename(p, ".app");
50742
+ processNames["darwin"] = path25.basename(p, ".app");
49801
50743
  break;
49802
50744
  }
49803
50745
  } else if (os24.platform() === "win32") {
@@ -49811,7 +50753,7 @@ function registerProviderCommands(program2) {
49811
50753
  }
49812
50754
  console.log(import_chalk7.default.green(` \u2713 Path verified: ${p}`));
49813
50755
  osPaths["win32"] = [p];
49814
- processNames["win32"] = path24.basename(p, ".exe");
50756
+ processNames["win32"] = path25.basename(p, ".exe");
49815
50757
  break;
49816
50758
  }
49817
50759
  }