dsh-agent-enhancer 0.3.11 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.en.md +6 -6
  2. package/README.md +6 -6
  3. package/lib/client/browser-agent/overlay.d.ts.map +1 -1
  4. package/lib/client/browser-agent/tab.d.ts.map +1 -1
  5. package/lib/client/context/right-tab.d.ts.map +1 -1
  6. package/lib/client/dsh/controls.d.ts.map +1 -1
  7. package/lib/client/index.d.ts.map +1 -1
  8. package/lib/client/locales.d.ts +65 -5
  9. package/lib/client/locales.d.ts.map +1 -1
  10. package/lib/client/mcp-connectors/remote.d.ts +7 -1
  11. package/lib/client/mcp-connectors/remote.d.ts.map +1 -1
  12. package/lib/client/mcp-connectors/tab.d.ts.map +1 -1
  13. package/lib/client/quote/position.d.ts +8 -6
  14. package/lib/client/quote/position.d.ts.map +1 -1
  15. package/lib/client/remote.d.ts +4 -1
  16. package/lib/client/remote.d.ts.map +1 -1
  17. package/lib/client/soft-pause/action.d.ts.map +1 -1
  18. package/lib/client/web-chat-bridge/capture.d.ts +2 -0
  19. package/lib/client/web-chat-bridge/capture.d.ts.map +1 -1
  20. package/lib/client/web-chat-bridge/dom-to-markdown.d.ts +13 -0
  21. package/lib/client/web-chat-bridge/dom-to-markdown.d.ts.map +1 -0
  22. package/lib/client/web-chat-bridge/panel.d.ts.map +1 -1
  23. package/lib/client/web-chat-bridge/preview.d.ts.map +1 -1
  24. package/lib/client/web-chat-bridge/remote.d.ts.map +1 -1
  25. package/lib/client/web-chat-bridge/share-fetch.d.ts +4 -0
  26. package/lib/client/web-chat-bridge/share-fetch.d.ts.map +1 -1
  27. package/lib/client.js +874 -175
  28. package/lib/client.js.map +1 -1
  29. package/lib/errors.d.ts +1 -1
  30. package/lib/errors.d.ts.map +1 -1
  31. package/lib/host/auto-route/errors.d.ts +8 -0
  32. package/lib/host/auto-route/errors.d.ts.map +1 -0
  33. package/lib/host/auto-route/router.d.ts.map +1 -1
  34. package/lib/host/auto-route/session-hook.d.ts.map +1 -1
  35. package/lib/host/browser-agent/driver.d.ts +3 -1
  36. package/lib/host/browser-agent/driver.d.ts.map +1 -1
  37. package/lib/host/browser-agent/install.d.ts +17 -0
  38. package/lib/host/browser-agent/install.d.ts.map +1 -1
  39. package/lib/host/browser-agent/playwright-driver.d.ts +3 -1
  40. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
  41. package/lib/host/browser-agent/prompt.d.ts.map +1 -1
  42. package/lib/host/browser-agent/tools.d.ts.map +1 -1
  43. package/lib/host/context-compact.d.ts.map +1 -1
  44. package/lib/host/index.d.ts +5 -2
  45. package/lib/host/index.d.ts.map +1 -1
  46. package/lib/host/mcp-connectors/io.d.ts +3 -1
  47. package/lib/host/mcp-connectors/io.d.ts.map +1 -1
  48. package/lib/host/mcp-connectors/probe-message.d.ts +7 -0
  49. package/lib/host/mcp-connectors/probe-message.d.ts.map +1 -0
  50. package/lib/host/mcp-connectors/runtime.d.ts +11 -0
  51. package/lib/host/mcp-connectors/runtime.d.ts.map +1 -1
  52. package/lib/host/mcp-connectors/status.d.ts +32 -0
  53. package/lib/host/mcp-connectors/status.d.ts.map +1 -0
  54. package/lib/host/mcp-connectors/types.d.ts +33 -0
  55. package/lib/host/mcp-connectors/types.d.ts.map +1 -1
  56. package/lib/host/model.d.ts.map +1 -1
  57. package/lib/host/rpc.d.ts +372 -0
  58. package/lib/host/rpc.d.ts.map +1 -1
  59. package/lib/host/web-chat-bridge/import-session.d.ts +10 -1
  60. package/lib/host/web-chat-bridge/import-session.d.ts.map +1 -1
  61. package/lib/host/web-chat-bridge/share-link.d.ts +1 -0
  62. package/lib/host/web-chat-bridge/share-link.d.ts.map +1 -1
  63. package/lib/identity.d.ts +1 -1
  64. package/lib/index.js +717 -151
  65. package/lib/index.js.map +4 -4
  66. package/package.json +56 -56
