@adhdev/daemon-standalone 0.8.57 → 0.8.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -27874,9 +27874,16 @@ var require_dist2 = __commonJS({
27874
27874
  loadConfig: () => loadConfig2,
27875
27875
  markSetupComplete: () => markSetupComplete,
27876
27876
  resetConfig: () => resetConfig,
27877
+ resolveProviderSourceMode: () => resolveProviderSourceMode,
27877
27878
  saveConfig: () => saveConfig,
27878
27879
  updateConfig: () => updateConfig
27879
27880
  });
27881
+ function resolveProviderSourceMode(providerSourceMode, legacyDisableUpstream) {
27882
+ if (providerSourceMode === "normal" || providerSourceMode === "no-upstream") {
27883
+ return providerSourceMode;
27884
+ }
27885
+ return legacyDisableUpstream === true ? "no-upstream" : "normal";
27886
+ }
27880
27887
  function isPlainObject2(value) {
27881
27888
  return !!value && typeof value === "object" && !Array.isArray(value);
27882
27889
  }
@@ -27914,7 +27921,7 @@ var require_dist2 = __commonJS({
27914
27921
  registeredMachineId: asOptionalString(parsed.registeredMachineId),
27915
27922
  providerSettings: isPlainObject2(parsed.providerSettings) ? parsed.providerSettings : {},
27916
27923
  ideSettings: isPlainObject2(parsed.ideSettings) ? parsed.ideSettings : {},
27917
- disableUpstream: asBoolean(parsed.disableUpstream, DEFAULT_CONFIG.disableUpstream ?? false),
27924
+ providerSourceMode: resolveProviderSourceMode(parsed.providerSourceMode, parsed.disableUpstream),
27918
27925
  providerDir: asOptionalString(parsed.providerDir),
27919
27926
  terminalSizingMode: parsed.terminalSizingMode === "fit" ? "fit" : "measured"
27920
27927
  };
@@ -28068,7 +28075,7 @@ var require_dist2 = __commonJS({
28068
28075
  registeredMachineId: void 0,
28069
28076
  providerSettings: {},
28070
28077
  ideSettings: {},
28071
- disableUpstream: false,
28078
+ providerSourceMode: "normal",
28072
28079
  terminalSizingMode: "measured"
28073
28080
  };
28074
28081
  MACHINE_ID_PREFIX = "mach_";
@@ -29747,7 +29754,7 @@ var require_dist2 = __commonJS({
29747
29754
  `[${this.cliType}] Waiting for interactive prompt: hasPrompt=${hasPrompt} stableMs=${stableMs} recentOutputMs=${recentlyOutput} status=${status} startup=${startupLikelyActive} screen=${JSON.stringify(summarizeCliTraceText(screenText, 220)).slice(0, 260)}`
29748
29755
  );
29749
29756
  }
29750
- await new Promise((resolve12) => setTimeout(resolve12, 50));
29757
+ await new Promise((resolve11) => setTimeout(resolve11, 50));
29751
29758
  }
29752
29759
  const finalScreenText = this.terminalScreen.getText() || "";
29753
29760
  LOG2.warn(
@@ -30320,7 +30327,7 @@ ${data.message || ""}`.trim();
30320
30327
  const deadline = Date.now() + 1e4;
30321
30328
  while (this.startupParseGate && Date.now() < deadline) {
30322
30329
  this.resolveStartupState("send_wait");
30323
- await new Promise((resolve12) => setTimeout(resolve12, 50));
30330
+ await new Promise((resolve11) => setTimeout(resolve11, 50));
30324
30331
  }
30325
30332
  }
30326
30333
  await this.waitForInteractivePrompt();
@@ -30390,12 +30397,12 @@ ${data.message || ""}`.trim();
30390
30397
  if (this.isWaitingForResponse) this.finishResponse();
30391
30398
  }, this.timeouts.maxResponse);
30392
30399
  };
30393
- await new Promise((resolve12) => {
30400
+ await new Promise((resolve11) => {
30394
30401
  let resolved = false;
30395
30402
  const resolveOnce = () => {
30396
30403
  if (resolved) return;
30397
30404
  resolved = true;
30398
- resolve12();
30405
+ resolve11();
30399
30406
  };
30400
30407
  const submit = () => {
30401
30408
  if (!this.ptyProcess) {
@@ -30569,17 +30576,17 @@ ${data.message || ""}`.trim();
30569
30576
  }
30570
30577
  }
30571
30578
  waitForStopped(timeoutMs) {
30572
- return new Promise((resolve12) => {
30579
+ return new Promise((resolve11) => {
30573
30580
  const startedAt = Date.now();
30574
30581
  const timer = setInterval(() => {
30575
30582
  if (!this.ptyProcess || this.currentStatus === "stopped") {
30576
30583
  clearInterval(timer);
30577
- resolve12(true);
30584
+ resolve11(true);
30578
30585
  return;
30579
30586
  }
30580
30587
  if (Date.now() - startedAt >= timeoutMs) {
30581
30588
  clearInterval(timer);
30582
- resolve12(false);
30589
+ resolve11(false);
30583
30590
  }
30584
30591
  }, 100);
30585
30592
  });
@@ -30932,6 +30939,7 @@ ${data.message || ""}`.trim();
30932
30939
  normalizeInputEnvelope: () => normalizeInputEnvelope,
30933
30940
  normalizeManagedStatus: () => normalizeManagedStatus,
30934
30941
  normalizeMessageParts: () => normalizeMessageParts,
30942
+ parseProviderSourceConfigUpdate: () => parseProviderSourceConfigUpdate,
30935
30943
  partitionSessionHostDiagnosticsSessions: () => partitionSessionHostDiagnosticsSessions,
30936
30944
  partitionSessionHostRecords: () => partitionSessionHostRecords,
30937
30945
  probeCdpPort: () => probeCdpPort,
@@ -31123,6 +31131,66 @@ ${data.message || ""}`.trim();
31123
31131
  return { config: { ...config2, defaultWorkspaceId: id } };
31124
31132
  }
31125
31133
  var path22 = __toESM2(require("path"));
31134
+ function normalizeSummaryItem(item) {
31135
+ if (!item || typeof item !== "object") return null;
31136
+ const id = String(item.id || "").trim();
31137
+ const value = String(item.value || "").trim();
31138
+ if (!id || !value) return null;
31139
+ const normalized = {
31140
+ id,
31141
+ value
31142
+ };
31143
+ if (typeof item.label === "string" && item.label.trim()) normalized.label = item.label.trim();
31144
+ if (typeof item.shortValue === "string" && item.shortValue.trim()) normalized.shortValue = item.shortValue.trim();
31145
+ if (typeof item.icon === "string" && item.icon.trim()) normalized.icon = item.icon.trim();
31146
+ if (typeof item.order === "number" && Number.isFinite(item.order)) normalized.order = item.order;
31147
+ return normalized;
31148
+ }
31149
+ function normalizeProviderSummaryMetadata(summary) {
31150
+ if (!summary || !Array.isArray(summary.items)) return void 0;
31151
+ const items = summary.items.map((item) => normalizeSummaryItem(item)).filter((item) => !!item).sort((left, right) => {
31152
+ const orderDiff = (left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER);
31153
+ if (orderDiff !== 0) return orderDiff;
31154
+ return left.id.localeCompare(right.id);
31155
+ });
31156
+ return items.length > 0 ? { items } : void 0;
31157
+ }
31158
+ function buildProviderSummaryMetadata(items) {
31159
+ return normalizeProviderSummaryMetadata({ items: items.filter(Boolean) });
31160
+ }
31161
+ function buildLegacyModelModeSummaryMetadata(params) {
31162
+ return buildProviderSummaryMetadata([
31163
+ params.model ? {
31164
+ id: "model",
31165
+ label: "Model",
31166
+ value: String(params.modelLabel || params.model).trim(),
31167
+ shortValue: String(params.model).trim(),
31168
+ order: 10
31169
+ } : null,
31170
+ params.mode ? {
31171
+ id: "mode",
31172
+ label: "Mode",
31173
+ value: String(params.modeLabel || params.mode).trim(),
31174
+ shortValue: String(params.mode).trim(),
31175
+ order: 20
31176
+ } : null
31177
+ ]);
31178
+ }
31179
+ function resolveProviderStateSummaryMetadata(params) {
31180
+ const explicit = normalizeProviderSummaryMetadata(params.summaryMetadata);
31181
+ if (explicit) return explicit;
31182
+ const model = typeof params.controlValues?.model === "string" ? params.controlValues.model : void 0;
31183
+ const mode = typeof params.controlValues?.mode === "string" ? params.controlValues.mode : void 0;
31184
+ return buildLegacyModelModeSummaryMetadata({
31185
+ model,
31186
+ mode,
31187
+ modelLabel: params.modelLabel,
31188
+ modeLabel: params.modeLabel
31189
+ });
31190
+ }
31191
+ function normalizePersistedSummaryMetadata(params) {
31192
+ return normalizeProviderSummaryMetadata(params.summaryMetadata);
31193
+ }
31126
31194
  var MAX_ACTIVITY = 30;
31127
31195
  function normalizeWorkspace(workspace) {
31128
31196
  if (!workspace) return "";
@@ -31146,6 +31214,9 @@ ${data.message || ""}`.trim();
31146
31214
  const nextEntry = {
31147
31215
  ...entry,
31148
31216
  workspace: entry.workspace ? normalizeWorkspace(entry.workspace) : void 0,
31217
+ summaryMetadata: normalizePersistedSummaryMetadata({
31218
+ summaryMetadata: entry.summaryMetadata
31219
+ }),
31149
31220
  id: buildRecentActivityKeyForEntry(entry),
31150
31221
  lastUsedAt: entry.lastUsedAt || Date.now()
31151
31222
  };
@@ -31156,7 +31227,12 @@ ${data.message || ""}`.trim();
31156
31227
  };
31157
31228
  }
31158
31229
  function getRecentActivity(state, limit = 20) {
31159
- return [...state.recentActivity || []].sort((a, b2) => b2.lastUsedAt - a.lastUsedAt).slice(0, limit);
31230
+ return [...state.recentActivity || []].map((entry) => ({
31231
+ ...entry,
31232
+ summaryMetadata: normalizePersistedSummaryMetadata({
31233
+ summaryMetadata: entry.summaryMetadata
31234
+ })
31235
+ })).sort((a, b2) => b2.lastUsedAt - a.lastUsedAt).slice(0, limit);
31160
31236
  }
31161
31237
  function getSessionSeenAt(state, sessionId) {
31162
31238
  return state.sessionReads?.[sessionId] || 0;
@@ -31206,7 +31282,9 @@ ${data.message || ""}`.trim();
31206
31282
  providerName: entry.providerName,
31207
31283
  providerSessionId,
31208
31284
  workspace: entry.workspace ? normalizeWorkspace2(entry.workspace) : void 0,
31209
- currentModel: entry.currentModel,
31285
+ summaryMetadata: normalizePersistedSummaryMetadata({
31286
+ summaryMetadata: entry.summaryMetadata
31287
+ }),
31210
31288
  title: entry.title,
31211
31289
  createdAt: existing?.createdAt || entry.createdAt || Date.now(),
31212
31290
  lastUsedAt: entry.lastUsedAt || Date.now()
@@ -31222,7 +31300,12 @@ ${data.message || ""}`.trim();
31222
31300
  if (filters?.providerType && entry.providerType !== filters.providerType) return false;
31223
31301
  if (filters?.kind && entry.kind !== filters.kind) return false;
31224
31302
  return true;
31225
- }).sort((a, b2) => b2.lastUsedAt - a.lastUsedAt);
31303
+ }).map((entry) => ({
31304
+ ...entry,
31305
+ summaryMetadata: normalizePersistedSummaryMetadata({
31306
+ summaryMetadata: entry.summaryMetadata
31307
+ })
31308
+ })).sort((a, b2) => b2.lastUsedAt - a.lastUsedAt);
31226
31309
  }
31227
31310
  var import_fs2 = require("fs");
31228
31311
  var import_path22 = require("path");
@@ -31412,15 +31495,15 @@ ${data.message || ""}`.trim();
31412
31495
  return null;
31413
31496
  }
31414
31497
  function execAsync(cmd, timeoutMs = 5e3) {
31415
- return new Promise((resolve12) => {
31498
+ return new Promise((resolve11) => {
31416
31499
  const child = (0, import_child_process22.exec)(cmd, { encoding: "utf-8", timeout: timeoutMs }, (err, stdout) => {
31417
31500
  if (err || !stdout?.trim()) {
31418
- resolve12(null);
31501
+ resolve11(null);
31419
31502
  } else {
31420
- resolve12(stdout.trim());
31503
+ resolve11(stdout.trim());
31421
31504
  }
31422
31505
  });
31423
- child.on("error", () => resolve12(null));
31506
+ child.on("error", () => resolve11(null));
31424
31507
  });
31425
31508
  }
31426
31509
  async function detectCLIs(providerLoader, options) {
@@ -31627,7 +31710,7 @@ ${data.message || ""}`.trim();
31627
31710
  * Returns multiple entries if multiple IDE windows are open on same port
31628
31711
  */
31629
31712
  static listAllTargets(port) {
31630
- return new Promise((resolve12) => {
31713
+ return new Promise((resolve11) => {
31631
31714
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
31632
31715
  let data = "";
31633
31716
  res.on("data", (chunk) => data += chunk.toString());
@@ -31643,16 +31726,16 @@ ${data.message || ""}`.trim();
31643
31726
  (t) => !isNonMain(t.title || "") && t.url?.includes("workbench.html") && !t.url?.includes("agent")
31644
31727
  );
31645
31728
  const fallbackPages = pages.filter((t) => !isNonMain(t.title || ""));
31646
- resolve12(mainPages.length > 0 ? mainPages : fallbackPages);
31729
+ resolve11(mainPages.length > 0 ? mainPages : fallbackPages);
31647
31730
  } catch {
31648
- resolve12([]);
31731
+ resolve11([]);
31649
31732
  }
31650
31733
  });
31651
31734
  });
31652
- req.on("error", () => resolve12([]));
31735
+ req.on("error", () => resolve11([]));
31653
31736
  req.setTimeout(2e3, () => {
31654
31737
  req.destroy();
31655
- resolve12([]);
31738
+ resolve11([]);
31656
31739
  });
31657
31740
  });
31658
31741
  }
@@ -31692,7 +31775,7 @@ ${data.message || ""}`.trim();
31692
31775
  }
31693
31776
  }
31694
31777
  findTargetOnPort(port) {
31695
- return new Promise((resolve12) => {
31778
+ return new Promise((resolve11) => {
31696
31779
  const req = http.get(`http://127.0.0.1:${port}/json`, (res) => {
31697
31780
  let data = "";
31698
31781
  res.on("data", (chunk) => data += chunk.toString());
@@ -31703,7 +31786,7 @@ ${data.message || ""}`.trim();
31703
31786
  (t) => (t.type === "page" || t.type === "browser" || t.type === "Page") && t.webSocketDebuggerUrl
31704
31787
  );
31705
31788
  if (pages.length === 0) {
31706
- resolve12(targets.find((t) => t.webSocketDebuggerUrl) || null);
31789
+ resolve11(targets.find((t) => t.webSocketDebuggerUrl) || null);
31707
31790
  return;
31708
31791
  }
31709
31792
  const mainPages = pages.filter((t) => !this.isNonMainTitle(t.title || ""));
@@ -31713,24 +31796,24 @@ ${data.message || ""}`.trim();
31713
31796
  const specific = list.find((t) => t.id === this._targetId);
31714
31797
  if (specific) {
31715
31798
  this._pageTitle = specific.title || "";
31716
- resolve12(specific);
31799
+ resolve11(specific);
31717
31800
  } else {
31718
31801
  this.log(`[CDP] Target ${this._targetId} not found in page list`);
31719
- resolve12(null);
31802
+ resolve11(null);
31720
31803
  }
31721
31804
  return;
31722
31805
  }
31723
31806
  this._pageTitle = list[0]?.title || "";
31724
- resolve12(list[0]);
31807
+ resolve11(list[0]);
31725
31808
  } catch {
31726
- resolve12(null);
31809
+ resolve11(null);
31727
31810
  }
31728
31811
  });
31729
31812
  });
31730
- req.on("error", () => resolve12(null));
31813
+ req.on("error", () => resolve11(null));
31731
31814
  req.setTimeout(2e3, () => {
31732
31815
  req.destroy();
31733
- resolve12(null);
31816
+ resolve11(null);
31734
31817
  });
31735
31818
  });
31736
31819
  }
@@ -31741,7 +31824,7 @@ ${data.message || ""}`.trim();
31741
31824
  this.extensionProviders = providers;
31742
31825
  }
31743
31826
  connectToTarget(wsUrl) {
31744
- return new Promise((resolve12) => {
31827
+ return new Promise((resolve11) => {
31745
31828
  this.ws = new import_ws2.default(wsUrl);
31746
31829
  this.ws.on("open", async () => {
31747
31830
  this._connected = true;
@@ -31751,17 +31834,17 @@ ${data.message || ""}`.trim();
31751
31834
  }
31752
31835
  this.connectBrowserWs().catch(() => {
31753
31836
  });
31754
- resolve12(true);
31837
+ resolve11(true);
31755
31838
  });