package/lib/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/host/index.ts
2
- import { existsSync as existsSync21, mkdirSync as mkdirSync11, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
2
+ import { existsSync as existsSync21, mkdirSync as mkdirSync12, readdirSync as readdirSync7, renameSync as renameSync9, rmdirSync } from "node:fs";
3
3
  import { homedir as homedir7 } from "node:os";
4
- import { join as join33 } from "node:path";
4
+ import { join as join32 } from "node:path";
5
5
  import z5 from "@deepseek-ai/schemastery";
6
6
  import { RemoteError as RemoteError2, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
7
7
 
@@ -1129,7 +1129,7 @@ var PlaywrightDriver = class {
1129
1129
  return null;
1130
1130
  }
1131
1131
  if (!existsSync2(webkitExe)) {
1132
- this.lastError = "Playwright WebKit is not installed. Run: npx playwright install webkit";
1132
+ this.lastError = "WEBKIT_MISSING: Playwright WebKit is not installed. Run: npx playwright install webkit";
1133
1133
  return null;
1134
1134
  }
1135
1135
  return webkit.launchPersistentContext(profileDir, {
@@ -1184,26 +1184,33 @@ var PlaywrightDriver = class {
1184
1184
  connected: true,
1185
1185
  url: page.url(),
1186
1186
  title: await page.title().catch(() => ""),
1187
- tabId: 1,
1187
+ tabId: tabIdOf(page.context(), page),
1188
1188
  bound: true
1189
1189
  };
1190
1190
  }
1191
- async navigate(url) {
1192
- const page = await this.requirePage();
1191
+ async navigate(url, options = {}) {
1192
+ await this.ensureReady();
1193
+ const context = this.context;
1194
+ if (context === null) throw new Error("Playwright context is not available");
1195
+ let page = this.page;
1196
+ if (options.newTab === true || page === null || page.isClosed()) {
1197
+ page = await context.newPage();
1198
+ this.page = page;
1199
+ }
1193
1200
  await page.goto(url, { waitUntil: "domcontentloaded" });
1194
1201
  await settlePage(page);
1195
1202
  this.lastRefs.clear();
1196
1203
  return {
1197
1204
  url: page.url(),
1198
1205
  title: await page.title().catch(() => ""),
1199
- tabId: 1
1206
+ tabId: tabIdOf(page.context(), page)
1200
1207
  };
1201
1208
  }
1202
1209
  async snapshot() {
1203
1210
  const page = await this.requirePage();
1204
1211
  const { body, refs } = await capturePlaywrightSnapshot(page);
1205
1212
  this.lastRefs = new Map(refs);
1206
- return body;
1213
+ return { ...body, tabId: tabIdOf(page.context(), page) };
1207
1214
  }
1208
1215
  async extract(input = {}) {
1209
1216
  const page = await this.requirePage();
@@ -1216,7 +1223,7 @@ var PlaywrightDriver = class {
1216
1223
  text: clipped.slice(0, maxChars),
1217
1224
  truncated: clipped.length > maxChars,
1218
1225
  ...input.focus === void 0 || input.focus.trim() === "" ? {} : { focus: input.focus.trim() },
1219
- tabId: 1
1226
+ tabId: tabIdOf(page.context(), page)
1220
1227
  };
1221
1228
  }
1222
1229
  async click(ref) {
@@ -1246,7 +1253,7 @@ var PlaywrightDriver = class {
1246
1253
  title: await page.title().catch(() => ""),
1247
1254
  changed: pathsDiffer(beforeUrl, after),
1248
1255
  href,
1249
- tabId: 1,
1256
+ tabId: tabIdOf(page.context(), page),
1250
1257
  warning: "Opened this ref's href after snapshot bound a nearby document link."
1251
1258
  };
1252
1259
  }
@@ -1298,7 +1305,7 @@ var PlaywrightDriver = class {
1298
1305
  url: afterUrl,
1299
1306
  title: await page.title().catch(() => ""),
1300
1307
  changed,
1301
- tabId: 1,
1308
+ tabId: tabIdOf(page.context(), page),
1302
1309
  ...href !== "" ? { href } : {},
1303
1310
  ...pageLinks.length > 0 ? { pageLinks: pageLinks.slice(0, 8) } : {},
1304
1311
  ...followedHref ? { warning: "Click missed; opened this ref's own href via navigation." } : !changed ? {
@@ -1317,7 +1324,7 @@ var PlaywrightDriver = class {
1317
1324
  title: await page.title().catch(() => ""),
1318
1325
  changed: pathsDiffer(beforeUrl, after),
1319
1326
  href,
1320
- tabId: 1,
1327
+ tabId: tabIdOf(page.context(), page),
1321
1328
  warning: "Ref stamp missing; opened this ref's href directly."
1322
1329
  };
1323
1330
  }
@@ -1332,7 +1339,7 @@ var PlaywrightDriver = class {
1332
1339
  url: afterUrl,
1333
1340
  title: await page.title().catch(() => ""),
1334
1341
  changed,
1335
- tabId: 1,
1342
+ tabId: tabIdOf(page.context(), page),
1336
1343
  ...href !== "" ? { href } : {},
1337
1344
  ...!changed ? {
1338
1345
  warning: "Pathname unchanged after coordinate click. browser_snapshot again or browser_navigate by href."
@@ -1362,14 +1369,19 @@ var PlaywrightDriver = class {
1362
1369
  url: page.url(),
1363
1370
  title: await page.title().catch(() => ""),
1364
1371
  changed: false,
1365
- tabId: 1
1372
+ tabId: tabIdOf(page.context(), page)
1366
1373
  };
1367
1374
  }
1368
1375
  async scroll(dy) {
1369
1376
  const page = await this.requirePage();
1370
1377
  await page.mouse.wheel(0, dy);
1371
1378
  await sleep(80);
1372
- return { url: page.url(), title: await page.title().catch(() => ""), changed: false, tabId: 1 };
1379
+ return {
1380
+ url: page.url(),
1381
+ title: await page.title().catch(() => ""),
1382
+ changed: false,
1383
+ tabId: tabIdOf(page.context(), page)
1384
+ };
1373
1385
  }
1374
1386
  async wait(input = {}) {
1375
1387
  const page = await this.requirePage();
@@ -1389,23 +1401,30 @@ var PlaywrightDriver = class {
1389
1401
  url: page.url(),
1390
1402
  title: await page.title().catch(() => ""),
1391
1403
  matched,
1392
- tabId: 1
1404
+ tabId: tabIdOf(page.context(), page)
1393
1405
  };
1394
1406
  }
1395
1407
  async screenshot() {
1396
1408
  const page = await this.requirePage();
1397
1409
  const buf = await page.screenshot({ type: "png", fullPage: false });
1398
- return { mime: "image/png", base64: buf.toString("base64"), tabId: 1 };
1410
+ return {
1411
+ mime: "image/png",
1412
+ base64: buf.toString("base64"),
1413
+ tabId: tabIdOf(page.context(), page)
1414
+ };
1399
1415
  }
1400
1416
  async listTabs() {
1401
- await this.ensureReady();
1402
1417
  const pages = this.context?.pages() ?? [];
1418
+ if (pages.length === 0) {
1419
+ return { tabs: [], boundTabId: null };
1420
+ }
1403
1421
  return {
1404
1422
  tabs: await Promise.all(pages.map(async (p, index) => ({
1405
1423
  tabId: index + 1,
1406
1424
  title: await p.title().catch(() => ""),
1407
1425
  url: p.url(),
1408
1426
  active: p === this.page,
1427
+ // Session bind is layered in install.listTabs; driver marks the live page.
1409
1428
  bound: p === this.page
1410
1429
  }))),
1411
1430
  boundTabId: this.page ? pages.indexOf(this.page) + 1 : null
@@ -1501,8 +1520,10 @@ var SECTION_NAME = "agent-enhancer:browser-agent";
1501
1520
  var GUIDANCE = [
1502
1521
  "## Browser agent (Desktop dedicated browser: Safari/Chrome on Mac, Chrome/Edge on Windows)",
1503
1522
  "When the user asks to open a website, browse the web, click pages, fill forms, read on-page content, log into a site, or verify UI in a real browser, you MUST use the browser_* tools \u2014 do not only describe steps or ask the user to open a browser manually.",
1523
+ "Do NOT open the system default browser via shell (Start-Process, open, xdg-open, cmd start). That bypasses the dedicated browser agent. Use browser_navigate (and then snapshot/click) instead. web_fetch / web_search are fine for raw HTTP/API reads, not as a substitute for interactive browsing.",
1504
1524
  "Goal phases: (1) reach the target page once, (2) stay and observe/extract, (3) answer the user. Do not keep navigating without a new user goal.",
1505
1525
  "Preferred loop: browser_navigate (or reuse a tab) \u2192 browser_wait if slow \u2192 browser_snapshot \u2192 click/type/scroll using listed refs \u2192 browser_snapshot or browser_extract again.",
1526
+ "browser_navigate replaces the current tab by default. When the user asks to open another site without closing the current one, compare two pages, or keep a previous page (search results, docs, etc.), call browser_navigate with newTab=true. Then browser_list_tabs / browser_follow_tab (or the Desktop sidebar tab list) to switch.",
1506
1527
  "Perception is accessibility-tree based (Playwright MCP style): prefer refs that show href=\u2026. browser_screenshot exists but is optional \u2014 do not wait for screenshots; dead clicks are usually missing hrefs on SPA cards, not missing vision.",
1507
1528
  "If browser_click leaves pathname unchanged and that ref has an http(s) href, the host may open that same href once. If the tool says the ref has no href / lists page_links: do NOT re-click the same ref \u2014 browser_navigate once to a page_links URL or pick another ref that lists href=. Never invent URLs.",
1508
1529
  "Below-the-fold or long content: browser_scroll \u2192 browser_wait \u2192 browser_extract. Report what extract returns; do not hop to unrelated pages.",
@@ -2091,44 +2112,57 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2091
2112
  )));
2092
2113
  disposers.push(ctx.tools.register(textTool(
2093
2114
  "browser_navigate",
2094
- "Open or navigate the dedicated Desktop browser to an http(s) URL. Prefer this over telling the user to open a browser themselves. Auto-launches when disconnected. Requires approval unless the origin is already allowed. After navigation call browser_snapshot (it will pause for login/captcha if needed).",
2115
+ "Open or navigate the dedicated Desktop browser to an http(s) URL. Prefer this over telling the user to open a browser themselves. Auto-launches when disconnected. Requires approval unless the origin is already allowed. After navigation call browser_snapshot (it will pause for login/captcha if needed). Use newTab=true when the user wants to keep the previous page open, compare sites, or explicitly asks for a new tab \u2014 otherwise the current tab is replaced.",
2095
2116
  {
2096
2117
  url: {
2097
2118
  type: "string",
2098
2119
  required: true,
2099
- description: "Absolute http(s) URL to open in the bound tab."
2120
+ description: "Absolute http(s) URL to open."
2121
+ },
2122
+ newTab: {
2123
+ type: "boolean",
2124
+ description: "When true, open in a new tab and keep the previous tab. Default false (navigate current tab)."
2100
2125
  }
2101
2126
  },
2102
2127
  async (args, exec) => {
2103
2128
  guardEnabled();
2104
2129
  const sessionId = sessionIdOf(exec);
2105
2130
  const url = String(args.url ?? "").trim();
2131
+ const newTab = args.newTab === true;
2106
2132
  if (url === "") throw new Error("url is required");
2107
2133
  await ensureConnected(url);
2108
2134
  await ensureSessionTab(sessionId);
2109
- await requireMutation(exec, "browser_navigate", `Navigate to ${url}`, url);
2135
+ await requireMutation(
2136
+ exec,
2137
+ "browser_navigate",
2138
+ `${newTab ? "Open new tab" : "Navigate"} to ${url}`,
2139
+ url
2140
+ );
2110
2141
  try {
2111
- const result = await runBridge(() => driverOf(options).navigate(url));
2142
+ const result = await runBridge(() => driverOf(options).navigate(url, { newTab }));
2112
2143
  await rememberTab(sessionId, result.tabId);
2113
2144
  options.sessions.rememberHttpUrl(sessionId, result.url);
2114
2145
  options.sessions.record({
2115
2146
  sessionId,
2116
2147
  tool: "browser_navigate",
2117
- summary: `Navigate to ${url}`,
2148
+ summary: `${newTab ? "Open new tab" : "Navigate"} to ${url}`,
2118
2149
  url: result.url,
2119
2150
  outcome: "ok"
2120
2151
  });
2121
2152
  options.onMutation?.({ sessionId, tool: "browser_navigate", url: result.url });
2122
- return `navigated
2123
- url: ${result.url}
2124
- title: ${result.title}
2125
- Action: call browser_snapshot next. For long page content use browser_extract after scroll if needed.`;
2153
+ return [
2154
+ newTab ? "opened_new_tab" : "navigated",
2155
+ `url: ${result.url}`,
2156
+ `title: ${result.title}`,
2157
+ result.tabId !== void 0 ? `tabId: ${result.tabId}` : null,
2158
+ "Action: call browser_snapshot next. For long page content use browser_extract after scroll if needed. Use browser_list_tabs / browser_follow_tab (or the sidebar tab list) to switch among tabs."
2159
+ ].filter((line) => line !== null).join("\n");
2126
2160
  } catch (error) {
2127
2161
  noteHuman(sessionId, {}, error);
2128
2162
  options.sessions.record({
2129
2163
  sessionId,
2130
2164
  tool: "browser_navigate",
2131
- summary: `Navigate to ${url}`,
2165
+ summary: `${newTab ? "Open new tab" : "Navigate"} to ${url}`,
2132
2166
  url,
2133
2167
  outcome: "error"
2134
2168
  });
@@ -2621,7 +2655,12 @@ function installBrowserAgent(ctx, options) {
2621
2655
  const detail = error instanceof Error ? error.message : String(error);
2622
2656
  ctx.logger.warn(`agent-enhancer: browser driver remount failed: ${detail}`);
2623
2657
  }).finally(() => {
2624
- if (epoch === switchEpoch) switchPending = false;
2658
+ if (epoch !== switchEpoch) return;
2659
+ switchPending = false;
2660
+ if (options.enabled() && unregisterTools === null) {
2661
+ active = true;
2662
+ mount();
2663
+ }
2625
2664
  });
2626
2665
  };
2627
2666
  const tearDownDriverAsync = async () => {
@@ -2685,7 +2724,9 @@ function installBrowserAgent(ctx, options) {
2685
2724
  approval,
2686
2725
  human,
2687
2726
  sessions,
2688
- enabled: () => active && options.enabled(),
2727
+ // Gate on settings only — `active` flips false during driver align and
2728
+ // must not make browser_* look "disabled" mid-turn.
2729
+ enabled: () => options.enabled(),
2689
2730
  onMutation: options.onBrowserMutation
2690
2731
  });
2691
2732
  }
@@ -2735,16 +2776,25 @@ function installBrowserAgent(ctx, options) {
2735
2776
  const refresh = () => {
2736
2777
  const want = options.enabled();
2737
2778
  if (!want) {
2738
- if (!active && playwrightDriver === null && !switchPending) return;
2779
+ if (!active && playwrightDriver === null && unregisterTools === null && !switchPending) {
2780
+ return;
2781
+ }
2739
2782
  active = false;
2740
2783
  approval.clearAll();
2741
2784
  human.clearAll();
2742
2785
  enqueueSwitch(() => tearDownActiveAsync());
2743
2786
  return;
2744
2787
  }
2745
- if (active || playwrightDriver !== null || switchPending) return;
2788
+ if (switchPending) {
2789
+ active = true;
2790
+ return;
2791
+ }
2792
+ if (playwrightDriver === null) {
2793
+ mount();
2794
+ } else {
2795
+ ensureToolsRegistered();
2796
+ }
2746
2797
  active = true;
2747
- mount();
2748
2798
  };
2749
2799
  refresh();
2750
2800
  return {
@@ -2767,6 +2817,57 @@ function installBrowserAgent(ctx, options) {
2767
2817
  return alignToPreference(startUrl);
2768
2818
  },
2769
2819
  refresh,
2820
+ async listTabs() {
2821
+ if (!options.enabled() || activeDriver === null || activeDriver.status().ready !== true) {
2822
+ return { tabs: [], boundTabId: null };
2823
+ }
2824
+ try {
2825
+ const body = await activeDriver.listTabs();
2826
+ return {
2827
+ tabs: body.tabs.map((tab) => ({
2828
+ ...tab,
2829
+ bound: sessions.sessionOf(tab.tabId) !== void 0
2830
+ })),
2831
+ boundTabId: body.boundTabId
2832
+ };
2833
+ } catch {
2834
+ return { tabs: [], boundTabId: null };
2835
+ }
2836
+ },
2837
+ async selectTab(input) {
2838
+ if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
2839
+ await switchGate.catch(() => void 0);
2840
+ try {
2841
+ const aligned = await alignToPreference();
2842
+ if (!aligned.ok) return { ok: false, error: aligned.error };
2843
+ const followed = await requireDriver().followTab(input.tabId, true);
2844
+ const sessionId = typeof input.sessionId === "string" && input.sessionId.trim() !== "" ? input.sessionId.trim() : void 0;
2845
+ if (sessionId !== void 0) {
2846
+ sessions.bind(sessionId, followed.tabId);
2847
+ sessions.rememberHttpUrl(sessionId, followed.url);
2848
+ }
2849
+ sessions.record({
2850
+ sessionId: sessionId ?? "sidebar",
2851
+ tool: "browser_select_tab",
2852
+ summary: `Select tab ${followed.tabId}`,
2853
+ url: followed.url,
2854
+ outcome: "ok"
2855
+ });
2856
+ options.onBrowserMutation?.({
2857
+ sessionId: sessionId ?? "sidebar",
2858
+ tool: "browser_select_tab",
2859
+ url: followed.url
2860
+ });
2861
+ return {
2862
+ ok: true,
2863
+ tabId: followed.tabId,
2864
+ url: followed.url,
2865
+ title: followed.title
2866
+ };
2867
+ } catch (error) {
2868
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2869
+ }
2870
+ },
2770
2871
  async resolveTabConflict(decision) {
2771
2872
  const conflict = sessions.currentConflict();
2772
2873
  if (conflict === null || activeDriver === null) return { ok: false };
@@ -2887,6 +2988,7 @@ function installBrowserAgent(ctx, options) {
2887
2988
  // src/errors.ts
2888
2989
  var MESSAGES = {
2889
2990
  MODEL_UNAVAILABLE: "No model is available for Agent Enhance",
2991
+ AUTO_ROUTE_UNCONFIGURED: "Auto routing is not configured. Open Settings \u2192 Built-in plugins \u2192 Agent Enhancer \u2192 Models & routing and map Instant / Thinking / Pro.",
2890
2992
  MODEL_FAILED: "Auxiliary model request failed",
2891
2993
  INVALID_OUTPUT: "Auxiliary model returned invalid output",
2892
2994
  SESSION_CHANGED: "The session changed during the auxiliary request",
@@ -2916,7 +3018,7 @@ var AuxiliaryError = class extends Error {
2916
3018
  // src/identity.ts
2917
3019
  var PACKAGE_NAME = "dsh-agent-enhancer";
2918
3020
  var PLUGIN_ID = "agent-enhancer";
2919
- var PACKAGE_VERSION = "0.3.11";
3021
+ var PACKAGE_VERSION = "0.3.12";
2920
3022
  var LEGACY_PACKAGE_NAME = "dsh-composer-enhancer";
2921
3023
  var ROLLBACK_PREFIX = `${PACKAGE_NAME}:rollback:`;
2922
3024
  var UNDO_PREFIX = `${PACKAGE_NAME}:undo:`;
@@ -5656,6 +5758,16 @@ function createClassifier(llm, route) {
5656
5758
  });
5657
5759
  }
5658
5760
 
5761
+ // src/host/auto-route/errors.ts
5762
+ var AutoRouteUnconfiguredError = class extends Error {
5763
+ code = "AUTO_ROUTE_UNCONFIGURED";
5764
+ constructor(message = "Auto routing is not configured. Open Settings \u2192 Built-in plugins \u2192 Agent Enhancer \u2192 Models & routing and map Instant / Thinking / Pro to real models.") {
5765
+ super(message);
5766
+ this.name = "AutoRouteUnconfiguredError";
5767
+ }
5768
+ };
5769
+ var AUTO_ROUTE_UNCONFIGURED_LLM_MESSAGE = "Auto routing is not configured / \u5C1A\u672A\u914D\u7F6E Auto \u6863\u4F4D\u6A21\u578B\u3002 Open Settings \u2192 Built-in plugins \u2192 Agent Enhancer \u2192 Models & routing\uFF08\u8BBE\u7F6E \u2192 \u5185\u7F6E\u63D2\u4EF6 \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6A21\u578B\u4E0E\u8DEF\u7531\uFF09and map Instant / Thinking / Pro.";
5770
+
5659
5771
  // src/host/auto-route/session-resolved-route.ts
5660
5772
  var byAgent = /* @__PURE__ */ new WeakMap();
5661
5773
  var bySession = /* @__PURE__ */ new WeakMap();
@@ -5865,7 +5977,9 @@ function pickTierHeuristic(input) {
5865
5977
  var TIER_ORDER = ["pro", "thinking", "instant"];
5866
5978
  function tiersFrom(start) {
5867
5979
  const idx = TIER_ORDER.indexOf(start);
5868
- return TIER_ORDER.slice(idx);
5980
+ const weaker = TIER_ORDER.slice(idx + 1);
5981
+ const stronger = TIER_ORDER.slice(0, idx).reverse();
5982
+ return [start, ...weaker, ...stronger];
5869
5983
  }
5870
5984
  function routeForTier(map, tier, isAvailable) {
5871
5985
  const route = map[tier];
@@ -5897,8 +6011,11 @@ async function resolveAutoRoute(options) {
5897
6011
  return { ...route, tier: candidate };
5898
6012
  }
5899
6013
  }
5900
- const fallback = options.fallback ?? options.map.thinking;
5901
- return { ...fallback, tier: "thinking" };
6014
+ const fallback = options.fallback;
6015
+ if (fallback !== void 0 && options.isAvailable(fallback.provider, fallback.model)) {
6016
+ return { ...fallback, tier: "thinking" };
6017
+ }
6018
+ throw new AutoRouteUnconfiguredError();
5902
6019
  }
5903
6020
 
5904
6021
  // src/host/context-compact.ts
@@ -6497,7 +6614,7 @@ async function deleteSessionNow(options) {
6497
6614
 
6498
6615
  // src/host/web-chat-bridge/import-session.ts
6499
6616
  import { randomUUID as randomUUID6 } from "node:crypto";
6500
- import { existsSync as existsSync5, statSync } from "node:fs";
6617
+ import { existsSync as existsSync5, mkdirSync as mkdirSync2, statSync } from "node:fs";
6501
6618
  import { resolve as resolve2 } from "node:path";
6502
6619
  import { RemoteError } from "@deepseek-ai/dsh-typert-protocol";
6503
6620
  import {
@@ -6839,27 +6956,31 @@ function appendSessionTitle(session, title, firstUserMessageSeq) {
6839
6956
  });
6840
6957
  }
6841
6958
  function appendAssistantMessage(session, turn, step, text3) {
6842
- session.append("step/start", { turn, step });
6843
6959
  const message = createAssistantMessage({
6844
6960
  content: [{ type: "text", text: text3 }],
6845
6961
  source: { provider: "web-chat-bridge", model: "imported-history" }
6846
6962
  });
6847
- session.append("assistant/message", {
6848
- turn,
6849
- step,
6850
- message,
6851
- stream: []
6852
- }, { surfaceOp: "append" });
6853
- session.append("step/end", { turn, step });
6963
+ session.append([
6964
+ ["step/start", { turn, step }],
6965
+ ["assistant/message", {
6966
+ turn,
6967
+ step,
6968
+ message,
6969
+ stream: []
6970
+ }, { surfaceOp: "append" }],
6971
+ ["step/end", { turn, step }]
6972
+ ]);
6854
6973
  }
6855
6974
  function appendProtectedSystemHead(session, turn, step) {
6856
- session.append("step/start", { turn, step });
6857
- session.append("system/message", {
6858
- turn,
6859
- step,
6860
- message: createSystemMessage("")
6861
- }, { surfaceOp: "append" });
6862
- session.append("step/end", { turn, step });
6975
+ session.append([
6976
+ ["step/start", { turn, step }],
6977
+ ["system/message", {
6978
+ turn,
6979
+ step,
6980
+ message: createSystemMessage("")
6981
+ }, { surfaceOp: "append" }],
6982
+ ["step/end", { turn, step }]
6983
+ ]);
6863
6984
  }
6864
6985
  function appendTranscript(session, transcript) {
6865
6986
  const provenance = importProvenancePrefix(transcript);
@@ -6921,17 +7042,28 @@ function appendTranscript(session, transcript) {
6921
7042
  }
6922
7043
  function buildWebChatImportSeed(transcript) {
6923
7044
  const events = [];
7045
+ const recordOne = (type, data, intent) => {
7046
+ const event = {
7047
+ type,
7048
+ seq: SessionSeq2(events.length),
7049
+ time: Date.now(),
7050
+ data,
7051
+ ...intent?.surfaceOp === void 0 ? {} : { surfaceOp: intent.surfaceOp }
7052
+ };
7053
+ events.push(event);
7054
+ return event;
7055
+ };
6924
7056
  const recorder = {
6925
- append(type, data, intent) {
6926
- const event = {
6927
- type,
6928
- seq: SessionSeq2(events.length),
6929
- time: Date.now(),
6930
- data,
6931
- ...intent?.surfaceOp === void 0 ? {} : { surfaceOp: intent.surfaceOp }
6932
- };
6933
- events.push(event);
6934
- return event;
7057
+ append(typeOrInputs, data, intent) {
7058
+ if (typeof typeOrInputs !== "string") {
7059
+ return typeOrInputs.map((input) => {
7060
+ const type = input[0];
7061
+ const payload = input[1];
7062
+ const surface = input[2];
7063
+ return recordOne(type, payload, surface);
7064
+ });
7065
+ }
7066
+ return recordOne(typeOrInputs, data, intent);
6935
7067
  }
6936
7068
  };
6937
7069
  appendTranscript(recorder, transcript);
@@ -7005,9 +7137,30 @@ async function openAgentWorkSession(input, cwd) {
7005
7137
  }
7006
7138
  return { session, dispose: onceDispose(() => handle.dispose()) };
7007
7139
  }
7140
+ function ensureResolvableWorkspaceCwd(cwd) {
7141
+ const absolute = resolve2(cwd);
7142
+ try {
7143
+ if (!existsSync5(absolute)) {
7144
+ mkdirSync2(absolute, { recursive: true });
7145
+ }
7146
+ if (!statSync(absolute).isDirectory()) {
7147
+ throw new WebChatImportError(
7148
+ "missing-cwd",
7149
+ `Workspace path exists but is not a directory: ${absolute}`
7150
+ );
7151
+ }
7152
+ } catch (error) {
7153
+ if (error instanceof WebChatImportError) throw error;
7154
+ throw new WebChatImportError(
7155
+ "missing-cwd",
7156
+ `Workspace folder could not be created or read: ${absolute}`
7157
+ );
7158
+ }
7159
+ return absolute;
7160
+ }
7008
7161
  async function importWebChatHistoryNow(input) {
7009
7162
  assertTranscript(input.transcript);
7010
- const cwd = resolve2(input.cwd);
7163
+ const cwd = ensureResolvableWorkspaceCwd(input.cwd);
7011
7164
  const opened = await openAgentWorkSession(input, cwd);
7012
7165
  try {
7013
7166
  const flushed = await input.sessions.flush(opened.session);
@@ -7690,7 +7843,7 @@ async function fetchWebChatShareContent(shareId, signal) {
7690
7843
  }
7691
7844
 
7692
7845
  // src/host/web-chat-bridge/login-snapshot.ts
7693
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7846
+ import { existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7694
7847
  import { dirname, join as join9 } from "node:path";
7695
7848
 
7696
7849
  // src/host/web-chat-bridge/login-snapshot-types.ts
@@ -7784,7 +7937,7 @@ function saveWebChatLoginSnapshot(pluginDataPackageRoot, input, options) {
7784
7937
  savedAt: typeof input.savedAt === "string" && input.savedAt.trim() !== "" ? input.savedAt : (/* @__PURE__ */ new Date()).toISOString()
7785
7938
  };
7786
7939
  const path = webChatLoginSnapshotPath(pluginDataPackageRoot);
7787
- mkdirSync2(dirname(path), { recursive: true });
7940
+ mkdirSync3(dirname(path), { recursive: true });
7788
7941
  const tmp = `${path}.${process.pid}.tmp`;
7789
7942
  writeFileSync(tmp, `${JSON.stringify(snapshot, null, 2)}
7790
7943
  `, "utf8");
@@ -8064,7 +8217,7 @@ function loadExtraRootPaths(store, primaryCwd) {
8064
8217
  }
8065
8218
 
8066
8219
  // src/host/extra-folders/store.ts
8067
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
8220
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync2, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "node:fs";
8068
8221
  import { dirname as dirname2, join as join11 } from "node:path";
8069
8222
  function emptyDoc(primaryCwd) {
8070
8223
  return {
@@ -8097,7 +8250,7 @@ function parseDoc(raw, primaryCwd) {
8097
8250
  }
8098
8251
  }
8099
8252
  function createExtraFoldersStore(rootDir) {
8100
- mkdirSync3(rootDir, { recursive: true });
8253
+ mkdirSync4(rootDir, { recursive: true });
8101
8254
  const fileOf = (primaryCwd) => join11(rootDir, `${cwdStorageKey(primaryCwd)}.json`);
8102
8255
  return {
8103
8256
  rootDir,
@@ -8118,7 +8271,7 @@ function createExtraFoldersStore(rootDir) {
8118
8271
  roots: [...roots]
8119
8272
  };
8120
8273
  const file = fileOf(primaryCwd);
8121
- mkdirSync3(dirname2(file), { recursive: true });
8274
+ mkdirSync4(dirname2(file), { recursive: true });
8122
8275
  const tmp = `${file}.${process.pid}.tmp`;
8123
8276
  writeFileSync2(tmp, `${JSON.stringify(doc, null, 2)}
8124
8277
  `, "utf8");
@@ -8467,7 +8620,7 @@ import { existsSync as existsSync17, readFileSync as readFileSync7, statSync as
8467
8620
  import { basename as basename13, join as join26, resolve as resolve16, sep as sep7 } from "node:path";
8468
8621
 
8469
8622
  // src/host/instructions-skills/create.ts
8470
- import { existsSync as existsSync9, mkdirSync as mkdirSync4, writeFileSync as writeFileSync3 } from "node:fs";
8623
+ import { existsSync as existsSync9, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
8471
8624
  import { dirname as dirname5, join as join14, resolve as resolve8 } from "node:path";
8472
8625
 
8473
8626
  // src/host/instructions-skills/paths.ts
@@ -8595,7 +8748,7 @@ function createWorkspaceAgentsFile(projectRoot) {
8595
8748
  if (existsSync9(path)) {
8596
8749
  throw new AuxiliaryError("FILE_DENIED", "AGENTS.md already exists at the workspace root");
8597
8750
  }
8598
- mkdirSync4(dirname5(path), { recursive: true });
8751
+ mkdirSync5(dirname5(path), { recursive: true });
8599
8752
  writeFileSync3(path, AGENTS_STUB, "utf8");
8600
8753
  return { path, created: true };
8601
8754
  }
@@ -8609,7 +8762,7 @@ function createWorkspaceSkill(projectRoot, rawName) {
8609
8762
  if (existsSync9(path) || existsSync9(dir)) {
8610
8763
  throw new AuxiliaryError("FILE_DENIED", "A skill with that name already exists");
8611
8764
  }
8612
- mkdirSync4(dir, { recursive: true });
8765
+ mkdirSync5(dir, { recursive: true });
8613
8766
  writeFileSync3(path, skillStubMarkdown(name2), "utf8");
8614
8767
  return { path, created: true, name: name2 };
8615
8768
  }
@@ -8696,14 +8849,14 @@ import { lstatSync as lstatSync3 } from "node:fs";
8696
8849
  import { basename as basename8, dirname as dirname7, join as join18, resolve as resolve11 } from "node:path";
8697
8850
 
8698
8851
  // src/host/instructions-skills/install-ledger.ts
8699
- import { existsSync as existsSync11, mkdirSync as mkdirSync5, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
8852
+ import { existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync3, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
8700
8853
  import { dirname as dirname6, join as join16 } from "node:path";
8701
8854
  function ledgerPath(dataRoot) {
8702
8855
  return join16(dataRoot, "skills-install", "registry.json");
8703
8856
  }
8704
8857
  function writeLedger(dataRoot, ledger) {
8705
8858
  const path = ledgerPath(dataRoot);
8706
- mkdirSync5(dirname6(path), { recursive: true });
8859
+ mkdirSync6(dirname6(path), { recursive: true });
8707
8860
  const tmp = `${path}.${process.pid}.tmp`;
8708
8861
  writeFileSync4(tmp, `${JSON.stringify(ledger, null, 2)}
8709
8862
  `, "utf8");
@@ -9357,7 +9510,7 @@ import { promisify as promisify3 } from "node:util";
9357
9510
  import { execFile as execFile2 } from "node:child_process";
9358
9511
  import {
9359
9512
  createWriteStream,
9360
- mkdirSync as mkdirSync6,
9513
+ mkdirSync as mkdirSync7,
9361
9514
  readdirSync as readdirSync4,
9362
9515
  renameSync as renameSync5,
9363
9516
  rmSync as rmSync3,
@@ -9408,7 +9561,7 @@ async function downloadUrl(url, destFile, signal, onBytes) {
9408
9561
  }
9409
9562
  async function extractZip(zipPath, destDir, signal) {
9410
9563
  signal.throwIfAborted();
9411
- mkdirSync6(destDir, { recursive: true });
9564
+ mkdirSync7(destDir, { recursive: true });
9412
9565
  try {
9413
9566
  await execFileAsync2("tar", ["-xf", zipPath, "-C", destDir], {
9414
9567
  windowsHide: true,
@@ -9466,10 +9619,10 @@ function archiveCandidates(owner, repo, defaultBranch) {
9466
9619
  }
9467
9620
  async function fetchGithubRepoArchive(options) {
9468
9621
  const { owner, repo, workDir, signal, onDownloadProgress, onStage } = options;
9469
- mkdirSync6(workDir, { recursive: true });
9622
+ mkdirSync7(workDir, { recursive: true });
9470
9623
  const zipPath = join20(workDir, "repo.zip");
9471
9624
  const extractDir = join20(workDir, "extract");
9472
- mkdirSync6(extractDir, { recursive: true });
9625
+ mkdirSync7(extractDir, { recursive: true });
9473
9626
  const defaultBranch = await resolveDefaultBranch(owner, repo, signal);
9474
9627
  const candidates = archiveCandidates(owner, repo, defaultBranch);
9475
9628
  const errors = [];
@@ -9480,7 +9633,7 @@ async function fetchGithubRepoArchive(options) {
9480
9633
  try {
9481
9634
  rmSync3(zipPath, { force: true });
9482
9635
  rmSync3(extractDir, { recursive: true, force: true });
9483
- mkdirSync6(extractDir, { recursive: true });
9636
+ mkdirSync7(extractDir, { recursive: true });
9484
9637
  const detail = index === 0 ? `${owner}/${repo}` : `${owner}/${repo} \xB7 retry ${index + 1}/${candidates.length}`;
9485
9638
  if (!downloadStarted) {
9486
9639
  onStage?.("downloading", detail);
@@ -9524,7 +9677,7 @@ import {
9524
9677
  cpSync,
9525
9678
  existsSync as existsSync14,
9526
9679
  lstatSync as lstatSync4,
9527
- mkdirSync as mkdirSync7,
9680
+ mkdirSync as mkdirSync8,
9528
9681
  readdirSync as readdirSync5,
9529
9682
  readFileSync as readFileSync5,
9530
9683
  renameSync as renameSync6,
@@ -9673,7 +9826,7 @@ function copySkillTree(source, dest) {
9673
9826
  }
9674
9827
  }
9675
9828
  function copySkillTreeAtomic(source, dest, kind) {
9676
- mkdirSync7(dirname9(dest), { recursive: true });
9829
+ mkdirSync8(dirname9(dest), { recursive: true });
9677
9830
  if (kind === "file") {
9678
9831
  if (destinationPresent(dest)) removeDestination(dest);
9679
9832
  copySkillTree(source, dest);
@@ -9701,7 +9854,7 @@ function copySkillTreeAtomic(source, dest, kind) {
9701
9854
  }
9702
9855
  }
9703
9856
  function linkOrCopy(source, dest, mode, kind) {
9704
- mkdirSync7(dirname9(dest), { recursive: true });
9857
+ mkdirSync8(dirname9(dest), { recursive: true });
9705
9858
  if (mode === "copy") {
9706
9859
  copySkillTreeAtomic(source, dest, kind);
9707
9860
  return "copy";
@@ -10176,7 +10329,7 @@ async function checkGithubSkillUpdate(record2, options) {
10176
10329
 
10177
10330
  // src/host/instructions-skills/zip-install.ts
10178
10331
  import { execFile as execFile4 } from "node:child_process";
10179
- import { existsSync as existsSync16, mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
10332
+ import { existsSync as existsSync16, mkdirSync as mkdirSync9, mkdtempSync as mkdtempSync3, realpathSync as realpathSync3, rmSync as rmSync6 } from "node:fs";
10180
10333
  import { tmpdir as tmpdir5 } from "node:os";
10181
10334
  import { basename as basename12, join as join25, resolve as resolve15 } from "node:path";
10182
10335
  import { promisify as promisify4 } from "node:util";
@@ -10191,7 +10344,7 @@ function tempWorkDir3(prefix) {
10191
10344
  }
10192
10345
  async function extractZipArchive(zipPath, destDir, signal) {
10193
10346
  signal.throwIfAborted();
10194
- mkdirSync8(destDir, { recursive: true });
10347
+ mkdirSync9(destDir, { recursive: true });
10195
10348
  try {
10196
10349
  await execFileAsync4("tar", ["-xf", zipPath, "-C", destDir], {
10197
10350
  windowsHide: true,
@@ -10775,7 +10928,7 @@ function parseMcpJsonText(jsonText) {
10775
10928
  }
10776
10929
 
10777
10930
  // src/host/mcp-connectors/install-git.ts
10778
- import { existsSync as existsSync18, mkdirSync as mkdirSync9, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
10931
+ import { existsSync as existsSync18, mkdirSync as mkdirSync10, readFileSync as readFileSync8, renameSync as renameSync7, rmSync as rmSync7 } from "node:fs";
10779
10932
  import { join as join28 } from "node:path";
10780
10933
 
10781
10934
  // src/host/mcp-connectors/paths.ts
@@ -10873,11 +11026,11 @@ async function installMcpServerFromGit(options) {
10873
11026
  }
10874
11027
  removePathRobust(installDir);
10875
11028
  }
10876
- mkdirSync9(join28(options.rootDir, "mcp-servers"), { recursive: true });
11029
+ mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
10877
11030
  const staging = `${installDir}.staging.${process.pid}`;
10878
11031
  try {
10879
11032
  if (existsSync18(staging)) removePathRobust(staging);
10880
- mkdirSync9(staging, { recursive: true });
11033
+ mkdirSync10(staging, { recursive: true });
10881
11034
  if (parsed.github === null) {
10882
11035
  throw new AuxiliaryError(
10883
11036
  "FILE_EDIT_FAILED",
@@ -10899,7 +11052,7 @@ async function installMcpServerFromGit(options) {
10899
11052
  }
10900
11053
  contentRoot = nested;
10901
11054
  }
10902
- mkdirSync9(join28(options.rootDir, "mcp-servers"), { recursive: true });
11055
+ mkdirSync10(join28(options.rootDir, "mcp-servers"), { recursive: true });
10903
11056
  if (contentRoot !== repoDir) {
10904
11057
  const nestedStaging = `${installDir}.nested.${process.pid}`;
10905
11058
  renameSync7(contentRoot, nestedStaging);
@@ -10936,6 +11089,7 @@ async function installMcpServerFromGit(options) {
10936
11089
  function snapshotOf2(host) {
10937
11090
  return {
10938
11091
  connectors: host.store.load().connectors,
11092
+ statuses: host.runtime.statusRows(),
10939
11093
  bridgeAvailable: host.runtime.bridgeAvailable,
10940
11094
  bridgeError: host.runtime.lastBridgeError
10941
11095
  };
@@ -11146,9 +11300,25 @@ function listMcpConnectorToolsNow(host, request) {
11146
11300
  }));
11147
11301
  return { serverName, tools };
11148
11302
  }
11303
+ async function restartMcpConnectorNow(host, request) {
11304
+ const restarted = await host.runtime.restart(request.id);
11305
+ return {
11306
+ id: request.id,
11307
+ ok: restarted.ok,
11308
+ error: restarted.error,
11309
+ snapshot: snapshotOf2(host)
11310
+ };
11311
+ }
11312
+ async function probeMcpConnectorNow(host, request, signal) {
11313
+ const probed = await host.runtime.probe(request.id, signal);
11314
+ return {
11315
+ ...probed,
11316
+ snapshot: snapshotOf2(host)
11317
+ };
11318
+ }
11149
11319
 
11150
11320
  // src/host/mcp-connectors/store.ts
11151
- import { mkdirSync as mkdirSync10, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
11321
+ import { mkdirSync as mkdirSync11, readFileSync as readFileSync9, renameSync as renameSync8, writeFileSync as writeFileSync5 } from "node:fs";
11152
11322
  import { dirname as dirname11 } from "node:path";
11153
11323
 
11154
11324
  // src/host/mcp-connectors/types.ts
@@ -11231,7 +11401,7 @@ function parseDoc2(raw) {
11231
11401
  }
11232
11402
  }
11233
11403
  function createMcpConnectorsStore(rootDir) {
11234
- mkdirSync10(rootDir, { recursive: true });
11404
+ mkdirSync11(rootDir, { recursive: true });
11235
11405
  const file = mcpConnectorsLedgerPath(rootDir);
11236
11406
  return {
11237
11407
  rootDir,
@@ -11250,7 +11420,7 @@ function createMcpConnectorsStore(rootDir) {
11250
11420
  version: MCP_CONNECTORS_VERSION,
11251
11421
  connectors: [...connectors]
11252
11422
  };
11253
- mkdirSync10(dirname11(file), { recursive: true });
11423
+ mkdirSync11(dirname11(file), { recursive: true });
11254
11424
  const tmp = `${file}.${process.pid}.tmp`;
11255
11425
  writeFileSync5(tmp, `${JSON.stringify(doc, null, 2)}
11256
11426
  `, "utf8");
@@ -11260,6 +11430,80 @@ function createMcpConnectorsStore(rootDir) {
11260
11430
  };
11261
11431
  }
11262
11432
 
11433
+ // src/host/mcp-connectors/probe-message.ts
11434
+ function classifyMcpProbeFailure(message) {
11435
+ const lower = message.toLowerCase();
11436
+ if (lower.includes("url is expired") || lower.includes("url expired") || lower.includes('"url is expired"')) {
11437
+ return "url-expired";
11438
+ }
11439
+ return "generic";
11440
+ }
11441
+ function rewriteMcpProbeFailure(message) {
11442
+ const code = classifyMcpProbeFailure(message);
11443
+ switch (code) {
11444
+ case "url-expired":
11445
+ return "url-expired";
11446
+ case "generic":
11447
+ return message;
11448
+ default: {
11449
+ const _exhaustive = code;
11450
+ return _exhaustive;
11451
+ }
11452
+ }
11453
+ }
11454
+
11455
+ // src/host/mcp-connectors/status.ts
11456
+ function summarizeMcpConnectionStatus(status) {
11457
+ if (status === null || status === void 0) {
11458
+ return { state: "unmounted", detail: null, toolCount: null };
11459
+ }
11460
+ switch (status.state) {
11461
+ case "connected":
11462
+ return {
11463
+ state: "connected",
11464
+ detail: null,
11465
+ toolCount: status.toolCount
11466
+ };
11467
+ case "connecting":
11468
+ return {
11469
+ state: "connecting",
11470
+ detail: status.attempt > 0 ? `attempt ${status.attempt + 1}` : null,
11471
+ toolCount: null
11472
+ };
11473
+ case "reconnecting":
11474
+ return {
11475
+ state: "reconnecting",
11476
+ detail: status.lastError.trim() !== "" ? status.lastError : `attempt ${status.attempt}/${status.maxAttempts}`,
11477
+ toolCount: null
11478
+ };
11479
+ case "waiting-credentials":
11480
+ return {
11481
+ state: "waiting-credentials",
11482
+ detail: status.lastError.trim() !== "" ? status.lastError : null,
11483
+ toolCount: null
11484
+ };
11485
+ case "failed":
11486
+ return {
11487
+ state: "failed",
11488
+ detail: status.lastError?.trim() ? `${status.reason}: ${status.lastError}` : status.reason,
11489
+ toolCount: null
11490
+ };
11491
+ case "closed":
11492
+ return {
11493
+ state: "closed",
11494
+ detail: status.result?.cleanupError ?? null,
11495
+ toolCount: null
11496
+ };
11497
+ default: {
11498
+ const _exhaustive = status;
11499
+ return _exhaustive;
11500
+ }
11501
+ }
11502
+ }
11503
+ function disabledMcpStatus() {
11504
+ return { state: "disabled", detail: null, toolCount: null };
11505
+ }
11506
+
11263
11507
  // src/host/mcp-connectors/runtime.ts
11264
11508
  function toPluginConfig(entry) {
11265
11509
  const base = {
@@ -11296,6 +11540,7 @@ var McpConnectorRuntime = class {
11296
11540
  store;
11297
11541
  mounts = /* @__PURE__ */ new Map();
11298
11542
  module = null;
11543
+ clientApi = null;
11299
11544
  bridgeError = null;
11300
11545
  featureEnabled = true;
11301
11546
  get bridgeAvailable() {
@@ -11314,23 +11559,155 @@ var McpConnectorRuntime = class {
11314
11559
  if (typeof loaded.apply !== "function") {
11315
11560
  this.bridgeError = "@deepseek-ai/dsh-mcp-client apply() missing";
11316
11561
  this.module = null;
11562
+ this.clientApi = null;
11317
11563
  return false;
11318
11564
  }
11319
11565
  this.module = loaded;
11566
+ this.clientApi = loaded;
11320
11567
  this.bridgeError = null;
11321
11568
  return true;
11322
11569
  } catch (error) {
11323
11570
  const detail = error instanceof Error ? error.message : String(error);
11324
11571
  this.bridgeError = detail;
11325
11572
  this.module = null;
11573
+ this.clientApi = null;
11326
11574
  this.ctx.logger.warn(`agent-enhancer: dsh-mcp-client unavailable: ${detail}`);
11327
11575
  return false;
11328
11576
  }
11329
11577
  }
11578
+ statusOf(id, entry) {
11579
+ const connector = entry ?? this.store.load().connectors.find((row) => row.id === id);
11580
+ if (connector === void 0) {
11581
+ return summarizeMcpConnectionStatus(void 0);
11582
+ }
11583
+ if (!connector.enabled || !this.featureEnabled) {
11584
+ return disabledMcpStatus();
11585
+ }
11586
+ const mount = this.mounts.get(id);
11587
+ if (mount === void 0) {
11588
+ return summarizeMcpConnectionStatus(void 0);
11589
+ }
11590
+ try {
11591
+ const handle = this.clientApi?.connectionStatusOf?.(mount.fiber);
11592
+ return summarizeMcpConnectionStatus(handle?.current());
11593
+ } catch {
11594
+ return summarizeMcpConnectionStatus(void 0);
11595
+ }
11596
+ }
11597
+ statusRows() {
11598
+ return this.store.load().connectors.map((entry) => ({
11599
+ id: entry.id,
11600
+ status: this.statusOf(entry.id, entry)
11601
+ }));
11602
+ }
11603
+ async restart(id) {
11604
+ const entry = this.store.load().connectors.find((row) => row.id === id);
11605
+ if (entry === void 0) {
11606
+ return { ok: false, error: `MCP connector not found: ${id}` };
11607
+ }
11608
+ if (!entry.enabled) {
11609
+ return { ok: false, error: "Connector is disabled" };
11610
+ }
11611
+ if (!this.featureEnabled) {
11612
+ return { ok: false, error: "MCP connectors feature is disabled" };
11613
+ }
11614
+ const ok = await this.ensureBridge();
11615
+ if (!ok) {
11616
+ return { ok: false, error: this.bridgeError ?? "mcp-client bridge unavailable" };
11617
+ }
11618
+ await this.disposeOne(id);
11619
+ await this.mountOne(entry);
11620
+ if (!this.mounts.has(id)) {
11621
+ return { ok: false, error: "Restart failed to remount connector" };
11622
+ }
11623
+ return { ok: true, error: null };
11624
+ }
11625
+ async probe(id, signal) {
11626
+ const entry = this.store.load().connectors.find((row) => row.id === id);
11627
+ if (entry === void 0) {
11628
+ return {
11629
+ id,
11630
+ ok: false,
11631
+ message: `MCP connector not found: ${id}`,
11632
+ toolNames: [],
11633
+ truncated: false,
11634
+ durationMs: 0
11635
+ };
11636
+ }
11637
+ const live = this.statusOf(id, entry);
11638
+ if (live.state === "connected") {
11639
+ const toolNames = this.liveToolNames(entry.serverName);
11640
+ const count = live.toolCount ?? toolNames.length;
11641
+ return {
11642
+ id,
11643
+ ok: true,
11644
+ message: `live \xB7 ${count} tools`,
11645
+ toolNames,
11646
+ truncated: false,
11647
+ durationMs: 0
11648
+ };
11649
+ }
11650
+ const ok = await this.ensureBridge();
11651
+ if (!ok || this.clientApi?.probeServer === void 0) {
11652
+ return {
11653
+ id,
11654
+ ok: false,
11655
+ message: this.bridgeError ?? "mcp-client probeServer unavailable",
11656
+ toolNames: [],
11657
+ truncated: false,
11658
+ durationMs: 0
11659
+ };
11660
+ }
11661
+ try {
11662
+ const result = await this.clientApi.probeServer(this.ctx, toPluginConfig(entry), {
11663
+ timeoutMs: 15e3,
11664
+ ...signal === void 0 ? {} : { signal }
11665
+ });
11666
+ if (result.ok) {
11667
+ const toolNames = result.toolNames ?? [];
11668
+ return {
11669
+ id,
11670
+ ok: true,
11671
+ message: result.serverInfo === void 0 ? `ok \xB7 ${toolNames.length} tools` : `ok \xB7 ${result.serverInfo.name}@${result.serverInfo.version} \xB7 ${toolNames.length} tools`,
11672
+ toolNames,
11673
+ truncated: result.truncated === true,
11674
+ durationMs: result.durationMs ?? 0
11675
+ };
11676
+ }
11677
+ const raw = `${result.stage ?? "probe"}: ${result.message ?? "failed"}`;
11678
+ return {
11679
+ id,
11680
+ ok: false,
11681
+ message: rewriteMcpProbeFailure(raw),
11682
+ toolNames: [],
11683
+ truncated: false,
11684
+ durationMs: result.durationMs ?? 0
11685
+ };
11686
+ } catch (error) {
11687
+ const detail = error instanceof Error ? error.message : String(error);
11688
+ return {
11689
+ id,
11690
+ ok: false,
11691
+ message: rewriteMcpProbeFailure(detail),
11692
+ toolNames: [],
11693
+ truncated: false,
11694
+ durationMs: 0
11695
+ };
11696
+ }
11697
+ }
11698
+ liveToolNames(serverName) {
11699
+ const prefix = `mcp__${serverName}__`;
11700
+ try {
11701
+ const definitions = this.ctx.tools.definitions();
11702
+ return definitions.filter((def) => def.name.startsWith(prefix)).map((def) => def.name.slice(prefix.length)).filter((name2) => name2.length > 0);
11703
+ } catch {
11704
+ return [];
11705
+ }
11706
+ }
11330
11707
  async disposeAll() {
11331
11708
  const ids = [...this.mounts.keys()];
11332
- for (const id of ids) {
11333
- await this.disposeOne(id);
11709
+ for (const nextId of ids) {
11710
+ await this.disposeOne(nextId);
11334
11711
  }
11335
11712
  }
11336
11713
  async disposeOne(id) {
@@ -11686,7 +12063,7 @@ var AutoCatalogAdapter = class extends LlmAdapter {
11686
12063
  stream(_options) {
11687
12064
  throw new LlmError(
11688
12065
  "Auto is a routing sentinel and is not sent to a provider",
11689
- "AUTO_SENTINEL"
12066
+ "UNSUPPORTED_OPTION"
11690
12067
  );
11691
12068
  }
11692
12069
  };
@@ -11844,17 +12221,28 @@ function installAutoSessionRoute(ctx, options) {
11844
12221
  const map = autoRouteMapOf(settings);
11845
12222
  const note = (agent === void 0 ? void 0 : notes.get(agent)) ?? loggedTurn(asAgent(agent));
11846
12223
  const classify = settings.autoClassifierEnabled ? createClassifier({ prepareCall: innerPrepare }, map.classifier) : void 0;
11847
- const mapped = await resolveAutoRoute({
11848
- text: note?.text ?? "",
11849
- feature,
11850
- toolHeavy: note?.toolHeavy ?? false,
11851
- map,
11852
- classifierEnabled: settings.autoClassifierEnabled,
11853
- classify,
11854
- isAvailable: (provider, model) => provider !== "" && model !== "" && !isAutoModel({ provider, model }),
11855
- signal,
11856
- fallback: fallbackRoute(ctx, asAgent(agent))
11857
- });
12224
+ let mapped;
12225
+ try {
12226
+ mapped = await resolveAutoRoute({
12227
+ text: note?.text ?? "",
12228
+ feature,
12229
+ toolHeavy: note?.toolHeavy ?? false,
12230
+ map,
12231
+ classifierEnabled: settings.autoClassifierEnabled,
12232
+ classify,
12233
+ isAvailable: (provider, model) => provider !== "" && model !== "" && !isAutoModel({ provider, model }),
12234
+ signal,
12235
+ fallback: fallbackRoute(ctx, asAgent(agent))
12236
+ });
12237
+ } catch (error) {
12238
+ if (error instanceof AutoRouteUnconfiguredError) {
12239
+ throw new LlmError(AUTO_ROUTE_UNCONFIGURED_LLM_MESSAGE, "INVALID_CONFIG");
12240
+ }
12241
+ throw error;
12242
+ }
12243
+ if (mapped.provider === "" || mapped.model === "" || isAutoModel({ provider: mapped.provider, model: mapped.model })) {
12244
+ throw new LlmError(AUTO_ROUTE_UNCONFIGURED_LLM_MESSAGE, "INVALID_CONFIG");
12245
+ }
11858
12246
  if (agent !== void 0 && feature === "session") setSessionResolvedRoute(agent, mapped);
11859
12247
  return mapped;
11860
12248
  };
@@ -12234,16 +12622,27 @@ var AuxiliaryModels = class {
12234
12622
  const settings = this.enhancerSettings();
12235
12623
  const map = autoRouteMapOf(settings);
12236
12624
  const classify = settings.autoClassifierEnabled ? createClassifier(this.ctx.llm, map.classifier) : void 0;
12237
- const mapped = await resolveAutoRoute({
12238
- text: text3,
12239
- feature,
12240
- toolHeavy,
12241
- map,
12242
- classifierEnabled: settings.autoClassifierEnabled,
12243
- classify,
12244
- isAvailable: (provider, model) => this.modelExists(provider, model),
12245
- fallback: this.fallbackFromSession(session, override)
12246
- });
12625
+ let mapped;
12626
+ try {
12627
+ mapped = await resolveAutoRoute({
12628
+ text: text3,
12629
+ feature,
12630
+ toolHeavy,
12631
+ map,
12632
+ classifierEnabled: settings.autoClassifierEnabled,
12633
+ classify,
12634
+ isAvailable: (provider, model) => this.modelExists(provider, model),
12635
+ fallback: this.fallbackFromSession(session, override)
12636
+ });
12637
+ } catch (error) {
12638
+ if (error instanceof AutoRouteUnconfiguredError) {
12639
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED", error.message);
12640
+ }
12641
+ throw error;
12642
+ }
12643
+ if (!this.modelExists(mapped.provider, mapped.model) || isAutoModel(mapped)) {
12644
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED");
12645
+ }
12247
12646
  if (feature === "session") {
12248
12647
  setSessionResolvedRouteForSession(session, {
12249
12648
  provider: mapped.provider,
@@ -12378,6 +12777,9 @@ var AuxiliaryModels = class {
12378
12777
  } catch (error) {
12379
12778
  if (controller.signal.aborted) throw controller.signal.reason;
12380
12779
  if (error instanceof AuxiliaryError) throw error;
12780
+ if (error instanceof AutoRouteUnconfiguredError) {
12781
+ throw new AuxiliaryError("AUTO_ROUTE_UNCONFIGURED", error.message);
12782
+ }
12381
12783
  throw new AuxiliaryError("MODEL_FAILED");
12382
12784
  } finally {
12383
12785
  signal.removeEventListener("abort", abort);
@@ -13921,6 +14323,15 @@ var browserAgentAuditEntrySchema = z4.strictObject({
13921
14323
  url: z4.string().optional(),
13922
14324
  outcome: z4.enum(["ok", "denied", "error", "needs_human"])
13923
14325
  });
14326
+ var browserAgentTabEntrySchema = z4.strictObject({
14327
+ tabId: z4.number().int().positive(),
14328
+ title: z4.string(),
14329
+ url: z4.string(),
14330
+ /** True when this is the driver's currently focused page. */
14331
+ active: z4.boolean(),
14332
+ /** True when any chat session is bound to this tab. */
14333
+ bound: z4.boolean()
14334
+ });
13924
14335
  var browserAgentSnapshotSchema = z4.strictObject({
13925
14336
  enabled: z4.boolean(),
13926
14337
  /** Settings preference (auto / chrome / edge / safari). */
@@ -13941,6 +14352,8 @@ var browserAgentSnapshotSchema = z4.strictObject({
13941
14352
  tabConflict: browserAgentTabConflictSchema.nullable(),
13942
14353
  needsHuman: browserAgentNeedsHumanSchema.nullable(),
13943
14354
  boundTabId: z4.number().int().nullable(),
14355
+ /** Open tabs in the dedicated browser (empty when not launched). */
14356
+ tabs: z4.array(browserAgentTabEntrySchema),
13944
14357
  audit: z4.array(browserAgentAuditEntrySchema),
13945
14358
  /** Dedicated Chromium profile used by one-click launch (user-level). */
13946
14359
  profileDir: z4.string().min(1)
@@ -14068,6 +14481,26 @@ var browserAgentSetBrowserResultCodec = codec(
14068
14481
  "dsh-agent-enhancer#BrowserAgentSetBrowserResult",
14069
14482
  browserAgentSetBrowserResultSchema
14070
14483
  );
14484
+ var browserAgentSelectTabRequestSchema = z4.strictObject({
14485
+ tabId: z4.number().int().positive(),
14486
+ sessionId: z4.string().min(1).optional()
14487
+ });
14488
+ var browserAgentSelectTabRequestCodec = codec(
14489
+ "dsh-agent-enhancer#BrowserAgentSelectTabRequest",
14490
+ browserAgentSelectTabRequestSchema
14491
+ );
14492
+ var browserAgentSelectTabResultSchema = z4.strictObject({
14493
+ ok: z4.boolean(),
14494
+ tabId: z4.number().int().positive().optional(),
14495
+ url: z4.string().optional(),
14496
+ title: z4.string().optional(),
14497
+ error: z4.string().optional(),
14498
+ snapshot: browserAgentSnapshotSchema
14499
+ });
14500
+ var browserAgentSelectTabResultCodec = codec(
14501
+ "dsh-agent-enhancer#BrowserAgentSelectTabResult",
14502
+ browserAgentSelectTabResultSchema
14503
+ );
14071
14504
  var instructionScopeSchema = z4.enum(["global", "shared", "project"]);
14072
14505
  var instructionFileEntrySchema = z4.strictObject({
14073
14506
  id: z4.string().min(1),
@@ -14290,8 +14723,28 @@ var mcpConnectorEntrySchema = z4.strictObject({
14290
14723
  createdAt: z4.number(),
14291
14724
  updatedAt: z4.number()
14292
14725
  });
14726
+ var mcpConnectorStatusStateSchema = z4.enum([
14727
+ "disabled",
14728
+ "unmounted",
14729
+ "connecting",
14730
+ "connected",
14731
+ "reconnecting",
14732
+ "waiting-credentials",
14733
+ "failed",
14734
+ "closed"
14735
+ ]);
14736
+ var mcpConnectorRuntimeStatusSchema = z4.strictObject({
14737
+ state: mcpConnectorStatusStateSchema,
14738
+ detail: z4.string().nullable(),
14739
+ toolCount: z4.number().int().nullable()
14740
+ });
14741
+ var mcpConnectorStatusRowSchema = z4.strictObject({
14742
+ id: z4.string().min(1),
14743
+ status: mcpConnectorRuntimeStatusSchema
14744
+ });
14293
14745
  var mcpConnectorsSnapshotSchema = z4.strictObject({
14294
14746
  connectors: z4.array(mcpConnectorEntrySchema),
14747
+ statuses: z4.array(mcpConnectorStatusRowSchema),
14295
14748
  bridgeAvailable: z4.boolean(),
14296
14749
  bridgeError: z4.string().nullable()
14297
14750
  });
@@ -14368,6 +14821,27 @@ var listMcpConnectorToolsResultSchema = z4.strictObject({
14368
14821
  description: z4.string()
14369
14822
  }))
14370
14823
  });
14824
+ var restartMcpConnectorRequestSchema = z4.strictObject({
14825
+ id: z4.string().min(1)
14826
+ });
14827
+ var restartMcpConnectorResultSchema = z4.strictObject({
14828
+ id: z4.string().min(1),
14829
+ ok: z4.boolean(),
14830
+ error: z4.string().nullable(),
14831
+ snapshot: mcpConnectorsSnapshotSchema
14832
+ });
14833
+ var probeMcpConnectorRequestSchema = z4.strictObject({
14834
+ id: z4.string().min(1)
14835
+ });
14836
+ var probeMcpConnectorResultSchema = z4.strictObject({
14837
+ id: z4.string().min(1),
14838
+ ok: z4.boolean(),
14839
+ message: z4.string(),
14840
+ toolNames: z4.array(z4.string()),
14841
+ truncated: z4.boolean(),
14842
+ durationMs: z4.number(),
14843
+ snapshot: mcpConnectorsSnapshotSchema
14844
+ });
14371
14845
  var listMcpConnectorsRequestCodec = codec(
14372
14846
  "dsh-agent-enhancer#ListMcpConnectorsRequest",
14373
14847
  listMcpConnectorsRequestSchema
@@ -14432,6 +14906,22 @@ var listMcpConnectorToolsResultCodec = codec(
14432
14906
  "dsh-agent-enhancer#ListMcpConnectorToolsResult",
14433
14907
  listMcpConnectorToolsResultSchema
14434
14908
  );
14909
+ var restartMcpConnectorRequestCodec = codec(
14910
+ "dsh-agent-enhancer#RestartMcpConnectorRequest",
14911
+ restartMcpConnectorRequestSchema
14912
+ );
14913
+ var restartMcpConnectorResultCodec = codec(
14914
+ "dsh-agent-enhancer#RestartMcpConnectorResult",
14915
+ restartMcpConnectorResultSchema
14916
+ );
14917
+ var probeMcpConnectorRequestCodec = codec(
14918
+ "dsh-agent-enhancer#ProbeMcpConnectorRequest",
14919
+ probeMcpConnectorRequestSchema
14920
+ );
14921
+ var probeMcpConnectorResultCodec = codec(
14922
+ "dsh-agent-enhancer#ProbeMcpConnectorResult",
14923
+ probeMcpConnectorResultSchema
14924
+ );
14435
14925
  var remoteInfo = createTypertRemoteInfo({
14436
14926
  package: "dsh-agent-enhancer",
14437
14927
  methods: {
@@ -14751,6 +15241,18 @@ var remoteInfo = createTypertRemoteInfo({
14751
15241
  }],
14752
15242
  result: browserAgentSetBrowserResultCodec
14753
15243
  },
15244
+ "agentEnhancer/browserAgentSelectTab": {
15245
+ service: "agentEnhancer",
15246
+ implementation: "browserAgentSelectTab",
15247
+ invocation: { kind: "direct" },
15248
+ parameters: [{
15249
+ name: "request",
15250
+ source: "json",
15251
+ codec: browserAgentSelectTabRequestCodec,
15252
+ strictCodec: browserAgentSelectTabRequestCodec
15253
+ }],
15254
+ result: browserAgentSelectTabResultCodec
15255
+ },
14754
15256
  "agentEnhancer/listInstructionsSkills": {
14755
15257
  service: "agentEnhancer",
14756
15258
  implementation: "listInstructionsSkills",
@@ -14972,6 +15474,32 @@ var remoteInfo = createTypertRemoteInfo({
14972
15474
  cancellation: { parameter: "signal" },
14973
15475
  result: listMcpConnectorToolsResultCodec
14974
15476
  },
15477
+ "agentEnhancer/restartMcpConnector": {
15478
+ service: "agentEnhancer",
15479
+ implementation: "restartMcpConnector",
15480
+ invocation: { kind: "direct" },
15481
+ parameters: [{
15482
+ name: "request",
15483
+ source: "json",
15484
+ codec: restartMcpConnectorRequestCodec,
15485
+ strictCodec: restartMcpConnectorRequestCodec
15486
+ }],
15487
+ cancellation: { parameter: "signal" },
15488
+ result: restartMcpConnectorResultCodec
15489
+ },
15490
+ "agentEnhancer/probeMcpConnector": {
15491
+ service: "agentEnhancer",
15492
+ implementation: "probeMcpConnector",
15493
+ invocation: { kind: "direct" },
15494
+ parameters: [{
15495
+ name: "request",
15496
+ source: "json",
15497
+ codec: probeMcpConnectorRequestCodec,
15498
+ strictCodec: probeMcpConnectorRequestCodec
15499
+ }],
15500
+ cancellation: { parameter: "signal" },
15501
+ result: probeMcpConnectorResultCodec
15502
+ },
14975
15503
  "agentEnhancer/listWebChatWorkspaces": {
14976
15504
  service: "agentEnhancer",
14977
15505
  implementation: "listWebChatWorkspaces",
@@ -15360,7 +15888,7 @@ async function showOsNotificationNow(input) {
15360
15888
 
15361
15889
  // src/host/update/check.ts
15362
15890
  import { homedir as homedir6 } from "node:os";
15363
- import { join as join32 } from "node:path";
15891
+ import { join as join31 } from "node:path";
15364
15892
 
15365
15893
  // src/host/update/cli.ts
15366
15894
  import { spawn as nodeSpawn } from "node:child_process";
@@ -15481,9 +16009,9 @@ async function runPluginAdd(latest, spawnFn = defaultSpawn, options = {}) {
15481
16009
 
15482
16010
  // src/host/update/install-kind.ts
15483
16011
  import { lstatSync as lstatSync5 } from "node:fs";
15484
- import { join as join31 } from "node:path";
16012
+ import { join as join30 } from "node:path";
15485
16013
  function detectInstallKind(profileDir) {
15486
- const pkgPath = join31(profileDir, "node_modules", PACKAGE_NAME);
16014
+ const pkgPath = join30(profileDir, "node_modules", PACKAGE_NAME);
15487
16015
  try {
15488
16016
  const stat = lstatSync5(pkgPath);
15489
16017
  if (stat.isSymbolicLink()) return "link";
@@ -15614,8 +16142,8 @@ function isNewerVersion(latest, current) {
15614
16142
 
15615
16143
  // src/host/update/check.ts
15616
16144
  function resolveDesktopProfileDir(env = process.env, home = homedir6()) {
15617
- const dshHome2 = env.DSH_HOME ?? join32(home, ".dsh");
15618
- return join32(dshHome2, "profiles", "desktop");
16145
+ const dshHome2 = env.DSH_HOME ?? join31(home, ".dsh");
16146
+ return join31(dshHome2, "profiles", "desktop");
15619
16147
  }
15620
16148
  async function checkPluginUpdate(deps) {
15621
16149
  const latest = await deps.fetchLatest();
@@ -15761,12 +16289,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
15761
16289
  };
15762
16290
  }
15763
16291
  }, sessionCleanup = new SessionCleanupRegistry(), extraFolders = createExtraFoldersStore(
15764
- join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
16292
+ join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME, "extra-folders")
15765
16293
  ), softPause = new SoftPauseGate(), softPauseEnabled = () => true, installLedgerRoot = void 0, mcpHost = null, browserAgent = null, browserAgentSettings = () => ({
15766
16294
  enabled: false,
15767
16295
  browser: "auto"
15768
16296
  }), setBrowserAgentBrowser = () => void 0, browserAgentProfileDir = defaultBrowserAgentProfileDir(
15769
- join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
16297
+ join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME)
15770
16298
  )) {
15771
16299
  super(ctx, "agentEnhancer");
15772
16300
  this.models = models;
@@ -15796,7 +16324,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
15796
16324
  browserAgentSettings;
15797
16325
  setBrowserAgentBrowser;
15798
16326
  browserAgentProfileDir;
15799
- browserSnapshotNow() {
16327
+ async browserSnapshotNow() {
15800
16328
  const settings = this.browserAgentSettings();
15801
16329
  const driverStatus = this.browserAgent?.driverStatus();
15802
16330
  const pending = this.browserAgent?.approval.current() ?? null;
@@ -15806,8 +16334,11 @@ var AgentEnhancerService = class extends TypertRemoteService {
15806
16334
  sessionId: waiting.sessionId,
15807
16335
  detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail
15808
16336
  } : this.browserAgent?.sessions.anyNeedsHuman() ?? null;
15809
- const boundTabId = pending !== null ? this.browserAgent?.sessions.tabOf(pending.sessionId) ?? null : conflict !== null ? conflict.boundTabId : needsHuman !== null ? this.browserAgent?.sessions.tabOf(needsHuman.sessionId) ?? null : null;
16337
+ const overlayBound = pending !== null ? this.browserAgent?.sessions.tabOf(pending.sessionId) ?? null : conflict !== null ? conflict.boundTabId : needsHuman !== null ? this.browserAgent?.sessions.tabOf(needsHuman.sessionId) ?? null : null;
15810
16338
  const connected = driverStatus?.ready === true;
16339
+ const listed = connected ? await this.browserAgent?.listTabs() : void 0;
16340
+ const tabs = listed?.tabs ?? [];
16341
+ const boundTabId = overlayBound ?? listed?.boundTabId ?? null;
15811
16342
  const endpoint = driverStatus?.endpoint ?? "playwright:unlaunched";
15812
16343
  const launched = endpoint === "playwright:msedge" ? "edge" : endpoint === "playwright:chrome" ? "chrome" : endpoint === "playwright:webkit" ? "safari" : null;
15813
16344
  return {
@@ -15834,6 +16365,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
15834
16365
  tabConflict: conflict,
15835
16366
  needsHuman,
15836
16367
  boundTabId,
16368
+ tabs: [...tabs],
15837
16369
  audit: [...this.browserAgent?.sessions.recentAudit(12) ?? []],
15838
16370
  profileDir: this.browserAgent?.activeProfileDir() ?? this.browserAgentProfileDir
15839
16371
  };
@@ -15868,7 +16400,8 @@ var AgentEnhancerService = class extends TypertRemoteService {
15868
16400
  } catch (error) {
15869
16401
  if (signal.aborted) throw error;
15870
16402
  const code = error instanceof AuxiliaryError ? error.code : "MODEL_FAILED";
15871
- throw new RemoteError2("agent-enhancer/failed", "Agent Enhance request failed", { code });
16403
+ const detail = error instanceof AuxiliaryError ? error.message : "Agent Enhance request failed";
16404
+ throw new RemoteError2("agent-enhancer/failed", detail || "Agent Enhance request failed", { code });
15872
16405
  }
15873
16406
  }
15874
16407
  /** Same Desktop catalog the official model selector uses (`llm` registry). */
@@ -16011,7 +16544,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16011
16544
  }
16012
16545
  }
16013
16546
  webChatPluginDataRoot() {
16014
- return this.installLedgerRoot ?? join33(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
16547
+ return this.installLedgerRoot ?? join32(homedir7(), ".dsh", "profiles", "desktop", "plugin-data", PACKAGE_NAME);
16015
16548
  }
16016
16549
  /** User-level web chat guest login snapshot (non-HttpOnly storage only). */
16017
16550
  async loadWebChatLoginSnapshot(_request, signal) {
@@ -16383,6 +16916,26 @@ var AgentEnhancerService = class extends TypertRemoteService {
16383
16916
  throw instructionsSkillsRemoteError(error);
16384
16917
  }
16385
16918
  }
16919
+ async restartMcpConnector(request, signal) {
16920
+ this.assertOwner();
16921
+ signal.throwIfAborted();
16922
+ try {
16923
+ return await restartMcpConnectorNow(this.requireMcpHost(), request);
16924
+ } catch (error) {
16925
+ if (signal.aborted) throw error;
16926
+ throw instructionsSkillsRemoteError(error);
16927
+ }
16928
+ }
16929
+ async probeMcpConnector(request, signal) {
16930
+ this.assertOwner();
16931
+ signal.throwIfAborted();
16932
+ try {
16933
+ return await probeMcpConnectorNow(this.requireMcpHost(), request, signal);
16934
+ } catch (error) {
16935
+ if (signal.aborted) throw error;
16936
+ throw instructionsSkillsRemoteError(error);
16937
+ }
16938
+ }
16386
16939
  async listMcpConnectorTools(request, signal) {
16387
16940
  this.assertOwner();
16388
16941
  signal.throwIfAborted();
@@ -16420,22 +16973,22 @@ var AgentEnhancerService = class extends TypertRemoteService {
16420
16973
  }
16421
16974
  async browserAgentSnapshot() {
16422
16975
  this.assertOwner();
16423
- return this.browserSnapshotNow();
16976
+ return await this.browserSnapshotNow();
16424
16977
  }
16425
16978
  async browserAgentResolve(request) {
16426
16979
  this.assertOwner();
16427
16980
  const ok = this.browserAgent?.approval.resolve(request.id, request.decision) ?? false;
16428
- return { ok, snapshot: this.browserSnapshotNow() };
16981
+ return { ok, snapshot: await this.browserSnapshotNow() };
16429
16982
  }
16430
16983
  async browserAgentResolveTabConflict(request) {
16431
16984
  this.assertOwner();
16432
16985
  const result = await this.browserAgent?.resolveTabConflict(request.decision);
16433
- return { ok: result?.ok === true, snapshot: this.browserSnapshotNow() };
16986
+ return { ok: result?.ok === true, snapshot: await this.browserSnapshotNow() };
16434
16987
  }
16435
16988
  async browserAgentAcknowledgeHuman(request) {
16436
16989
  this.assertOwner();
16437
16990
  const ok = this.browserAgent?.acknowledgeHuman(request.sessionId) === true;
16438
- return { ok, snapshot: this.browserSnapshotNow() };
16991
+ return { ok, snapshot: await this.browserSnapshotNow() };
16439
16992
  }
16440
16993
  async browserAgentOpenUrl(request) {
16441
16994
  this.assertOwner();
@@ -16448,7 +17001,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16448
17001
  ...result?.url === void 0 ? {} : { url: result.url },
16449
17002
  ...result?.title === void 0 ? {} : { title: result.title },
16450
17003
  ...result?.error === void 0 ? {} : { error: result.error },
16451
- snapshot: this.browserSnapshotNow()
17004
+ snapshot: await this.browserSnapshotNow()
16452
17005
  };
16453
17006
  }
16454
17007
  async browserAgentQuotePage(request) {
@@ -16460,7 +17013,7 @@ var AgentEnhancerService = class extends TypertRemoteService {
16460
17013
  ...result?.url === void 0 ? {} : { url: result.url },
16461
17014
  ...result?.title === void 0 ? {} : { title: result.title },
16462
17015
  ...result?.error === void 0 ? {} : { error: result.error },
16463
- snapshot: this.browserSnapshotNow()
17016
+ snapshot: await this.browserSnapshotNow()
16464
17017
  };
16465
17018
  }
16466
17019
  async browserAgentLaunchBrowser(request) {
@@ -16471,13 +17024,13 @@ var AgentEnhancerService = class extends TypertRemoteService {
16471
17024
  ok: false,
16472
17025
  profileDir: this.browserAgentProfileDir,
16473
17026
  error: "Browser agent is disabled in settings.",
16474
- snapshot: this.browserSnapshotNow()
17027
+ snapshot: await this.browserSnapshotNow()
16475
17028
  };
16476
17029
  }
16477
17030
  const preference = hostBrowserPreference(request.browser ?? settings.browser);
16478
17031
  this.setBrowserAgentBrowser(preference);
16479
17032
  const launched = await this.browserAgent?.launchDedicated(void 0, preference);
16480
- const snapshot = this.browserSnapshotNow();
17033
+ const snapshot = await this.browserSnapshotNow();
16481
17034
  return {
16482
17035
  ok: launched?.ok === true,
16483
17036
  profileDir: this.browserAgent?.activeProfileDir() ?? this.browserAgentProfileDir,
@@ -16497,7 +17050,22 @@ var AgentEnhancerService = class extends TypertRemoteService {
16497
17050
  return {
16498
17051
  ok: true,
16499
17052
  browser: preference,
16500
- snapshot: this.browserSnapshotNow()
17053
+ snapshot: await this.browserSnapshotNow()
17054
+ };
17055
+ }
17056
+ async browserAgentSelectTab(request) {
17057
+ this.assertOwner();
17058
+ const result = await this.browserAgent?.selectTab({
17059
+ tabId: request.tabId,
17060
+ ...request.sessionId === void 0 ? {} : { sessionId: request.sessionId }
17061
+ });
17062
+ return {
17063
+ ok: result?.ok === true,
17064
+ ...result?.tabId === void 0 ? {} : { tabId: result.tabId },
17065
+ ...result?.url === void 0 ? {} : { url: result.url },
17066
+ ...result?.title === void 0 ? {} : { title: result.title },
17067
+ ...result?.error === void 0 ? {} : { error: result.error },
17068
+ snapshot: await this.browserSnapshotNow()
16501
17069
  };
16502
17070
  }
16503
17071
  async applyUpdate() {
@@ -16512,14 +17080,14 @@ var AgentEnhancerService = class extends TypertRemoteService {
16512
17080
  }
16513
17081
  };
16514
17082
  function resolveCheckpointRoot(dshHome2) {
16515
- const base = join33(dshHome2, "profiles", "desktop", "plugin-data");
16516
- const nextPkg = join33(base, PACKAGE_NAME);
16517
- const next = join33(nextPkg, "checkpoint");
16518
- const prev = join33(base, LEGACY_PACKAGE_NAME, "checkpoint");
17083
+ const base = join32(dshHome2, "profiles", "desktop", "plugin-data");
17084
+ const nextPkg = join32(base, PACKAGE_NAME);
17085
+ const next = join32(nextPkg, "checkpoint");
17086
+ const prev = join32(base, LEGACY_PACKAGE_NAME, "checkpoint");
16519
17087
  if (!existsSync21(next) && existsSync21(prev)) {
16520
- mkdirSync11(nextPkg, { recursive: true });
17088
+ mkdirSync12(nextPkg, { recursive: true });
16521
17089
  renameSync9(prev, next);
16522
- const prevPkg = join33(base, LEGACY_PACKAGE_NAME);
17090
+ const prevPkg = join32(base, LEGACY_PACKAGE_NAME);
16523
17091
  try {
16524
17092
  if (existsSync21(prevPkg) && readdirSync7(prevPkg).length === 0) rmdirSync(prevPkg);
16525
17093
  } catch {
@@ -16624,9 +17192,9 @@ function apply(ctx, config) {
16624
17192
  const settings = () => readSettings(config);
16625
17193
  const models = new AuxiliaryModels(ctx, settings);
16626
17194
  installAutoSessionRoute(ctx, { settings });
16627
- const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join33(homedir7(), ".dsh"));
16628
- const pluginDataPackageRoot = join33(storageRoot, "..");
16629
- const usage = new UsageLedger(join33(storageRoot, "..", "usage"), (message) => {
17195
+ const storageRoot = resolveCheckpointRoot(process.env.DSH_HOME ?? join32(homedir7(), ".dsh"));
17196
+ const pluginDataPackageRoot = join32(storageRoot, "..");
17197
+ const usage = new UsageLedger(join32(storageRoot, "..", "usage"), (message) => {
16630
17198
  ctx.logger.warn(message);
16631
17199
  });
16632
17200
  const balancesFacade = (() => {
@@ -16656,12 +17224,12 @@ function apply(ctx, config) {
16656
17224
  })();
16657
17225
  installUsageObserver(ctx, usage);
16658
17226
  const store = new CheckpointStore(storageRoot);
16659
- const cutStore = new SessionCutStore(join33(storageRoot, "cuts"));
17227
+ const cutStore = new SessionCutStore(join32(storageRoot, "cuts"));
16660
17228
  const cutCache = /* @__PURE__ */ new Map();
16661
17229
  const sessionCleanup = new SessionCleanupRegistry();
16662
17230
  sessionCleanup.register(createCheckpointCleaner({ store, cutStore, storageRoot }));
16663
- sessionCleanup.register(createContextExcludeCleaner(join33(storageRoot, "..")));
16664
- const extraFoldersStore = createExtraFoldersStore(join33(storageRoot, "..", "extra-folders"));
17231
+ sessionCleanup.register(createContextExcludeCleaner(join32(storageRoot, "..")));
17232
+ const extraFoldersStore = createExtraFoldersStore(join32(storageRoot, "..", "extra-folders"));
16665
17233
  const softPauseGate = new SoftPauseGate();
16666
17234
  const mcpStore = createMcpConnectorsStore(mcpConnectorsRoot(pluginDataPackageRoot));
16667
17235
  const mcpRuntime = new McpConnectorRuntime(ctx, mcpStore);
@@ -16741,13 +17309,11 @@ function apply(ctx, config) {
16741
17309
  const detail = error instanceof Error ? error.message : String(error);
16742
17310
  ctx.logger.warn(`agent-enhancer: MCP connector sync after settings update failed: ${detail}`);
16743
17311
  });
16744
- const prevEnabled = browserAgentLive.enabled;
16745
17312
  const prevBrowser = browserAgentLive.browser;
16746
17313
  browserAgentLive.enabled = cfg.browserAgentEnabled.get();
16747
17314
  browserAgentLive.browser = hostBrowserPreference(cfg.browserAgentBrowser.get());
16748
- if (prevEnabled !== browserAgentLive.enabled) {
16749
- browserAgent.refresh();
16750
- } else if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
17315
+ browserAgent.refresh();
17316
+ if (browserAgentLive.enabled && prevBrowser !== browserAgentLive.browser && browserAgent.driverStatus()?.ready === true) {
16751
17317
  void browserAgent.alignToPreference().catch((error) => {
16752
17318
  const detail = error instanceof Error ? error.message : String(error);
16753
17319
  ctx.logger.warn(`agent-enhancer: browser preference align after settings failed: ${detail}`);