31756
31839
  this.ws.on("message", (data) => {
31757
31840
  try {
31758
31841
  const msg = JSON.parse(data.toString());
31759
31842
  if (msg.id && this.pending.has(msg.id)) {
31760
- const { resolve: resolve13, reject } = this.pending.get(msg.id);
31843
+ const { resolve: resolve12, reject } = this.pending.get(msg.id);
31761
31844
  this.pending.delete(msg.id);
31762
31845
  this.failureCount = 0;
31763
31846
  if (msg.error) reject(new Error(msg.error.message));
31764
- else resolve13(msg.result);
31847
+ else resolve12(msg.result);
31765
31848
  } else if (msg.method === "Runtime.executionContextCreated") {
31766
31849
  this.contexts.add(msg.params.context.id);
31767
31850
  } else if (msg.method === "Runtime.executionContextDestroyed") {
@@ -31784,7 +31867,7 @@ ${data.message || ""}`.trim();
31784
31867
  this.ws.on("error", (err) => {
31785
31868
  this.log(`[CDP] WebSocket error: ${err.message}`);
31786
31869
  this._connected = false;
31787
- resolve12(false);
31870
+ resolve11(false);
31788
31871
  });
31789
31872
  });
31790
31873
  }
@@ -31798,7 +31881,7 @@ ${data.message || ""}`.trim();
31798
31881
  return;
31799
31882
  }
31800
31883
  this.log(`[CDP] Connecting browser WS for target discovery...`);
31801
- await new Promise((resolve12, reject) => {
31884
+ await new Promise((resolve11, reject) => {
31802
31885
  this.browserWs = new import_ws2.default(browserWsUrl);
31803
31886
  this.browserWs.on("open", async () => {
31804
31887
  this._browserConnected = true;
@@ -31808,16 +31891,16 @@ ${data.message || ""}`.trim();
31808
31891
  } catch (e) {
31809
31892
  this.log(`[CDP] setDiscoverTargets failed: ${e.message}`);
31810
31893
  }
31811
- resolve12();
31894
+ resolve11();
31812
31895
  });
31813
31896
  this.browserWs.on("message", (data) => {
31814
31897
  try {
31815
31898
  const msg = JSON.parse(data.toString());
31816
31899
  if (msg.id && this.browserPending.has(msg.id)) {
31817
- const { resolve: resolve13, reject: reject2 } = this.browserPending.get(msg.id);
31900
+ const { resolve: resolve12, reject: reject2 } = this.browserPending.get(msg.id);
31818
31901
  this.browserPending.delete(msg.id);
31819
31902
  if (msg.error) reject2(new Error(msg.error.message));
31820
- else resolve13(msg.result);
31903
+ else resolve12(msg.result);
31821
31904
  }
31822
31905
  } catch {
31823
31906
  }
@@ -31837,31 +31920,31 @@ ${data.message || ""}`.trim();
31837
31920
  }
31838
31921
  }
31839
31922
  getBrowserWsUrl() {
31840
- return new Promise((resolve12) => {
31923
+ return new Promise((resolve11) => {
31841
31924
  const req = http.get(`http://127.0.0.1:${this.port}/json/version`, (res) => {
31842
31925
  let data = "";
31843
31926
  res.on("data", (chunk) => data += chunk.toString());
31844
31927
  res.on("end", () => {
31845
31928
  try {
31846
31929
  const info = JSON.parse(data);
31847
- resolve12(info.webSocketDebuggerUrl || null);
31930
+ resolve11(info.webSocketDebuggerUrl || null);
31848
31931
  } catch {
31849
- resolve12(null);
31932
+ resolve11(null);
31850
31933
  }
31851
31934
  });
31852
31935
  });
31853
- req.on("error", () => resolve12(null));
31936
+ req.on("error", () => resolve11(null));
31854
31937
  req.setTimeout(3e3, () => {
31855
31938
  req.destroy();
31856
- resolve12(null);
31939
+ resolve11(null);
31857
31940
  });
31858
31941
  });
31859
31942
  }
31860
31943
  sendBrowser(method, params = {}, timeoutMs = 15e3) {
31861
- return new Promise((resolve12, reject) => {
31944
+ return new Promise((resolve11, reject) => {
31862
31945
  if (!this.browserWs || !this._browserConnected) return reject(new Error("Browser WS not connected"));
31863
31946
  const id = this.browserMsgId++;
31864
- this.browserPending.set(id, { resolve: resolve12, reject });
31947
+ this.browserPending.set(id, { resolve: resolve11, reject });
31865
31948
  this.browserWs.send(JSON.stringify({ id, method, params }));
31866
31949
  setTimeout(() => {
31867
31950
  if (this.browserPending.has(id)) {
@@ -31901,11 +31984,11 @@ ${data.message || ""}`.trim();
31901
31984
  }
31902
31985
  // ─── CDP Protocol ────────────────────────────────────────
31903
31986
  sendInternal(method, params = {}, timeoutMs = 15e3) {
31904
- return new Promise((resolve12, reject) => {
31987
+ return new Promise((resolve11, reject) => {
31905
31988
  if (!this.ws || !this._connected) return reject(new Error("CDP not connected"));
31906
31989
  if (this.ws.readyState !== import_ws2.default.OPEN) return reject(new Error("WebSocket not open"));
31907
31990
  const id = this.msgId++;
31908
- this.pending.set(id, { resolve: resolve12, reject });
31991
+ this.pending.set(id, { resolve: resolve11, reject });
31909
31992
  this.ws.send(JSON.stringify({ id, method, params }));
31910
31993
  setTimeout(() => {
31911
31994
  if (this.pending.has(id)) {
@@ -32154,7 +32237,7 @@ ${data.message || ""}`.trim();
32154
32237
  const browserWs = this.browserWs;
32155
32238
  let msgId = this.browserMsgId;
32156
32239
  const sendWs = (method, params = {}, sessionId) => {
32157
- return new Promise((resolve12, reject) => {
32240
+ return new Promise((resolve11, reject) => {
32158
32241
  const mid = msgId++;
32159
32242
  this.browserMsgId = msgId;
32160
32243
  const handler = (raw) => {
@@ -32163,7 +32246,7 @@ ${data.message || ""}`.trim();
32163
32246
  if (msg.id === mid) {
32164
32247
  browserWs.removeListener("message", handler);
32165
32248
  if (msg.error) reject(new Error(msg.error.message || JSON.stringify(msg.error)));
32166
- else resolve12(msg.result);
32249
+ else resolve11(msg.result);
32167
32250
  }
32168
32251
  } catch {
32169
32252
  }
@@ -32364,14 +32447,14 @@ ${data.message || ""}`.trim();
32364
32447
  if (!ws2 || ws2.readyState !== import_ws2.default.OPEN) {
32365
32448
  throw new Error("CDP not connected");
32366
32449
  }
32367
- return new Promise((resolve12, reject) => {
32450
+ return new Promise((resolve11, reject) => {
32368
32451
  const id = getNextId();
32369
32452
  pendingMap.set(id, {
32370
32453
  resolve: (result) => {
32371
32454
  if (result?.result?.subtype === "error") {
32372
32455
  reject(new Error(result.result.description));
32373
32456
  } else {
32374
- resolve12(result?.result?.value);
32457
+ resolve11(result?.result?.value);
32375
32458
  }
32376
32459
  },
32377
32460
  reject
@@ -32403,10 +32486,10 @@ ${data.message || ""}`.trim();
32403
32486
  throw new Error("CDP not connected");
32404
32487
  }
32405
32488
  const sendViaSession = (method, params = {}) => {
32406
- return new Promise((resolve12, reject) => {
32489
+ return new Promise((resolve11, reject) => {
32407
32490
  const pendingMap = this._browserConnected ? this.browserPending : this.pending;
32408
32491
  const id = this._browserConnected ? this.browserMsgId++ : this.msgId++;
32409
- pendingMap.set(id, { resolve: resolve12, reject });
32492
+ pendingMap.set(id, { resolve: resolve11, reject });
32410
32493
  ws2.send(JSON.stringify({ id, sessionId, method, params }));
32411
32494
  setTimeout(() => {
32412
32495
  if (pendingMap.has(id)) {
@@ -32961,8 +33044,6 @@ ${data.message || ""}`.trim();
32961
33044
  if (rawValue === void 0 || rawValue === null) continue;
32962
33045
  values[ctrl.id] = normalizeControlValue(rawValue);
32963
33046
  }
32964
- if (data.model !== void 0 && values.model === void 0) values.model = normalizeControlValue(data.model);
32965
- if (data.mode !== void 0 && values.mode === void 0) values.mode = normalizeControlValue(data.mode);
32966
33047
  return Object.keys(values).length > 0 ? values : void 0;
32967
33048
  }
32968
33049
  function normalizeProviderEffects(data) {
@@ -33064,7 +33145,7 @@ ${data.message || ""}`.trim();
33064
33145
  }
33065
33146
  if (!option || typeof option !== "object") return null;
33066
33147
  const record2 = option;
33067
- const value = typeof record2.value === "string" ? record2.value : typeof record2.id === "string" ? record2.id : null;
33148
+ const value = typeof record2.value === "string" ? record2.value : typeof record2.id === "string" ? record2.id : typeof record2.name === "string" ? record2.name : null;
33068
33149
  if (!value) return null;
33069
33150
  const label = typeof record2.label === "string" ? record2.label : typeof record2.name === "string" ? record2.name : value;
33070
33151
  const normalized = { value, label };
@@ -33306,6 +33387,30 @@ ${data.message || ""}`.trim();
33306
33387
  options.historySessionId
33307
33388
  );
33308
33389
  }
33390
+ writeSessionStart(agentType, historySessionId, workspace, instanceId) {
33391
+ const id = String(historySessionId || "").trim();
33392
+ const ws2 = String(workspace || "").trim();
33393
+ if (!id || !ws2) return;
33394
+ try {
33395
+ const dir = path7.join(HISTORY_DIR, this.sanitize(agentType));
33396
+ fs32.mkdirSync(dir, { recursive: true });
33397
+ const date5 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
33398
+ const filePath = path7.join(dir, `${this.sanitize(id)}_${date5}.jsonl`);
33399
+ const record2 = {
33400
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
33401
+ receivedAt: Date.now(),
33402
+ role: "system",
33403
+ kind: "session_start",
33404
+ content: ws2,
33405
+ agent: agentType,
33406
+ instanceId,
33407
+ historySessionId: id,
33408
+ workspace: ws2
33409
+ };
33410
+ fs32.appendFileSync(filePath, JSON.stringify(record2) + "\n", "utf-8");
33411
+ } catch {
33412
+ }
33413
+ }
33309
33414
  promoteHistorySession(agentType, previousHistorySessionId, nextHistorySessionId) {
33310
33415
  const fromId = String(previousHistorySessionId || "").trim();
33311
33416
  const toId = String(nextHistorySessionId || "").trim();
@@ -33525,6 +33630,7 @@ ${data.message || ""}`.trim();
33525
33630
  let lastMessageAt = 0;
33526
33631
  let sessionTitle = "";
33527
33632
  let preview = "";
33633
+ let workspace = "";
33528
33634
  for (const file2 of files.sort()) {
33529
33635
  const filePath = path7.join(dir, file2);
33530
33636
  const content = fs32.readFileSync(filePath, "utf-8");
@@ -33537,6 +33643,10 @@ ${data.message || ""}`.trim();
33537
33643
  parsed = null;
33538
33644
  }
33539
33645
  if (!parsed || parsed.historySessionId !== historySessionId) continue;
33646
+ if (parsed.kind === "session_start") {
33647
+ if (!workspace && parsed.workspace) workspace = parsed.workspace;
33648
+ continue;
33649
+ }
33540
33650
  messageCount += 1;
33541
33651
  if (!firstMessageAt || parsed.receivedAt < firstMessageAt) firstMessageAt = parsed.receivedAt;
33542
33652
  if (!lastMessageAt || parsed.receivedAt > lastMessageAt) lastMessageAt = parsed.receivedAt;
@@ -33551,7 +33661,8 @@ ${data.message || ""}`.trim();
33551
33661
  messageCount,
33552
33662
  firstMessageAt,
33553
33663
  lastMessageAt,
33554
- preview: preview || void 0
33664
+ preview: preview || void 0,
33665
+ workspace: workspace || void 0
33555
33666
  });
33556
33667
  }
33557
33668
  summaries.sort((a, b2) => b2.lastMessageAt - a.lastMessageAt);
@@ -33566,6 +33677,59 @@ ${data.message || ""}`.trim();
33566
33677
  return { sessions: [], hasMore: false };
33567
33678
  }
33568
33679
  }
33680
+ function isControlValue(value) {
33681
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
33682
+ }
33683
+ function asControlValueMap(value) {
33684
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
33685
+ const result = {};
33686
+ for (const [entryKey, entryValue] of Object.entries(value)) {
33687
+ if (isControlValue(entryValue)) result[entryKey] = entryValue;
33688
+ }
33689
+ return Object.keys(result).length > 0 ? result : void 0;
33690
+ }
33691
+ function getLegacyModelModeValues(data) {
33692
+ if (!data || typeof data !== "object") return void 0;
33693
+ const legacy = {};
33694
+ if (typeof data.model === "string" && data.model.trim()) legacy.model = data.model.trim();
33695
+ if (typeof data.mode === "string" && data.mode.trim()) legacy.mode = data.mode.trim();
33696
+ return Object.keys(legacy).length > 0 ? legacy : void 0;
33697
+ }
33698
+ function mergeProviderPatchState(params) {
33699
+ const {
33700
+ providerControls,
33701
+ data,
33702
+ currentControlValues,
33703
+ currentSummaryMetadata,
33704
+ mergeWithCurrent = true
33705
+ } = params;
33706
+ const sources = [
33707
+ mergeWithCurrent ? asControlValueMap(currentControlValues) : void 0,
33708
+ asControlValueMap(data?.controlValues),
33709
+ asControlValueMap(extractProviderControlValues(providerControls, data)),
33710
+ getLegacyModelModeValues(data)
33711
+ ];
33712
+ const controlValues = Object.assign({}, ...sources.filter(Boolean));
33713
+ return {
33714
+ controlValues,
33715
+ summaryMetadata: data?.summaryMetadata !== void 0 ? data.summaryMetadata : currentSummaryMetadata
33716
+ };
33717
+ }
33718
+ function normalizeProviderStateControlValues(controlValues) {
33719
+ return controlValues && Object.keys(controlValues).length > 0 ? controlValues : void 0;
33720
+ }
33721
+ function resolveProviderStateSurface(params) {
33722
+ const controlValues = normalizeProviderStateControlValues(params.controlValues);
33723
+ return {
33724
+ controlValues,
33725
+ summaryMetadata: resolveProviderStateSummaryMetadata({
33726
+ summaryMetadata: params.summaryMetadata,
33727
+ controlValues,
33728
+ modelLabel: params.modelLabel,
33729
+ modeLabel: params.modeLabel
33730
+ })
33731
+ };
33732
+ }
33569
33733
  var ExtensionProviderInstance = class {
33570
33734
  type;
33571
33735
  category = "extension";
@@ -33579,9 +33743,8 @@ ${data.message || ""}`.trim();
33579
33743
  messages = [];
33580
33744
  prevMessageHashes = /* @__PURE__ */ new Map();
33581
33745
  activeModal = null;
33582
- currentModel = "";
33583
- currentMode = "";
33584
33746
  controlValues = {};
33747
+ summaryMetadata = void 0;
33585
33748
  appliedEffectKeys = /* @__PURE__ */ new Set();
33586
33749
  runtimeMessages = [];
33587
33750
  lastAgentStatus = "idle";
@@ -33616,6 +33779,10 @@ ${data.message || ""}`.trim();
33616
33779
  if (!this.context?.cdp?.isConnected) return;
33617
33780
  }
33618
33781
  getState() {
33782
+ const surface = resolveProviderStateSurface({
33783
+ summaryMetadata: this.summaryMetadata,
33784
+ controlValues: this.controlValues
33785
+ });
33619
33786
  return {
33620
33787
  type: this.type,
33621
33788
  name: this.provider.name,
@@ -33629,10 +33796,9 @@ ${data.message || ""}`.trim();
33629
33796
  activeModal: this.activeModal,
33630
33797
  inputContent: ""
33631
33798
  } : null,
33632
- currentModel: this.currentModel || void 0,
33633
- currentPlan: this.currentMode || void 0,
33634
- controlValues: this.controlValues,
33799
+ controlValues: surface.controlValues,
33635
33800
  providerControls: this.provider.controls,
33801
+ summaryMetadata: surface.summaryMetadata,
33636
33802
  agentStreams: this.agentStreams,
33637
33803
  instanceId: this.instanceId,
33638
33804
  lastUpdated: Date.now(),
@@ -33645,10 +33811,14 @@ ${data.message || ""}`.trim();
33645
33811
  if (data?.streams) this.agentStreams = data.streams;
33646
33812
  if (data?.messages) this.messages = this.assignReceivedAt(data.messages);
33647
33813
  if (data?.activeModal !== void 0) this.activeModal = data.activeModal;
33648
- if (data?.model) this.currentModel = data.model;
33649
- if (data?.mode) this.currentMode = data.mode;
33650
- const controlValues = extractProviderControlValues(this.provider.controls, data) || data?.controlValues;
33651
- if (controlValues) this.controlValues = controlValues;
33814
+ const patchedState = mergeProviderPatchState({
33815
+ providerControls: this.provider.controls,
33816
+ data,
33817
+ currentControlValues: this.controlValues,
33818
+ currentSummaryMetadata: this.summaryMetadata
33819
+ });
33820
+ this.controlValues = patchedState.controlValues;
33821
+ this.summaryMetadata = patchedState.summaryMetadata;
33652
33822
  if (typeof data?.sessionId === "string" && data.sessionId.trim()) this.chatId = data.sessionId;
33653
33823
  if (typeof data?.title === "string" && data.title.trim()) this.chatTitle = data.title;
33654
33824
  if (typeof data?.agentName === "string" && data.agentName.trim()) this.agentName = data.agentName;
@@ -33749,8 +33919,14 @@ ${data.message || ""}`.trim();
33749
33919
  }
33750
33920
  applyProviderResponse(data, options) {
33751
33921
  if (!data || typeof data !== "object") return;
33752
- const controlValues = extractProviderControlValues(this.provider.controls, data);
33753
- if (controlValues) this.controlValues = { ...this.controlValues, ...controlValues };
33922
+ const patchedState = mergeProviderPatchState({
33923
+ providerControls: this.provider.controls,
33924
+ data,
33925
+ currentControlValues: this.controlValues,
33926
+ currentSummaryMetadata: this.summaryMetadata
33927
+ });
33928
+ this.controlValues = patchedState.controlValues;
33929
+ this.summaryMetadata = patchedState.summaryMetadata;
33754
33930
  const effects = normalizeProviderEffects(data);
33755
33931
  for (const effect of effects) {
33756
33932
  const effectWhen = effect.when || "immediate";
@@ -33900,8 +34076,6 @@ ${effect.notification.body || ""}`.trim();
33900
34076
  this.messages = [];
33901
34077
  this.prevMessageHashes.clear();
33902
34078
  this.activeModal = null;
33903
- this.currentModel = "";
33904
- this.currentMode = "";
33905
34079
  this.controlValues = {};
33906
34080
  this.currentStatus = "idle";
33907
34081
  this.chatId = null;
@@ -34031,6 +34205,10 @@ ${effect.notification.body || ""}`.trim();
34031
34205
  for (const ext of this.extensions.values()) {
34032
34206
  extensionStates.push(ext.getState());
34033
34207
  }
34208
+ const surface = resolveProviderStateSurface({
34209
+ summaryMetadata: this.cachedChat?.summaryMetadata,
34210
+ controlValues: this.cachedChat?.controlValues
34211
+ });
34034
34212
  return {
34035
34213
  type: this.type,
34036
34214
  name: this.provider.name,
@@ -34047,11 +34225,9 @@ ${effect.notification.body || ""}`.trim();
34047
34225
  workspace: this.workspace || null,
34048
34226
  extensions: extensionStates,
34049
34227
  cdpConnected: cdp?.isConnected || false,
34050
- currentModel: this.cachedChat?.model || void 0,
34051
- currentPlan: this.cachedChat?.mode || void 0,
34052
- currentAutoApprove: this.cachedChat?.autoApprove || void 0,
34053
- controlValues: this.cachedChat?.controlValues || void 0,
34228
+ controlValues: surface.controlValues,
34054
34229
  providerControls: this.provider.controls,
34230
+ summaryMetadata: surface.summaryMetadata,
34055
34231
  instanceId: this.instanceId,
34056
34232
  lastUpdated: Date.now(),
34057
34233
  settings: this.settings,
@@ -34223,8 +34399,13 @@ ${effect.notification.body || ""}`.trim();
34223
34399
  chat.messages = messages.filter((m) => !hiddenKinds.has(m.kind || ""));
34224
34400
  }
34225
34401
  }
34226
- const controlValues = extractProviderControlValues(this.provider.controls, chat);
34227
- if (controlValues) chat.controlValues = controlValues;
34402
+ const patchedState = mergeProviderPatchState({
34403
+ providerControls: this.provider.controls,
34404
+ data: chat,
34405
+ mergeWithCurrent: false
34406
+ });
34407
+ chat.controlValues = Object.keys(patchedState.controlValues).length > 0 ? patchedState.controlValues : void 0;
34408
+ chat.summaryMetadata = patchedState.summaryMetadata;
34228
34409
  this.cachedChat = { ...chat, activeModal };
34229
34410
  this.detectAgentTransitions(chat, now);
34230
34411
  const persistedMessages = chat.messages || messages;
@@ -34311,14 +34492,18 @@ ${effect.notification.body || ""}`.trim();
34311
34492
  }
34312
34493
  applyProviderResponse(data, options) {
34313
34494
  if (!data || typeof data !== "object") return;
34314
- const controlValues = extractProviderControlValues(this.provider.controls, data);
34315
- if (controlValues) {
34316
- this.cachedChat = {
34317
- ...this.cachedChat || {},
34318
- ...data,
34319
- controlValues: { ...this.cachedChat?.controlValues || {}, ...controlValues }
34320
- };
34321
- }
34495
+ const patchedState = mergeProviderPatchState({
34496
+ providerControls: this.provider.controls,
34497
+ data,
34498
+ currentControlValues: this.cachedChat?.controlValues,
34499
+ currentSummaryMetadata: this.cachedChat?.summaryMetadata
34500
+ });
34501
+ this.cachedChat = {
34502
+ ...this.cachedChat || {},
34503
+ ...data,
34504
+ controlValues: Object.keys(patchedState.controlValues).length > 0 ? patchedState.controlValues : void 0,
34505
+ summaryMetadata: patchedState.summaryMetadata
34506
+ };
34322
34507
  const effects = normalizeProviderEffects(data);
34323
34508
  for (const effect of effects) {
34324
34509
  const effectWhen = effect.when || "immediate";
@@ -35091,6 +35276,8 @@ ${effect.notification.body || ""}`.trim();
35091
35276
  function buildIdeWorkspaceSession(state, cdpManagers, options) {
35092
35277
  const profile = options.profile || "full";
35093
35278
  const activeChat = normalizeActiveChatData(state.activeChat, getActiveChatOptions(profile));
35279
+ const summaryMetadata = normalizeProviderSummaryMetadata(state.summaryMetadata);
35280
+ const controlValues = normalizeProviderStateControlValues(state.controlValues);
35094
35281
  const includeSessionMetadata = shouldIncludeSessionMetadata(profile);
35095
35282
  const includeSessionControls = shouldIncludeSessionControls(profile);
35096
35283
  const title = activeChat?.title || state.name;
@@ -35107,13 +35294,11 @@ ${effect.notification.body || ""}`.trim();
35107
35294
  title,
35108
35295
  ...includeSessionMetadata && { workspace: state.workspace || null },
35109
35296
  activeChat,
35297
+ ...summaryMetadata && { summaryMetadata },
35110
35298
  ...includeSessionMetadata && { capabilities: IDE_SESSION_CAPABILITIES },
35111
35299
  cdpConnected: state.cdpConnected ?? isCdpConnected(cdpManagers, state.type),
35112
- currentModel: state.currentModel,
35113
- currentPlan: state.currentPlan,
35114
- currentAutoApprove: state.currentAutoApprove,
35115
35300
  ...includeSessionControls && {
35116
- controlValues: state.controlValues,
35301
+ ...controlValues && { controlValues },
35117
35302
  providerControls: state.providerControls
35118
35303
  },
35119
35304
  errorMessage: state.errorMessage,
@@ -35124,6 +35309,8 @@ ${effect.notification.body || ""}`.trim();
35124
35309
  function buildExtensionAgentSession(parent, ext, options) {
35125
35310
  const profile = options.profile || "full";
35126
35311
  const activeChat = normalizeActiveChatData(ext.activeChat, getActiveChatOptions(profile));
35312
+ const summaryMetadata = normalizeProviderSummaryMetadata(ext.summaryMetadata);
35313
+ const controlValues = normalizeProviderStateControlValues(ext.controlValues);
35127
35314
  const includeSessionMetadata = shouldIncludeSessionMetadata(profile);
35128
35315
  const includeSessionControls = shouldIncludeSessionControls(profile);
35129
35316
  return {
@@ -35139,11 +35326,10 @@ ${effect.notification.body || ""}`.trim();
35139
35326
  title: activeChat?.title || ext.name,
35140
35327
  ...includeSessionMetadata && { workspace: parent.workspace || null },
35141
35328
  activeChat,
35329
+ ...summaryMetadata && { summaryMetadata },
35142
35330
  ...includeSessionMetadata && { capabilities: EXTENSION_SESSION_CAPABILITIES },
35143
- currentModel: ext.currentModel,
35144
- currentPlan: ext.currentPlan,
35145
35331
  ...includeSessionControls && {
35146
- controlValues: ext.controlValues,
35332
+ ...controlValues && { controlValues },
35147
35333
  providerControls: ext.providerControls
35148
35334
  },
35149
35335
  errorMessage: ext.errorMessage,
@@ -35154,6 +35340,8 @@ ${effect.notification.body || ""}`.trim();
35154
35340
  function buildCliSession(state, options) {
35155
35341
  const profile = options.profile || "full";
35156
35342
  const activeChat = normalizeActiveChatData(state.activeChat, getActiveChatOptions(profile));
35343
+ const summaryMetadata = normalizeProviderSummaryMetadata(state.summaryMetadata);
35344
+ const controlValues = normalizeProviderStateControlValues(state.controlValues);
35157
35345
  const includeSessionMetadata = shouldIncludeSessionMetadata(profile);
35158
35346
  const includeRuntimeMetadata = shouldIncludeRuntimeMetadata(profile);
35159
35347
  const includeSessionControls = shouldIncludeSessionControls(profile);
@@ -35180,11 +35368,12 @@ ${effect.notification.body || ""}`.trim();
35180
35368
  mode: state.mode,
35181
35369
  resume: state.resume,
35182
35370
  activeChat,
35371
+ ...summaryMetadata && { summaryMetadata },
35183
35372
  ...includeSessionMetadata && {
35184
35373
  capabilities: state.mode === "terminal" ? PTY_SESSION_CAPABILITIES : CLI_CHAT_SESSION_CAPABILITIES
35185
35374
  },
35186
35375
  ...includeSessionControls && {
35187
- controlValues: state.controlValues,
35376
+ ...controlValues && { controlValues },
35188
35377
  providerControls: state.providerControls
35189
35378
  },
35190
35379
  errorMessage: state.errorMessage,
@@ -35195,6 +35384,8 @@ ${effect.notification.body || ""}`.trim();
35195
35384
  function buildAcpSession(state, options) {
35196
35385
  const profile = options.profile || "full";
35197
35386
  const activeChat = normalizeActiveChatData(state.activeChat, getActiveChatOptions(profile));
35387
+ const summaryMetadata = normalizeProviderSummaryMetadata(state.summaryMetadata);
35388
+ const controlValues = normalizeProviderStateControlValues(state.controlValues);
35198
35389
  const includeSessionMetadata = shouldIncludeSessionMetadata(profile);
35199
35390
  const includeSessionControls = shouldIncludeSessionControls(profile);
35200
35391
  return {
@@ -35210,13 +35401,10 @@ ${effect.notification.body || ""}`.trim();
35210
35401
  title: activeChat?.title || state.name,
35211
35402
  ...includeSessionMetadata && { workspace: state.workspace || null },
35212
35403
  activeChat,
35404
+ ...summaryMetadata && { summaryMetadata },
35213
35405
  ...includeSessionMetadata && { capabilities: ACP_SESSION_CAPABILITIES },
35214
- currentModel: state.currentModel,
35215
- currentPlan: state.currentPlan,
35216
35406
  ...includeSessionControls && {
35217
- acpConfigOptions: state.acpConfigOptions,
35218
- acpModes: state.acpModes,
35219
- controlValues: state.controlValues,
35407
+ ...controlValues && { controlValues },
35220
35408
  providerControls: state.providerControls
35221
35409
  },
35222
35410
  errorMessage: state.errorMessage,
@@ -35892,7 +36080,7 @@ ${effect.notification.body || ""}`.trim();
35892
36080
  async function getStableExtensionBaseline(h) {
35893
36081
  const first = await readExtensionChatState(h);
35894
36082
  if (getStateMessageCount(first) > 0 || getStateLastSignature(first)) return first;
35895
- await new Promise((resolve12) => setTimeout(resolve12, 150));
36083
+ await new Promise((resolve11) => setTimeout(resolve11, 150));
35896
36084
  const second = await readExtensionChatState(h);
35897
36085
  return getStateMessageCount(second) >= getStateMessageCount(first) ? second : first;
35898
36086
  }
@@ -35900,7 +36088,7 @@ ${effect.notification.body || ""}`.trim();
35900
36088
  const beforeCount = getStateMessageCount(before);
35901
36089
  const beforeSignature = getStateLastSignature(before);
35902
36090
  for (let attempt = 0; attempt < 12; attempt += 1) {
35903
- await new Promise((resolve12) => setTimeout(resolve12, 250));
36091
+ await new Promise((resolve11) => setTimeout(resolve11, 250));
35904
36092
  const state = await readExtensionChatState(h);
35905
36093
  if (state?.status === "waiting_approval") return true;
35906
36094
  const afterCount = getStateMessageCount(state);
@@ -37089,6 +37277,26 @@ ${effect.notification.body || ""}`.trim();
37089
37277
  return { success: false, error: e.message };
37090
37278
  }
37091
37279
  }
37280
+ init_config();
37281
+ function normalizeProviderDir(value) {
37282
+ if (typeof value !== "string") return void 0;
37283
+ const trimmed = value.trim();
37284
+ return trimmed ? trimmed : void 0;
37285
+ }
37286
+ function parseProviderSourceConfigUpdate(input) {
37287
+ const updates = {};
37288
+ if (Object.prototype.hasOwnProperty.call(input, "providerSourceMode")) {
37289
+ const { providerSourceMode } = input;
37290
+ if (providerSourceMode !== "normal" && providerSourceMode !== "no-upstream") {
37291
+ return { ok: false, error: "providerSourceMode must be 'normal' or 'no-upstream'" };
37292
+ }
37293
+ updates.providerSourceMode = providerSourceMode;
37294
+ }
37295
+ if (Object.prototype.hasOwnProperty.call(input, "providerDir")) {
37296
+ updates.providerDir = normalizeProviderDir(input.providerDir);
37297
+ }
37298
+ return { ok: true, updates };
37299
+ }
37092
37300
  function parseCliScriptResult(result) {
37093
37301
  if (typeof result === "string") {
37094
37302
  try {
@@ -37198,8 +37406,49 @@ ${effect.notification.body || ""}`.trim();
37198
37406
  }
37199
37407
  return { success: false, error: `Failed to set ${providerType}.${key} \u2014 invalid key, value, or not a public setting` };
37200
37408
  }
37201
- function normalizeProviderScriptArgs(args) {
37409
+ function handleGetProviderSourceConfig(h, _args) {
37410
+ const loader = h.ctx.providerLoader;
37411
+ if (!loader) return { success: false, error: "providerLoader not available" };
37412
+ return { success: true, ...loader.getSourceConfig() };
37413
+ }
37414
+ async function handleSetProviderSourceConfig(h, args) {
37415
+ const loader = h.ctx.providerLoader;
37416
+ if (!loader) return { success: false, error: "providerLoader not available" };
37417
+ const parsed = parseProviderSourceConfigUpdate(args || {});
37418
+ if ("error" in parsed) {
37419
+ return { success: false, error: parsed.error };
37420
+ }
37421
+ const currentConfig2 = loadConfig2();
37422
+ const nextConfig = {
37423
+ ...currentConfig2,
37424
+ ...parsed.updates.providerSourceMode ? { providerSourceMode: parsed.updates.providerSourceMode } : {},
37425
+ ...Object.prototype.hasOwnProperty.call(parsed.updates, "providerDir") ? { providerDir: parsed.updates.providerDir } : {}
37426
+ };
37427
+ saveConfig(nextConfig);
37428
+ const sourceConfig = loader.applySourceConfig({
37429
+ sourceMode: nextConfig.providerSourceMode,
37430
+ userDir: Object.prototype.hasOwnProperty.call(parsed.updates, "providerDir") ? parsed.updates.providerDir : loader.getSourceConfig().explicitProviderDir || void 0
37431
+ });
37432
+ loader.reload();
37433
+ loader.registerToDetector();
37434
+ await h.ctx.onProviderSourceConfigChanged?.();
37435
+ LOG2.info(
37436
+ "Command",
37437
+ `[set_provider_source_config] mode=${sourceConfig.sourceMode} explicitProviderDir=${sourceConfig.explicitProviderDir || "-"} userDir=${sourceConfig.userDir}`
37438
+ );
37439
+ return { success: true, reloaded: true, ...sourceConfig };
37440
+ }
37441
+ function normalizeProviderScriptArgs(args, scriptName) {
37202
37442
  const normalizedArgs = { ...args || {} };
37443
+ const normalizedScriptName = String(scriptName || "").toLowerCase();
37444
+ if (Object.prototype.hasOwnProperty.call(normalizedArgs, "value")) {
37445
+ if (normalizedArgs.model === void 0 && (normalizedScriptName === "setmodel" || normalizedScriptName === "setmodelgui" || normalizedScriptName === "webviewsetmodel")) {
37446
+ normalizedArgs.model = normalizedArgs.value;
37447
+ }
37448
+ if (normalizedArgs.mode === void 0 && (normalizedScriptName === "setmode" || normalizedScriptName === "webviewsetmode")) {
37449
+ normalizedArgs.mode = normalizedArgs.value;
37450
+ }
37451
+ }
37203
37452
  for (const key of ["mode", "model", "message", "action", "button", "text", "sessionId", "value"]) {
37204
37453
  if (key in normalizedArgs && !(key.toUpperCase() in normalizedArgs)) {
37205
37454
  normalizedArgs[key.toUpperCase()] = normalizedArgs[key];
@@ -37245,7 +37494,7 @@ ${effect.notification.body || ""}`.trim();
37245
37494
  if (!provider.scripts?.[actualScriptName]) {
37246
37495
  return { success: false, error: `Script '${actualScriptName}' not available for ${resolvedProviderType}` };
37247
37496
  }
37248
- const normalizedArgs = normalizeProviderScriptArgs(args);
37497
+ const normalizedArgs = normalizeProviderScriptArgs(args, actualScriptName);
37249
37498
  if (provider.category === "cli") {
37250
37499
  const adapter = h.getCliAdapter(args?.targetSessionId || resolvedProviderType);
37251
37500
  if (!adapter?.invokeScript) {
@@ -37887,6 +38136,10 @@ ${effect.notification.body || ""}`.trim();
37887
38136
  return handleGetProviderSettings(this, args);
37888
38137
  case "set_provider_setting":
37889
38138
  return handleSetProviderSetting(this, args);
38139
+ case "get_provider_source_config":
38140
+ return handleGetProviderSourceConfig(this, args);
38141
+ case "set_provider_source_config":
38142
+ return handleSetProviderSourceConfig(this, args);
37890
38143
  // ─── IDE Extension Settings (stream-commands.ts) ──────────
37891
38144
  case "get_ide_extensions":
37892
38145
  return handleGetIdeExtensions(this, args);
@@ -37926,7 +38179,7 @@ ${effect.notification.body || ""}`.trim();
37926
38179
  try {
37927
38180
  const http3 = await import("http");
37928
38181
  const postData = JSON.stringify(body);
37929
- const result = await new Promise((resolve12, reject) => {
38182
+ const result = await new Promise((resolve11, reject) => {
37930
38183
  const req = http3.request({
37931
38184
  hostname: "127.0.0.1",
37932
38185
  port: 19280,
@@ -37938,9 +38191,9 @@ ${effect.notification.body || ""}`.trim();
37938
38191
  res.on("data", (chunk) => data += chunk);
37939
38192
  res.on("end", () => {
37940
38193
  try {
37941
- resolve12(JSON.parse(data));
38194
+ resolve11(JSON.parse(data));
37942
38195
  } catch {
37943
- resolve12({ raw: data });
38196
+ resolve11({ raw: data });
37944
38197
  }
37945
38198
  });
37946
38199
  });
@@ -37958,15 +38211,15 @@ ${effect.notification.body || ""}`.trim();
37958
38211
  if (!providerType) return { success: false, error: "providerType required" };
37959
38212
  try {
37960
38213
  const http3 = await import("http");
37961
- const result = await new Promise((resolve12, reject) => {
38214
+ const result = await new Promise((resolve11, reject) => {
37962
38215
  http3.get(`http://127.0.0.1:19280/api/providers/${providerType}/${endpoint}`, (res) => {
37963
38216
  let data = "";
37964
38217
  res.on("data", (chunk) => data += chunk);
37965
38218
  res.on("end", () => {
37966
38219
  try {
37967
- resolve12(JSON.parse(data));
38220
+ resolve11(JSON.parse(data));
37968
38221
  } catch {
37969
- resolve12({ raw: data });
38222
+ resolve11({ raw: data });
37970
38223
  }
37971
38224
  });
37972
38225
  }).on("error", reject);
@@ -37980,7 +38233,7 @@ ${effect.notification.body || ""}`.trim();
37980
38233
  try {
37981
38234
  const http3 = await import("http");
37982
38235
  const postData = JSON.stringify(args || {});
37983
- const result = await new Promise((resolve12, reject) => {
38236
+ const result = await new Promise((resolve11, reject) => {
37984
38237
  const req = http3.request({
37985
38238
  hostname: "127.0.0.1",
37986
38239
  port: 19280,
@@ -37992,9 +38245,9 @@ ${effect.notification.body || ""}`.trim();
37992
38245
  res.on("data", (chunk) => data += chunk);
37993
38246
  res.on("end", () => {
37994
38247
  try {
37995
- resolve12(JSON.parse(data));
38248
+ resolve11(JSON.parse(data));
37996
38249
  } catch {
37997
- resolve12({ raw: data });
38250
+ resolve11({ raw: data });
37998
38251
  }
37999
38252
  });
38000
38253
  });
@@ -38040,6 +38293,9 @@ ${effect.notification.body || ""}`.trim();
38040
38293
  const controls = Array.isArray(provider.controls) ? provider.controls : [];
38041
38294
  for (const control of controls) {
38042
38295
  if (control?.type !== "action") continue;
38296
+ if (typeof control?.confirmTitle === "string" && control.confirmTitle.trim()) continue;
38297
+ if (typeof control?.confirmMessage === "string" && control.confirmMessage.trim()) continue;
38298
+ if (typeof control?.confirmLabel === "string" && control.confirmLabel.trim()) continue;
38043
38299
  const invokeScript = typeof control?.invokeScript === "string" ? control.invokeScript.trim() : "";
38044
38300
  if (!invokeScript) continue;
38045
38301
  const controlId = typeof control?.id === "string" ? control.id.trim() : "";
@@ -38049,6 +38305,20 @@ ${effect.notification.body || ""}`.trim();
38049
38305
  }
38050
38306
  return null;
38051
38307
  }
38308
+ async function waitForCliAdapterReady(adapter, options) {
38309
+ const timeoutMs = Math.max(100, options?.timeoutMs ?? 15e3);
38310
+ const pollMs = Math.max(10, options?.pollMs ?? 50);
38311
+ const deadline = Date.now() + timeoutMs;
38312
+ while (Date.now() < deadline) {
38313
+ if (adapter?.isReady?.()) return;
38314
+ const status = adapter?.getStatus?.()?.status;
38315
+ if (status === "stopped") {
38316
+ throw new Error("CLI runtime stopped before it became ready");
38317
+ }
38318
+ await new Promise((resolve11) => setTimeout(resolve11, pollMs));
38319
+ }
38320
+ throw new Error(`CLI runtime did not become ready within ${timeoutMs}ms`);
38321
+ }
38052
38322
  var CliProviderInstance = class {
38053
38323
  constructor(provider, workingDir, cliArgs = [], instanceId, transportFactory, options) {
38054
38324
  this.provider = provider;
@@ -38077,6 +38347,7 @@ ${effect.notification.body || ""}`.trim();
38077
38347
  generatingDebouncePending = null;
38078
38348
  lastApprovalEventAt = 0;
38079
38349
  controlValues = {};
38350
+ summaryMetadata = void 0;
38080
38351
  appliedEffectKeys = /* @__PURE__ */ new Set();
38081
38352
  historyWriter;
38082
38353
  runtimeMessages = [];
@@ -38219,13 +38490,7 @@ ${effect.notification.body || ""}`.trim();
38219
38490
  if (historyMessageCount !== null) {
38220
38491
  parsedMessages = historyMessageCount > 0 ? parsedMessages.slice(-historyMessageCount) : [];
38221
38492
  }
38222
- const controlValues = extractProviderControlValues(this.provider.controls, parsedStatus);
38223
- if (controlValues) {
38224
- this.controlValues = { ...this.controlValues, ...controlValues };
38225
- }
38226
38493
  const mergedMessages = this.mergeConversationMessages(parsedMessages);
38227
- const currentModel = typeof parsedStatus?.model === "string" && parsedStatus.model.trim() ? parsedStatus.model.trim() : typeof this.controlValues.model === "string" && this.controlValues.model.trim() ? this.controlValues.model.trim() : void 0;
38228
- const currentPlan = typeof parsedStatus?.mode === "string" && parsedStatus.mode.trim() ? parsedStatus.mode.trim() : typeof this.controlValues.mode === "string" && this.controlValues.mode.trim() ? this.controlValues.mode.trim() : void 0;
38229
38494
  const dirName = this.workingDir.split("/").filter(Boolean).pop() || "session";
38230
38495
  if (parsedMessages.length > 0) {
38231
38496
  const shouldSkipReplayPersist = this.suppressIdleHistoryReplay && adapterStatus.status === "idle" && parsedStatus?.status === "idle";
@@ -38247,6 +38512,10 @@ ${effect.notification.body || ""}`.trim();
38247
38512
  }
38248
38513
  }
38249
38514
  this.applyProviderResponse(parsedStatus, { phase: "immediate" });
38515
+ const surface = resolveProviderStateSurface({
38516
+ summaryMetadata: this.summaryMetadata,
38517
+ controlValues: this.controlValues
38518
+ });
38250
38519
  return {
38251
38520
  type: this.type,
38252
38521
  name: this.provider.name,
@@ -38262,8 +38531,6 @@ ${effect.notification.body || ""}`.trim();
38262
38531
  inputContent: ""
38263
38532
  },
38264
38533
  workspace: this.workingDir,
38265
- currentModel,
38266
- currentPlan,
38267
38534
  instanceId: this.instanceId,
38268
38535
  providerSessionId: this.providerSessionId,
38269
38536
  lastUpdated: Date.now(),
@@ -38278,8 +38545,9 @@ ${effect.notification.body || ""}`.trim();
38278
38545
  attachedClients: runtime.attachedClients || []
38279
38546
  } : void 0,
38280
38547
  resume: this.provider.resume,
38281
- controlValues: this.controlValues,
38282
- providerControls: this.provider.controls
38548
+ controlValues: surface.controlValues,
38549
+ providerControls: this.provider.controls,
38550
+ summaryMetadata: surface.summaryMetadata
38283
38551
  };
38284
38552
  }
38285
38553
  setPresentationMode(mode) {
@@ -38327,6 +38595,7 @@ ${effect.notification.body || ""}`.trim();
38327
38595
  const scriptName = getForcedNewSessionScriptName(this.provider, this.launchMode);
38328
38596
  if (!scriptName) return;
38329
38597
  LOG2.info("CLI", `[${this.type}] forcing fresh session launch via script: ${scriptName}`);
38598
+ await waitForCliAdapterReady(this.adapter);
38330
38599
  const raw = await this.adapter.invokeScript(scriptName, {});
38331
38600
  const parsed = parseCliScriptResult(raw);
38332
38601
  if (!parsed.success) {
@@ -38482,10 +38751,14 @@ ${effect.notification.body || ""}`.trim();
38482
38751
  this.suppressIdleHistoryReplay = false;
38483
38752
  this.adapter.clearHistory();
38484
38753
  }
38485
- const controlValues = extractProviderControlValues(this.provider.controls, data);
38486
- if (controlValues) {
38487
- this.controlValues = { ...this.controlValues, ...controlValues };
38488
- }
38754
+ const patchedState = mergeProviderPatchState({
38755
+ providerControls: this.provider.controls,
38756
+ data,
38757
+ currentControlValues: this.controlValues,
38758
+ currentSummaryMetadata: this.summaryMetadata
38759
+ });
38760
+ this.controlValues = patchedState.controlValues;
38761
+ this.summaryMetadata = patchedState.summaryMetadata;
38489
38762
  const effects = normalizeProviderEffects(data);
38490
38763
  for (const effect of effects) {
38491
38764
  const effectWhen = effect.when || "immediate";
@@ -38676,6 +38949,7 @@ ${effect.notification.body || ""}`.trim();
38676
38949
  const previousProviderSessionId = this.providerSessionId;
38677
38950
  this.providerSessionId = nextSessionId;
38678
38951
  this.historyWriter.promoteHistorySession(this.type, previousHistorySessionId, nextSessionId);
38952
+ this.historyWriter.writeSessionStart(this.type, nextSessionId, this.workingDir, this.instanceId);
38679
38953
  this.adapter.updateRuntimeMeta({ providerSessionId: nextSessionId });
38680
38954
  this.onProviderSessionResolved?.({
38681
38955
  instanceId: this.instanceId,
@@ -38848,8 +39122,7 @@ ${effect.notification.body || ""}`.trim();
38848
39122
  lastStatus = "starting";
38849
39123
  generatingStartedAt = 0;
38850
39124
  agentCapabilities = {};
38851
- currentModel;
38852
- currentMode;
39125
+ currentSelections = {};
38853
39126
  activeToolCalls = [];
38854
39127
  stopReason = null;
38855
39128
  partialContent = "";
@@ -38929,8 +39202,6 @@ ${effect.notification.body || ""}`.trim();
38929
39202
  inputContent: ""
38930
39203
  },
38931
39204
  workspace: this.workingDir,
38932
- currentModel: this.currentModel,
38933
- currentPlan: this.currentMode,
38934
39205
  instanceId: this.instanceId,
38935
39206
  lastUpdated: Date.now(),
38936
39207
  settings: this.settings,
@@ -38941,11 +39212,9 @@ ${effect.notification.body || ""}`.trim();
38941
39212
  // Error details for dashboard display
38942
39213
  errorMessage: this.errorMessage || void 0,
38943
39214
  errorReason: this.errorReason || void 0,
38944
- controlValues: {
38945
- ...this.currentModel ? { model: this.currentModel } : {},
38946
- ...this.currentMode ? { mode: this.currentMode } : {}
38947
- },
38948
- providerControls: this.provider.controls
39215
+ controlValues: this.getSelectionControlValues(),
39216
+ providerControls: this.provider.controls,
39217
+ summaryMetadata: this.buildSelectionSummaryMetadata()
38949
39218
  };
38950
39219
  }
38951
39220
  onEvent(event, data) {
@@ -38979,6 +39248,54 @@ ${effect.notification.body || ""}`.trim();
38979
39248
  getInstanceId() {
38980
39249
  return this.instanceId;
38981
39250
  }
39251
+ resolveConfigOptionLabel(category, value) {
39252
+ if (!value) return void 0;
39253
+ const option = this.configOptions.find((entry) => entry.category === category);
39254
+ return option?.options.find((candidate) => candidate.value === value)?.name || value;
39255
+ }
39256
+ resolveModeLabel(modeId) {
39257
+ if (!modeId) return void 0;
39258
+ return this.availableModes.find((mode) => mode.id === modeId)?.name || modeId;
39259
+ }
39260
+ getCurrentSelection(category) {
39261
+ return this.currentSelections[category];
39262
+ }
39263
+ setCurrentSelection(category, value) {
39264
+ const normalized = typeof value === "string" ? value.trim() : "";
39265
+ if (normalized) {
39266
+ this.currentSelections[category] = normalized;
39267
+ return;
39268
+ }
39269
+ delete this.currentSelections[category];
39270
+ }
39271
+ getSelectionControlValues() {
39272
+ const model = this.getCurrentSelection("model");
39273
+ const mode = this.getCurrentSelection("mode");
39274
+ return {
39275
+ ...model ? { model } : {},
39276
+ ...mode ? { mode } : {}
39277
+ };
39278
+ }
39279
+ resolveSelectionLabel(category, value) {
39280
+ if (!value) return void 0;
39281
+ const configLabel = this.resolveConfigOptionLabel(category, value);
39282
+ if (configLabel && configLabel !== value) return configLabel;
39283
+ if (category === "mode") {
39284
+ const modeLabel = this.resolveModeLabel(value);
39285
+ if (modeLabel) return modeLabel;
39286
+ }
39287
+ return configLabel || value;
39288
+ }
39289
+ buildSelectionSummaryMetadata() {
39290
+ const model = this.getCurrentSelection("model");
39291
+ const mode = this.getCurrentSelection("mode");
39292
+ return buildLegacyModelModeSummaryMetadata({
39293
+ model,
39294
+ mode,
39295
+ modelLabel: this.resolveSelectionLabel("model", model),
39296
+ modeLabel: this.resolveSelectionLabel("mode", mode)
39297
+ });
39298
+ }
38982
39299
  // ─── ACP Config Options & Modes ─────────────────────
38983
39300
  parseConfigOptions(raw) {
38984
39301
  if (!Array.isArray(raw)) return;
@@ -39010,12 +39327,14 @@ ${effect.notification.body || ""}`.trim();
39010
39327
  }
39011
39328
  }
39012
39329
  this.configOptions.push({ category, configId, currentValue, options: flatOptions });
39013
- if (category === "model" && currentValue) this.currentModel = currentValue;
39330
+ if (category === "model" || category === "mode") {
39331
+ this.setCurrentSelection(category, currentValue);
39332
+ }
39014
39333
  }
39015
39334
  }
39016
39335
  parseModes(raw) {
39017
39336
  if (!raw) return;
39018
- if (raw.currentModeId) this.currentMode = raw.currentModeId;
39337
+ this.setCurrentSelection("mode", raw.currentModeId);
39019
39338
  if (Array.isArray(raw.availableModes)) {
39020
39339
  this.availableModes = raw.availableModes.map((m) => ({
39021
39340
  id: m.id,
@@ -39034,8 +39353,7 @@ ${effect.notification.body || ""}`.trim();
39034
39353
  if (this.useStaticConfig) {
39035
39354
  opt.currentValue = value;
39036
39355
  this.selectedConfig[opt.configId] = value;
39037
- if (category === "model") this.currentModel = value;
39038
- if (category === "mode") this.currentMode = value;
39356
+ if (category === "model" || category === "mode") this.setCurrentSelection(category, value);
39039
39357
  this.log.info(`[${this.type}] Static config ${category} set to: ${value} \u2014 restarting agent`);
39040
39358
  await this.restartWithNewConfig();
39041
39359
  return;
@@ -39053,7 +39371,7 @@ ${effect.notification.body || ""}`.trim();
39053
39371
  value
39054
39372
  });
39055
39373
  opt.currentValue = value;
39056
- if (category === "model") this.currentModel = value;
39374
+ if (category === "model" || category === "mode") this.setCurrentSelection(category, value);
39057
39375
  if (result?.configOptions) this.parseConfigOptions(result.configOptions);
39058
39376
  this.log.info(`[${this.type}] Config ${category} set to: ${value} | response: ${JSON.stringify(result)?.slice(0, 300)}`);
39059
39377
  } catch (e) {
@@ -39069,7 +39387,7 @@ ${effect.notification.body || ""}`.trim();
39069
39387
  opt.currentValue = modeId;
39070
39388
  this.selectedConfig[opt.configId] = modeId;
39071
39389
  }
39072
- this.currentMode = modeId;
39390
+ this.setCurrentSelection("mode", modeId);
39073
39391
  this.log.info(`[${this.type}] Static mode set to: ${modeId} \u2014 restarting agent`);
39074
39392
  await this.restartWithNewConfig();
39075
39393
  return;
@@ -39084,7 +39402,7 @@ ${effect.notification.body || ""}`.trim();
39084
39402
  sessionId: this.sessionId,
39085
39403
  modeId
39086
39404
  });
39087
- this.currentMode = modeId;
39405
+ this.setCurrentSelection("mode", modeId);
39088
39406
  this.log.info(`[${this.type}] Mode set to: ${modeId}`);
39089
39407
  } catch (e) {
39090
39408
  const message = e?.message || "Unknown ACP mode error";
@@ -39255,13 +39573,13 @@ ${effect.notification.body || ""}`.trim();
39255
39573
  }
39256
39574
  this.currentStatus = "waiting_approval";
39257
39575
  this.detectStatusTransition();
39258
- const approved = await new Promise((resolve12) => {
39259
- this.permissionResolvers.push(resolve12);
39576
+ const approved = await new Promise((resolve11) => {
39577
+ this.permissionResolvers.push(resolve11);
39260
39578
  setTimeout(() => {
39261
- const idx = this.permissionResolvers.indexOf(resolve12);
39579
+ const idx = this.permissionResolvers.indexOf(resolve11);
39262
39580
  if (idx >= 0) {
39263
39581
  this.permissionResolvers.splice(idx, 1);
39264
- resolve12(false);
39582
+ resolve11(false);
39265
39583
  }
39266
39584
  }, 3e5);
39267
39585
  });
@@ -39342,8 +39660,8 @@ ${effect.notification.body || ""}`.trim();
39342
39660
  if (result?.modes) this.log.debug(`[${this.type}] modes: ${JSON.stringify(result.modes).slice(0, 300)}`);
39343
39661
  this.parseConfigOptions(result?.configOptions);
39344
39662
  this.parseModes(result?.modes);
39345
- if (!this.currentModel && result?.models?.currentModelId) {
39346
- this.currentModel = result.models.currentModelId;
39663
+ if (!this.getCurrentSelection("model") && result?.models?.currentModelId) {
39664
+ this.setCurrentSelection("model", result.models.currentModelId);
39347
39665
  }
39348
39666
  if (this.configOptions.length === 0 && this.provider.staticConfigOptions?.length) {
39349
39667
  this.useStaticConfig = true;
@@ -39357,13 +39675,16 @@ ${effect.notification.body || ""}`.trim();
39357
39675
  });
39358
39676
  if (defaultVal) {
39359
39677
  this.selectedConfig[sc2.configId] = defaultVal;
39360
- if (sc2.category === "model") this.currentModel = defaultVal;
39361
- if (sc2.category === "mode") this.currentMode = defaultVal;
39678
+ if (sc2.category === "model" || sc2.category === "mode") {
39679
+ this.setCurrentSelection(sc2.category, defaultVal);
39680
+ }
39362
39681
  }
39363
39682
  }
39364
39683
  this.log.info(`[${this.type}] Using static configOptions (${this.configOptions.length} options)`);
39365
39684
  }
39366
- this.log.info(`[${this.type}] Session created: ${this.sessionId}${this.currentModel ? ` (model: ${this.currentModel})` : ""}${this.currentMode ? ` (mode: ${this.currentMode})` : ""}`);
39685
+ const currentModel = this.getCurrentSelection("model");
39686
+ const currentMode = this.getCurrentSelection("mode");
39687
+ this.log.info(`[${this.type}] Session created: ${this.sessionId}${currentModel ? ` (model: ${currentModel})` : ""}${currentMode ? ` (mode: ${currentMode})` : ""}`);
39367
39688
  if (this.configOptions.length > 0) {
39368
39689
  this.log.info(`[${this.type}] Config options: ${this.configOptions.map((c) => `${c.category}(${c.options.length})`).join(", ")}`);
39369
39690
  }
@@ -39538,7 +39859,7 @@ ${effect.notification.body || ""}`.trim();
39538
39859
  break;
39539
39860
  }
39540
39861
  case "current_mode_update": {
39541
- this.currentMode = update.currentModeId;
39862
+ this.setCurrentSelection("mode", update.currentModeId);
39542
39863
  break;
39543
39864
  }
39544
39865
  case "config_option_update": {
@@ -39611,7 +39932,7 @@ ${effect.notification.body || ""}`.trim();
39611
39932
  this.detectStatusTransition();
39612
39933
  }
39613
39934
  if (params.model) {
39614
- this.currentModel = params.model;
39935
+ this.setCurrentSelection("model", params.model);
39615
39936
  }
39616
39937
  }
39617
39938
  /** Map SDK ToolCallStatus to internal status */
@@ -39894,7 +40215,11 @@ ${effect.notification.body || ""}`.trim();
39894
40215
  }
39895
40216
  persistRecentActivity(entry) {
39896
40217
  try {
39897
- let nextState = appendRecentActivity(loadState(), entry);
40218
+ const summaryMetadata = normalizeProviderSummaryMetadata(entry.summaryMetadata);
40219
+ let nextState = appendRecentActivity(loadState(), {
40220
+ ...entry,
40221
+ summaryMetadata
40222
+ });
39898
40223
  if (entry.providerSessionId && (entry.kind === "cli" || entry.kind === "acp")) {
39899
40224
  nextState = upsertSavedProviderSession(nextState, {
39900
40225
  kind: entry.kind,
@@ -39902,7 +40227,7 @@ ${effect.notification.body || ""}`.trim();
39902
40227
  providerName: entry.providerName,
39903
40228
  providerSessionId: entry.providerSessionId,
39904
40229
  workspace: entry.workspace,
39905
- currentModel: entry.currentModel,
40230
+ summaryMetadata,
39906
40231
  title: entry.title
39907
40232
  });
39908
40233
  }
@@ -40092,7 +40417,7 @@ ${installInfo}`
40092
40417
  providerType: normalizedType,
40093
40418
  providerName: provider.displayName || provider.name || normalizedType,
40094
40419
  workspace: resolvedDir,
40095
- currentModel: initialModel,
40420
+ summaryMetadata: buildLegacyModelModeSummaryMetadata({ model: initialModel }),
40096
40421
  sessionId,
40097
40422
  title: provider.displayName || provider.name || normalizedType
40098
40423
  });
@@ -40194,7 +40519,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
40194
40519
  providerName: provider?.displayName || provider?.name || normalizedType,
40195
40520
  providerSessionId: sessionBinding.providerSessionId,
40196
40521
  workspace: resolvedDir,
40197
- currentModel: initialModel,
40522
+ summaryMetadata: buildLegacyModelModeSummaryMetadata({ model: initialModel }),
40198
40523
  sessionId: key,
40199
40524
  title: provider?.displayName || provider?.name || normalizedType
40200
40525
  });
@@ -40565,6 +40890,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
40565
40890
  warnings.push(`Unknown provider field: ${key}`);
40566
40891
  }
40567
40892
  }
40893
+ if (provider.disableUpstream !== void 0) {
40894
+ warnings.push("disableUpstream is deprecated in provider definitions; use machine-level provider source policy instead");
40895
+ }
40568
40896
  const category = provider.category;
40569
40897
  if (category === "cli" || category === "acp") {
40570
40898
  const spawn4 = provider.spawn;
@@ -40622,8 +40950,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
40622
40950
  var ProviderLoader = class _ProviderLoader {
40623
40951
  providers = /* @__PURE__ */ new Map();
40624
40952
  providerAvailability = /* @__PURE__ */ new Map();
40953
+ defaultProvidersDir;
40954
+ explicitProviderDir = null;
40625
40955
  userDir;
40626
40956
  upstreamDir;
40957
+ sourceMode = "normal";
40627
40958
  disableUpstream;
40628
40959
  watchers = [];
40629
40960
  logFn;
@@ -40637,22 +40968,15 @@ Run 'adhdev doctor' for detailed diagnostics.`
40637
40968
  static META_FILE = ".meta.json";
40638
40969
  constructor(options) {
40639
40970
  this.logFn = options?.logFn || LOG2.forComponent("Provider").asLogFn();
40640
- const defaultProvidersDir = path14.join(os13.homedir(), ".adhdev", "providers");
40641
- if (options?.userDir) {
40642
- this.userDir = options.userDir;
40643
- this.log(`Config 'providerDir' applied: ${this.userDir}`);
40644
- } else {
40645
- const localRepoPath = path14.resolve(__dirname, "../../../../../adhdev-providers");
40646
- if (fs6.existsSync(localRepoPath)) {
40647
- this.userDir = localRepoPath;
40648
- this.log(`Auto-detected local public repository: ${this.userDir} (Dev workspace speedup)`);
40649
- } else {
40650
- this.userDir = defaultProvidersDir;
40651
- this.log(`Using default user providers directory: ${this.userDir}`);
40652
- }
40653
- }
40654
- this.upstreamDir = path14.join(defaultProvidersDir, ".upstream");
40655
- this.disableUpstream = options?.disableUpstream ?? false;
40971
+ this.defaultProvidersDir = path14.join(os13.homedir(), ".adhdev", "providers");
40972
+ this.userDir = this.defaultProvidersDir;
40973
+ this.upstreamDir = path14.join(this.defaultProvidersDir, ".upstream");
40974
+ this.disableUpstream = false;
40975
+ this.applySourceConfig({
40976
+ userDir: options?.userDir,
40977
+ sourceMode: options?.sourceMode,
40978
+ disableUpstream: options?.disableUpstream
40979
+ });
40656
40980
  }
40657
40981
  log(msg) {
40658
40982
  this.logFn(`[ProviderLoader] ${msg}`);
@@ -40677,6 +41001,33 @@ Run 'adhdev doctor' for detailed diagnostics.`
40677
41001
  getProviderRoots() {
40678
41002
  return [this.userDir, this.upstreamDir];
40679
41003
  }
41004
+ getSourceConfig() {
41005
+ return {
41006
+ sourceMode: this.sourceMode,
41007
+ disableUpstream: this.disableUpstream,
41008
+ explicitProviderDir: this.explicitProviderDir,
41009
+ userDir: this.userDir,
41010
+ upstreamDir: this.upstreamDir,
41011
+ providerRoots: this.getProviderRoots()
41012
+ };
41013
+ }
41014
+ applySourceConfig(options) {
41015
+ const nextSourceMode = options?.sourceMode === "no-upstream" ? "no-upstream" : options?.sourceMode === "normal" ? "normal" : options?.disableUpstream ? "no-upstream" : this.sourceMode || "normal";
41016
+ if (options && Object.prototype.hasOwnProperty.call(options, "userDir")) {
41017
+ this.explicitProviderDir = options.userDir?.trim() ? options.userDir : null;
41018
+ }
41019
+ this.sourceMode = nextSourceMode;
41020
+ this.userDir = this.explicitProviderDir || this.defaultProvidersDir;
41021
+ this.upstreamDir = path14.join(this.defaultProvidersDir, ".upstream");
41022
+ this.disableUpstream = this.sourceMode === "no-upstream";
41023
+ if (this.explicitProviderDir) {
41024
+ this.log(`Config 'providerDir' applied: ${this.userDir}`);
41025
+ } else {
41026
+ this.log(`Using default user providers directory: ${this.userDir}`);
41027
+ }
41028
+ this.log(`Provider source config: mode=${this.sourceMode} explicitProviderDir=${this.explicitProviderDir || "-"} userDir=${this.userDir} upstreamDir=${this.upstreamDir}`);
41029
+ return this.getSourceConfig();
41030
+ }
40680
41031
  /**
40681
41032
  * Canonical provider directory shape for a given root.
40682
41033
  */
@@ -40727,7 +41078,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
40727
41078
  this.log(`Loaded ${upstreamCount} upstream providers (auto-updated)`);
40728
41079
  }
40729
41080
  } else if (this.disableUpstream) {
40730
- this.log("Upstream loading disabled (disableUpstream=true)");
41081
+ this.log("Upstream loading disabled (sourceMode=no-upstream)");
40731
41082
  }
40732
41083
  if (fs6.existsSync(this.userDir)) {
40733
41084
  const userCount = this.loadDir(this.userDir, [".upstream"]);
@@ -41238,7 +41589,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
41238
41589
  */
41239
41590
  async fetchLatest() {
41240
41591
  if (this.disableUpstream) {
41241
- this.log("Upstream fetch skipped (disableUpstream=true)");
41592
+ this.log("Upstream fetch skipped (sourceMode=no-upstream)");
41242
41593
  return { updated: false };
41243
41594
  }
41244
41595
  const https = require("https");
@@ -41260,7 +41611,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
41260
41611
  return { updated: false };
41261
41612
  }
41262
41613
  try {
41263
- const etag = await new Promise((resolve12, reject) => {
41614
+ const etag = await new Promise((resolve11, reject) => {
41264
41615
  const options = {
41265
41616
  method: "HEAD",
41266
41617
  hostname: "github.com",
@@ -41278,7 +41629,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
41278
41629
  headers: { "User-Agent": "adhdev-launcher" },
41279
41630
  timeout: 1e4
41280
41631
  }, (res2) => {
41281
- resolve12(res2.headers.etag || res2.headers["last-modified"] || "");
41632
+ resolve11(res2.headers.etag || res2.headers["last-modified"] || "");
41282
41633
  });
41283
41634
  req2.on("error", reject);
41284
41635
  req2.on("timeout", () => {
@@ -41287,7 +41638,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
41287
41638
  });
41288
41639
  req2.end();
41289
41640
  } else {
41290
- resolve12(res.headers.etag || res.headers["last-modified"] || "");
41641
+ resolve11(res.headers.etag || res.headers["last-modified"] || "");
41291
41642
  }
41292
41643
  });
41293
41644
  req.on("error", reject);
@@ -41351,7 +41702,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
41351
41702
  downloadFile(url2, destPath) {
41352
41703
  const https = require("https");
41353
41704
  const http3 = require("http");
41354
- return new Promise((resolve12, reject) => {
41705
+ return new Promise((resolve11, reject) => {
41355
41706
  const doRequest = (reqUrl, redirectCount = 0) => {
41356
41707
  if (redirectCount > 5) {
41357
41708
  reject(new Error("Too many redirects"));
@@ -41371,7 +41722,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
41371
41722
  res.pipe(ws2);
41372
41723
  ws2.on("finish", () => {
41373
41724
  ws2.close();
41374
- resolve12();
41725
+ resolve11();
41375
41726
  });
41376
41727
  ws2.on("error", reject);
41377
41728
  });
@@ -41844,17 +42195,17 @@ Run 'adhdev doctor' for detailed diagnostics.`
41844
42195
  throw new Error("No free port found");
41845
42196
  }
41846
42197
  function checkPortFree(port) {
41847
- return new Promise((resolve12) => {
42198
+ return new Promise((resolve11) => {
41848
42199
  const server = net3.createServer();
41849
42200
  server.unref();
41850
- server.on("error", () => resolve12(false));
42201
+ server.on("error", () => resolve11(false));
41851
42202
  server.listen(port, "127.0.0.1", () => {
41852
- server.close(() => resolve12(true));
42203
+ server.close(() => resolve11(true));
41853
42204
  });
41854
42205
  });
41855
42206
  }
41856
42207
  async function isCdpActive(port) {
41857
- return new Promise((resolve12) => {
42208
+ return new Promise((resolve11) => {
41858
42209
  const req = require("http").get(`http://127.0.0.1:${port}/json/version`, {
41859
42210
  timeout: 2e3
41860
42211
  }, (res) => {
@@ -41863,16 +42214,16 @@ Run 'adhdev doctor' for detailed diagnostics.`
41863
42214
  res.on("end", () => {
41864
42215
  try {
41865
42216
  const info = JSON.parse(data);
41866
- resolve12(!!info["WebKit-Version"] || !!info["Browser"]);
42217
+ resolve11(!!info["WebKit-Version"] || !!info["Browser"]);
41867
42218
  } catch {
41868
- resolve12(false);
42219
+ resolve11(false);
41869
42220
  }
41870
42221
  });
41871
42222
  });
41872
- req.on("error", () => resolve12(false));
42223
+ req.on("error", () => resolve11(false));
41873
42224
  req.on("timeout", () => {
41874
42225
  req.destroy();
41875
- resolve12(false);
42226
+ resolve11(false);
41876
42227
  });
41877
42228
  });
41878
42229
  }
@@ -42316,11 +42667,87 @@ Run 'adhdev doctor' for detailed diagnostics.`
42316
42667
  }
42317
42668
  cleanOldFiles();
42318
42669
  init_logger();
42670
+ var LIVE_LIFECYCLES = /* @__PURE__ */ new Set(["starting", "running", "stopping", "interrupted"]);
42671
+ function isSessionHostLiveRuntime(record2) {
42672
+ const lifecycle = String(record2?.lifecycle || "").trim();
42673
+ return LIVE_LIFECYCLES.has(lifecycle);
42674
+ }
42675
+ function getSessionHostRecoveryLabel(meta3) {
42676
+ const recoveryState = typeof meta3?.runtimeRecoveryState === "string" ? String(meta3.runtimeRecoveryState).trim() : "";
42677
+ if (!recoveryState) return null;
42678
+ if (recoveryState === "auto_resumed") return "restored after restart";
42679
+ if (recoveryState === "resume_failed") return "restore failed";
42680
+ if (recoveryState === "host_restart_interrupted") return "host restart interrupted";
42681
+ if (recoveryState === "orphan_snapshot") return "snapshot recovered";
42682
+ return recoveryState.replace(/_/g, " ");
42683
+ }
42684
+ function isSessionHostRecoverySnapshot(record2) {
42685
+ if (!record2) return false;
42686
+ if (isSessionHostLiveRuntime(record2)) return false;
42687
+ const lifecycle = String(record2.lifecycle || "").trim();
42688
+ if (lifecycle && lifecycle !== "stopped" && lifecycle !== "failed") {
42689
+ return false;
42690
+ }
42691
+ const meta3 = record2.meta || void 0;
42692
+ if (meta3?.restoredFromStorage === true) return true;
42693
+ return getSessionHostRecoveryLabel(meta3) !== null;
42694
+ }
42695
+ function getSessionHostSurfaceKind(record2) {
42696
+ if (isSessionHostLiveRuntime(record2)) return "live_runtime";
42697
+ if (isSessionHostRecoverySnapshot(record2)) return "recovery_snapshot";
42698
+ return "inactive_record";
42699
+ }
42700
+ function partitionSessionHostRecords(records) {
42701
+ const liveRuntimes = [];
42702
+ const recoverySnapshots = [];
42703
+ const inactiveRecords = [];
42704
+ for (const record2 of records) {
42705
+ const kind = getSessionHostSurfaceKind(record2);
42706
+ if (kind === "live_runtime") {
42707
+ liveRuntimes.push(record2);
42708
+ } else if (kind === "recovery_snapshot") {
42709
+ recoverySnapshots.push(record2);
42710
+ } else {
42711
+ inactiveRecords.push(record2);
42712
+ }
42713
+ }
42714
+ return {
42715
+ liveRuntimes,
42716
+ recoverySnapshots,
42717
+ inactiveRecords
42718
+ };
42719
+ }
42720
+ function partitionSessionHostDiagnosticsSessions(records) {
42721
+ return partitionSessionHostRecords(records || []);
42722
+ }
42319
42723
  var os16 = __toESM2(require("os"));
42320
42724
  init_config();
42321
42725
  init_terminal_screen();
42322
42726
  init_logger();
42323
42727
  var READ_DEBUG_ENABLED = process.argv.includes("--dev") || process.env.ADHDEV_READ_DEBUG === "1";
42728
+ var recentReadDebugSignatureBySession = /* @__PURE__ */ new Map();
42729
+ function buildRecentReadDebugSignature(snapshot) {
42730
+ return [
42731
+ snapshot.providerType,
42732
+ snapshot.status,
42733
+ snapshot.inboxBucket,
42734
+ snapshot.unread ? "1" : "0",
42735
+ String(snapshot.lastSeenAt),
42736
+ snapshot.completionMarker,
42737
+ snapshot.seenCompletionMarker,
42738
+ String(snapshot.lastUpdated),
42739
+ String(snapshot.lastUsedAt),
42740
+ snapshot.lastRole,
42741
+ String(snapshot.messageUpdatedAt)
42742
+ ].join("|");
42743
+ }
42744
+ function shouldEmitRecentReadDebugLog(cache, snapshot) {
42745
+ const nextSignature = buildRecentReadDebugSignature(snapshot);
42746
+ const previousSignature = cache.get(snapshot.sessionId);
42747
+ if (previousSignature === nextSignature) return false;
42748
+ cache.set(snapshot.sessionId, nextSignature);
42749
+ return true;
42750
+ }
42324
42751
  function buildDetectedIdeInfos(detectedIdes, cdpManagers) {
42325
42752
  return detectedIdes.filter((ide) => ide.installed !== false).map((ide) => ({
42326
42753
  id: ide.id,
@@ -42472,7 +42899,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
42472
42899
  providerSessionId: item.providerSessionId,
42473
42900
  title: item.title || item.providerName,
42474
42901
  workspace: item.workspace,
42475
- currentModel: item.currentModel,
42902
+ summaryMetadata: item.summaryMetadata,
42476
42903
  lastLaunchedAt: item.lastUsedAt
42477
42904
  })).sort((a, b2) => b2.lastLaunchedAt - a.lastLaunchedAt).slice(0, 12);
42478
42905
  }
@@ -42513,9 +42940,24 @@ Run 'adhdev doctor' for detailed diagnostics.`
42513
42940
  session.unread = unread;
42514
42941
  session.inboxBucket = inboxBucket;
42515
42942
  if (READ_DEBUG_ENABLED && (session.unread || session.inboxBucket !== "idle" || session.providerType.includes("codex"))) {
42943
+ const recentReadSnapshot = {
42944
+ sessionId: session.id,
42945
+ providerType: session.providerType,
42946
+ status: String(session.status || ""),
42947
+ inboxBucket,
42948
+ unread,
42949
+ lastSeenAt,
42950
+ completionMarker: completionMarker || "-",
42951
+ seenCompletionMarker: seenCompletionMarker || "-",
42952
+ lastUpdated: Number(session.lastUpdated || 0),
42953
+ lastUsedAt,
42954
+ lastRole: getLastMessageRole(sourceSession),
42955
+ messageUpdatedAt: getSessionMessageUpdatedAt(sourceSession)
42956
+ };
42957
+ if (!shouldEmitRecentReadDebugLog(recentReadDebugSignatureBySession, recentReadSnapshot)) continue;
42516
42958
  LOG2.info(
42517
42959
  "RecentRead",
42518
- `snapshot session id=${session.id} provider=${session.providerType} status=${String(session.status || "")} bucket=${inboxBucket} unread=${String(unread)} lastSeenAt=${lastSeenAt} completionMarker=${completionMarker || "-"} seenMarker=${seenCompletionMarker || "-"} lastUpdated=${String(session.lastUpdated || 0)} lastUsedAt=${lastUsedAt} lastRole=${getLastMessageRole(sourceSession)} msgUpdatedAt=${getSessionMessageUpdatedAt(sourceSession)}`
42960
+ `snapshot session id=${recentReadSnapshot.sessionId} provider=${recentReadSnapshot.providerType} status=${recentReadSnapshot.status} bucket=${recentReadSnapshot.inboxBucket} unread=${String(recentReadSnapshot.unread)} lastSeenAt=${recentReadSnapshot.lastSeenAt} completionMarker=${recentReadSnapshot.completionMarker} seenMarker=${recentReadSnapshot.seenCompletionMarker} lastUpdated=${String(recentReadSnapshot.lastUpdated)} lastUsedAt=${recentReadSnapshot.lastUsedAt} lastRole=${recentReadSnapshot.lastRole} msgUpdatedAt=${recentReadSnapshot.messageUpdatedAt}`
42519
42961
  );
42520
42962
  }
42521
42963
  const lastDisplayMessage = getLastDisplayMessage(sourceSession);
@@ -42591,7 +43033,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
42591
43033
  while (Date.now() - start < timeoutMs) {
42592
43034
  try {
42593
43035
  process.kill(pid, 0);
42594
- await new Promise((resolve12) => setTimeout(resolve12, 250));
43036
+ await new Promise((resolve11) => setTimeout(resolve11, 250));
42595
43037
  } catch {
42596
43038
  return;
42597
43039
  }
@@ -42706,7 +43148,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
42706
43148
  appendUpgradeLog(installOutput.trim());
42707
43149
  }
42708
43150
  if (process.platform === "win32") {
42709
- await new Promise((resolve12) => setTimeout(resolve12, 500));
43151
+ await new Promise((resolve11) => setTimeout(resolve11, 500));
42710
43152
  cleanupStaleGlobalInstallDirs(payload.packageName);
42711
43153
  appendUpgradeLog("Post-install staging cleanup complete");
42712
43154
  }
@@ -42786,11 +43228,104 @@ Run 'adhdev doctor' for detailed diagnostics.`
42786
43228
  providerSessionId: typeof record2.meta?.providerSessionId === "string" ? String(record2.meta.providerSessionId) : void 0
42787
43229
  };
42788
43230
  }
43231
+ function getWriteConflictOwnerClientId(error48) {
43232
+ const message = typeof error48 === "string" ? error48 : error48 instanceof Error ? error48.message : "";
43233
+ const match = /^Write owned by\s+(.+)$/.exec(message.trim());
43234
+ return match?.[1]?.trim() || void 0;
43235
+ }
43236
+ function summarizeSessionHostRecord(result) {
43237
+ if (!result || typeof result !== "object") return {};
43238
+ const record2 = result;
43239
+ return {
43240
+ runtimeKey: typeof record2.runtimeKey === "string" ? record2.runtimeKey : void 0,
43241
+ lifecycle: typeof record2.lifecycle === "string" ? record2.lifecycle : void 0,
43242
+ surfaceKind: getSessionHostSurfaceKind(record2),
43243
+ attachedClientCount: Array.isArray(record2.attachedClients) ? record2.attachedClients.length : void 0,
43244
+ hasWriteOwner: !!record2.writeOwner,
43245
+ writeOwnerClientId: typeof record2.writeOwner?.clientId === "string" ? record2.writeOwner.clientId : void 0
43246
+ };
43247
+ }
43248
+ function summarizeSessionHostRecords(result) {
43249
+ const records = Array.isArray(result) ? result : [];
43250
+ const groups = partitionSessionHostRecords(records);
43251
+ return {
43252
+ sessionCount: records.length,
43253
+ liveRuntimeCount: groups.liveRuntimes.length,
43254
+ recoverySnapshotCount: groups.recoverySnapshots.length,
43255
+ inactiveRecordCount: groups.inactiveRecords.length
43256
+ };
43257
+ }
43258
+ function summarizeSessionHostDiagnostics(result) {
43259
+ const diagnostics = result && typeof result === "object" ? result : {};
43260
+ const sessions = Array.isArray(diagnostics.sessions) ? diagnostics.sessions : [];
43261
+ return {
43262
+ runtimeCount: typeof diagnostics.runtimeCount === "number" ? diagnostics.runtimeCount : void 0,
43263
+ ...summarizeSessionHostRecords(sessions)
43264
+ };
43265
+ }
43266
+ function summarizeSessionHostPruneResult(result) {
43267
+ const value = result && typeof result === "object" ? result : {};
43268
+ return {
43269
+ duplicateGroupCount: typeof value.duplicateGroupCount === "number" ? value.duplicateGroupCount : void 0,
43270
+ prunedCount: Array.isArray(value.prunedSessionIds) ? value.prunedSessionIds.length : void 0,
43271
+ keptCount: Array.isArray(value.keptSessionIds) ? value.keptSessionIds.length : void 0
43272
+ };
43273
+ }
42789
43274
  var DaemonCommandRouter = class {
42790
43275
  deps;
42791
43276
  constructor(deps) {
42792
43277
  this.deps = deps;
42793
43278
  }
43279
+ async traceSessionHostAction(action, args, run, summarizeResult) {
43280
+ const interactionId = typeof args?._interactionId === "string" ? args._interactionId : void 0;
43281
+ const sessionId = typeof args?.sessionId === "string" ? args.sessionId : void 0;
43282
+ const requestedPayload = { action };
43283
+ if (sessionId) requestedPayload.sessionId = sessionId;
43284
+ if (typeof args?.clientId === "string") requestedPayload.clientId = args.clientId;
43285
+ if (typeof args?.signal === "string") requestedPayload.signal = args.signal;
43286
+ if (typeof args?.providerType === "string") requestedPayload.providerType = args.providerType;
43287
+ if (typeof args?.workspace === "string") requestedPayload.workspace = args.workspace;
43288
+ if (typeof args?.dryRun === "boolean") requestedPayload.dryRun = args.dryRun;
43289
+ recordDebugTrace({
43290
+ interactionId,
43291
+ category: "session_host",
43292
+ stage: "action_requested",
43293
+ level: "info",
43294
+ sessionId,
43295
+ payload: requestedPayload
43296
+ });
43297
+ try {
43298
+ const result = await run();
43299
+ recordDebugTrace({
43300
+ interactionId,
43301
+ category: "session_host",
43302
+ stage: "action_result",
43303
+ level: "info",
43304
+ sessionId,
43305
+ payload: {
43306
+ ...requestedPayload,
43307
+ success: true,
43308
+ ...summarizeResult ? summarizeResult(result) : {}
43309
+ }
43310
+ });
43311
+ return result;
43312
+ } catch (error48) {
43313
+ recordDebugTrace({
43314
+ interactionId,
43315
+ category: "session_host",
43316
+ stage: "action_failed",
43317
+ level: "error",
43318
+ sessionId,
43319
+ payload: {
43320
+ ...requestedPayload,
43321
+ error: error48?.message || String(error48),
43322
+ failureKind: getWriteConflictOwnerClientId(error48) ? "write_conflict" : "request_failed",
43323
+ conflictOwnerClientId: getWriteConflictOwnerClientId(error48)
43324
+ }
43325
+ });
43326
+ throw error48;
43327
+ }
43328
+ }
42794
43329
  /**
42795
43330
  * Unified command routing.
42796
43331
  * Returns result for all commands:
@@ -42900,44 +43435,60 @@ Run 'adhdev doctor' for detailed diagnostics.`
42900
43435
  }
42901
43436
  case "session_host_get_diagnostics": {
42902
43437
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
42903
- const diagnostics = await this.deps.sessionHostControl.getDiagnostics({
43438
+ const diagnostics = await this.traceSessionHostAction("session_host_get_diagnostics", args, () => this.deps.sessionHostControl.getDiagnostics({
42904
43439
  includeSessions: args?.includeSessions !== false,
42905
43440
  limit: Number(args?.limit) || void 0
42906
- });
43441
+ }), (result) => ({
43442
+ includeSessions: args?.includeSessions !== false,
43443
+ limit: Number(args?.limit) || void 0,
43444
+ ...summarizeSessionHostDiagnostics(result)
43445
+ }));
42907
43446
  return { success: true, diagnostics };
42908
43447
  }
42909
43448
  case "session_host_list_sessions": {
42910
43449
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
42911
- const sessions = await this.deps.sessionHostControl.listSessions();
43450
+ const sessions = await this.traceSessionHostAction("session_host_list_sessions", args, () => this.deps.sessionHostControl.listSessions(), (records) => summarizeSessionHostRecords(records));
42912
43451
  return { success: true, sessions };
42913
43452
  }
42914
43453
  case "session_host_stop_session": {
42915
43454
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
42916
43455
  const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
42917
43456
  if (!sessionId) return { success: false, error: "sessionId required" };
42918
- const record2 = await this.deps.sessionHostControl.stopSession(sessionId);
43457
+ const record2 = await this.traceSessionHostAction("session_host_stop_session", args, () => this.deps.sessionHostControl.stopSession(sessionId), (result) => summarizeSessionHostRecord(result));
42919
43458
  return { success: true, record: record2 };
42920
43459
  }
42921
43460
  case "session_host_resume_session": {
42922
43461
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
42923
43462
  const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
42924
43463
  if (!sessionId) return { success: false, error: "sessionId required" };
42925
- const record2 = await this.deps.sessionHostControl.resumeSession(sessionId);
42926
- const hosted = toHostedCliRuntimeDescriptor(record2);
42927
- if (hosted) {
42928
- await this.deps.cliManager.restoreHostedSessions([hosted]);
42929
- }
43464
+ const record2 = await this.traceSessionHostAction("session_host_resume_session", args, async () => {
43465
+ const nextRecord = await this.deps.sessionHostControl.resumeSession(sessionId);
43466
+ const hosted = toHostedCliRuntimeDescriptor(nextRecord);
43467
+ if (hosted) {
43468
+ await this.deps.cliManager.restoreHostedSessions([hosted]);
43469
+ }
43470
+ return nextRecord;
43471
+ }, (result) => ({
43472
+ ...summarizeSessionHostRecord(result),
43473
+ restoredHostedSession: !!toHostedCliRuntimeDescriptor(result)
43474
+ }));
42930
43475
  return { success: true, record: record2 };
42931
43476
  }
42932
43477
  case "session_host_restart_session": {
42933
43478
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
42934
43479
  const sessionId = typeof args?.sessionId === "string" ? args.sessionId : "";
42935
43480
  if (!sessionId) return { success: false, error: "sessionId required" };
42936
- const record2 = await this.deps.sessionHostControl.restartSession(sessionId);
42937
- const hosted = toHostedCliRuntimeDescriptor(record2);
42938
- if (hosted) {
42939
- await this.deps.cliManager.restoreHostedSessions([hosted]);
42940
- }
43481
+ const record2 = await this.traceSessionHostAction("session_host_restart_session", args, async () => {
43482
+ const nextRecord = await this.deps.sessionHostControl.restartSession(sessionId);
43483
+ const hosted = toHostedCliRuntimeDescriptor(nextRecord);
43484
+ if (hosted) {
43485
+ await this.deps.cliManager.restoreHostedSessions([hosted]);
43486
+ }
43487
+ return nextRecord;
43488
+ }, (result) => ({
43489
+ ...summarizeSessionHostRecord(result),
43490
+ restoredHostedSession: !!toHostedCliRuntimeDescriptor(result)
43491
+ }));
42941
43492
  return { success: true, record: record2 };
42942
43493
  }
42943
43494
  case "session_host_send_signal": {
@@ -42946,7 +43497,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
42946
43497
  const signal = typeof args?.signal === "string" ? args.signal : "";
42947
43498
  if (!sessionId) return { success: false, error: "sessionId required" };
42948
43499
  if (!signal) return { success: false, error: "signal required" };
42949
- const record2 = await this.deps.sessionHostControl.sendSignal(sessionId, signal);
43500
+ const record2 = await this.traceSessionHostAction("session_host_send_signal", args, () => this.deps.sessionHostControl.sendSignal(sessionId, signal), (result) => summarizeSessionHostRecord(result));
42950
43501
  return { success: true, record: record2 };
42951
43502
  }
42952
43503
  case "session_host_force_detach_client": {
@@ -42955,16 +43506,16 @@ Run 'adhdev doctor' for detailed diagnostics.`
42955
43506
  const clientId = typeof args?.clientId === "string" ? args.clientId : "";
42956
43507
  if (!sessionId) return { success: false, error: "sessionId required" };
42957
43508
  if (!clientId) return { success: false, error: "clientId required" };
42958
- const record2 = await this.deps.sessionHostControl.forceDetachClient(sessionId, clientId);
43509
+ const record2 = await this.traceSessionHostAction("session_host_force_detach_client", args, () => this.deps.sessionHostControl.forceDetachClient(sessionId, clientId), (result) => summarizeSessionHostRecord(result));
42959
43510
  return { success: true, record: record2 };
42960
43511
  }
42961
43512
  case "session_host_prune_duplicate_sessions": {
42962
43513
  if (!this.deps.sessionHostControl) return { success: false, error: "Session host control unavailable" };
42963
- const result = await this.deps.sessionHostControl.pruneDuplicateSessions({
43514
+ const result = await this.traceSessionHostAction("session_host_prune_duplicate_sessions", args, () => this.deps.sessionHostControl.pruneDuplicateSessions({
42964
43515
  providerType: typeof args?.providerType === "string" ? args.providerType : void 0,
42965
43516
  workspace: typeof args?.workspace === "string" ? args.workspace : void 0,
42966
43517
  dryRun: args?.dryRun === true
42967
- });
43518
+ }), (value) => summarizeSessionHostPruneResult(value));
42968
43519
  return { success: true, result };
42969
43520
  }
42970
43521
  case "session_host_acquire_write": {
@@ -42974,12 +43525,15 @@ Run 'adhdev doctor' for detailed diagnostics.`
42974
43525
  const ownerType = args?.ownerType === "agent" ? "agent" : "user";
42975
43526
  if (!sessionId) return { success: false, error: "sessionId required" };
42976
43527
  if (!clientId) return { success: false, error: "clientId required" };
42977
- const record2 = await this.deps.sessionHostControl.acquireWrite({
43528
+ const record2 = await this.traceSessionHostAction("session_host_acquire_write", args, () => this.deps.sessionHostControl.acquireWrite({
42978
43529
  sessionId,
42979
43530
  clientId,
42980
43531
  ownerType,
42981
43532
  force: args?.force !== false
42982
- });
43533
+ }), (result) => ({
43534
+ ...summarizeSessionHostRecord(result),
43535
+ ownerType
43536
+ }));
42983
43537
  return { success: true, record: record2 };
42984
43538
  }
42985
43539
  case "session_host_release_write": {
@@ -42988,7 +43542,10 @@ Run 'adhdev doctor' for detailed diagnostics.`
42988
43542
  const clientId = typeof args?.clientId === "string" ? args.clientId : "";
42989
43543
  if (!sessionId) return { success: false, error: "sessionId required" };
42990
43544
  if (!clientId) return { success: false, error: "clientId required" };
42991
- const record2 = await this.deps.sessionHostControl.releaseWrite({ sessionId, clientId });
43545
+ const record2 = await this.traceSessionHostAction("session_host_release_write", args, () => this.deps.sessionHostControl.releaseWrite({
43546
+ sessionId,
43547
+ clientId
43548
+ }), (result) => summarizeSessionHostRecord(result));
42992
43549
  return { success: true, record: record2 };
42993
43550
  }
42994
43551
  case "list_saved_sessions": {
@@ -42997,8 +43554,9 @@ Run 'adhdev doctor' for detailed diagnostics.`
42997
43554
  if (!providerType) {
42998
43555
  return { success: false, error: "providerType required" };
42999
43556
  }
43000
- const offset = Math.max(0, Number(args?.offset) || 0);
43001
- const limit = Math.max(1, Math.min(100, Number(args?.limit) || 30));
43557
+ const wantsAll = args?.all === true;
43558
+ const offset = wantsAll ? 0 : Math.max(0, Number(args?.offset) || 0);
43559
+ const limit = wantsAll ? Number.MAX_SAFE_INTEGER : Math.max(1, Math.min(100, Number(args?.limit) || 30));
43002
43560
  const { sessions: historySessions, hasMore } = listSavedHistorySessions(providerType, { offset, limit });
43003
43561
  const state = loadState();
43004
43562
  const savedSessions = getSavedProviderSessions(state, { providerType, kind });
@@ -43019,13 +43577,13 @@ Run 'adhdev doctor' for detailed diagnostics.`
43019
43577
  providerName: saved?.providerName || recent?.providerName || providerType,
43020
43578
  kind: saved?.kind || recent?.kind || kind,
43021
43579
  title: saved?.title || recent?.title || session.sessionTitle || session.preview || providerType,
43022
- workspace: saved?.workspace || recent?.workspace,
43023
- currentModel: saved?.currentModel || recent?.currentModel,
43580
+ workspace: saved?.workspace || recent?.workspace || session.workspace,
43581
+ summaryMetadata: saved?.summaryMetadata || recent?.summaryMetadata,
43024
43582
  preview: session.preview,
43025
43583
  messageCount: session.messageCount,
43026
43584
  firstMessageAt: session.firstMessageAt,
43027
43585
  lastMessageAt: session.lastMessageAt,
43028
- canResume: !!(saved?.workspace || recent?.workspace) && canResumeById
43586
+ canResume: !!(saved?.workspace || recent?.workspace || session.workspace) && canResumeById
43029
43587
  };
43030
43588
  }),
43031
43589
  hasMore
@@ -43457,7 +44015,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
43457
44015
  const ideSummary = ideStates.map((s15) => {
43458
44016
  const msgs = s15.activeChat?.messages?.length || 0;
43459
44017
  const exts = s15.extensions.length;
43460
- return `${s15.type}(${s15.status},${msgs}msg,${exts}ext${s15.currentModel ? ",model=" + s15.currentModel : ""})`;
44018
+ return `${s15.type}(${s15.status},${msgs}msg,${exts}ext)`;
43461
44019
  }).join(", ");
43462
44020
  const cliSummary = cliStates.map((s15) => `${s15.type}(${s15.status})`).join(", ");
43463
44021
  const acpSummary = acpStates.map((s15) => `${s15.type}(${s15.status})`).join(", ");
@@ -43519,9 +44077,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
43519
44077
  workspace: session.workspace ?? null,
43520
44078
  title: session.title,
43521
44079
  cdpConnected: session.cdpConnected,
43522
- currentModel: session.currentModel,
43523
- currentPlan: session.currentPlan,
43524
- currentAutoApprove: session.currentAutoApprove
44080
+ summaryMetadata: session.summaryMetadata
43525
44081
  })),
43526
44082
  p2p: payload.p2p,
43527
44083
  timestamp: now
@@ -43634,7 +44190,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
43634
44190
  const beforeCount = this.messageCount(before);
43635
44191
  const beforeSignature = this.lastMessageSignature(before);
43636
44192
  for (let attempt = 0; attempt < 12; attempt += 1) {
43637
- await new Promise((resolve12) => setTimeout(resolve12, 250));
44193
+ await new Promise((resolve11) => setTimeout(resolve11, 250));
43638
44194
  let state;
43639
44195
  try {
43640
44196
  state = await this.readChat(evaluate);
@@ -43656,7 +44212,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
43656
44212
  if (this.messageCount(first) > 0 || this.lastMessageSignature(first)) {
43657
44213
  return first;
43658
44214
  }
43659
- await new Promise((resolve12) => setTimeout(resolve12, 150));
44215
+ await new Promise((resolve11) => setTimeout(resolve11, 150));
43660
44216
  const second = await this.readChat(evaluate);
43661
44217
  return this.messageCount(second) >= this.messageCount(first) ? second : first;
43662
44218
  }
@@ -43681,15 +44237,18 @@ Run 'adhdev doctor' for detailed diagnostics.`
43681
44237
  status: data.status || "idle",
43682
44238
  messages: data.messages || [],
43683
44239
  inputContent: data.inputContent || "",
43684
- model: data.model,
43685
- mode: data.mode,
43686
44240
  activeModal: data.activeModal
43687
44241
  };
43688
44242
  if (typeof data.title === "string" && data.title.trim()) {
43689
44243
  state.title = data.title.trim();
43690
44244
  }
43691
44245
  const controlValues = extractProviderControlValues(this.provider.controls, data);
43692
- if (controlValues) state.controlValues = controlValues;
44246
+ const surface = resolveProviderStateSurface({
44247
+ controlValues,
44248
+ summaryMetadata: data.summaryMetadata
44249
+ });
44250
+ if (surface.controlValues) state.controlValues = surface.controlValues;
44251
+ if (surface.summaryMetadata) state.summaryMetadata = surface.summaryMetadata;
43693
44252
  const effects = normalizeProviderEffects(data);
43694
44253
  if (effects.length > 0) state.effects = effects;
43695
44254
  if (state.messages.length > 0) {
@@ -43796,7 +44355,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
43796
44355
  if (typeof data.error === "string" && data.error.trim()) return false;
43797
44356
  }
43798
44357
  for (let attempt = 0; attempt < 6; attempt += 1) {
43799
- await new Promise((resolve12) => setTimeout(resolve12, 250));
44358
+ await new Promise((resolve11) => setTimeout(resolve11, 250));
43800
44359
  const state = await this.readChat(evaluate);
43801
44360
  const title = this.getStateTitle(state);
43802
44361
  if (this.titlesMatch(title, sessionId)) return true;
@@ -43961,7 +44520,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
43961
44520
  const evaluate = (expr, timeout) => cdp.evaluateInSessionFrame(agent.cdpSessionId, expr, timeout);
43962
44521
  const state = await agent.adapter.readChat(evaluate);
43963
44522
  const stateError = this.getStateError(state);
43964
- LOG2.debug("AgentStream", `[AgentStream] readChat(${type}) result: status=${state.status} msgs=${state.messages?.length || 0} model=${state.model || ""}${state.status === "error" ? " error=" + JSON.stringify(stateError) : ""}`);
44523
+ const selectedModelValue = typeof state.controlValues?.model === "string" ? state.controlValues.model : "";
44524
+ LOG2.debug("AgentStream", `[AgentStream] readChat(${type}) result: status=${state.status} msgs=${state.messages?.length || 0} model=${selectedModelValue}${state.status === "error" ? " error=" + JSON.stringify(stateError) : ""}`);
43965
44525
  if (state.status === "error" && this.isRecoverableSessionError(stateError)) {
43966
44526
  throw new Error(stateError);
43967
44527
  }
@@ -44305,9 +44865,8 @@ Run 'adhdev doctor' for detailed diagnostics.`
44305
44865
  messages: stream.messages || [],
44306
44866
  status: stream.status || "idle",
44307
44867
  activeModal: stream.activeModal || null,
44308
- model: stream.model || void 0,
44309
- mode: stream.mode || void 0,
44310
44868
  controlValues: stream.controlValues || void 0,
44869
+ summaryMetadata: stream.summaryMetadata || void 0,
44311
44870
  effects: stream.effects || void 0,
44312
44871
  sessionId: stream.sessionId || stream.instanceId || void 0,
44313
44872
  title: stream.title || stream.agentName || void 0,
@@ -44706,6 +45265,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
44706
45265
  var http2 = __toESM2(require("http"));
44707
45266
  var fs14 = __toESM2(require("fs"));
44708
45267
  var path222 = __toESM2(require("path"));
45268
+ init_config();
44709
45269
  function generateFiles(type, name, category, opts = {}) {
44710
45270
  const { cdpPorts, cli, processName, installPath, binary, extensionId, version: version2 = "0.1" } = opts;
44711
45271
  if (category === "cli" || category === "acp") {
@@ -44834,7 +45394,11 @@ module.exports.setMode = (params) => {
44834
45394
  * 5. Approval dialog detection (buttons, modal)
44835
45395
  * 6. Input field selector
44836
45396
  *
44837
- * \u2192 { id, status, title, messages[], inputContent, activeModal }
45397
+ * Preferred live-state surface:
45398
+ * - controlValues: explicit current control selections (model/mode/etc.)
45399
+ * - summaryMetadata: compact always-visible metadata for dashboard/recent views
45400
+ * Legacy top-level model/mode output is no longer the preferred shape.
45401
+ * \u2192 { id, status, title, messages[], inputContent, activeModal, controlValues?, summaryMetadata? }
44838
45402
  */
44839
45403
  (() => {
44840
45404
  try {
@@ -44862,6 +45426,9 @@ module.exports.setMode = (params) => {
44862
45426
  messages,
44863
45427
  inputContent,
44864
45428
  activeModal,
45429
+ // TODO: Return explicit selections when available, e.g.
45430
+ // controlValues: { model: selectedModel, mode: selectedMode },
45431
+ // summaryMetadata: { items: [{ id: 'model', value: selectedModelLabel || selectedModel, shortValue: selectedModel, order: 10 }] },
44865
45432
  });
44866
45433
  } catch(e) {
44867
45434
  return JSON.stringify({ id: '', status: 'error', messages: [], error: e.message });
@@ -46234,7 +46801,7 @@ async (params) => {
46234
46801
  return { target, instance, adapter };
46235
46802
  }
46236
46803
  function sleep(ms2) {
46237
- return new Promise((resolve12) => setTimeout(resolve12, ms2));
46804
+ return new Promise((resolve11) => setTimeout(resolve11, ms2));
46238
46805
  }
46239
46806
  async function waitForCliReady(ctx, type, instanceId, timeoutMs) {
46240
46807
  const startedAt = Date.now();
@@ -46596,7 +47163,6 @@ async (params) => {
46596
47163
  lastMessage: s15.activeChat?.messages?.slice(-1)[0] || null,
46597
47164
  activeModal: s15.activeChat?.activeModal || null,
46598
47165
  pendingEvents: s15.pendingEvents || [],
46599
- currentModel: s15.currentModel,
46600
47166
  settings: s15.settings
46601
47167
  }));
46602
47168
  ctx.json(res, 200, { instances: result, count: result.length });
@@ -47079,18 +47645,6 @@ async (params) => {
47079
47645
  if (!fs13.existsSync(providerJson)) {
47080
47646
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
47081
47647
  }
47082
- try {
47083
- const providerData = JSON.parse(fs13.readFileSync(providerJson, "utf-8"));
47084
- if (providerData.disableUpstream !== true) {
47085
- providerData.disableUpstream = true;
47086
- fs13.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
47087
- }
47088
- } catch (error48) {
47089
- return {
47090
- dir: null,
47091
- reason: `Failed to update provider.json in writable provider directory: ${error48.message}`
47092
- };
47093
- }
47094
47648
  return { dir: desiredDir };
47095
47649
  }
47096
47650
  function loadAutoImplReferenceScripts(ctx, referenceType) {
@@ -47763,7 +48317,7 @@ async (params) => {
47763
48317
  lines.push("## Required Return Format");
47764
48318
  lines.push("| Function | Return JSON |");
47765
48319
  lines.push("|---|---|");
47766
- lines.push("| readChat | `{ id, status, title, messages: [{role, content, index, kind?, meta?}], inputContent, activeModal }` \u2014 optional `kind`: standard, thought, tool, terminal; optional `meta`: e.g. `{ label, isRunning }` for dashboard |");
48320
+ lines.push("| readChat | `{ id, status, title, messages: [{role, content, index, kind?, meta?}], inputContent, activeModal, controlValues?, summaryMetadata? }` \u2014 optional `kind`: standard, thought, tool, terminal; prefer explicit `controlValues` for current selections and `summaryMetadata` for compact always-visible UI metadata |");
47767
48321
  lines.push("| sendMessage | `{ sent: false, needsTypeAndSend: true, selector }` |");
47768
48322
  lines.push("| resolveAction | `{ resolved: true/false, clicked? }` |");
47769
48323
  lines.push("| listSessions | `{ sessions: [{ id, title, active, index }] }` |");
@@ -48375,6 +48929,7 @@ data: ${JSON.stringify(msg.data)}
48375
48929
  cdpManagers;
48376
48930
  instanceManager;
48377
48931
  cliManager;
48932
+ onProviderSourceConfigChanged;
48378
48933
  logFn;
48379
48934
  sseClients = [];
48380
48935
  watchScriptPath = null;
@@ -48391,6 +48946,7 @@ data: ${JSON.stringify(msg.data)}
48391
48946
  this.cdpManagers = options.cdpManagers;
48392
48947
  this.instanceManager = options.instanceManager || null;
48393
48948
  this.cliManager = options.cliManager || null;
48949
+ this.onProviderSourceConfigChanged = options.onProviderSourceConfigChanged || null;
48394
48950
  this.logFn = options.logFn || LOG2.forComponent("DevServer").asLogFn();
48395
48951
  }
48396
48952
  log(msg) {
@@ -48400,6 +48956,8 @@ data: ${JSON.stringify(msg.data)}
48400
48956
  routes = [
48401
48957
  // Static routes
48402
48958
  { method: "GET", pattern: "/api/providers", handler: (q2, s15) => this.handleListProviders(q2, s15) },
48959
+ { method: "GET", pattern: "/api/providers/source-config", handler: (q2, s15) => this.handleGetProviderSourceConfig(q2, s15) },
48960
+ { method: "POST", pattern: "/api/providers/source-config", handler: (q2, s15) => this.handleSetProviderSourceConfig(q2, s15) },
48403
48961
  { method: "GET", pattern: "/api/providers/versions", handler: (q2, s15) => this.handleDetectVersions(q2, s15) },
48404
48962
  { method: "POST", pattern: "/api/providers/reload", handler: (q2, s15) => this.handleReload(q2, s15) },
48405
48963
  { method: "POST", pattern: "/api/cdp/evaluate", handler: (q2, s15) => this.handleCdpEvaluate(q2, s15) },
@@ -48497,15 +49055,15 @@ data: ${JSON.stringify(msg.data)}
48497
49055
  this.json(res, 500, { error: e.message });
48498
49056
  }
48499
49057
  });
48500
- return new Promise((resolve12, reject) => {
49058
+ return new Promise((resolve11, reject) => {
48501
49059
  this.server.listen(port, "127.0.0.1", () => {
48502
49060
  this.log(`Dev server listening on http://127.0.0.1:${port}`);
48503
- resolve12();
49061
+ resolve11();
48504
49062
  });
48505
49063
  this.server.on("error", (e) => {
48506
49064
  if (e.code === "EADDRINUSE") {
48507
49065
  this.log(`Port ${port} in use, skipping dev server`);
48508
- resolve12();
49066
+ resolve11();
48509
49067
  } else {
48510
49068
  reject(e);
48511
49069
  }
@@ -48519,7 +49077,33 @@ data: ${JSON.stringify(msg.data)}
48519
49077
  // ─── Handlers ───
48520
49078
  async handleListProviders(_req, res) {
48521
49079
  const providers = this.providerLoader.getAll().map(toProviderListEntry);
48522
- this.json(res, 200, { providers, count: providers.length });
49080
+ this.json(res, 200, { providers, count: providers.length, sourceConfig: this.providerLoader.getSourceConfig() });
49081
+ }
49082
+ async handleGetProviderSourceConfig(_req, res) {
49083
+ this.json(res, 200, { success: true, sourceConfig: this.providerLoader.getSourceConfig() });
49084
+ }
49085
+ async handleSetProviderSourceConfig(req, res) {
49086
+ const body = await this.readBody(req);
49087
+ const parsed = parseProviderSourceConfigUpdate(body || {});
49088
+ if (!parsed.ok) {
49089
+ this.json(res, 400, { success: false, error: parsed.error });
49090
+ return;
49091
+ }
49092
+ const currentConfig2 = loadConfig2();
49093
+ const nextConfig = {
49094
+ ...currentConfig2,
49095
+ ...parsed.updates.providerSourceMode ? { providerSourceMode: parsed.updates.providerSourceMode } : {},
49096
+ ...Object.prototype.hasOwnProperty.call(parsed.updates, "providerDir") ? { providerDir: parsed.updates.providerDir } : {}
49097
+ };
49098
+ saveConfig(nextConfig);
49099
+ const sourceConfig = this.providerLoader.applySourceConfig({
49100
+ sourceMode: nextConfig.providerSourceMode,
49101
+ userDir: Object.prototype.hasOwnProperty.call(parsed.updates, "providerDir") ? parsed.updates.providerDir : this.providerLoader.getSourceConfig().explicitProviderDir || void 0
49102
+ });
49103
+ this.providerLoader.reload();
49104
+ this.providerLoader.registerToDetector();
49105
+ await this.onProviderSourceConfigChanged?.();
49106
+ this.json(res, 200, { success: true, reloaded: true, sourceConfig });
48523
49107
  }
48524
49108
  async handleProviderConfig(type, _req, res) {
48525
49109
  const provider = this.providerLoader.resolve(type);
@@ -48561,20 +49145,20 @@ data: ${JSON.stringify(msg.data)}
48561
49145
  child.stderr?.on("data", (d) => {
48562
49146
  stderr += d.toString().slice(0, 2e3);
48563
49147
  });
48564
- await new Promise((resolve12) => {
49148
+ await new Promise((resolve11) => {
48565
49149
  const timer = setTimeout(() => {
48566
49150
  child.kill();
48567
- resolve12();
49151
+ resolve11();
48568
49152
  }, 3e3);
48569
49153
  child.on("exit", () => {
48570
49154
  clearTimeout(timer);
48571
- resolve12();
49155
+ resolve11();
48572
49156
  });
48573
49157
  child.stdout?.once("data", () => {
48574
49158
  setTimeout(() => {
48575
49159
  child.kill();
48576
49160
  clearTimeout(timer);
48577
- resolve12();
49161
+ resolve11();
48578
49162
  }, 500);
48579
49163
  });
48580
49164
  });
@@ -49070,14 +49654,14 @@ data: ${JSON.stringify(msg.data)}
49070
49654
  child.stderr?.on("data", (d) => {
49071
49655
  stderr += d.toString();
49072
49656
  });
49073
- await new Promise((resolve12) => {
49657
+ await new Promise((resolve11) => {
49074
49658
  const timer = setTimeout(() => {
49075
49659
  child.kill();
49076
- resolve12();
49660
+ resolve11();
49077
49661
  }, timeout);
49078
49662
  child.on("exit", () => {
49079
49663
  clearTimeout(timer);
49080
- resolve12();
49664
+ resolve11();
49081
49665
  });
49082
49666
  });
49083
49667
  const elapsed = Date.now() - start;
@@ -49222,18 +49806,6 @@ data: ${JSON.stringify(msg.data)}
49222
49806
  if (!fs14.existsSync(providerJson)) {
49223
49807
  return { dir: null, reason: `provider.json not found in writable provider directory: ${desiredDir}` };
49224
49808
  }
49225
- try {
49226
- const providerData = JSON.parse(fs14.readFileSync(providerJson, "utf-8"));
49227
- if (providerData.disableUpstream !== true) {
49228
- providerData.disableUpstream = true;
49229
- fs14.writeFileSync(providerJson, JSON.stringify(providerData, null, 2));
49230
- }
49231
- } catch (error48) {
49232
- return {
49233
- dir: null,
49234
- reason: `Failed to update provider.json in writable provider directory: ${error48.message}`
49235
- };
49236
- }
49237
49809
  return { dir: desiredDir };
49238
49810
  }
49239
49811
  async handleAutoImplement(type, req, res) {
@@ -49378,7 +49950,7 @@ data: ${JSON.stringify(msg.data)}
49378
49950
  lines.push("## Required Return Format");
49379
49951
  lines.push("| Function | Return JSON |");
49380
49952
  lines.push("|---|---|");
49381
- lines.push("| readChat | `{ id, status, title, messages: [{role, content, index, kind?, meta?}], inputContent, activeModal }` \u2014 optional `kind`: standard, thought, tool, terminal; optional `meta`: e.g. `{ label, isRunning }` for dashboard |");
49953
+ lines.push("| readChat | `{ id, status, title, messages: [{role, content, index, kind?, meta?}], inputContent, activeModal, controlValues?, summaryMetadata? }` \u2014 optional `kind`: standard, thought, tool, terminal; prefer explicit `controlValues` for current selections and `summaryMetadata` for compact always-visible UI metadata |");
49382
49954
  lines.push("| sendMessage | `{ sent: false, needsTypeAndSend: true, selector }` |");
49383
49955
  lines.push("| resolveAction | `{ resolved: true/false, clicked? }` |");
49384
49956
  lines.push("| listSessions | `{ sessions: [{ id, title, active, index }] }` |");
@@ -49759,14 +50331,14 @@ data: ${JSON.stringify(msg.data)}
49759
50331
  res.end(JSON.stringify(data, null, 2));
49760
50332
  }
49761
50333
  async readBody(req) {
49762
- return new Promise((resolve12) => {
50334
+ return new Promise((resolve11) => {
49763
50335
  let body = "";
49764
50336
  req.on("data", (chunk) => body += chunk);
49765
50337
  req.on("end", () => {
49766
50338
  try {
49767
- resolve12(JSON.parse(body));
50339
+ resolve11(JSON.parse(body));
49768
50340
  } catch {
49769
- resolve12({});
50341
+ resolve11({});
49770
50342
  }
49771
50343
  });
49772
50344
  });
@@ -50236,7 +50808,7 @@ data: ${JSON.stringify(msg.data)}
50236
50808
  const deadline = Date.now() + timeoutMs;
50237
50809
  while (Date.now() < deadline) {
50238
50810
  if (await canConnect(endpoint)) return;
50239
- await new Promise((resolve12) => setTimeout(resolve12, STARTUP_POLL_MS));
50811
+ await new Promise((resolve11) => setTimeout(resolve11, STARTUP_POLL_MS));
50240
50812
  }
50241
50813
  throw new Error(`Session host did not become ready within ${timeoutMs}ms`);
50242
50814
  }
@@ -50275,59 +50847,6 @@ data: ${JSON.stringify(msg.data)}
50275
50847
  });
50276
50848
  }
50277
50849
  }
50278
- var LIVE_LIFECYCLES = /* @__PURE__ */ new Set(["starting", "running", "stopping", "interrupted"]);
50279
- function isSessionHostLiveRuntime(record2) {
50280
- const lifecycle = String(record2?.lifecycle || "").trim();
50281
- return LIVE_LIFECYCLES.has(lifecycle);
50282
- }
50283
- function getSessionHostRecoveryLabel(meta3) {
50284
- const recoveryState = typeof meta3?.runtimeRecoveryState === "string" ? String(meta3.runtimeRecoveryState).trim() : "";
50285
- if (!recoveryState) return null;
50286
- if (recoveryState === "auto_resumed") return "restored after restart";
50287
- if (recoveryState === "resume_failed") return "restore failed";
50288
- if (recoveryState === "host_restart_interrupted") return "host restart interrupted";
50289
- if (recoveryState === "orphan_snapshot") return "snapshot recovered";
50290
- return recoveryState.replace(/_/g, " ");
50291
- }
50292
- function isSessionHostRecoverySnapshot(record2) {
50293
- if (!record2) return false;
50294
- if (isSessionHostLiveRuntime(record2)) return false;
50295
- const lifecycle = String(record2.lifecycle || "").trim();
50296
- if (lifecycle && lifecycle !== "stopped" && lifecycle !== "failed") {
50297
- return false;
50298
- }
50299
- const meta3 = record2.meta || void 0;
50300
- if (meta3?.restoredFromStorage === true) return true;
50301
- return getSessionHostRecoveryLabel(meta3) !== null;
50302
- }
50303
- function getSessionHostSurfaceKind(record2) {
50304
- if (isSessionHostLiveRuntime(record2)) return "live_runtime";
50305
- if (isSessionHostRecoverySnapshot(record2)) return "recovery_snapshot";
50306
- return "inactive_record";
50307
- }
50308
- function partitionSessionHostRecords(records) {
50309
- const liveRuntimes = [];
50310
- const recoverySnapshots = [];
50311
- const inactiveRecords = [];
50312
- for (const record2 of records) {
50313
- const kind = getSessionHostSurfaceKind(record2);
50314
- if (kind === "live_runtime") {
50315
- liveRuntimes.push(record2);
50316
- } else if (kind === "recovery_snapshot") {
50317
- recoverySnapshots.push(record2);
50318
- } else {
50319
- inactiveRecords.push(record2);
50320
- }
50321
- }
50322
- return {
50323
- liveRuntimes,
50324
- recoverySnapshots,
50325
- inactiveRecords
50326
- };
50327
- }
50328
- function partitionSessionHostDiagnosticsSessions(records) {
50329
- return partitionSessionHostRecords(records || []);
50330
- }
50331
50850
  function shouldAutoRestoreHostedSessionsOnStartup2(env = process.env) {
50332
50851
  const raw = typeof env.ADHDEV_RESTORE_HOSTED_SESSIONS_ON_STARTUP === "string" ? env.ADHDEV_RESTORE_HOSTED_SESSIONS_ON_STARTUP.trim().toLowerCase() : "";
50333
50852
  return raw === "1" || raw === "true" || raw === "yes";
@@ -50461,10 +50980,10 @@ data: ${JSON.stringify(msg.data)}
50461
50980
  const buffer = Buffer.from(await res.arrayBuffer());
50462
50981
  const fs15 = await import("fs");
50463
50982
  fs15.writeFileSync(vsixPath, buffer);
50464
- return new Promise((resolve12) => {
50983
+ return new Promise((resolve11) => {
50465
50984
  const cmd = `"${ide.cliCommand}" --install-extension "${vsixPath}" --force`;
50466
50985
  (0, import_child_process10.exec)(cmd, { timeout: 6e4 }, (error48, _stdout, stderr) => {
50467
- resolve12({
50986
+ resolve11({
50468
50987
  extensionId: extension.id,
50469
50988
  marketplaceId: extension.marketplaceId,
50470
50989
  success: !error48,
@@ -50477,11 +50996,11 @@ data: ${JSON.stringify(msg.data)}
50477
50996
  } catch (e) {
50478
50997
  }
50479
50998
  }
50480
- return new Promise((resolve12) => {
50999
+ return new Promise((resolve11) => {
50481
51000
  const cmd = `"${ide.cliCommand}" --install-extension ${extension.marketplaceId} --force`;
50482
51001
  (0, import_child_process10.exec)(cmd, { timeout: 6e4 }, (error48, stdout, stderr) => {
50483
51002
  if (error48) {
50484
- resolve12({
51003
+ resolve11({
50485
51004
  extensionId: extension.id,
50486
51005
  marketplaceId: extension.marketplaceId,
50487
51006
  success: false,
@@ -50489,7 +51008,7 @@ data: ${JSON.stringify(msg.data)}
50489
51008
  error: stderr || error48.message
50490
51009
  });
50491
51010
  } else {
50492
- resolve12({
51011
+ resolve11({
50493
51012
  extensionId: extension.id,
50494
51013
  marketplaceId: extension.marketplaceId,
50495
51014
  success: true,
@@ -50582,10 +51101,11 @@ data: ${JSON.stringify(msg.data)}
50582
51101
  async function initDaemonComponents2(config2) {
50583
51102
  installGlobalInterceptor();
50584
51103
  const appConfig = loadConfig2();
50585
- const disableUpstream = appConfig.disableUpstream ?? false;
51104
+ const providerSourceMode = appConfig.providerSourceMode || "normal";
51105
+ const disableUpstream = providerSourceMode === "no-upstream";
50586
51106
  const providerLoader = new ProviderLoader({
50587
51107
  logFn: config2.providerLogFn,
50588
- disableUpstream,
51108
+ sourceMode: providerSourceMode,
50589
51109
  userDir: appConfig.providerDir
50590
51110
  });
50591
51111
  if (!disableUpstream && !providerLoader.hasUpstream()) {
@@ -50690,6 +51210,10 @@ data: ${JSON.stringify(msg.data)}
50690
51210
  onProviderSettingChanged: async (providerType) => {
50691
51211
  await refreshProviderAvailability(providerType);
50692
51212
  config2.onStatusChange?.();
51213
+ },
51214
+ onProviderSourceConfigChanged: async () => {
51215
+ await refreshProviderAvailability();
51216
+ config2.onStatusChange?.();
50693
51217
  }
50694
51218
  });
50695
51219
  agentStreamManager = new DaemonAgentStreamManager(
@@ -50739,7 +51263,8 @@ data: ${JSON.stringify(msg.data)}
50739
51263
  cdpInitializer,
50740
51264
  cdpManagers,
50741
51265
  sessionRegistry,
50742
- detectedIdes: detectedIdesRef
51266
+ detectedIdes: detectedIdesRef,
51267
+ refreshProviderAvailability
50743
51268
  };
50744
51269
  }
50745
51270
  async function startDaemonDevSupport2(options) {
@@ -50748,7 +51273,10 @@ data: ${JSON.stringify(msg.data)}
50748
51273
  cdpManagers: options.components.cdpManagers,
50749
51274
  instanceManager: options.components.instanceManager,
50750
51275
  cliManager: options.components.cliManager,
50751
- logFn: options.logFn
51276
+ logFn: options.logFn,
51277
+ onProviderSourceConfigChanged: async () => {
51278
+ await options.components.refreshProviderAvailability();
51279
+ }
50752
51280
  });
50753
51281
  await devServer.start();
50754
51282
  options.components.providerLoader.watch();
@@ -52419,9 +52947,6 @@ var StandaloneServer = class {
52419
52947
  status: session.status,
52420
52948
  title: session.title,
52421
52949
  cdpConnected: session.cdpConnected,
52422
- currentModel: session.currentModel,
52423
- currentPlan: session.currentPlan,
52424
- currentAutoApprove: session.currentAutoApprove,
52425
52950
  lastSeenAt: session.lastSeenAt,
52426
52951
  unread: session.unread,
52427
52952
  inboxBucket: session.inboxBucket,
@@ -52449,8 +52974,10 @@ var StandaloneServer = class {
52449
52974
  return { success: false, error: "command type required" };
52450
52975
  }
52451
52976
  const result = await this.components.router.execute(type, args, "standalone");
52452
- if (type.startsWith("workspace_") || type.startsWith("session_host_")) this.scheduleBroadcastStatus();
52453
- if (type === "get_status_metadata" || type === "set_user_name" || type === "set_machine_nickname" || type.startsWith("workspace_") || type.startsWith("session_host_")) {
52977
+ if (type === "invoke_provider_script" || type.startsWith("workspace_") || type.startsWith("session_host_")) {
52978
+ this.scheduleBroadcastStatus();
52979
+ }
52980
+ if (type === "invoke_provider_script" || type === "get_status_metadata" || type === "set_user_name" || type === "set_machine_nickname" || type.startsWith("workspace_") || type.startsWith("session_host_")) {
52454
52981
  void this.flushWsDaemonMetadataSubscriptions();
52455
52982
  }
52456
52983
  if (type.startsWith("session_host_")) void this.flushWsSessionHostDiagnosticsSubscriptions();